Skip to main content
aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.c-feature/pom.xml2
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/plugin.xml124
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IEditorChangeLogContrib.java62
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IEditorChangeLogContrib2.java12
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IFormatterChangeLogContrib.java6
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IParserChangeLogContrib.java40
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogExtensionManager.java416
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogPreferencesPage.java458
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogWriter.java158
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangelogPlugin.java40
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangelogPreferenceInitializer.java90
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/LineComparator.java114
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/Messages.java42
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogAction.java578
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerContentProvider.java38
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerSelectionDialog.java30
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerSelectionGroup.java464
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogRootContainer.java18
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/FormatChangeLogAction.java22
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/InsertChangeLogKeyHandler.java278
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchFile.java238
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchFileComparator.java8
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchRangeElement.java48
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareChangeLogAction.java1032
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareChangelogKeyHandler.java178
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareCommitHandler.java404
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/SourceEditorInput.java26
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/StorageEditorInput.java148
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogDocumentProvider.java8
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogDocumentSetupParticipant.java96
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogEditor.java156
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogFormattingStrategy.java420
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ColorManager.java28
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/FileHyperlink.java62
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUEditorConfiguration.java282
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUElementScanner.java170
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUFileEntryDamagerRepairer.java42
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUFileEntryRule.java246
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUHyperlinkDetector.java298
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUPartitionScanner.java52
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/IChangeLogColorConstants.java16
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/MultilineRuleDamagerRepairer.java48
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/formatters/GNUFormat.java738
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ui/ChangeLogActionProvider.java56
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.cparser/src/org/eclipse/linuxtools/internal/changelog/parsers/CParser.java330
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.doc/build-helper.xml86
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.doc/toc-doc.xml2
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.doc/toc.xml22
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.javaparser/src/org/eclipse/linuxtools/internal/changelog/parsers/java/JavaParser.java264
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.tests/pom.xml2
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/formatters/tests/GNUFormatTest.java948
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/tests/AllTests.java16
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/tests/ChangeLogWriterTest.java518
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/parsers/tests/CParserTest.java776
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/parsers/tests/JavaParserTest.java844
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/CStringStorage.java62
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/CStringStorageInput.java82
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/ChangeLogTestProject.java222
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/TestChangeLogTestProject.java232
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/helpers/EditorHelper.java94
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/pom.xml2
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/log4j.xml110
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/AddChangelogEntrySWTBotTest.java380
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/AllSWTBotTests.java14
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/CreateChangeLogFromHistorySWTBotTest.java270
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/DisabledPrepareChangelogSWTBotTest.java114
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/FormatChangeLogSWTBotTest.java172
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/PrepareChangelogSWTBotTest.java390
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ChangeLogTestProject.java204
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ContextMenuHelper.java292
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ProjectExplorer.java130
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ProjectExplorerTreeItemAppearsCondition.java66
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNProject.java258
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNProjectCreatedCondition.java52
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNReporsitoriesView.java72
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/TableAppearsCondition.java46
-rw-r--r--changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/TreeItemAppearsCondition.java60
-rw-r--r--gcov/org.eclipse.linuxtools.gcov-feature/pom.xml2
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/plugin.xml2
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/Activator.java80
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/action/SwitchContentProviderAction.java42
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/dialog/Messages.java44
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/AbstractTreeElement.java138
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFileTreeElement.java16
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFolderTreeElement.java16
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFunctionTreeElement.java86
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovRootTreeElement.java16
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/TreeElement.java18
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Arc.java226
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Block.java318
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/CovManager.java10
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/CoverageInfo.java70
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Folder.java94
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/GcnoFunction.java4
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Line.java34
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Messages.java42
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/SourceFile.java184
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/preferences/Messages.java28
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/utils/BEDataInputStream.java350
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/utils/MasksGenerator.java2
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFileContentProvider.java72
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFolderContentProvider.java92
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFunctionContentProvider.java56
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovViewer.java122
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/annotatedsource/GcovAnnotationModel.java6
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/annotatedsource/STAnnotatedSourceNotFoundEditorInput.java90
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.docs/build-helper.xml82
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.docs/toc.xml18
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.launch/plugin.xml2
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchConfigurationDelegate.java226
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchConfigurationTabGroup.java14
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchMessages.java10
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchPlugin.java8
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchShortcut.java26
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.test/pom.xml4
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/AllGcovTests.java6
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTest.java898
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestC.java58
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestCLibrary.java50
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestCPP.java58
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/JobsRunning.java42
-rw-r--r--gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/ProgressMonitor.java20
-rwxr-xr-xgcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/STJunitUtils.java118
-rw-r--r--gprof/org.eclipse.linuxtools.gprof-feature/pom.xml2
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.docs/build-doc.xml86
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.docs/toc.xml20
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.launch/plugin.xml2
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.test/pom.xml2
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/AllGprofTests.java4
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofAggregatorTest.java78
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofBinaryTest.java22
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofLaunchTest.java106
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofParserTest.java66
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofShortcutTest.java110
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofTest.java320
-rw-r--r--gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/STJunitUtils.java398
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/Activator.java74
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/OpenGmonAction.java76
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/SwitchContentProviderAction.java46
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/SwitchSampleTimeAction.java62
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/CallGraphDecoder.java134
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/GmonDecoder.java100
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/HistogramDecoder.java542
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/symbolManager/Bucket.java38
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/utils/LEDataInputStream.java236
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/utils/PPC64ElfBinaryObjectWrapper.java104
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/CallGraphContentProvider.java224
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FileHistogramContentProvider.java94
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FlatHistogramContentProvider.java54
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FunctionHistogramContentProvider.java82
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/GmonView.java120
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/GmonViewer.java100
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/fields/SampleProfField.java328
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/AbstractTreeElement.java138
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistBucket.java72
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistLine.java86
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistRoot.java122
-rw-r--r--gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/TreeElement.java44
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover-feature/pom.xml4
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp-feature/pom.xml2
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/pom.xml2
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/src/org/eclipse/linuxtools/cdt/libhover/devhelp/test/AllTests.java6
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/src/org/eclipse/linuxtools/cdt/libhover/devhelp/test/CheckDevhelp.java214
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpContentProducer.java38
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpPlugin.java176
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpToc.java106
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpTocProvider.java34
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpTopic.java220
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/ParseDevHelp.java4
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/SimpleTopic.java122
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LabelFieldEditor.java48
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LibHoverMessages.java72
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LibHoverPreferencePage.java250
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/PreferenceConstants.java4
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/PreferenceInitializer.java20
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.glibc/data/glibc-2.14.xml732
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.glibc/toc.xml2
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.library.docs/build-helper.xml88
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.library.docs/toc.xml22
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.libstdcxx/src/org/eclipse/linuxtools/internal/cdt/libhover/libstdcxx/DoxygenCPPInfo.java4
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.libstdcxx/toc.xml2
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.newlib/toc.xml2
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/build.xml1
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseAutoconfTexinfo.java1208
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseAutomakeTexinfo.java1240
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseGlibcTexinfo.java1722
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseNewlibTexinfo.java1072
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/TexinfoUtils.java1432
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/ClassInfo.java132
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/FunctionInfo.java186
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/HelpBook.java42
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/LibHoverInfo.java8
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/LibhoverPlugin.java128
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/MemberInfo.java212
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/TypedefInfo.java204
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHover.java1118
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverLibrary.java412
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverLoadJob.java40
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverMessages.java72
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/LibHoverPreferencePage.java76
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/PreferenceConstants.java6
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/PreferenceInitializer.java22
-rw-r--r--libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/utils/BuildFunctionInfos.java178
-rw-r--r--lttng/org.eclipse.linuxtools.ctf.core/src/org/eclipse/linuxtools/ctf/core/event/types/SequenceDeclaration.java2
-rw-r--r--lttng/org.eclipse.linuxtools.gdbtrace.core/src/org/eclipse/linuxtools/internal/gdbtrace/core/trace/DsfGdbAdaptor.java2
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_invalid/invalid_view_multipledisplays.xml40
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_invalid/test_invalid.xml6
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_valid.xml1198
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.analysis.xml.ui.tests/test_xml_files/test_builtin.xml26
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core.tests/src/org/eclipse/linuxtools/tmf/core/tests/TmfCoreTestPlugin.java64
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core.tests/src/org/eclipse/linuxtools/tmf/core/tests/component/TmfEventProviderTest.java8
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/CreateTestFiles.java2
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/component/TmfClientStub.java4
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/trace/TmfEventParserStub.java4
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/internal/tmf/core/trace/TmfExperimentCheckpoint.java24
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/exceptions/TmfTraceException.java14
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/ITmfFilterTreeNode.java200
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterAndNode.java110
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java284
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterContainsNode.java206
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEqualsNode.java190
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEventTypeNode.java132
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterNode.java132
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterOrNode.java108
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterRootNode.java62
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterContentHandler.java268
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLWriter.java220
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/parsers/custom/CustomTxtEvent.java6
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/parsers/custom/CustomXmlEventType.java6
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfEndSynchSignal.java6
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfSignalHandler.java6
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfSignalTracer.java26
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/timestamp/TmfTimestamp.java2
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/trace/ITmfEventParser.java16
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.help/build.xml4
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui.tests/plugin.xml16
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui.tests/src/org/eclipse/linuxtools/tmf/ui/tests/views/uml2sd/loader/TmfUml2SDSyncLoaderFindTest.java4
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui.tests/src/org/eclipse/linuxtools/tmf/ui/tests/views/uml2sd/loader/TmfUml2SDSyncLoaderSignalTest.java2
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/adaption/TsfImplProvider.java50
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/EventImpl.java104
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceModelImplFactory.java290
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/plugin.xml16
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/commands/ManageCustomParsersCommandHandler.java2
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RefreshHandler.java6
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RenameExperimentHandler.java6
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RenameTraceHandler.java8
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/SelectTracesHandler.java4
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditor.java4
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfMultiPageEditorPart.java4
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSetting.java326
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsManager.java202
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterManager.java24
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisEntry.java2
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartDecorationProvider.java2
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartEvent.java26
-rwxr-xr-xlttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/core/LifelineCategories.java78
-rwxr-xr-xlttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/dialogs/FilterListDialog.java4
-rwxr-xr-xlttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/dialogs/TabContents.java4
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/loader/TmfUml2SDSyncLoader.java78
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/rawviewer/TmfRawEventViewer.java404
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/IDoubleClickListener.java14
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/TmfVirtualTable.java6
-rw-r--r--lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/TooltipProvider.java14
-rw-r--r--lttng/org.eclipse.linuxtools.tmf/pom.xml2
-rw-r--r--man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/Activator.java80
-rw-r--r--man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/parser/ManDocument.java84
-rw-r--r--man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/parser/ManParser.java74
-rw-r--r--man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/ManPathPage.java58
-rw-r--r--man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/Messages.java32
-rw-r--r--man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/PreferenceConstants.java8
-rw-r--r--man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/PreferenceInitializer.java22
-rw-r--r--man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/views/ManTextViewer.java66
-rw-r--r--man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/man/parser/ManPage.java216
-rw-r--r--man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/man/views/ManView.java70
-rw-r--r--oprofile/org.eclipse.linuxtools.oprofile.remote-feature/pom.xml2
-rw-r--r--perf/org.eclipse.linuxtools.perf.doc/build-helper.xml78
-rw-r--r--perf/org.eclipse.linuxtools.perf.doc/toc-doc.xml2
-rw-r--r--perf/org.eclipse.linuxtools.perf.doc/toc.xml52
-rw-r--r--perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AbstractSWTBotTest.java498
-rw-r--r--perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AbstractStyledTextViewTest.java50
-rw-r--r--perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AllPerfTests.java8
-rw-r--r--perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/ReportComparisonViewTest.java26
-rw-r--r--perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/SourceDisassemblyViewTest.java50
-rw-r--r--perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/StatComparisonViewTest.java38
-rw-r--r--perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/StatViewTest.java58
-rw-r--r--perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/AllPerfTests.java4
-rw-r--r--perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/DataManipulatorTest.java276
-rw-r--r--perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/FindActionTest.java148
-rw-r--r--perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchRemoteTest.java114
-rw-r--r--perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchTabsTest.java394
-rw-r--r--perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchTest.java96
-rw-r--r--perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/ModelTest.java868
-rw-r--r--perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/SaveSessionTest.java212
-rw-r--r--perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/StatsComparisonTest.java348
-rw-r--r--perf/org.eclipse.linuxtools.perf/contexts.xml20
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/AbstractDataManipulator.java304
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/BaseDataManipulator.java72
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/IPerfData.java20
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/Messages.java16
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/PerfCore.java1256
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/PerfPlugin.java460
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ReportComparisonData.java44
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/SourceDisassemblyData.java50
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/StatComparisonData.java538
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/StatData.java192
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/AbstractSaveDataHandler.java244
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/Messages.java56
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfSaveSessionHandler.java110
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfSaveStatsHandler.java68
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfStatDataOpenHandler.java84
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfStatsQuickDiffHandler.java122
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/Messages.java34
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfEventsTab.java692
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchConfigDelegate.java344
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchConfigurationTabGroup.java10
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchShortcut.java24
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfOpenData.java66
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfOptionsTab.java698
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMCommand.java32
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMDso.java82
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMEvent.java6
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMFile.java36
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMLineRef.java24
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMStatEntry.java398
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMSymbol.java82
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/TreeParent.java272
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigDelegate.java412
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigurationTabGroup.java8
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfOptionsTab.java28
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfDoubleClickAction.java80
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfProfileView.java202
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfViewContentProvider.java72
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfViewLabelProvider.java62
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/ReportComparisonView.java392
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/ReportComparisonViewCreator.java8
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/SourceDisassemblyView.java376
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatComparisonView.java394
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatComparisonViewCreator.java8
-rw-r--r--perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatView.java104
-rw-r--r--profiling/org.eclipse.linuxtools.binutils/src/org/eclipse/linuxtools/binutils/utils/STSymbolManager.java20
-rw-r--r--profiling/org.eclipse.linuxtools.binutils/src/org/eclipse/linuxtools/internal/Activator.java6
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers-feature/pom.xml2
-rwxr-xr-xprofiling/org.eclipse.linuxtools.dataviewers.charts/src/org/eclipse/linuxtools/dataviewers/charts/actions/ChartAction.java6
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers.piechart/src/org/eclipse/linuxtools/dataviewers/piechart/PieChart.java62
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers.piechart/src/org/eclipse/linuxtools/dataviewers/piechart/PieChartPaintListener.java12
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractview/AbstractSTDataView.java8
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractPercentageDrawerField.java4
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractSTDataViewersField.java4
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractSTViewer.java12
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersCSVExporter.java4
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersComparator.java4
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersSettings.java2
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STOwnerDrawLabelProvider.java12
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/TreeColumnViewerFilter.java2
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCollapseAllTreeAction.java2
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCollapseSelectionAction.java2
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCopyAction.java2
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STDataViewersSortAction.java18
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExpandAllTreeAction.java2
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExpandSelectionAction.java2
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExportToCSVAction.java14
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STHideShowColAction.java8
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersExportToCSVDialog.java18
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersHideShowColumnsDialog.java22
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersSortDialog.java16
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STColumnSizeListener.java2
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STDisposeListener.java2
-rw-r--r--profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STHeaderListener.java6
-rw-r--r--profiling/org.eclipse.linuxtools.profiling-feature/feature.xml4
-rw-r--r--profiling/org.eclipse.linuxtools.profiling-feature/pom.xml2
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.docs/build-helper.xml80
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.docs/toc.xml12
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch.ui.rdt.proxy/src/org/eclipse/linuxtools/internal/profiling/launch/ui/rdt/proxy/Messages.java18
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/plugin.xml38
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/AbstractProfilingOptionsTab.java794
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/CApplicationLaunchShortcut.java110
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/CProfilingOptionsTab.java92
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/LocalFileProxy.java64
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/LocalLauncher.java68
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/Messages.java48
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/ProfileContextualLaunchAction.java6
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/ProfileLaunchPlugin.java230
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/AbstractProviderPreferencesPage.java246
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/AbstractProviderPropertyTab.java358
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/CoveragePropertyTab.java24
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/MemoryPropertyTab.java24
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProfilingCategoriesPreferencesPage.java52
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProfilingPropertyPage.java14
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderLaunchConfigurationTabGroup.java88
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderOptionsTab.java42
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderPreferencesPage.java52
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderProfileConstants.java84
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/TimingPropertyTab.java22
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderFramework.java872
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderLaunchConfigurationDelegate.java148
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderLaunchShortcut.java532
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ConfigUtils.java186
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteCommandLauncher.java26
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteFileProxy.java20
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteProxyManager.java18
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/PlaceHolderLaunchConfigurationTabGroup.java4
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchConfigurationTabGroup.java24
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchShortcut.java520
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProxyLaunchMessages.java68
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteConnection.java356
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteConnectionException.java10
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteEnvProxyManager.java38
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteMessages.java18
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyCMainTab.java2166
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyManager.java300
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyNatureMapping.java42
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyProfileLaunchConfigurationTabGroup.java26
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/FileSystemElement.java54
-rwxr-xr-xprofiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/FileSystemSelectionArea.java348
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/IRemoteResourceSelectorProxy.java4
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/LocalResourceSelectorProxy.java64
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/ResourceSelectorWidget.java390
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/ResourceSelectorWidgetMessages.java32
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.provider.tests/fragment.xml10
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/ExtensionPointTest.java80
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/LaunchTest.java270
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/PreferencesTest.java528
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchConfigurationDelegate.java16
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchConfigurationTabGroup.java10
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchShortcut.java18
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyTimingLaunchConfigurationDelegate.java30
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/internal/profiling/tests/CProjectHelper.java562
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/internal/profiling/tests/ResourceHelper.java178
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/AbstractRemoteTest.java388
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/AbstractTest.java596
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/Messages.java24
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.ui.capability/plugin.xml250
-rw-r--r--profiling/org.eclipse.linuxtools.profiling.ui/src/org/eclipse/linuxtools/internal/profiling/ui/ProfileUIPlugin.java88
-rw-r--r--profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/LaunchCoreConstants.java6
-rw-r--r--profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/CdtSpawnerProcessFactory.java50
-rw-r--r--profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/LinuxtoolsProcessFactory.java170
-rw-r--r--profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/RuntimeProcessFactory.java664
-rw-r--r--profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/properties/LinuxtoolsPathProperty.java156
-rw-r--r--rpm/org.eclipse.linuxtools.rpm-feature/feature.xml4
-rw-r--r--rpm/org.eclipse.linuxtools.rpm-feature/pom.xml2
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core.tests/pom.xml2
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/DownloadPrepareSourcesTest.java488
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectCreatorTest.java54
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectNatureTest.java56
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectTest.java362
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/utils/tests/RPMQueryTest.java82
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core/plugin.xml10
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/FlatBuildConfiguration.java136
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/Messages.java22
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/RPMCoreInitializer.java22
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/utils/FileDownloadJob.java72
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/utils/Messages.java22
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/RPMProject.java360
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/RPMProjectNature.java100
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/utils/Messages.java22
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/utils/Utils.java2
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/AllTests.java12
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoImportRPMsPageTest.java320
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoMetadataPageTest.java430
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoProjectCreatorTest.java130
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoProjectTest.java348
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoRepoFormEditorTest.java90
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoUtilsTest.java118
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/ICreaterepoTestConstants.java156
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/TestCreaterepoProject.java242
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/TestUtils.java202
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/listener/tests/CreaterepoResourceListenerTest.java142
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoDeltaPropertyPageTest.java304
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoGeneralPropertyPageTest.java458
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoPreferenceInitializationTest.java98
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoPreferencePageTest.java362
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tests/CreaterepoCommandCreatorTest.java444
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tests/CreaterepoTest.java140
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/tests/CreaterepoTreeCategoryTest.java46
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/tests/CreaterepoTreeTest.java366
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/tests/CreaterepoWizardTest.java168
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/plugin.xml14
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Activator.java148
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Createrepo.java6
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoCommandCreator.java356
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProject.java416
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProjectCreator.java58
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProjectNature.java70
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/ICreaterepoConstants.java2
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/IRepoFileConstants.java32
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Messages.java400
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/dnd/ImportRPMDropListener.java120
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/ImportRPMsPage.java742
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/MetadataPage.java708
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/RepoFormEditor.java204
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/handler/CreaterepoCommandHandler.java80
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/listener/CreaterepoResourceChangeListener.java106
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoDeltaPropertyPage.java290
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoGeneralPropertyPage.java712
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPathEditor.java76
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPreferenceInitializer.java78
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPreferencePage.java348
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPropertyPage.java146
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoCategoryModel.java146
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeCategory.java98
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeContentProvider.java116
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeLabelProvider.java50
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoNewWizardPageOne.java30
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoNewWizardPageTwo.java336
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoWizard.java234
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.rpmlint/plugin.xml14
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/parser/RpmlintItem.java316
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/preferences/PreferenceConstants.java26
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/MacroInChangelog.java42
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/RpmBuildrootUsage.java24
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/RpmlintMarkerResolutionGenerator.java130
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/build-helper.xml82
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/plugin.xml2
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/toc-doc.xml2
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/toc.xml86
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/pom.xml2
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/ActionsAllTests.java4
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/SpecfileChangelogFormatterTest.java68
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/SpecfileChangelogParserTest.java28
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/HyperlinkAllTests.java10
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/MailHyperlinkDetectorTest.java68
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SourcesFileCreateHyperlinkTest.java26
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SourcesFileHyperlinkDetectorTest.java164
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SpecfileElementHyperlinkDetectorTest.java98
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/URLHyperlinkWithMacroDetectorTest.java34
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/ScannersAllTests.java4
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfileChangelogScannerTest.java114
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfilePackagesScannerTest.java184
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfileScannerTest.java206
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/AScannerTest.java66
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/AllTests.java12
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/EpochTagTest.java168
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/FileTestCase.java126
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/HeaderRecognitionTest.java198
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LabelProviderTest.java72
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LicenseTagTest.java12
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LinePositionTest.java60
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/NameTagTest.java128
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/PatchApplicationTest.java58
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/ReleaseTagTest.java116
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/RpmMacroProposalsListTest.java146
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/RpmPackageProposalsListTest.java100
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileCompletionProcessorTest.java306
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileTestFailure.java30
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileTestProject.java74
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/VersionTagTest.java140
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/ParserAllTests.java4
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SourceComparatorTest.java60
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SpecfileDefineTest.java254
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SpecfileTest.java110
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/plugin.xml94
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/Activator.java322
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ColorManager.java28
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ISpecfileColorConstants.java30
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ISpecfileSpecialSymbols.java40
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/Messages.java48
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/NonRuleBasedDamagerRepairer.java254
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RPMHandlerUtils.java136
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmMacroOccurrencesUpdater.java416
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmMacroProposalsList.java380
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmPackageBuildProposalsJob.java420
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmPackageProposalsList.java290
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmSections.java32
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmTags.java58
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileCompletionProcessor.java1132
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileConfiguration.java476
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileDocumentProvider.java212
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileDoubleClickStrategy.java226
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileFoldingStructureProvider.java204
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileHover.java480
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileLog.java24
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileReconcilingStrategy.java110
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/UiUtils.java108
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/Messages.java46
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileChangelogFormatter.java36
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileChangelogParser.java16
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorDownloadSourcesActionDelegate.java92
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorOrganizePatchesActionDelegate.java26
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorPrepareSourcesActionDelegate.java244
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorShowOutlineActionDelegate.java20
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorToggleCommentActionDelegate.java138
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/Messages.java22
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecMergeViewer.java92
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecMergeViewerCreator.java16
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecStructureCreator.java440
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecStructureMergeViewerCreator.java20
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/IStrictWordDetector.java2
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/KeywordWordDetector.java16
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/MacroWordDetector.java16
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/PackageWordDetector.java16
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/PatchNumberDetector.java24
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/SuffixNumberDetector.java26
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/TagWordDetector.java16
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/MainPackagePage.java278
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/Messages.java36
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/RpmSectionPage.java54
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/RpmTagText.java110
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/SpecfileFormEditor.java88
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/MailHyperlink.java38
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/MailHyperlinkDetector.java396
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/Messages.java36
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileCreateHyperlink.java162
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileDownloadHyperlink.java176
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileHyperlink.java124
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileHyperlinkDetector.java148
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SpecfileElementHyperlink.java96
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SpecfileElementHyperlinkDetector.java264
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/URLHyperlinkWithMacroDetector.java60
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/ContainsFilter.java66
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/Messages.java22
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileContentOutlinePage.java160
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileContentProvider.java154
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileLabelProvider.java120
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileQuickOutlineDialog.java266
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/Messages.java26
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SourceComparator.java36
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileParseException.java92
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfilePatchMacro.java30
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileSource.java260
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileTag.java154
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/MacroProposalsPreferencePage.java760
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/MainPreferencePage.java208
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/Messages.java90
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/PreferenceConstants.java170
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/PreferenceInitializer.java126
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/RpmInformationsPreferencePage.java86
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/RpmProposalsPreferencePage.java242
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/SpecTemplatePreferencePage.java68
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/TaskTagsPreferencePage.java86
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/AuthorEmailRule.java232
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/CommentRule.java20
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/MacroRule.java24
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/SectionRule.java238
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/StringWithEndingRule.java160
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/VersionReleaseRule.java298
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfileChangelogScanner.java60
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfilePackagesScanner.java74
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfilePartitionScanner.java128
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfileScanner.java168
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/wizards/NoExecutableWizardPage.java56
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/wizards/SpecfileNewWizard.java242
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/SpecfileEditor.java404
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileErrorHandler.java280
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileMarkerHandler.java78
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileTaskHandler.java124
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/Specfile.java528
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileDefine.java38
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileElement.java178
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfilePackage.java210
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfilePackageContainer.java168
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileParser.java1210
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileSection.java98
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/utils/RPMUtils.java164
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/wizards/Messages.java76
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/wizards/SpecfileNewWizardPage.java846
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui.editor/templates/templates.xml8
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/plugin.xml8
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/Activator.java82
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/BuildType.java32
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/ErrorLineMatcher.java64
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/Messages.java32
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/NewProjectCreationPage.java322
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RPMDetailsPanel.java214
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RPMNewProject.java80
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RpmConsole.java96
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/SRPMImportPage.java388
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/SRPMImportWizard.java74
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/handlers/SpecfileEditorRPMBuildHandler.java150
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/AbstractRPMPropertyPage.java40
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/ChangelogPage.java36
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/InstallScriptsPage.java80
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/Messages.java24
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/ProvidesPage.java44
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/SpecFileHeaderPage.java36
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/TargetPage.java76
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/rpm/ui/RPMExportOperation.java116
-rw-r--r--rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/rpm/ui/SRPMImportOperation.java160
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph-feature/pom.xml2
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/plugin.xml6
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/CallgraphCorePlugin.java144
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/DocWriter.java88
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/FileFinderOpener.java100
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/Helper.java106
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/LaunchConfigurationConstants.java148
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/Messages.java26
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/PluginConstants.java94
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/StapUIJob.java74
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapCommandGenerator.java156
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapErrorHandler.java64
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapParser.java610
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapTextParser.java72
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapTextView.java410
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapUIErrorMessages.java48
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapView.java72
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/ViewFactory.java124
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/XMLParser.java328
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.docs/build-doc.xml84
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.docs/toc-doc.xml4
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.docs/toc.xml36
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/pom.xml2
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.jdt.ui/dialog_settings.xml14
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ltk.ui.refactoring/dialog_settings.xml8
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ui.ide/dialog_settings.xml8
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ui.workbench/dialog_settings.xml4
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/AbstractStapTest.java62
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/AllTests.java4
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/ConfigurationTest.java164
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/LaunchShortcutsTest.java68
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapCommandGeneratorTest.java76
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapCommandTest.java46
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapErrorHandlerTest.java94
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapTabTest.java38
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/plugin.xml14
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/ConfigurationOptionsSetter.java254
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/LaunchStapGraph.java344
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/LaunchWizard.java474
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/ListTreeContentProvider.java252
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/Messages.java26
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/RuledTreeSelectionDialog.java88
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchConfigurationDelegate.java764
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchConfigurationTabGroup.java24
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchShortcut.java1456
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapOptionsTab.java1786
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/TranslationUnitVisitor.java32
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.tests/pom.xml2
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/Activator.java28
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/MouseListenerTest.java38
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/StapGraphParserTest.java208
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/SystemTapGraphTest.java164
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/SystemTapGraphViewTest.java22
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/plugin.xml4
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/AggregateLayoutAlgorithm.java92
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/CallGraphConstants.java4
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/CallgraphView.java1894
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/Messages.java26
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapData.java246
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapGraphParser.java1038
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapNode.java142
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/AutoScrollHelper.java78
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/AutoScrollSelectionListener.java34
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/Messages.java20
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/Projectionist.java120
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphFocusListener.java22
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphKeyListener.java58
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseExitListener.java20
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseListener.java446
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseMoveListener.java110
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseWheelListener.java98
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeContentProvider.java88
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeDoubleClickListener.java54
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeLabelProvider.java36
-rw-r--r--systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeListener.java80
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap-feature/pom.xml2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/pom.xml2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/AllTests.java42
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/MockDataSet.java106
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/AverageAggregateTest.java74
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/CountAggregateTest.java74
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/MaxAggregateTest.java72
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/MinAggregateTest.java74
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/SumAggregateTest.java76
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/FilteredRowDataSetTest.java516
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowDataSetTest.java284
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowEntryTest.java200
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowParserTest.java42
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/FilteredTableDataSetTest.java500
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableDataSetTest.java296
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableEntryTest.java216
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableParserTest.java42
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/MatchFilterTest.java70
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/RangeFilterTest.java354
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/SortFilterTest.java122
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/UniqueFilterTest.java90
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/ChartStreamDaemonTest.java48
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/NumberTypeTest.java84
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/UpdateManagerTest.java76
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/internal/systemtap/graphing/core/GraphingCorePlugin.java8
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/internal/systemtap/graphing/core/Localization.java24
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/IGraphColorConstants.java528
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/BlockAdapter.java156
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/IAdapter.java14
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/ScrollAdapter.java166
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/AverageAggregate.java58
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/CountAggregate.java56
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/IDataAggregate.java4
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/MaxAggregate.java60
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/MinAggregate.java60
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/SumAggregate.java56
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IBlockDataSet.java2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataEntry.java20
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataSet.java24
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataSetParser.java2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IFilteredDataSet.java8
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IHistoricalDataSet.java12
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/FilteredRowDataSet.java290
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/LineParser.java60
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowDataSet.java354
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowEntry.java150
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowParser.java80
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/FilteredTableDataSet.java310
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableDataSet.java406
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableEntry.java198
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableParser.java122
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/IDataSetFilter.java20
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/MatchFilter.java106
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/RangeFilter.java250
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/SortFilter.java140
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/UniqueFilter.java190
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/ChartStreamDaemon.java76
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/GraphData.java104
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/NumberType.java168
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/plugin.xml110
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/GraphingUIPlugin.java74
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/Localization.java22
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AbstractChartWithAxisBuilder.java458
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AbstractChartWithoutAxisBuilder.java4
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AreaChartBuilder.java16
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/BarChart.java310
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/BarChartBuilder.java242
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/LineChartBuilder.java22
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/Messages.java22
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/PieChartBuilder.java170
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/ScatterChartBuilder.java18
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/BarChartMouseMoveListener.java50
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ChartMouseMoveListener.java92
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ChartWithAxisMouseMoveListener.java64
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/PieChartMouseMoveListener.java48
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ToolTipChartMouseMoveListener.java52
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/handlers/SaveGraphImageHandler.java66
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/DataTablePreferencePage.java54
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphPreferencePage.java66
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphingPreferenceConstants.java24
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphingPreferencePage.java38
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/PreferenceInitializer.java38
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/views/Messages.java18
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/AggregateFactory.java116
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/MatchFilterWizardPage.java4
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/RangeFilterWizardPage.java6
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/SortFilterWizardPage.java2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/UniqueFilterWizardPage.java2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/GraphDisplaySet.java460
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/charts/AbstractChartBuilder.java696
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/datadisplay/DataGrid.java652
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/views/GraphSelectorEditor.java396
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/views/GraphSelectorEditorInput.java68
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/ExceptionErrorDialog.java16
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphComposite.java186
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphContinuousXControl.java220
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphContinuousYControl.java220
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphDiscreteXControl.java270
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/Messages.java48
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/dataset/DataSetFactory.java50
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/GraphFactory.java306
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/SelectGraphAndSeriesWizard.java102
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/SelectGraphAndSeriesWizardPage.java810
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/pom.xml2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/AllTests.java8
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/CCodeFileFilterTest.java42
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/CopierTest.java46
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/IndexedObjectTest.java46
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/KernelSourceTreeTest.java76
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/LoggingStreamDaemonTest.java68
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/SortTest.java92
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/StringFormatterTest.java94
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/TreeDefinitionNodeTest.java94
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/TreeNodeTest.java434
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/runnable/CommandTest.java180
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/runnable/StreamGobblerTest.java86
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/internal/systemtap/structures/Localization.java24
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/internal/systemtap/structures/StructuresPlugin.java2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/CCodeFileFilter.java68
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/Copier.java64
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/IFormattingStyles.java22
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/IndexedObject.java38
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/KernelSourceTree.java192
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/LoggingStreamDaemon.java202
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/Sort.java100
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/StringFormatter.java84
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/TreeDefinitionNode.java32
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/TreeNode.java254
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/UpdateManager.java140
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/IGobblerListener.java10
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/ITabListener.java6
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/IUpdateListener.java2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/process/SystemTapRuntimeProcessFactory.java64
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/process/SystemtapProcessFactory.java130
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/Command.java606
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/Messages.java16
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/StreamGobbler.java254
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/StringStreamGobbler.java24
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/pom.xml2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/AllTests.java2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ConsoleStreamDaemonTest.java70
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ErrorStreamDaemonTest.java72
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ScriptConsoleTest.java26
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/plugin.xml40
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/CloseStapConsoleAction.java46
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/ConsoleAction.java20
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/SaveLogAction.java72
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/StopScriptAction.java64
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/preferences/Messages.java28
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/structures/Messages.java18
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/Messages.java22
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScpClient.java178
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScpExec.java146
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScriptConsolePageParticipant.java132
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/dialogs/Messages.java28
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/dialogs/SelectServerDialog.java230
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/internal/ConsoleLogPlugin.java60
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/internal/Localization.java24
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/ConsoleLogPreferenceConstants.java18
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/ConsoleLogPreferencePage.java44
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/PreferenceInitializer.java32
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ConsoleStreamDaemon.java98
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ErrorStreamDaemon.java102
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ErrorTableDisplay.java276
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/IErrorParser.java2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/RemoteScriptOptions.java80
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ScriptConsole.java990
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/views/ErrorView.java114
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.doc/build-helper.xml84
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.doc/toc-doc.xml2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.doc/toc.xml168
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.editor/plugin.xml74
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/internal/systemtap/ui/editor/EditorPlugin.java2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/internal/systemtap/ui/editor/Localization.java24
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/ColorManager.java28
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/DoubleClickStrategy.java254
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/PathEditorInput.java100
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/SimpleDocumentProvider.java312
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/SimpleEditor.java348
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/actions/file/NewFileAction.java16
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/actions/file/OpenFileAction.java242
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/pom.xml2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/AllTests.java6
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/ConditionalExpressionValidatorTest.java32
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/DirectoryValidatorTest.java28
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/AbstractAutoEditTest.java410
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPCompletionProcessorTest.java448
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPFormattingTest.java758
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPIndenterTest.java548
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPToggleCommentTest.java334
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/structures/StapErrorParserTest.java70
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/structures/TreeSettingsTest.java200
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/swtbot/TestCreateSystemtapScript.java2768
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/CommentRemover.java168
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDECloseMonitor.java28
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDEPerspective.java54
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDEPlugin.java154
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDESessionSettings.java288
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/Localization.java24
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/StringOutputStream.java18
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/BrowserViewAction.java92
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ExportDataSetHandler.java54
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/FunctionBrowserAction.java62
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ImportDataSetHandler.java86
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ImportTapsetHandler.java20
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/IndentHandler.java898
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/KernelSourceAction.java100
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/Messages.java36
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ProbeAliasAction.java110
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/RunScriptChartHandler.java68
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/RunScriptHandler.java940
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ToggleCommentHandler.java538
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/TreeExpandCollapseAction.java110
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/CodeFormatterUtil.java12
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/DocumentCharacterIterator.java422
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/IndentUtil.java594
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/Messages.java22
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPAutoEditStrategy.java2084
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPColorConstants.java14
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPCompletionProcessor.java912
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPConfiguration.java222
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPDefaultCodeFormatterConstants.java792
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPDocumentProvider.java48
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPEditor.java172
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPElementScanner.java156
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPHeuristicScanner.java2070
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPIndenter.java4588
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPMetadataSingleton.java202
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPPartitionScanner.java130
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPPartitioner.java24
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPProbeScanner.java48
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPReconcilingStrategy.java320
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPSymbols.java118
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/AddStapProbeHandler.java192
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/DefinitionHandler.java94
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/DefinitionMenuTester.java14
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/Messages.java22
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/Messages.java188
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptGraphOptionsTab.java3134
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunch.java160
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationDelegate.java264
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationTab.java586
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationTabGroup.java24
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchShortcut.java222
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptOptionsTab.java478
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/CodeAssistPreferencePage.java82
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ConditionalExpressionValidator.java52
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ConditionalFilterPreferencePage.java28
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/DirectoryValidator.java46
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/EditorPreferencePage.java40
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/EnvironmentVariablesPreferencePage.java256
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/IDEPreferenceConstants.java108
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/IDEPreferencePage.java40
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ListEditor.java38
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/LocalRemoteDirectoryEditor.java74
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/Messages.java36
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PathPreferencePage.java88
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PreferenceConstants.java14
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PreferenceInitializer.java174
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/SyntaxColoringPreferencePage.java192
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/SystemTapPreferencePage.java36
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/TapsetsPreferencePage.java40
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FuncparamNodeData.java40
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FunctionNodeData.java80
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FunctionParser.java298
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ISearchableNode.java4
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ISingleTypedNode.java2
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/Messages.java26
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbeNodeData.java60
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbeParser.java516
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbevarNodeData.java78
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/SharedParser.java92
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/StapErrorParser.java106
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TapsetLibrary.java736
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TapsetParser.java292
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TreeSettings.java480
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/BrowserView.java262
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/FunctionBrowserView.java174
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/KernelBrowserView.java376
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/ProbeAliasBrowserView.java136
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/wizards/StapNewWizard.java176
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/wizards/StapNewWizardPage.java316
-rw-r--r--systemtap/org.eclipse.linuxtools.systemtap.ui.tests/src/org/eclipse/linuxtools/systemtap/ui/tests/SystemtapTest.java32
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind-feature/pom.xml2
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/AbstractCachegrindTest.java44
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/AllTests.java4
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/BasicCachegrindTest.java82
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/CModelLabelsTest.java218
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/DoubleClickTest.java200
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ExpandCollapseTest.java110
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/LaunchConfigTabTest.java312
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/MultiProcessTest.java202
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ShortcutTest.java126
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ValgrindTestCachegrindLaunchShortcut.java18
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/plugin.xml2
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindCommandConstants.java14
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLabelProvider.java138
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchConfigurationTabGroup.java18
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchConstants.java60
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchDelegate.java196
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchShortcut.java34
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindParser.java180
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindPlugin.java6
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindToolPage.java700
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindViewPart.java594
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/Messages.java24
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindDescription.java38
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindFile.java138
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindFunction.java232
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindLine.java84
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindOutput.java142
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/ICachegrindElement.java10
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/Messages.java24
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/AbstractValgrindMessage.java80
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/Messages.java26
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/PluginConstants.java4
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindCommand.java152
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindCoreParser.java160
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindError.java22
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindInfo.java6
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindStackFrame.java36
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/CommandLineConstants.java42
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/IValgrindMessage.java12
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/ValgrindParserUtils.java240
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.doc/build-helper.xml84
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.doc/toc-doc.xml2
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.doc/toc.xml76
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/AbstractHelgrindTest.java8
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/BasicHelgrindTest.java36
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/LaunchConfigTabTest.java244
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/ShortcutTest.java92
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/ValgrindTestHelgrindLaunchShortcut.java18
-rwxr-xr-xvalgrind/org.eclipse.linuxtools.valgrind.helgrind/plugin.xml2
-rwxr-xr-xvalgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindCommandConstants.java8
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchConfigurationTabGroup.java18
-rwxr-xr-xvalgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchDelegate.java42
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchShortcut.java34
-rwxr-xr-xvalgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindPlugin.java6
-rwxr-xr-xvalgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindToolPage.java232
-rwxr-xr-xvalgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindViewPart.java34
-rwxr-xr-xvalgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/Messages.java24
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ClearMarkersHandler.java34
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ExportHandler.java28
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ExportWizardConstants.java8
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/LaunchConfigurationConstants.java82
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/Messages.java26
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ProjectBuildListener.java150
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindExportWizard.java108
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindExportWizardPage.java366
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchConfigurationDelegate.java646
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchConfigurationTabGroup.java18
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchPlugin.java464
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchShortcut.java32
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindOptionsTab.java1304
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindOutputDirectoryProvider.java22
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindRemoteProxyLaunchConfigurationTabGroup.java14
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindRemoteProxyLaunchDelegate.java536
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindSingleToolOptionsTab.java18
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindLaunchDelegate.java66
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindOutputDirectoryProvider.java10
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindToolPage.java16
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/AbstractMassifTest.java100
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/AllTests.java6
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/BasicMassifTest.java44
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ChartExportTest.java100
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ChartTests.java258
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/DoubleClickTest.java98
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ExpandCollapseTest.java110
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ExportWizardTest.java330
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/LaunchConfigTabTest.java610
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/MultiProcessTest.java270
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ShortcutTest.java126
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/SortTest.java156
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/TreeTest.java94
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ValgrindTestMassifLaunchShortcut.java18
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/plugin.xml2
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifCommandConstants.java34
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifHeapTreeNode.java248
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchConfigurationTabGroup.java18
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchConstants.java78
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchDelegate.java234
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchShortcut.java34
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifOutput.java36
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifParser.java452
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifPidMenuAction.java116
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifPlugin.java152
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifSnapshot.java188
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifToolPage.java964
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifTreeLabelProvider.java32
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifTreeViewer.java172
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifViewPart.java842
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/Messages.java26
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartEditor.java384
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartEditorInput.java88
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartLocationsDialog.java110
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/HeapChart.java314
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/Messages.java26
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/pom.xml2
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AbstractLinkedResourceMemcheckTest.java64
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AbstractMemcheckTest.java94
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AllTests.java8
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/BasicMemcheckTest.java38
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/DoubleClickTest.java222
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/ExpandCollapseTest.java116
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LaunchConfigTabTest.java914
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LinkedResourceDoubleClickTest.java116
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LinkedResourceMarkerTest.java92
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MarkerTest.java112
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MinVersionTest.java140
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MultiProcessTest.java62
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/ShortcutTest.java92
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/SignalTest.java38
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck/plugin.xml4
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckCommandConstants.java36
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchConfigurationTabGroup.java18
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchConstants.java92
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchDelegate.java106
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckPlugin.java20
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckToolPage.java864
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckViewPart.java30
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/Messages.java26
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/AbstractValgrindTest.java326
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubCommand.java24
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubProcess.java126
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubStreamsProxy.java22
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestLaunchDelegate.java70
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestLaunchShortcut.java18
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestsPlugin.java84
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ColorManager.java30
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ISuppressionsColorConstants.java12
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/Messages.java24
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionKindRule.java256
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionToolRule.java188
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsConfiguration.java112
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsContentAssistProcessor.java238
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsDocumentProvider.java28
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsEditor.java104
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsElementScanner.java88
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsPartitionScanner.java32
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsReconcilingStrategy.java112
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ValgrindEditorPlugin.java4
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/wizards/Messages.java24
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/wizards/NewSuppressionWizard.java232
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.tests/pom.xml2
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui.tests/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/tests/WrongDeallocationResolutionTest.java282
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui/plugin.xml6
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/CoreMessagesViewer.java352
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/Messages.java24
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/ValgrindUIPlugin.java328
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/ValgrindViewPart.java352
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/AbstractValgrindMarkerResolution.java90
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/ValgrindResolutionGenerator.java28
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/WrongDeallocationResolution.java430
-rw-r--r--valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/valgrind/ui/IValgrindToolView.java18
1206 files changed, 98204 insertions, 98307 deletions
diff --git a/changelog/org.eclipse.linuxtools.changelog.c-feature/pom.xml b/changelog/org.eclipse.linuxtools.changelog.c-feature/pom.xml
index e0863480de..542931d78b 100644
--- a/changelog/org.eclipse.linuxtools.changelog.c-feature/pom.xml
+++ b/changelog/org.eclipse.linuxtools.changelog.c-feature/pom.xml
@@ -22,7 +22,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools ChangeLog Feature for C/C++</name>
-
+
<build>
<plugins>
<plugin>
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/plugin.xml b/changelog/org.eclipse.linuxtools.changelog.core/plugin.xml
index 05cda5bf9a..ec5db8ff89 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/plugin.xml
+++ b/changelog/org.eclipse.linuxtools.changelog.core/plugin.xml
@@ -5,34 +5,34 @@
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-
+
Contributors:
Alexander Kurtakov (Red Hat) - initial API and implementation
-->
<plugin>
- <extension-point id="parserContribution"
- name="%extension-point.name"
- schema="schema/parserContribution.exsd"/>
+ <extension-point id="parserContribution"
+ name="%extension-point.name"
+ schema="schema/parserContribution.exsd"/>
<extension-point id="formatterContribution" name="%extension-point.name.0" schema="schema/formatterContribution.exsd"/>
<extension-point id="editorContribution" name="%extension-point.name.1" schema="schema/editorContribution.exsd"/>
-
+
<extension
- point="org.eclipse.ui.commands">
-
- <category
- name="%category.name"
- description="%category.description"
- id="org.eclipse.linuxtools.changelog">
- </category>
+ point="org.eclipse.ui.commands">
- <command
+ <category
+ name="%category.name"
+ description="%category.description"
+ id="org.eclipse.linuxtools.changelog">
+ </category>
+
+ <command
categoryId="org.eclipse.linuxtools.changelog"
description="%insertCLEntryDesc"
id="org.eclipse.linuxtools.changelog.core.actions.KeyActionCommand"
name="%insertCLEntry">
- </command>
+ </command>
<command
categoryId="org.eclipse.linuxtools.changelog"
description="%command.description"
@@ -54,16 +54,16 @@
id="org.eclipse.linuxtools.changelog.core.preparechangelog2"
name="%command.name.2">
</command>
- </extension>
-
- <extension point = "org.eclipse.ui.preferencePages">
- <page
- id="org.eclipse.linuxtools.changelog.core.Page1"
- class="org.eclipse.linuxtools.internal.changelog.core.ChangeLogPreferencesPage"
- name="%prefTitle">
- </page>
- </extension>
-
+ </extension>
+
+ <extension point = "org.eclipse.ui.preferencePages">
+ <page
+ id="org.eclipse.linuxtools.changelog.core.Page1"
+ class="org.eclipse.linuxtools.internal.changelog.core.ChangeLogPreferencesPage"
+ name="%prefTitle">
+ </page>
+ </extension>
+
<extension
point="org.eclipse.linuxtools.changelog.core.formatterContribution">
@@ -72,8 +72,8 @@
class="org.eclipse.linuxtools.internal.changelog.core.formatters.GNUFormat"
id="org.eclipse.linuxtools.changelog.GNUFormat"
name="%gnuFormatter">
- <fileName name="ChangeLog" />
- </formatter>
+ <fileName name="ChangeLog" />
+ </formatter>
</extension>
<extension
id="org.eclipse.linuxtools.changelog.core.editor"
@@ -191,20 +191,20 @@
</participant>
</extension>
<extension point="org.eclipse.core.runtime.preferences">
- <initializer
- class="org.eclipse.linuxtools.internal.changelog.core.ChangelogPreferenceInitializer" />
- </extension>
-
- <extension
- point="org.eclipse.ui.workbench.texteditor.hyperlinkDetectorTargets">
-<target id="org.eclipse.changelog.editor.target"
- name="%target.name">
+ <initializer
+ class="org.eclipse.linuxtools.internal.changelog.core.ChangelogPreferenceInitializer" />
+ </extension>
+
+ <extension
+ point="org.eclipse.ui.workbench.texteditor.hyperlinkDetectorTargets">
+<target id="org.eclipse.changelog.editor.target"
+ name="%target.name">
<context type="org.eclipse.ui.texteditor.ITextEditor"/>
</target>
</extension>
-
- <extension
+
+ <extension
point="org.eclipse.ui.workbench.texteditor.hyperlinkDetectors">
<hyperlinkDetector
id="org.eclipse.linuxtools.changelog.GNUHyperlinkDetector"
@@ -216,14 +216,14 @@
<extension point="org.eclipse.ui.menus">
<menuContribution locationURI="popup:#TextEditorContext?endof=group.edit">
<command commandId="org.eclipse.linuxtools.changelog.core.formatChangeLog">
- <visibleWhen
+ <visibleWhen
checkEnabled="false">
<and>
- <with variable="activeEditorId">
- <equals value="org.eclipse.linuxtools.changelog.core.editor6"/>
- </with>
- </and>
- </visibleWhen>
+ <with variable="activeEditorId">
+ <equals value="org.eclipse.linuxtools.changelog.core.editor6"/>
+ </with>
+ </and>
+ </visibleWhen>
</command>
</menuContribution>
<menuContribution
@@ -244,50 +244,50 @@
checkEnabled="false">
<with variable="selection">
<iterate operator="and" ifEmpty="false">
- <or>
+ <or>
<adapt
type="java.lang.Object">
</adapt>
- <adapt type="org.eclipse.core.resources.IResource">
- <test
- property="org.eclipse.core.resources.projectNature"
- value="org.eclipse.cdt.core.cnature"/>
+ <adapt type="org.eclipse.core.resources.IResource">
+ <test
+ property="org.eclipse.core.resources.projectNature"
+ value="org.eclipse.cdt.core.cnature"/>
</adapt>
<adapt type="org.eclipse.core.resources.IResource">
<test
property="org.eclipse.core.resources.projectNature"
value="org.eclipse.jdt.core.javanature"/>
</adapt>
- </or>
- <or>
- <adapt type="org.eclipse.core.resources.IResource">
- <test
+ </or>
+ <or>
+ <adapt type="org.eclipse.core.resources.IResource">
+ <test
args="org.eclipse.team.core.repository"
property="org.eclipse.core.resources.projectPersistentProperty"
value="org.eclipse.team.svn.core.svnnature"/>
</adapt>
- <adapt type="org.eclipse.core.resources.IResource">
- <test
- args="org.eclipse.team.core.repository"
+ <adapt type="org.eclipse.core.resources.IResource">
+ <test
+ args="org.eclipse.team.core.repository"
property="org.eclipse.core.resources.projectPersistentProperty"
value="org.eclipse.team.cvs.core.cvsnature"/>
</adapt>
- <adapt type="org.eclipse.core.resources.IResource">
- <test
+ <adapt type="org.eclipse.core.resources.IResource">
+ <test
args="org.eclipse.team.core.repository"
property="org.eclipse.core.resources.projectPersistentProperty"
value="org.tigris.subversion.subclipse.core.svnnature"/>
</adapt>
- <adapt type="org.eclipse.core.resources.IResource">
- <test
+ <adapt type="org.eclipse.core.resources.IResource">
+ <test
args="org.eclipse.team.core.repository"
property="org.eclipse.core.resources.projectPersistentProperty"
value="org.eclipse.egit.core.GitProvider"/>
</adapt>
- </or>
- </iterate>
- </with>
- </visibleWhen>
+ </or>
+ </iterate>
+ </with>
+ </visibleWhen>
</command>
</menuContribution>
</extension>
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IEditorChangeLogContrib.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IEditorChangeLogContrib.java
index 3240271e43..0b9a4c0045 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IEditorChangeLogContrib.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IEditorChangeLogContrib.java
@@ -21,39 +21,39 @@ import org.eclipse.ui.editors.text.TextEditor;
*/
public interface IEditorChangeLogContrib {
- /**
- * Set TextEditor that this configuration is going to be used.
- *
- * @param editor The text editor for this configuration.
- */
- void setTextEditor(TextEditor editor);
+ /**
+ * Set TextEditor that this configuration is going to be used.
+ *
+ * @param editor The text editor for this configuration.
+ */
+ void setTextEditor(TextEditor editor);
- /**
- * Set default content type. GNU Changelog only has one type.
- *
- * @return default content type.
- */
- String[] getConfiguredContentTypes(ISourceViewer sourceViewer);
+ /**
+ * Set default content type. GNU Changelog only has one type.
+ *
+ * @return default content type.
+ */
+ String[] getConfiguredContentTypes(ISourceViewer sourceViewer);
- /**
- * Detects hyperlinks in GNU formatted changelogs.
- *
- * @return link detector for GNU format.
- */
- IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer);
+ /**
+ * Detects hyperlinks in GNU formatted changelogs.
+ *
+ * @return link detector for GNU format.
+ */
+ IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer);
- /**
- * Hyperlink presenter (decorator).
- *
- * @return default presenter.
- */
- IHyperlinkPresenter getHyperlinkPresenter(ISourceViewer sourceViewer);
+ /**
+ * Hyperlink presenter (decorator).
+ *
+ * @return default presenter.
+ */
+ IHyperlinkPresenter getHyperlinkPresenter(ISourceViewer sourceViewer);
- /**
- * Highlights GNU format changelog syntaxes.
- *
- * @return reconciler for GNU format changelog.
- */
- IPresentationReconciler getPresentationReconciler(
- ISourceViewer sourceViewer);
+ /**
+ * Highlights GNU format changelog syntaxes.
+ *
+ * @return reconciler for GNU format changelog.
+ */
+ IPresentationReconciler getPresentationReconciler(
+ ISourceViewer sourceViewer);
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IEditorChangeLogContrib2.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IEditorChangeLogContrib2.java
index d1619c7901..257e4b07ce 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IEditorChangeLogContrib2.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IEditorChangeLogContrib2.java
@@ -14,10 +14,10 @@ import org.eclipse.jface.text.IDocument;
public interface IEditorChangeLogContrib2 {
- /**
- * Perform documentation setup. Use this to specify partitioning.
- *
- * @param document to set up.
- */
- void setup(IDocument document);
+ /**
+ * Perform documentation setup. Use this to specify partitioning.
+ *
+ * @param document to set up.
+ */
+ void setup(IDocument document);
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IFormatterChangeLogContrib.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IFormatterChangeLogContrib.java
index 92141aa524..eafb0729d5 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IFormatterChangeLogContrib.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IFormatterChangeLogContrib.java
@@ -17,7 +17,7 @@ import org.eclipse.ui.IEditorPart;
*/
public interface IFormatterChangeLogContrib {
- String formatDateLine(String authorName, String authorEmail);
- String mergeChangelog(String dateLine, String functionGuess,String defaultContent,
- IEditorPart changelog, String changeLogLocation, String fileLocation);
+ String formatDateLine(String authorName, String authorEmail);
+ String mergeChangelog(String dateLine, String functionGuess,String defaultContent,
+ IEditorPart changelog, String changeLogLocation, String fileLocation);
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IParserChangeLogContrib.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IParserChangeLogContrib.java
index 6ae9a1f1b6..2150714d1b 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IParserChangeLogContrib.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/changelog/core/IParserChangeLogContrib.java
@@ -19,26 +19,26 @@ import org.eclipse.ui.IEditorPart;
*/
public interface IParserChangeLogContrib {
- /**
- * Used to determine function name from a currently open editor, where the
- * cursor is at. Used by KeyAction.
- *
- * @param editor The editor to check for the function.
- * @return The name of the function.
- * @throws CoreException If unexpected error happens in the underlying Eclipse APIs.
- */
- String parseCurrentFunction(IEditorPart editor) throws CoreException;
+ /**
+ * Used to determine function name from a currently open editor, where the
+ * cursor is at. Used by KeyAction.
+ *
+ * @param editor The editor to check for the function.
+ * @return The name of the function.
+ * @throws CoreException If unexpected error happens in the underlying Eclipse APIs.
+ */
+ String parseCurrentFunction(IEditorPart editor) throws CoreException;
- /**
- * Used to determine function name from and editor input, with offset
- * supplied manualy. Used by prepare changelog.
- *
- * @param input If unexpected error happens in the underlying Eclipse APIs.
- * @param offset The offset at which to start.
- * @return The name of the function.
- * @throws CoreException If unexpected error happens in the underlying Eclipse APIs.
- */
- String parseCurrentFunction(IEditorInput input, int offset)
- throws CoreException;
+ /**
+ * Used to determine function name from and editor input, with offset
+ * supplied manualy. Used by prepare changelog.
+ *
+ * @param input If unexpected error happens in the underlying Eclipse APIs.
+ * @param offset The offset at which to start.
+ * @return The name of the function.
+ * @throws CoreException If unexpected error happens in the underlying Eclipse APIs.
+ */
+ String parseCurrentFunction(IEditorInput input, int offset)
+ throws CoreException;
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogExtensionManager.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogExtensionManager.java
index 237b17d5e0..d80647adf9 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogExtensionManager.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogExtensionManager.java
@@ -38,223 +38,223 @@ public final class ChangeLogExtensionManager {
private static final ChangeLogExtensionManager EXM = new ChangeLogExtensionManager();
- // These are used as a simple cache so we don't have to iterate over
- // all extensions to formatContribution every time the action is invoked.
- private IConfigurationElement cachedPrefFormatter = null;
+ // These are used as a simple cache so we don't have to iterate over
+ // all extensions to formatContribution every time the action is invoked.
+ private IConfigurationElement cachedPrefFormatter = null;
- private IConfigurationElement[] cachedInFileFormateters = null;
+ private IConfigurationElement[] cachedInFileFormateters = null;
- private IExtensionPoint parserExtensions = null;
+ private IExtensionPoint parserExtensions = null;
- private IExtensionPoint formatterExtensions = null;
+ private IExtensionPoint formatterExtensions = null;
- private IParserChangeLogContrib parserContributor = null;
+ private IParserChangeLogContrib parserContributor = null;
- private IConfigurationElement formatterConfigElementToUse = null;
+ private IConfigurationElement formatterConfigElementToUse = null;
- private ChangeLogExtensionManager() {
- getParserContributions();
- getFormatterContributions();
- }
+ private ChangeLogExtensionManager() {
+ getParserContributions();
+ getFormatterContributions();
+ }
- public static ChangeLogExtensionManager getExtensionManager() {
- return EXM;
- }
+ public static ChangeLogExtensionManager getExtensionManager() {
+ return EXM;
+ }
- private void getFormatterContributions() {
- formatterExtensions = Platform
- .getExtensionRegistry()
- .getExtensionPoint(
- "org.eclipse.linuxtools.changelog.core", "formatterContribution"); //$NON-NLS-1$
- }
+ private void getFormatterContributions() {
+ formatterExtensions = Platform
+ .getExtensionRegistry()
+ .getExtensionPoint(
+ "org.eclipse.linuxtools.changelog.core", "formatterContribution"); //$NON-NLS-1$
+ }
- private void getParserContributions() {
+ private void getParserContributions() {
- parserExtensions = Platform.getExtensionRegistry().getExtensionPoint(
- "org.eclipse.linuxtools.changelog.core", "parserContribution"); //$NON-NLS-1$
+ parserExtensions = Platform.getExtensionRegistry().getExtensionPoint(
+ "org.eclipse.linuxtools.changelog.core", "parserContribution"); //$NON-NLS-1$
- }
-
- public IParserChangeLogContrib getParserContributor(String editorName) {
-
- if (parserExtensions != null) {
- IConfigurationElement[] elements = parserExtensions
- .getConfigurationElements();
- for (int i = 0; i < elements.length; i++) {
- if (elements[i].getName().equals("parser") // $NON-NLS-1$
- && (elements[i].getAttribute("editor") // $NON-NLS-1$
- .equals(editorName))) {
- //$NON-NLS-1$
- try {
- IConfigurationElement bob = elements[i];
- parserContributor = (IParserChangeLogContrib) bob
- .createExecutableExtension("class"); // $NON-NLS-1$
- return parserContributor;
- } catch (CoreException e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
- IStatus.ERROR, e.getMessage(), e));
- }
-
- }
- }
- }
-
-
-
- return null;
- }
-
-
-
-
- public IConfigurationElement getFormatterConfigElement() {
- return formatterConfigElementToUse;
- }
-
- /**
- * Fetches formatterName formatter from extension, but if there exists a inline
- * formatter for entryFileName, then it uses that inline formatter.
- */
- public IFormatterChangeLogContrib getFormatterContributor(String entryFilePath, String formatterName) {
-
-
- // extract just file name;
- String fileName;
-
- int lastDir = entryFilePath.lastIndexOf('/');
- if ((lastDir >= 0) && (lastDir +1 <= entryFilePath.length()))
- fileName = entryFilePath.substring(lastDir + 1, entryFilePath.length());
- else
- fileName = entryFilePath;
-
- // We don't yet know which formatter to use
- formatterConfigElementToUse = null;
-
- // IFile file = null;
-
- if (formatterExtensions != null) {
- IConfigurationElement[] elements = formatterExtensions
- .getConfigurationElements();
-
- // cache the in-file formatters on the first run
- if (cachedInFileFormateters == null) {
- List<IConfigurationElement> inFileFormatters = new LinkedList<>();
- for (int i = 0; i < elements.length; i++) {
- IConfigurationElement formatterConfigElement = elements[i];
- if (formatterConfigElement.getName().equals("formatter") // $NON-NLS-1$
- && formatterConfigElement.getAttribute("inFile") // $NON-NLS-1$
- .equalsIgnoreCase("true")) { // $NON-NLS-1$
- inFileFormatters.add(elements[i]);
- }
- }
- cachedInFileFormateters = inFileFormatters
- .toArray(new IConfigurationElement[] {});
- }
-
- // check if there is an in-file changelog formatter for the
- // currently
- // edited file
- for (int i = 0; i < cachedInFileFormateters.length; i++) {
- IConfigurationElement formatterConfigElement = cachedInFileFormateters[i];
-
- IConfigurationElement[] patternElementTmp = formatterConfigElement
- .getChildren();
-
- // error check
- if (patternElementTmp == null)
- continue;
- IConfigurationElement patternElement = patternElementTmp[0];
-
- if (patternElement.getAttribute("pattern") == null) { // $NON-NLS-1$
- ChangelogPlugin
- .getDefault()
- .getLog()
- .log(
- new Status(
- IStatus.ERROR,
- ChangelogPlugin.PLUGIN_ID,
- IStatus.ERROR,
- Messages.getString("ChangeLog.ErrNonPattern"), // $NON-NLS-1$
- new Exception(Messages.getString("ChangeLog.ErrNonPattern")))); // $NON-NLS-1$
- } else {
- String filePattern = patternElement.getAttribute("pattern"); // $NON-NLS-1$
-
- try {
- Pattern pattern = Pattern.compile(filePattern);
- Matcher fileMatcher = pattern.matcher(fileName);
-
- // if the filename of the current editor matches the
- // file
- // pattern then we're done
- if (fileMatcher.matches()) {
- formatterConfigElementToUse = formatterConfigElement;
- break;
- }
- } catch (PatternSyntaxException e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
- IStatus.ERROR, e.getMessage(), e));
- }
- }
-
- }
-
- // if we haven't found an in-file formatter we try to get the user's
- // prefered formatter
- if (formatterConfigElementToUse == null) {
-
- // we cache the user's preferred formatter on the first run, and
- // whenever it changes
- if (cachedPrefFormatter == null
- || !cachedPrefFormatter.getAttribute("name").equals( // $NON-NLS-1$
- formatterName)) {
-
- for (int i = 0; i < elements.length; i++) {
- IConfigurationElement formatterConfigElement = elements[i];
- if (formatterConfigElement.getName()
- .equals("formatter") && formatterConfigElement.getAttribute("inFile").equalsIgnoreCase("false")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (formatterConfigElement.getAttribute("name") // $NON-NLS-1$
- .equals(formatterName))
- cachedPrefFormatter = formatterConfigElement;
- break;
-
- }
- }
- }
-
- formatterConfigElementToUse = cachedPrefFormatter;
-
- if (formatterConfigElementToUse == null) {
- ChangelogPlugin
- .getDefault()
- .getLog()
- .log(
- new Status(
- IStatus.ERROR,
- ChangelogPlugin.PLUGIN_ID,
- IStatus.ERROR,
- Messages.getString("ChangeLog.ErrRetrieveFormatter"), // $NON-NLS-1$
- new Exception(Messages.getString("ChangeLog.ErrRetrieveFormatter")))); // $NON-NLS-1$
-
- return null;
- }
-
- }
- }
-
-
-
- try {
- return (IFormatterChangeLogContrib) formatterConfigElementToUse
- .createExecutableExtension("class"); // $NON-NLS-1$
-
- } catch (CoreException e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
- .getMessage(), e));
- e.printStackTrace();
- }
- return null;
- }
+ }
+
+ public IParserChangeLogContrib getParserContributor(String editorName) {
+
+ if (parserExtensions != null) {
+ IConfigurationElement[] elements = parserExtensions
+ .getConfigurationElements();
+ for (int i = 0; i < elements.length; i++) {
+ if (elements[i].getName().equals("parser") // $NON-NLS-1$
+ && (elements[i].getAttribute("editor") // $NON-NLS-1$
+ .equals(editorName))) {
+ //$NON-NLS-1$
+ try {
+ IConfigurationElement bob = elements[i];
+ parserContributor = (IParserChangeLogContrib) bob
+ .createExecutableExtension("class"); // $NON-NLS-1$
+ return parserContributor;
+ } catch (CoreException e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
+ IStatus.ERROR, e.getMessage(), e));
+ }
+
+ }
+ }
+ }
+
+
+
+ return null;
+ }
+
+
+
+
+ public IConfigurationElement getFormatterConfigElement() {
+ return formatterConfigElementToUse;
+ }
+
+ /**
+ * Fetches formatterName formatter from extension, but if there exists a inline
+ * formatter for entryFileName, then it uses that inline formatter.
+ */
+ public IFormatterChangeLogContrib getFormatterContributor(String entryFilePath, String formatterName) {
+
+
+ // extract just file name;
+ String fileName;
+
+ int lastDir = entryFilePath.lastIndexOf('/');
+ if ((lastDir >= 0) && (lastDir +1 <= entryFilePath.length()))
+ fileName = entryFilePath.substring(lastDir + 1, entryFilePath.length());
+ else
+ fileName = entryFilePath;
+
+ // We don't yet know which formatter to use
+ formatterConfigElementToUse = null;
+
+ // IFile file = null;
+
+ if (formatterExtensions != null) {
+ IConfigurationElement[] elements = formatterExtensions
+ .getConfigurationElements();
+
+ // cache the in-file formatters on the first run
+ if (cachedInFileFormateters == null) {
+ List<IConfigurationElement> inFileFormatters = new LinkedList<>();
+ for (int i = 0; i < elements.length; i++) {
+ IConfigurationElement formatterConfigElement = elements[i];
+ if (formatterConfigElement.getName().equals("formatter") // $NON-NLS-1$
+ && formatterConfigElement.getAttribute("inFile") // $NON-NLS-1$
+ .equalsIgnoreCase("true")) { // $NON-NLS-1$
+ inFileFormatters.add(elements[i]);
+ }
+ }
+ cachedInFileFormateters = inFileFormatters
+ .toArray(new IConfigurationElement[] {});
+ }
+
+ // check if there is an in-file changelog formatter for the
+ // currently
+ // edited file
+ for (int i = 0; i < cachedInFileFormateters.length; i++) {
+ IConfigurationElement formatterConfigElement = cachedInFileFormateters[i];
+
+ IConfigurationElement[] patternElementTmp = formatterConfigElement
+ .getChildren();
+
+ // error check
+ if (patternElementTmp == null)
+ continue;
+ IConfigurationElement patternElement = patternElementTmp[0];
+
+ if (patternElement.getAttribute("pattern") == null) { // $NON-NLS-1$
+ ChangelogPlugin
+ .getDefault()
+ .getLog()
+ .log(
+ new Status(
+ IStatus.ERROR,
+ ChangelogPlugin.PLUGIN_ID,
+ IStatus.ERROR,
+ Messages.getString("ChangeLog.ErrNonPattern"), // $NON-NLS-1$
+ new Exception(Messages.getString("ChangeLog.ErrNonPattern")))); // $NON-NLS-1$
+ } else {
+ String filePattern = patternElement.getAttribute("pattern"); // $NON-NLS-1$
+
+ try {
+ Pattern pattern = Pattern.compile(filePattern);
+ Matcher fileMatcher = pattern.matcher(fileName);
+
+ // if the filename of the current editor matches the
+ // file
+ // pattern then we're done
+ if (fileMatcher.matches()) {
+ formatterConfigElementToUse = formatterConfigElement;
+ break;
+ }
+ } catch (PatternSyntaxException e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
+ IStatus.ERROR, e.getMessage(), e));
+ }
+ }
+
+ }
+
+ // if we haven't found an in-file formatter we try to get the user's
+ // prefered formatter
+ if (formatterConfigElementToUse == null) {
+
+ // we cache the user's preferred formatter on the first run, and
+ // whenever it changes
+ if (cachedPrefFormatter == null
+ || !cachedPrefFormatter.getAttribute("name").equals( // $NON-NLS-1$
+ formatterName)) {
+
+ for (int i = 0; i < elements.length; i++) {
+ IConfigurationElement formatterConfigElement = elements[i];
+ if (formatterConfigElement.getName()
+ .equals("formatter") && formatterConfigElement.getAttribute("inFile").equalsIgnoreCase("false")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if (formatterConfigElement.getAttribute("name") // $NON-NLS-1$
+ .equals(formatterName))
+ cachedPrefFormatter = formatterConfigElement;
+ break;
+
+ }
+ }
+ }
+
+ formatterConfigElementToUse = cachedPrefFormatter;
+
+ if (formatterConfigElementToUse == null) {
+ ChangelogPlugin
+ .getDefault()
+ .getLog()
+ .log(
+ new Status(
+ IStatus.ERROR,
+ ChangelogPlugin.PLUGIN_ID,
+ IStatus.ERROR,
+ Messages.getString("ChangeLog.ErrRetrieveFormatter"), // $NON-NLS-1$
+ new Exception(Messages.getString("ChangeLog.ErrRetrieveFormatter")))); // $NON-NLS-1$
+
+ return null;
+ }
+
+ }
+ }
+
+
+
+ try {
+ return (IFormatterChangeLogContrib) formatterConfigElementToUse
+ .createExecutableExtension("class"); // $NON-NLS-1$
+
+ } catch (CoreException e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
+ .getMessage(), e));
+ e.printStackTrace();
+ }
+ return null;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogPreferencesPage.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogPreferencesPage.java
index 13c02eacb1..2489b9f37a 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogPreferencesPage.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogPreferencesPage.java
@@ -38,233 +38,233 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
* preference dialog based on the registration.
*/
public class ChangeLogPreferencesPage extends PreferencePage implements
- IWorkbenchPreferencePage {
-
- private Text emailField;
-
- private Text nameField;
-
- private List formatterList;
-
- private List editorList;
-
- private Composite createComposite(Composite parent, int numColumns) {
- Composite composite = new Composite(parent, SWT.NULL);
-
- // GridLayout
- GridLayout layout = new GridLayout();
- layout.numColumns = numColumns;
- composite.setLayout(layout);
-
- // GridData
- GridData data = new GridData();
- data.verticalAlignment = GridData.FILL;
- data.horizontalAlignment = GridData.FILL;
- composite.setLayoutData(data);
- return composite;
- }
-
- private Label createLabel(Composite parent, String text) {
- Label label = new Label(parent, SWT.LEFT);
- label.setText(text);
- GridData data = new GridData();
- data.horizontalSpan = 2;
- data.horizontalAlignment = GridData.FILL;
- label.setLayoutData(data);
- return label;
- }
-
- private Text createTextField(Composite parent) {
- Text text = new Text(parent, SWT.SINGLE | SWT.BORDER);
- GridData data = new GridData();
- data.horizontalAlignment = GridData.FILL;
- data.grabExcessHorizontalSpace = true;
- data.verticalAlignment = GridData.CENTER;
- data.grabExcessVerticalSpace = false;
- text.setLayoutData(data);
- return text;
- }
-
- private List createListBox(Composite parent, int sizeHint) {
- List list = new List(parent, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL);
- GridData data = new GridData();
- data.horizontalAlignment = GridData.FILL;
- data.grabExcessHorizontalSpace = true;
- data.verticalAlignment = GridData.CENTER;
- data.grabExcessVerticalSpace = false;
- data.heightHint = list.getItemHeight() * sizeHint;
- list.setLayoutData(data);
-
- return list;
- }
-
- @Override
- public void init(IWorkbench workbench) {
- }
-
- @Override
- protected IPreferenceStore doGetPreferenceStore() {
- return ChangelogPlugin.getDefault().getPreferenceStore();
- }
-
- private void initializeDefaults() {
- IPreferenceStore store = getPreferenceStore();
- emailField.setText(store
- .getDefaultString("IChangeLogConstants.AUTHOR_EMAIL")); //$NON-NLS-1$
- nameField.setText(store
- .getDefaultString("IChangeLogConstants.AUTHOR_NAME")); //$NON-NLS-1$
- setDefaultFormatter(store);
- setDefaultEditor(store);
- storeValues();
- }
-
- private void setDefaultFormatter(IPreferenceStore store) {
-
- String defaultFormatter = store
- .getDefaultString("IChangeLogConstants.DEFAULT_FORMATTER"); //$NON-NLS-1$
- for (int i = 0; i < formatterList.getItemCount(); i++) {
- if (formatterList.getItem(i).equals(defaultFormatter)) {
- formatterList.setSelection(i);
- return;
- }
- }
- }
-
- private void setDefaultEditor(IPreferenceStore store) {
-
- String defaultEditor = store
- .getDefaultString("IChangeLogConstants.DEFAULT_EDITOR"); //$NON-NLS-1$
- for (int i = 0; i < editorList.getItemCount(); i++) {
- if (editorList.getItem(i).equals(defaultEditor)) {
- editorList.setSelection(i);
- return;
- }
- }
- }
-
- private void populateFormatList(IPreferenceStore store) {
- IExtensionPoint parserExtensions = Platform
- .getExtensionRegistry()
- .getExtensionPoint(
- "org.eclipse.linuxtools.changelog.core", "formatterContribution"); //$NON-NLS-1$ //$NON-NLS-2$
- if (parserExtensions != null) {
- IConfigurationElement[] elements = parserExtensions
- .getConfigurationElements();
- for (IConfigurationElement element : elements) {
- if (element.getName().equals("formatter")) {//$NON-NLS-1$
-
- String fname = element.getAttribute("name"); //$NON-NLS-1$\
- // only add formatters for external files, not in-file formatters.
- if (element.getAttribute("inFile").equalsIgnoreCase("false")) {
- formatterList.add(fname);
- }
-
- if (fname
- .equals(store
- .getString("IChangeLogConstants.DEFAULT_FORMATTER"))) { //$NON-NLS-1$
- formatterList
- .setSelection(formatterList.getItemCount() - 1);
- }
- }
- }
-
- }
- }
-
- private void populateEditorList(IPreferenceStore store) {
- IExtensionPoint editorExtensions = Platform
- .getExtensionRegistry()
- .getExtensionPoint(
- "org.eclipse.linuxtools.changelog.core", "editorContribution"); //$NON-NLS-1$ //$NON-NLS-2$
- if (editorExtensions != null) {
- IConfigurationElement[] elements = editorExtensions
- .getConfigurationElements();
- for (IConfigurationElement element : elements) {
- if (element.getName().equals("editor")) {//$NON-NLS-1$
- String fname = element.getAttribute("name"); //$NON-NLS-1$
- editorList.add(fname);
- if (fname.equals(store
- .getString("IChangeLogConstants.DEFAULT_EDITOR"))) {//$NON-NLS-1$
- editorList.setSelection(editorList.getItemCount() - 1);
- }
- }
- }
-
- }
- }
-
- private void initializeValues() {
- IPreferenceStore store = getPreferenceStore();
-
- emailField.setText(store.getString("IChangeLogConstants.AUTHOR_EMAIL")); //$NON-NLS-1$
- nameField.setText(store.getString("IChangeLogConstants.AUTHOR_NAME")); //$NON-NLS-1$
- populateFormatList(store);
- populateEditorList(store);
- }
-
- private void storeValues() {
- IPreferenceStore store = getPreferenceStore();
-
- store.setValue("IChangeLogConstants.AUTHOR_NAME", nameField.getText()); //$NON-NLS-1$
- store
- .setValue(
- "IChangeLogConstants.AUTHOR_EMAIL", emailField.getText()); //$NON-NLS-1$
- String[] selection = formatterList.getSelection();
- if (selection != null && selection.length > 0) {
- store.setValue("IChangeLogConstants.DEFAULT_FORMATTER", selection[0]); //$NON-NLS-1$
- }
- String[] selection2 = editorList.getSelection();
- if (selection2 != null && selection2.length > 0) {
- store.setValue("IChangeLogConstants.DEFAULT_EDITOR", selection2[0]); //$NON-NLS-1$
- }
-
- }
-
- /*
- * (non-Javadoc) Method declared on PreferencePage
- */
- @Override
- protected void performDefaults() {
- super.performDefaults();
- initializeDefaults();
-
- }
-
- /*
- * (non-Javadoc) Method declared on PreferencePage
- */
- @SuppressWarnings("deprecation")
- @Override
- public boolean performOk() {
- storeValues();
- ChangelogPlugin.getDefault().savePluginPreferences();
- return true;
- }
-
- @Override
- protected Control createContents(Composite parent) {
- // composite_textField << parent
- Composite composite_textField = createComposite(parent, 2);
- createLabel(composite_textField, Messages
- .getString("ChangeLogPreferencesPage.AuthorName")); //$NON-NLS-1$
- nameField = createTextField(composite_textField);
-
- // composite_textField << parent
-
- createLabel(composite_textField, Messages
- .getString("ChangeLogPreferencesPage.AuthorEmail")); //$NON-NLS-1$
- emailField = createTextField(composite_textField);
-
- createLabel(composite_textField, Messages
- .getString("ChangeLogPreferencesPage.Formatters")); //$NON-NLS-1$
- formatterList = createListBox(composite_textField, 3);
-
- createLabel(composite_textField, Messages
- .getString("ChangeLogPreferencesPage.Editors")); //$NON-NLS-1$
- editorList = createListBox(composite_textField, 3);
-
- initializeValues();
-
- return new Composite(parent, SWT.NULL);
- }
+ IWorkbenchPreferencePage {
+
+ private Text emailField;
+
+ private Text nameField;
+
+ private List formatterList;
+
+ private List editorList;
+
+ private Composite createComposite(Composite parent, int numColumns) {
+ Composite composite = new Composite(parent, SWT.NULL);
+
+ // GridLayout
+ GridLayout layout = new GridLayout();
+ layout.numColumns = numColumns;
+ composite.setLayout(layout);
+
+ // GridData
+ GridData data = new GridData();
+ data.verticalAlignment = GridData.FILL;
+ data.horizontalAlignment = GridData.FILL;
+ composite.setLayoutData(data);
+ return composite;
+ }
+
+ private Label createLabel(Composite parent, String text) {
+ Label label = new Label(parent, SWT.LEFT);
+ label.setText(text);
+ GridData data = new GridData();
+ data.horizontalSpan = 2;
+ data.horizontalAlignment = GridData.FILL;
+ label.setLayoutData(data);
+ return label;
+ }
+
+ private Text createTextField(Composite parent) {
+ Text text = new Text(parent, SWT.SINGLE | SWT.BORDER);
+ GridData data = new GridData();
+ data.horizontalAlignment = GridData.FILL;
+ data.grabExcessHorizontalSpace = true;
+ data.verticalAlignment = GridData.CENTER;
+ data.grabExcessVerticalSpace = false;
+ text.setLayoutData(data);
+ return text;
+ }
+
+ private List createListBox(Composite parent, int sizeHint) {
+ List list = new List(parent, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL);
+ GridData data = new GridData();
+ data.horizontalAlignment = GridData.FILL;
+ data.grabExcessHorizontalSpace = true;
+ data.verticalAlignment = GridData.CENTER;
+ data.grabExcessVerticalSpace = false;
+ data.heightHint = list.getItemHeight() * sizeHint;
+ list.setLayoutData(data);
+
+ return list;
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ }
+
+ @Override
+ protected IPreferenceStore doGetPreferenceStore() {
+ return ChangelogPlugin.getDefault().getPreferenceStore();
+ }
+
+ private void initializeDefaults() {
+ IPreferenceStore store = getPreferenceStore();
+ emailField.setText(store
+ .getDefaultString("IChangeLogConstants.AUTHOR_EMAIL")); //$NON-NLS-1$
+ nameField.setText(store
+ .getDefaultString("IChangeLogConstants.AUTHOR_NAME")); //$NON-NLS-1$
+ setDefaultFormatter(store);
+ setDefaultEditor(store);
+ storeValues();
+ }
+
+ private void setDefaultFormatter(IPreferenceStore store) {
+
+ String defaultFormatter = store
+ .getDefaultString("IChangeLogConstants.DEFAULT_FORMATTER"); //$NON-NLS-1$
+ for (int i = 0; i < formatterList.getItemCount(); i++) {
+ if (formatterList.getItem(i).equals(defaultFormatter)) {
+ formatterList.setSelection(i);
+ return;
+ }
+ }
+ }
+
+ private void setDefaultEditor(IPreferenceStore store) {
+
+ String defaultEditor = store
+ .getDefaultString("IChangeLogConstants.DEFAULT_EDITOR"); //$NON-NLS-1$
+ for (int i = 0; i < editorList.getItemCount(); i++) {
+ if (editorList.getItem(i).equals(defaultEditor)) {
+ editorList.setSelection(i);
+ return;
+ }
+ }
+ }
+
+ private void populateFormatList(IPreferenceStore store) {
+ IExtensionPoint parserExtensions = Platform
+ .getExtensionRegistry()
+ .getExtensionPoint(
+ "org.eclipse.linuxtools.changelog.core", "formatterContribution"); //$NON-NLS-1$ //$NON-NLS-2$
+ if (parserExtensions != null) {
+ IConfigurationElement[] elements = parserExtensions
+ .getConfigurationElements();
+ for (IConfigurationElement element : elements) {
+ if (element.getName().equals("formatter")) {//$NON-NLS-1$
+
+ String fname = element.getAttribute("name"); //$NON-NLS-1$\
+ // only add formatters for external files, not in-file formatters.
+ if (element.getAttribute("inFile").equalsIgnoreCase("false")) {
+ formatterList.add(fname);
+ }
+
+ if (fname
+ .equals(store
+ .getString("IChangeLogConstants.DEFAULT_FORMATTER"))) { //$NON-NLS-1$
+ formatterList
+ .setSelection(formatterList.getItemCount() - 1);
+ }
+ }
+ }
+
+ }
+ }
+
+ private void populateEditorList(IPreferenceStore store) {
+ IExtensionPoint editorExtensions = Platform
+ .getExtensionRegistry()
+ .getExtensionPoint(
+ "org.eclipse.linuxtools.changelog.core", "editorContribution"); //$NON-NLS-1$ //$NON-NLS-2$
+ if (editorExtensions != null) {
+ IConfigurationElement[] elements = editorExtensions
+ .getConfigurationElements();
+ for (IConfigurationElement element : elements) {
+ if (element.getName().equals("editor")) {//$NON-NLS-1$
+ String fname = element.getAttribute("name"); //$NON-NLS-1$
+ editorList.add(fname);
+ if (fname.equals(store
+ .getString("IChangeLogConstants.DEFAULT_EDITOR"))) {//$NON-NLS-1$
+ editorList.setSelection(editorList.getItemCount() - 1);
+ }
+ }
+ }
+
+ }
+ }
+
+ private void initializeValues() {
+ IPreferenceStore store = getPreferenceStore();
+
+ emailField.setText(store.getString("IChangeLogConstants.AUTHOR_EMAIL")); //$NON-NLS-1$
+ nameField.setText(store.getString("IChangeLogConstants.AUTHOR_NAME")); //$NON-NLS-1$
+ populateFormatList(store);
+ populateEditorList(store);
+ }
+
+ private void storeValues() {
+ IPreferenceStore store = getPreferenceStore();
+
+ store.setValue("IChangeLogConstants.AUTHOR_NAME", nameField.getText()); //$NON-NLS-1$
+ store
+ .setValue(
+ "IChangeLogConstants.AUTHOR_EMAIL", emailField.getText()); //$NON-NLS-1$
+ String[] selection = formatterList.getSelection();
+ if (selection != null && selection.length > 0) {
+ store.setValue("IChangeLogConstants.DEFAULT_FORMATTER", selection[0]); //$NON-NLS-1$
+ }
+ String[] selection2 = editorList.getSelection();
+ if (selection2 != null && selection2.length > 0) {
+ store.setValue("IChangeLogConstants.DEFAULT_EDITOR", selection2[0]); //$NON-NLS-1$
+ }
+
+ }
+
+ /*
+ * (non-Javadoc) Method declared on PreferencePage
+ */
+ @Override
+ protected void performDefaults() {
+ super.performDefaults();
+ initializeDefaults();
+
+ }
+
+ /*
+ * (non-Javadoc) Method declared on PreferencePage
+ */
+ @SuppressWarnings("deprecation")
+ @Override
+ public boolean performOk() {
+ storeValues();
+ ChangelogPlugin.getDefault().savePluginPreferences();
+ return true;
+ }
+
+ @Override
+ protected Control createContents(Composite parent) {
+ // composite_textField << parent
+ Composite composite_textField = createComposite(parent, 2);
+ createLabel(composite_textField, Messages
+ .getString("ChangeLogPreferencesPage.AuthorName")); //$NON-NLS-1$
+ nameField = createTextField(composite_textField);
+
+ // composite_textField << parent
+
+ createLabel(composite_textField, Messages
+ .getString("ChangeLogPreferencesPage.AuthorEmail")); //$NON-NLS-1$
+ emailField = createTextField(composite_textField);
+
+ createLabel(composite_textField, Messages
+ .getString("ChangeLogPreferencesPage.Formatters")); //$NON-NLS-1$
+ formatterList = createListBox(composite_textField, 3);
+
+ createLabel(composite_textField, Messages
+ .getString("ChangeLogPreferencesPage.Editors")); //$NON-NLS-1$
+ editorList = createListBox(composite_textField, 3);
+
+ initializeValues();
+
+ return new Composite(parent, SWT.NULL);
+ }
} \ No newline at end of file
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogWriter.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogWriter.java
index fe65976b65..04ce9da110 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogWriter.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangeLogWriter.java
@@ -17,114 +17,114 @@ import org.eclipse.ui.IEditorPart;
/**
* Writes changelog using extension point IFormatterChangeLogContrib.
- *
+ *
* @author klee
*
*/
public class ChangeLogWriter {
-
- private String defaultContent = ""; // $NON-NLS-1$
- private String entryFilePath = null;
+ private String defaultContent = ""; // $NON-NLS-1$
+
+ private String entryFilePath = null;
- private String guessedFName = null;
+ private String guessedFName = null;
- private IFormatterChangeLogContrib formatter = null;
+ private IFormatterChangeLogContrib formatter = null;
- private IEditorPart changelog = null;
+ private IEditorPart changelog = null;
- private String dateLine = null;
+ private String dateLine = null;
- private String changelogLocation = null;
+ private String changelogLocation = null;
- public IEditorPart getChangelog() {
- return changelog;
- }
+ public IEditorPart getChangelog() {
+ return changelog;
+ }
- public void setChangelog(IEditorPart changelog) {
- this.changelog = changelog;
- }
+ public void setChangelog(IEditorPart changelog) {
+ this.changelog = changelog;
+ }
- public String getChangelogLocation() {
- return changelogLocation;
- }
+ public String getChangelogLocation() {
+ return changelogLocation;
+ }
- public void setChangelogLocation(String changelogLocation) {
- this.changelogLocation = changelogLocation;
- }
+ public void setChangelogLocation(String changelogLocation) {
+ this.changelogLocation = changelogLocation;
+ }
- public String getDateLine() {
- return dateLine;
- }
+ public String getDateLine() {
+ return dateLine;
+ }
- public void setDateLine(String dateLine) {
- this.dateLine = dateLine;
- }
+ public void setDateLine(String dateLine) {
+ this.dateLine = dateLine;
+ }
- public String getEntryFilePath() {
- return entryFilePath;
- }
+ public String getEntryFilePath() {
+ return entryFilePath;
+ }
- public void setEntryFilePath(String entryFilePath) {
- // Replace characters in the name that are supposed to be
- // token markers such as blanks, parentheses, and colon with
- // escaped characters so they won't fool the colorization or
- // other parsing.
- String resolvedPath = entryFilePath.replace("(", "\\(");
- resolvedPath = resolvedPath.replace(")", "\\)");
- resolvedPath = resolvedPath.replace(":", "\\:");
- resolvedPath = resolvedPath.replace(" ", "\\ ");
- this.entryFilePath = resolvedPath;
- }
+ public void setEntryFilePath(String entryFilePath) {
+ // Replace characters in the name that are supposed to be
+ // token markers such as blanks, parentheses, and colon with
+ // escaped characters so they won't fool the colorization or
+ // other parsing.
+ String resolvedPath = entryFilePath.replace("(", "\\(");
+ resolvedPath = resolvedPath.replace(")", "\\)");
+ resolvedPath = resolvedPath.replace(":", "\\:");
+ resolvedPath = resolvedPath.replace(" ", "\\ ");
+ this.entryFilePath = resolvedPath;
+ }
- public IFormatterChangeLogContrib getFormatter() {
- return formatter;
- }
+ public IFormatterChangeLogContrib getFormatter() {
+ return formatter;
+ }
- public void setFormatter(IFormatterChangeLogContrib formatter) {
- this.formatter = formatter;
- }
+ public void setFormatter(IFormatterChangeLogContrib formatter) {
+ this.formatter = formatter;
+ }
- public String getGuessedFName() {
- return guessedFName;
- }
+ public String getGuessedFName() {
+ return guessedFName;
+ }
- public void setGuessedFName(String guessedFName) {
- this.guessedFName = guessedFName;
- }
+ public void setGuessedFName(String guessedFName) {
+ this.guessedFName = guessedFName;
+ }
- public void writeChangeLog() {
+ public void writeChangeLog() {
- // System.out.println("Debug Output :");
- // System.out.println(entryFilePath);
- // System.out.println(guessedFName);
- // System.out.println(formatter);
- // System.out.println(changelog);
- // System.out.println(dateLine);
- // System.out.println(changelogLocation);
- // System.out.println("\n");
+ // System.out.println("Debug Output :");
+ // System.out.println(entryFilePath);
+ // System.out.println(guessedFName);
+ // System.out.println(formatter);
+ // System.out.println(changelog);
+ // System.out.println(dateLine);
+ // System.out.println(changelogLocation);
+ // System.out.println("\n");
- if (entryFilePath == null || guessedFName == null || formatter == null
- || changelog == null || dateLine == null
- || changelogLocation == null) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR,
- Messages.getString("ChangeLogWriter.ErrUninitialized"), null)); // $NON-NLS-1$
+ if (entryFilePath == null || guessedFName == null || formatter == null
+ || changelog == null || dateLine == null
+ || changelogLocation == null) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR,
+ Messages.getString("ChangeLogWriter.ErrUninitialized"), null)); // $NON-NLS-1$
- return;
- }
+ return;
+ }
- formatter.mergeChangelog(dateLine, guessedFName, defaultContent, changelog,
- changelogLocation, entryFilePath);
+ formatter.mergeChangelog(dateLine, guessedFName, defaultContent, changelog,
+ changelogLocation, entryFilePath);
- }
+ }
- public String getDefaultContent() {
- return defaultContent;
- }
+ public String getDefaultContent() {
+ return defaultContent;
+ }
- public void setDefaultContent(String defaultContent) {
- this.defaultContent = defaultContent;
- }
+ public void setDefaultContent(String defaultContent) {
+ this.defaultContent = defaultContent;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangelogPlugin.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangelogPlugin.java
index 28dcb5c2b3..bb5c376e7f 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangelogPlugin.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangelogPlugin.java
@@ -22,25 +22,25 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
* The main plugin class to be used in the desktop.
*/
public class ChangelogPlugin extends AbstractUIPlugin {
-
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.changelog.core"; // $NON-NLS-1$
-
- // The shared instance.
- private static ChangelogPlugin plugin;
-
- /**
- * The constructor.
- */
- public ChangelogPlugin() {
- // super();
- plugin = this;
- }
-
- /**
- * Returns the shared instance.
- */
- public static ChangelogPlugin getDefault() {
- return plugin;
- }
+
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.changelog.core"; // $NON-NLS-1$
+
+ // The shared instance.
+ private static ChangelogPlugin plugin;
+
+ /**
+ * The constructor.
+ */
+ public ChangelogPlugin() {
+ // super();
+ plugin = this;
+ }
+
+ /**
+ * Returns the shared instance.
+ */
+ public static ChangelogPlugin getDefault() {
+ return plugin;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangelogPreferenceInitializer.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangelogPreferenceInitializer.java
index dfc2f65a3f..a5f8e2137e 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangelogPreferenceInitializer.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ChangelogPreferenceInitializer.java
@@ -16,56 +16,56 @@ import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
public class ChangelogPreferenceInitializer extends
- AbstractPreferenceInitializer {
+ AbstractPreferenceInitializer {
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = ChangelogPlugin.getDefault()
- .getPreferenceStore();
- store.setDefault("IChangeLogConstants.DATE_FORMAT", "true"); // $NON-NLS-1$
- // //
- // $NON-NLS-2$
- store.setDefault("IChangeLogConstants.APPEND_RESOURCE_PATH", "false"); // $NON-NLS-1$
- // //
- // $NON-NLS-2$
+ @Override
+ public void initializeDefaultPreferences() {
+ IPreferenceStore store = ChangelogPlugin.getDefault()
+ .getPreferenceStore();
+ store.setDefault("IChangeLogConstants.DATE_FORMAT", "true"); // $NON-NLS-1$
+ // //
+ // $NON-NLS-2$
+ store.setDefault("IChangeLogConstants.APPEND_RESOURCE_PATH", "false"); // $NON-NLS-1$
+ // //
+ // $NON-NLS-2$
- store.setDefault("IChangeLogConstants.AUTHOR_NAME", // $NON-NLS-1$
- getUserRealName());
- store.setDefault("IChangeLogConstants.AUTHOR_EMAIL", // $NON-NLS-2$
- getUserEmail());
- store.setDefault("IChangeLogConstants.DEFAULT_FORMATTER", // $NON-NLS-1$
- Messages.getString("ChangeLogPreferencesPage.gnuFormatter")); // $NON-NLS-1$
- store.setDefault("IChangeLogConstants.DEFAULT_EDITOR", // $NON-NLS-1$
- Messages.getString("ChangeLogPreferencesPage.gnuEditorConfig")); // $NON-NLS-1$
- }
+ store.setDefault("IChangeLogConstants.AUTHOR_NAME", // $NON-NLS-1$
+ getUserRealName());
+ store.setDefault("IChangeLogConstants.AUTHOR_EMAIL", // $NON-NLS-2$
+ getUserEmail());
+ store.setDefault("IChangeLogConstants.DEFAULT_FORMATTER", // $NON-NLS-1$
+ Messages.getString("ChangeLogPreferencesPage.gnuFormatter")); // $NON-NLS-1$
+ store.setDefault("IChangeLogConstants.DEFAULT_EDITOR", // $NON-NLS-1$
+ Messages.getString("ChangeLogPreferencesPage.gnuEditorConfig")); // $NON-NLS-1$
+ }
- private String getUserRealName() {
- String realUserName = System.getenv("ECLIPSE_CHANGELOG_REALNAME"); // $NON-NLS-1$
- if (realUserName != null)
- return realUserName;
- return System.getProperty("gnu.gcj.user.realname", //$NON-NLS-1$
- getUserName());
- }
+ private String getUserRealName() {
+ String realUserName = System.getenv("ECLIPSE_CHANGELOG_REALNAME"); // $NON-NLS-1$
+ if (realUserName != null)
+ return realUserName;
+ return System.getProperty("gnu.gcj.user.realname", //$NON-NLS-1$
+ getUserName());
+ }
- private String getUserEmail() {
- String emailID = System.getenv("ECLIPSE_CHANGELOG_EMAIL"); // $NON-NLS-1$
- if (emailID != null)
- return emailID;
- return getUserName() + "@" + getHostName(); // $NON-NLS-1$
- }
+ private String getUserEmail() {
+ String emailID = System.getenv("ECLIPSE_CHANGELOG_EMAIL"); // $NON-NLS-1$
+ if (emailID != null)
+ return emailID;
+ return getUserName() + "@" + getHostName(); // $NON-NLS-1$
+ }
- private String getUserName() {
- return System.getProperty("user.name"); //$NON-NLS-1$
- }
+ private String getUserName() {
+ return System.getProperty("user.name"); //$NON-NLS-1$
+ }
- private String getHostName() {
- try {
- return java.net.InetAddress.getLocalHost().getHostName();
- } catch (UnknownHostException e) {
- // instead of throwing exception, return default host name
- // RH bug#194406
- return "localhost.localdomain"; //$NON-NLS-1$
- }
- }
+ private String getHostName() {
+ try {
+ return java.net.InetAddress.getLocalHost().getHostName();
+ } catch (UnknownHostException e) {
+ // instead of throwing exception, return default host name
+ // RH bug#194406
+ return "localhost.localdomain"; //$NON-NLS-1$
+ }
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/LineComparator.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/LineComparator.java
index 45168fc8ac..dadedd7a34 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/LineComparator.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/LineComparator.java
@@ -39,75 +39,75 @@ public class LineComparator implements IRangeComparator {
*/
private static class TrailingLineFeedDetector extends FilterInputStream {
- boolean trailingLF = false;
-
- protected TrailingLineFeedDetector(InputStream in) {
- super(in);
- }
-
- @Override
- public int read() throws IOException {
- int c = super.read();
- trailingLF = isLineFeed(c);
- return c;
- }
-
- /*
- * We don't need to override read(byte[] buffer) as the javadoc of
- * FilterInputStream states that it will call read(byte[] buffer, int off, int len)
- */
- @Override
- public int read(byte[] buffer, int off, int len) throws IOException {
- int length = super.read(buffer, off, len);
- if (length != -1) {
- int index = off + length - 1;
- if (index >= buffer.length)
- index = buffer.length - 1;
- trailingLF = isLineFeed(buffer[index]);
- }
- return length;
- }
-
- private boolean isLineFeed(int c) {
- return c != -1 && c == '\n';
- }
-
- public boolean hadTrailingLineFeed() {
- return trailingLF;
- }
+ boolean trailingLF = false;
+
+ protected TrailingLineFeedDetector(InputStream in) {
+ super(in);
+ }
+
+ @Override
+ public int read() throws IOException {
+ int c = super.read();
+ trailingLF = isLineFeed(c);
+ return c;
+ }
+
+ /*
+ * We don't need to override read(byte[] buffer) as the javadoc of
+ * FilterInputStream states that it will call read(byte[] buffer, int off, int len)
+ */
+ @Override
+ public int read(byte[] buffer, int off, int len) throws IOException {
+ int length = super.read(buffer, off, len);
+ if (length != -1) {
+ int index = off + length - 1;
+ if (index >= buffer.length)
+ index = buffer.length - 1;
+ trailingLF = isLineFeed(buffer[index]);
+ }
+ return length;
+ }
+
+ private boolean isLineFeed(int c) {
+ return c != -1 && c == '\n';
+ }
+
+ public boolean hadTrailingLineFeed() {
+ return trailingLF;
+ }
}
public static LineComparator create(IStorage storage, String outputEncoding) throws CoreException {
- try (InputStream is = new BufferedInputStream(storage.getContents())) {
- String encoding = getEncoding(storage, outputEncoding);
- return new LineComparator(is, encoding);
- } catch (IOException e) {
- return null;
- }
+ try (InputStream is = new BufferedInputStream(storage.getContents())) {
+ String encoding = getEncoding(storage, outputEncoding);
+ return new LineComparator(is, encoding);
+ } catch (IOException e) {
+ return null;
+ }
}
- private static String getEncoding(IStorage storage, String outputEncoding) throws CoreException {
- if (storage instanceof IEncodedStorage) {
- IEncodedStorage es = (IEncodedStorage) storage;
- String charset = es.getCharset();
- if (charset != null)
- return charset;
- }
- return outputEncoding;
- }
+ private static String getEncoding(IStorage storage, String outputEncoding) throws CoreException {
+ if (storage instanceof IEncodedStorage) {
+ IEncodedStorage es = (IEncodedStorage) storage;
+ String charset = es.getCharset();
+ if (charset != null)
+ return charset;
+ }
+ return outputEncoding;
+ }
public LineComparator(InputStream is, String encoding) throws UnsupportedEncodingException {
TrailingLineFeedDetector trailingLineFeedDetector = new TrailingLineFeedDetector(is);
- BufferedReader br = new BufferedReader(new InputStreamReader(trailingLineFeedDetector, encoding));
+ BufferedReader br = new BufferedReader(new InputStreamReader(trailingLineFeedDetector, encoding));
String line;
ArrayList<String> ar = new ArrayList<>();
try {
while ((line = br.readLine()) != null)
ar.add(line);
} catch (IOException e) {
- // silently ignored
+ // silently ignored
}
try {
is.close();
@@ -117,7 +117,7 @@ public class LineComparator implements IRangeComparator {
// We do this because a BufferedReader doesn't distinguish the case
// where the last line has or doesn't have a trailing line separator
if (trailingLineFeedDetector.hadTrailingLineFeed()) {
- ar.add(""); //$NON-NLS-1$
+ ar.add(""); //$NON-NLS-1$
}
fLines = ar.toArray(new String[ar.size()]);
}
@@ -126,7 +126,7 @@ public class LineComparator implements IRangeComparator {
* @see org.eclipse.compare.rangedifferencer.IRangeComparator#getRangeCount()
*/
@Override
- public int getRangeCount() {
+ public int getRangeCount() {
return fLines.length;
}
@@ -134,7 +134,7 @@ public class LineComparator implements IRangeComparator {
* @see org.eclipse.compare.rangedifferencer.IRangeComparator#rangesEqual(int, org.eclipse.compare.rangedifferencer.IRangeComparator, int)
*/
@Override
- public boolean rangesEqual(int thisIndex, IRangeComparator other,
+ public boolean rangesEqual(int thisIndex, IRangeComparator other,
int otherIndex) {
String s1 = fLines[thisIndex];
String s2 = ((LineComparator) other).fLines[otherIndex];
@@ -145,7 +145,7 @@ public class LineComparator implements IRangeComparator {
* @see org.eclipse.compare.rangedifferencer.IRangeComparator#skipRangeComparison(int, int, org.eclipse.compare.rangedifferencer.IRangeComparator)
*/
@Override
- public boolean skipRangeComparison(int length, int maxLength, IRangeComparator other) {
+ public boolean skipRangeComparison(int length, int maxLength, IRangeComparator other) {
return false;
}
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/Messages.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/Messages.java
index b1c18c83fd..37171d613a 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/Messages.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/Messages.java
@@ -19,27 +19,27 @@ import java.util.ResourceBundle;
*/
public final class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.changelog.core.strings"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.changelog.core.strings"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE =
- ResourceBundle.getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE =
+ ResourceBundle.getBundle(BUNDLE_NAME);
- /**
- *
- */
- private Messages() {
- // It shouldn't be instantiated.
- }
- /**
- * Returns the message for the given key.
- * @param key The key of the message looking for.
- * @return The found message or "!key!" if no such key.
- */
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ /**
+ *
+ */
+ private Messages() {
+ // It shouldn't be instantiated.
+ }
+ /**
+ * Returns the message for the given key.
+ * @param key The key of the message looking for.
+ * @return The found message or "!key!" if no such key.
+ */
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogAction.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogAction.java
index c4b4f114d1..146b36e00f 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogAction.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogAction.java
@@ -53,294 +53,294 @@ import org.eclipse.ui.part.MultiPageEditorPart;
public abstract class ChangeLogAction extends Action {
- protected ChangeLogExtensionManager extensionManager = null;
-
- // Preference variables
- protected String pref_AuthorName;
-
- protected String pref_AuthorEmail;
-
- protected String pref_ChangeLogName = "ChangeLog"; // $NON-NLS-1$
-
- protected String pref_Formatter;
-
- // set selection here
- // selection can be either IEditorPart / IProject / IStructuredSelection
- // IEditorPart and IProject will be adapted to IStructuredSelection.
-
- public ChangeLogAction() {
- extensionManager = ChangeLogExtensionManager.getExtensionManager();
- }
-
- protected void reportErr(String msg, Exception e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, msg, e));
- }
-
- private IWorkspaceRoot getWorkspaceRoot() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
- protected IEditorPart openEditor(IFile diskresource) {
- IWorkbench ws = PlatformUI.getWorkbench();
-
- try {
- return org.eclipse.ui.ide.IDE.openEditor(ws
- .getActiveWorkbenchWindow().getActivePage(), diskresource,
- true);
- } catch (PartInitException e) {
- e.printStackTrace();
-
- return null;
- }
- }
-
- protected IFile createChangeLog(IPath changelog) {
- IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
- IWorkbench ws = PlatformUI.getWorkbench();
-
- final IFile changelog_File = myWorkspaceRoot.getFile(changelog);
- final InputStream initialContents = new ByteArrayInputStream(
- new byte[0]);
-
- WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
- @Override
- public void execute(IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(Messages.getString("ChangeLog.AddingChangeLog"), 2000); //$NON-NLS-1$
- changelog_File.create(initialContents, false, monitor);
-
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
-
- } finally {
- monitor.done();
- }
- }
- };
-
- try {
- new ProgressMonitorDialog(ws.getActiveWorkbenchWindow().getShell())
- .run(true, true, operation);
- } catch (InterruptedException e) {
- reportErr(Messages.getString("ChangeLog.ErrInterrupted"), e); // $NON-NLS-1$
- return null;
- } catch (InvocationTargetException e) {
- reportErr(Messages.getString("ChangeLog.ErrInvocation"), e); // $NON-NLS-1$
- return null;
- }
-
- // FIXME: we should put this refreshLocal call into a thread (filed as bug #256180)
- try {
- IContainer changelogContainer = myWorkspaceRoot.getContainerForLocation(changelog);
- if (changelogContainer != null)
- changelogContainer.refreshLocal(2, null);
- } catch (CoreException e) {
- reportErr(Messages.getString("ChangeLog.ErrRefresh"), e); // $NON-NLS-1$
- return null;
- }
-
- return changelog_File;
- }
-
- protected IEditorPart askChangeLogLocation(String editorLoc) {
- IWorkbench ws = PlatformUI.getWorkbench();
- IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
-
- IResource given_resource = myWorkspaceRoot.findMember(editorLoc);
-
- if (given_resource == null)
- return null;
-
- ChangeLogContainerSelectionDialog dialog = new ChangeLogContainerSelectionDialog(ws
- .getActiveWorkbenchWindow().getShell(), given_resource
- .getParent(), false, Messages
- .getString("AddAction.str_ChangeLog_Location")); //$NON-NLS-1$
- dialog.showClosedProjects(false);
-
- dialog.open();
-
- Object[] result = dialog.getResult();
- if (result == null)
- return null;
- final IPath result_path = new Path(result[0]
- + System.getProperty("file.separator") + pref_ChangeLogName); //$NON-NLS-1$ //$NON-NLS-2$
- IFile newChangeLog = createChangeLog(result_path);
-
- return openEditor(newChangeLog);
-
- }
-
- protected IEditorPart getChangelog(String currentEditorloc) {
- // Scenario 1: The Changelog is in in the current project file
- IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
- IResource given_resource = myWorkspaceRoot.findMember(currentEditorloc);
-
- if (given_resource != null) {
- IResource parent_dec = given_resource;
-
- while (parent_dec != null) {
- String parent_node = parent_dec.getFullPath()
- .removeLastSegments(1).toOSString();
- parent_node = parent_node
- + System.getProperty("file.separator") + pref_ChangeLogName; //$NON-NLS-1$
-
- IResource change_log_res = myWorkspaceRoot
- .findMember(parent_node);
-
- if (change_log_res != null) {
- IProject proj_loc = given_resource.getProject();
- IPath modified_changelog_path = change_log_res
- .getFullPath().removeFirstSegments(1);
- IFile change_log_file = proj_loc
- .getFile(modified_changelog_path);
-
- return openEditor(change_log_file);
- }
-
- parent_dec = parent_dec.getParent();
-
- if (parent_dec == null) {
- break;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Find the ChangeLog for a file that is being removed. It can't be found and
- * it is possible that the directory it is in has also been removed.
- *
- * @param path Path of removed file
- * @return ChangeLog editor part that must be used to report removed file
- */
- protected IEditorPart getChangelogForRemovePath(IPath path) {
- IResource parent_resource = null;
- IPath loc_path = path;
- // Look from current loc up to find first folder that is still existing
- IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
- while (loc_path.segmentCount() > 0) {
- parent_resource = myWorkspaceRoot.findMember(loc_path);
- if (parent_resource != null)
- break;
- loc_path = loc_path.removeLastSegments(1);
- }
-
- if (parent_resource != null) {
- IResource parent_dec = parent_resource;
-
- while (parent_dec != null) {
- String parent_node = parent_dec.getFullPath().toOSString();
- parent_node = parent_node
- + System.getProperty("file.separator") + pref_ChangeLogName; //$NON-NLS-1$
-
- IResource change_log_res = myWorkspaceRoot
- .findMember(parent_node);
-
- if (change_log_res != null) {
- IProject proj_loc = parent_resource.getProject();
- IPath modified_changelog_path = change_log_res
- .getFullPath().removeFirstSegments(1);
- IFile change_log_file = proj_loc
- .getFile(modified_changelog_path);
-
- return openEditor(change_log_file);
- }
-
- parent_dec = parent_dec.getParent();
-
- if (parent_dec == null) {
- break;
- }
- }
- }
-
- return null;
- }
-
- private IFile getDocumentIFile(IEditorPart currentEditor) {
- IEditorInput cc = currentEditor.getEditorInput();
-
- if (cc instanceof IFileEditorInput) {
- return ((IFileEditorInput) cc).getFile();
- }
- return null;
- }
-
- protected String getDocumentLocation(IEditorPart currentEditor,
- boolean appendRoot) {
-
-
- IFile loc = getDocumentIFile(currentEditor);
- IEditorInput cc = null;
- String WorkspaceRoot;
-
- IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
- WorkspaceRoot = myWorkspaceRoot.getLocation().toOSString();
-
- if (currentEditor instanceof MultiPageEditorPart) {
- Object ed = ((MultiPageEditorPart) currentEditor).getSelectedPage();
- if (ed instanceof IEditorPart)
- cc = ((IEditorPart) ed).getEditorInput();
- if (cc instanceof FileEditorInput)
- return (appendRoot) ? WorkspaceRoot + ((FileEditorInput) cc).getFile().getFullPath().toOSString() :
- ((FileEditorInput) cc).getFile().getFullPath().toOSString();
- }
-
- cc = currentEditor.getEditorInput();
-
-
- if (cc == null)
- return "";
-
- if ((cc instanceof SyncInfoCompareInput)
- || (cc instanceof CompareEditorInput)) {
-
- CompareEditorInput test = (CompareEditorInput) cc;
- if (test.getCompareResult() == null) {
- return "";
- } else if (test.getCompareResult() instanceof ICompareInput) {
- ITypedElement leftCompare = ((ICompareInput) test.getCompareResult())
- .getLeft();
- if (leftCompare instanceof IResourceProvider){
- String localPath = ((IResourceProvider)leftCompare).getResource().getFullPath().toString();
- if (appendRoot) {
- return WorkspaceRoot + localPath;
- }
- return localPath;
- }
- } else {
- if (appendRoot)
- return WorkspaceRoot + test.getCompareResult().toString();
- return test.getCompareResult().toString();
- }
- } else if (cc instanceof FileStoreEditorInput) {
- return ((FileStoreEditorInput)cc).getName();
- }
-
-
-
- if (appendRoot) {
- return WorkspaceRoot + loc.getFullPath().toOSString();
- } else if (loc != null) {
- return loc.getFullPath().toOSString();
- } else {
- return "";
- }
- }
-
- protected void loadPreferences() {
- IPreferenceStore store = ChangelogPlugin.getDefault()
- .getPreferenceStore();
-
- pref_AuthorName = store.getString("IChangeLogConstants.AUTHOR_NAME"); //$NON-NLS-1$
- pref_AuthorEmail = store.getString("IChangeLogConstants.AUTHOR_EMAIL"); //$NON-NLS-1$
-
- pref_Formatter = store
- .getString("IChangeLogConstants.DEFAULT_FORMATTER"); // $NON-NLS-1$
- }
+ protected ChangeLogExtensionManager extensionManager = null;
+
+ // Preference variables
+ protected String pref_AuthorName;
+
+ protected String pref_AuthorEmail;
+
+ protected String pref_ChangeLogName = "ChangeLog"; // $NON-NLS-1$
+
+ protected String pref_Formatter;
+
+ // set selection here
+ // selection can be either IEditorPart / IProject / IStructuredSelection
+ // IEditorPart and IProject will be adapted to IStructuredSelection.
+
+ public ChangeLogAction() {
+ extensionManager = ChangeLogExtensionManager.getExtensionManager();
+ }
+
+ protected void reportErr(String msg, Exception e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, msg, e));
+ }
+
+ private IWorkspaceRoot getWorkspaceRoot() {
+ return ResourcesPlugin.getWorkspace().getRoot();
+ }
+
+ protected IEditorPart openEditor(IFile diskresource) {
+ IWorkbench ws = PlatformUI.getWorkbench();
+
+ try {
+ return org.eclipse.ui.ide.IDE.openEditor(ws
+ .getActiveWorkbenchWindow().getActivePage(), diskresource,
+ true);
+ } catch (PartInitException e) {
+ e.printStackTrace();
+
+ return null;
+ }
+ }
+
+ protected IFile createChangeLog(IPath changelog) {
+ IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
+ IWorkbench ws = PlatformUI.getWorkbench();
+
+ final IFile changelog_File = myWorkspaceRoot.getFile(changelog);
+ final InputStream initialContents = new ByteArrayInputStream(
+ new byte[0]);
+
+ WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
+ @Override
+ public void execute(IProgressMonitor monitor) throws CoreException {
+ try {
+ monitor.beginTask(Messages.getString("ChangeLog.AddingChangeLog"), 2000); //$NON-NLS-1$
+ changelog_File.create(initialContents, false, monitor);
+
+ if (monitor.isCanceled()) {
+ throw new OperationCanceledException();
+ }
+
+ } finally {
+ monitor.done();
+ }
+ }
+ };
+
+ try {
+ new ProgressMonitorDialog(ws.getActiveWorkbenchWindow().getShell())
+ .run(true, true, operation);
+ } catch (InterruptedException e) {
+ reportErr(Messages.getString("ChangeLog.ErrInterrupted"), e); // $NON-NLS-1$
+ return null;
+ } catch (InvocationTargetException e) {
+ reportErr(Messages.getString("ChangeLog.ErrInvocation"), e); // $NON-NLS-1$
+ return null;
+ }
+
+ // FIXME: we should put this refreshLocal call into a thread (filed as bug #256180)
+ try {
+ IContainer changelogContainer = myWorkspaceRoot.getContainerForLocation(changelog);
+ if (changelogContainer != null)
+ changelogContainer.refreshLocal(2, null);
+ } catch (CoreException e) {
+ reportErr(Messages.getString("ChangeLog.ErrRefresh"), e); // $NON-NLS-1$
+ return null;
+ }
+
+ return changelog_File;
+ }
+
+ protected IEditorPart askChangeLogLocation(String editorLoc) {
+ IWorkbench ws = PlatformUI.getWorkbench();
+ IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
+
+ IResource given_resource = myWorkspaceRoot.findMember(editorLoc);
+
+ if (given_resource == null)
+ return null;
+
+ ChangeLogContainerSelectionDialog dialog = new ChangeLogContainerSelectionDialog(ws
+ .getActiveWorkbenchWindow().getShell(), given_resource
+ .getParent(), false, Messages
+ .getString("AddAction.str_ChangeLog_Location")); //$NON-NLS-1$
+ dialog.showClosedProjects(false);
+
+ dialog.open();
+
+ Object[] result = dialog.getResult();
+ if (result == null)
+ return null;
+ final IPath result_path = new Path(result[0]
+ + System.getProperty("file.separator") + pref_ChangeLogName); //$NON-NLS-1$ //$NON-NLS-2$
+ IFile newChangeLog = createChangeLog(result_path);
+
+ return openEditor(newChangeLog);
+
+ }
+
+ protected IEditorPart getChangelog(String currentEditorloc) {
+ // Scenario 1: The Changelog is in in the current project file
+ IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
+ IResource given_resource = myWorkspaceRoot.findMember(currentEditorloc);
+
+ if (given_resource != null) {
+ IResource parent_dec = given_resource;
+
+ while (parent_dec != null) {
+ String parent_node = parent_dec.getFullPath()
+ .removeLastSegments(1).toOSString();
+ parent_node = parent_node
+ + System.getProperty("file.separator") + pref_ChangeLogName; //$NON-NLS-1$
+
+ IResource change_log_res = myWorkspaceRoot
+ .findMember(parent_node);
+
+ if (change_log_res != null) {
+ IProject proj_loc = given_resource.getProject();
+ IPath modified_changelog_path = change_log_res
+ .getFullPath().removeFirstSegments(1);
+ IFile change_log_file = proj_loc
+ .getFile(modified_changelog_path);
+
+ return openEditor(change_log_file);
+ }
+
+ parent_dec = parent_dec.getParent();
+
+ if (parent_dec == null) {
+ break;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Find the ChangeLog for a file that is being removed. It can't be found and
+ * it is possible that the directory it is in has also been removed.
+ *
+ * @param path Path of removed file
+ * @return ChangeLog editor part that must be used to report removed file
+ */
+ protected IEditorPart getChangelogForRemovePath(IPath path) {
+ IResource parent_resource = null;
+ IPath loc_path = path;
+ // Look from current loc up to find first folder that is still existing
+ IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
+ while (loc_path.segmentCount() > 0) {
+ parent_resource = myWorkspaceRoot.findMember(loc_path);
+ if (parent_resource != null)
+ break;
+ loc_path = loc_path.removeLastSegments(1);
+ }
+
+ if (parent_resource != null) {
+ IResource parent_dec = parent_resource;
+
+ while (parent_dec != null) {
+ String parent_node = parent_dec.getFullPath().toOSString();
+ parent_node = parent_node
+ + System.getProperty("file.separator") + pref_ChangeLogName; //$NON-NLS-1$
+
+ IResource change_log_res = myWorkspaceRoot
+ .findMember(parent_node);
+
+ if (change_log_res != null) {
+ IProject proj_loc = parent_resource.getProject();
+ IPath modified_changelog_path = change_log_res
+ .getFullPath().removeFirstSegments(1);
+ IFile change_log_file = proj_loc
+ .getFile(modified_changelog_path);
+
+ return openEditor(change_log_file);
+ }
+
+ parent_dec = parent_dec.getParent();
+
+ if (parent_dec == null) {
+ break;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private IFile getDocumentIFile(IEditorPart currentEditor) {
+ IEditorInput cc = currentEditor.getEditorInput();
+
+ if (cc instanceof IFileEditorInput) {
+ return ((IFileEditorInput) cc).getFile();
+ }
+ return null;
+ }
+
+ protected String getDocumentLocation(IEditorPart currentEditor,
+ boolean appendRoot) {
+
+
+ IFile loc = getDocumentIFile(currentEditor);
+ IEditorInput cc = null;
+ String WorkspaceRoot;
+
+ IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
+ WorkspaceRoot = myWorkspaceRoot.getLocation().toOSString();
+
+ if (currentEditor instanceof MultiPageEditorPart) {
+ Object ed = ((MultiPageEditorPart) currentEditor).getSelectedPage();
+ if (ed instanceof IEditorPart)
+ cc = ((IEditorPart) ed).getEditorInput();
+ if (cc instanceof FileEditorInput)
+ return (appendRoot) ? WorkspaceRoot + ((FileEditorInput) cc).getFile().getFullPath().toOSString() :
+ ((FileEditorInput) cc).getFile().getFullPath().toOSString();
+ }
+
+ cc = currentEditor.getEditorInput();
+
+
+ if (cc == null)
+ return "";
+
+ if ((cc instanceof SyncInfoCompareInput)
+ || (cc instanceof CompareEditorInput)) {
+
+ CompareEditorInput test = (CompareEditorInput) cc;
+ if (test.getCompareResult() == null) {
+ return "";
+ } else if (test.getCompareResult() instanceof ICompareInput) {
+ ITypedElement leftCompare = ((ICompareInput) test.getCompareResult())
+ .getLeft();
+ if (leftCompare instanceof IResourceProvider){
+ String localPath = ((IResourceProvider)leftCompare).getResource().getFullPath().toString();
+ if (appendRoot) {
+ return WorkspaceRoot + localPath;
+ }
+ return localPath;
+ }
+ } else {
+ if (appendRoot)
+ return WorkspaceRoot + test.getCompareResult().toString();
+ return test.getCompareResult().toString();
+ }
+ } else if (cc instanceof FileStoreEditorInput) {
+ return ((FileStoreEditorInput)cc).getName();
+ }
+
+
+
+ if (appendRoot) {
+ return WorkspaceRoot + loc.getFullPath().toOSString();
+ } else if (loc != null) {
+ return loc.getFullPath().toOSString();
+ } else {
+ return "";
+ }
+ }
+
+ protected void loadPreferences() {
+ IPreferenceStore store = ChangelogPlugin.getDefault()
+ .getPreferenceStore();
+
+ pref_AuthorName = store.getString("IChangeLogConstants.AUTHOR_NAME"); //$NON-NLS-1$
+ pref_AuthorEmail = store.getString("IChangeLogConstants.AUTHOR_EMAIL"); //$NON-NLS-1$
+
+ pref_Formatter = store
+ .getString("IChangeLogConstants.DEFAULT_FORMATTER"); // $NON-NLS-1$
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerContentProvider.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerContentProvider.java
index eea4328865..c5f58846e5 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerContentProvider.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerContentProvider.java
@@ -39,21 +39,21 @@ public class ChangeLogContainerContentProvider implements ITreeContentProvider {
* to be disposed. Deallocate all allocated SWT resources.
*/
@Override
- public void dispose() {
+ public void dispose() {
}
/*
* @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
*/
@Override
- public Object[] getChildren(Object element) {
+ public Object[] getChildren(Object element) {
if (element instanceof IWorkspace) {
// check if closed projects should be shown
IProject[] allProjects = ((IWorkspace) element).getRoot()
.getProjects();
if (showClosedProjects) {
- return allProjects;
- }
+ return allProjects;
+ }
ArrayList<IProject> accessibleProjects = new ArrayList<>();
for (int i = 0; i < allProjects.length; i++) {
@@ -79,15 +79,15 @@ public class ChangeLogContainerContentProvider implements ITreeContentProvider {
}
}
} else if (element instanceof ChangeLogRootContainer) {
- ChangeLogRootContainer container = (ChangeLogRootContainer) element;
- List<IResource> children = new ArrayList<>();
- IResource[] members = container.members();
- for (int i = 0; i < members.length; i++) {
- if (members[i].getType() != IResource.FILE) {
- children.add(members[i]);
- }
- }
- return children.toArray();
+ ChangeLogRootContainer container = (ChangeLogRootContainer) element;
+ List<IResource> children = new ArrayList<>();
+ IResource[] members = container.members();
+ for (int i = 0; i < members.length; i++) {
+ if (members[i].getType() != IResource.FILE) {
+ children.add(members[i]);
+ }
+ }
+ return children.toArray();
}
return new Object[0];
}
@@ -96,7 +96,7 @@ public class ChangeLogContainerContentProvider implements ITreeContentProvider {
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
@Override
- public Object[] getElements(Object element) {
+ public Object[] getElements(Object element) {
return getChildren(element);
}
@@ -104,10 +104,10 @@ public class ChangeLogContainerContentProvider implements ITreeContentProvider {
* @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
*/
@Override
- public Object getParent(Object element) {
+ public Object getParent(Object element) {
if (element instanceof IResource) {
- return ((IResource) element).getParent();
- }
+ return ((IResource) element).getParent();
+ }
return null;
}
@@ -115,7 +115,7 @@ public class ChangeLogContainerContentProvider implements ITreeContentProvider {
* @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
*/
@Override
- public boolean hasChildren(Object element) {
+ public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
@@ -123,7 +123,7 @@ public class ChangeLogContainerContentProvider implements ITreeContentProvider {
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged
*/
@Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
/**
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerSelectionDialog.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerSelectionDialog.java
index 623e4a35df..22adc8abd1 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerSelectionDialog.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerSelectionDialog.java
@@ -40,20 +40,20 @@ import org.eclipse.ui.dialogs.SelectionDialog;
* <pre>
* ContainerSelectionDialog dialog =
* new ContainerSelectionDialog(getShell(), initialSelection, allowNewContainerName(), msg);
- * dialog.open();
- * Object[] result = dialog.getResult();
+ * dialog.open();
+ * Object[] result = dialog.getResult();
* </pre>
* </p>
* @noextend This class is not intended to be subclassed by clients.
*/
public class ChangeLogContainerSelectionDialog extends SelectionDialog {
- private static final String ContainerSelectionDialog_title = Messages.getString("ChangeLogContainerSelectionDialog.Title"); //$NON-NLS-1$
- private static final String ContainerSelectionDialog_message = Messages.getString("ChangeLogContainerSelectionDialog.Message"); //$NON-NLS-1$
- private static final String CONTAINER_SELECTION_DIALOG = "org.eclipse.ui.ide.container_selection_dialog_context"; //$NON-NLS-1$
+ private static final String ContainerSelectionDialog_title = Messages.getString("ChangeLogContainerSelectionDialog.Title"); //$NON-NLS-1$
+ private static final String ContainerSelectionDialog_message = Messages.getString("ChangeLogContainerSelectionDialog.Message"); //$NON-NLS-1$
+ private static final String CONTAINER_SELECTION_DIALOG = "org.eclipse.ui.ide.container_selection_dialog_context"; //$NON-NLS-1$
- // the widget group;
+ // the widget group;
ChangeLogContainerSelectionGroup group;
// the root resource to populate the viewer with
@@ -87,10 +87,10 @@ public class ChangeLogContainerSelectionDialog extends SelectionDialog {
this.initialSelection = initialRoot;
this.allowNewContainerName = allowNewContainerName;
if (message != null) {
- setMessage(message);
- } else {
- setMessage(ContainerSelectionDialog_message);
- }
+ setMessage(message);
+ } else {
+ setMessage(ContainerSelectionDialog_message);
+ }
setShellStyle(getShellStyle() | SWT.SHEET);
}
@@ -98,7 +98,7 @@ public class ChangeLogContainerSelectionDialog extends SelectionDialog {
* Method declared in Window.
*/
@Override
- protected void configureShell(Shell shell) {
+ protected void configureShell(Shell shell) {
super.configureShell(shell);
PlatformUI.getWorkbench().getHelpSystem()
.setHelp(shell, CONTAINER_SELECTION_DIALOG);
@@ -108,7 +108,7 @@ public class ChangeLogContainerSelectionDialog extends SelectionDialog {
* Method declared on Dialog.
*/
@Override
- protected Control createDialogArea(Composite parent) {
+ protected Control createDialogArea(Composite parent) {
// create composite
Composite area = (Composite) super.createDialogArea(parent);
@@ -133,13 +133,13 @@ public class ChangeLogContainerSelectionDialog extends SelectionDialog {
* for later retrieval by the client and closes this dialog.
*/
@Override
- protected void okPressed() {
+ protected void okPressed() {
List<IPath> chosenContainerPathList = new ArrayList<>();
IPath returnValue = group.getContainerFullPath();
if (returnValue != null) {
- chosenContainerPathList.add(returnValue);
- }
+ chosenContainerPathList.add(returnValue);
+ }
setResult(chosenContainerPathList);
super.okPressed();
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerSelectionGroup.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerSelectionGroup.java
index 7eff5a9fce..ad914b66ca 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerSelectionGroup.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogContainerSelectionGroup.java
@@ -8,8 +8,8 @@
* Contributors:
* IBM Corporation - initial API and implementation
* Igor Fedorenko <igorfie@yahoo.com> -
- * Fix for Bug 136921 [IDE] New File dialog locks for 20 seconds
- * Red Hat Inc. - modified this file to work with ChangeLog Plugin
+ * Fix for Bug 136921 [IDE] New File dialog locks for 20 seconds
+ * Red Hat Inc. - modified this file to work with ChangeLog Plugin
*******************************************************************************/
package org.eclipse.linuxtools.internal.changelog.core.actions;
@@ -46,262 +46,262 @@ import org.eclipse.ui.part.DrillDownComposite;
* Workbench-level composite for choosing a container.
*/
public class ChangeLogContainerSelectionGroup extends Composite {
- // The listener to notify of events
- private Listener listener;
+ // The listener to notify of events
+ private Listener listener;
- // Enable user to type in new container name
- private boolean allowNewContainerName = true;
+ // Enable user to type in new container name
+ private boolean allowNewContainerName = true;
- // show all projects by default
- private boolean showClosedProjects = true;
+ // show all projects by default
+ private boolean showClosedProjects = true;
- // Last selection made by user
- private IContainer selectedContainer;
+ // Last selection made by user
+ private IContainer selectedContainer;
- // handle on parts
- private Text containerNameField;
+ // handle on parts
+ private Text containerNameField;
- TreeViewer treeViewer;
+ TreeViewer treeViewer;
- private IContainer initialSelection;
+ private IContainer initialSelection;
- // the message to display at the top of this dialog
- private static final String DEFAULT_MSG_NEW_ALLOWED = Messages.getString("ChangeLogContainerSelectionGroup.DefaultMessageNewAllowed"); //$NON-NLS-1$
+ // the message to display at the top of this dialog
+ private static final String DEFAULT_MSG_NEW_ALLOWED = Messages.getString("ChangeLogContainerSelectionGroup.DefaultMessageNewAllowed"); //$NON-NLS-1$
- private static final String DEFAULT_MSG_SELECT_ONLY = Messages.getString("ChangeLogContainerSelectionGroup.DefaultMessageSelectOnly"); //$NON-NLS-1$
+ private static final String DEFAULT_MSG_SELECT_ONLY = Messages.getString("ChangeLogContainerSelectionGroup.DefaultMessageSelectOnly"); //$NON-NLS-1$
- // sizing constants
- private static final int SIZING_SELECTION_PANE_WIDTH = 320;
+ // sizing constants
+ private static final int SIZING_SELECTION_PANE_WIDTH = 320;
- private static final int SIZING_SELECTION_PANE_HEIGHT = 300;
+ private static final int SIZING_SELECTION_PANE_HEIGHT = 300;
- /**
- * Creates a new instance of the widget.
- *
- * @param parent
- * The parent widget of the group.
- * @param allowNewContainerName
- * Enable the user to type in a new container name instead of
- * just selecting from the existing ones.
- * @param message
- * The text to present to the user.
- * @param showClosedProjects
- * Whether or not to show closed projects.
- */
- public ChangeLogContainerSelectionGroup(Composite parent, boolean allowNewContainerName, String message,
- boolean showClosedProjects, IContainer initialSelection) {
- this(parent, allowNewContainerName, message,
- showClosedProjects, SIZING_SELECTION_PANE_HEIGHT,
- SIZING_SELECTION_PANE_WIDTH, initialSelection);
- }
+ /**
+ * Creates a new instance of the widget.
+ *
+ * @param parent
+ * The parent widget of the group.
+ * @param allowNewContainerName
+ * Enable the user to type in a new container name instead of
+ * just selecting from the existing ones.
+ * @param message
+ * The text to present to the user.
+ * @param showClosedProjects
+ * Whether or not to show closed projects.
+ */
+ public ChangeLogContainerSelectionGroup(Composite parent, boolean allowNewContainerName, String message,
+ boolean showClosedProjects, IContainer initialSelection) {
+ this(parent, allowNewContainerName, message,
+ showClosedProjects, SIZING_SELECTION_PANE_HEIGHT,
+ SIZING_SELECTION_PANE_WIDTH, initialSelection);
+ }
- /**
- * Creates a new instance of the widget.
- *
- * @param parent
- * The parent widget of the group.
- * @param allowNewContainerName
- * Enable the user to type in a new container name instead of
- * just selecting from the existing ones.
- * @param message
- * The text to present to the user.
- * @param showClosedProjects
- * Whether or not to show closed projects.
- * @param heightHint
- * height hint for the drill down composite
- * @param widthHint
- * width hint for the drill down composite
- */
- public ChangeLogContainerSelectionGroup(Composite parent,
- boolean allowNewContainerName, String message,
- boolean showClosedProjects, int heightHint, int widthHint, IContainer initialSelection) {
- super(parent, SWT.NONE);
- this.allowNewContainerName = allowNewContainerName;
- this.showClosedProjects = showClosedProjects;
- this.initialSelection = initialSelection;
- if (message != null) {
- createContents(message, heightHint, widthHint);
- } else if (allowNewContainerName) {
- createContents(DEFAULT_MSG_NEW_ALLOWED, heightHint, widthHint);
- } else {
- createContents(DEFAULT_MSG_SELECT_ONLY, heightHint, widthHint);
- }
- }
+ /**
+ * Creates a new instance of the widget.
+ *
+ * @param parent
+ * The parent widget of the group.
+ * @param allowNewContainerName
+ * Enable the user to type in a new container name instead of
+ * just selecting from the existing ones.
+ * @param message
+ * The text to present to the user.
+ * @param showClosedProjects
+ * Whether or not to show closed projects.
+ * @param heightHint
+ * height hint for the drill down composite
+ * @param widthHint
+ * width hint for the drill down composite
+ */
+ public ChangeLogContainerSelectionGroup(Composite parent,
+ boolean allowNewContainerName, String message,
+ boolean showClosedProjects, int heightHint, int widthHint, IContainer initialSelection) {
+ super(parent, SWT.NONE);
+ this.allowNewContainerName = allowNewContainerName;
+ this.showClosedProjects = showClosedProjects;
+ this.initialSelection = initialSelection;
+ if (message != null) {
+ createContents(message, heightHint, widthHint);
+ } else if (allowNewContainerName) {
+ createContents(DEFAULT_MSG_NEW_ALLOWED, heightHint, widthHint);
+ } else {
+ createContents(DEFAULT_MSG_SELECT_ONLY, heightHint, widthHint);
+ }
+ }
- /**
- * The container selection has changed in the tree view. Update the
- * container name field value and notify all listeners.
- *
- * @param container
- * The container that changed
- */
- public void containerSelectionChanged(IContainer container) {
- selectedContainer = container;
+ /**
+ * The container selection has changed in the tree view. Update the
+ * container name field value and notify all listeners.
+ *
+ * @param container
+ * The container that changed
+ */
+ public void containerSelectionChanged(IContainer container) {
+ selectedContainer = container;
- if (allowNewContainerName) {
- if (container == null) {
- containerNameField.setText("");//$NON-NLS-1$
- } else {
- String text = TextProcessor.process(container.getFullPath()
- .makeRelative().toString());
- containerNameField.setText(text);
- containerNameField.setToolTipText(text);
- }
- }
+ if (allowNewContainerName) {
+ if (container == null) {
+ containerNameField.setText("");//$NON-NLS-1$
+ } else {
+ String text = TextProcessor.process(container.getFullPath()
+ .makeRelative().toString());
+ containerNameField.setText(text);
+ containerNameField.setToolTipText(text);
+ }
+ }
- // fire an event so the parent can update its controls
- if (listener != null) {
- Event changeEvent = new Event();
- changeEvent.type = SWT.Selection;
- changeEvent.widget = this;
- listener.handleEvent(changeEvent);
- }
- }
+ // fire an event so the parent can update its controls
+ if (listener != null) {
+ Event changeEvent = new Event();
+ changeEvent.type = SWT.Selection;
+ changeEvent.widget = this;
+ listener.handleEvent(changeEvent);
+ }
+ }
- /**
- * Creates the contents of the composite.
- *
- * @param message message
- */
- public void createContents(String message) {
- createContents(message, SIZING_SELECTION_PANE_HEIGHT,
- SIZING_SELECTION_PANE_WIDTH);
- }
+ /**
+ * Creates the contents of the composite.
+ *
+ * @param message message
+ */
+ public void createContents(String message) {
+ createContents(message, SIZING_SELECTION_PANE_HEIGHT,
+ SIZING_SELECTION_PANE_WIDTH);
+ }
- /**
- * Creates the contents of the composite.
- *
- * @param message message
- * @param heightHint height hint for the drill down composite
- * @param widthHint specifies the perfered width in pixels
- */
- private void createContents(String message, int heightHint, int widthHint) {
- GridLayout layout = new GridLayout();
- layout.marginWidth = 0;
- setLayout(layout);
- setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ /**
+ * Creates the contents of the composite.
+ *
+ * @param message message
+ * @param heightHint height hint for the drill down composite
+ * @param widthHint specifies the perfered width in pixels
+ */
+ private void createContents(String message, int heightHint, int widthHint) {
+ GridLayout layout = new GridLayout();
+ layout.marginWidth = 0;
+ setLayout(layout);
+ setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Label label = new Label(this, SWT.WRAP);
- label.setText(message);
- label.setFont(this.getFont());
+ Label label = new Label(this, SWT.WRAP);
+ label.setText(message);
+ label.setFont(this.getFont());
- if (allowNewContainerName) {
- containerNameField = new Text(this, SWT.SINGLE | SWT.BORDER);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.widthHint = widthHint;
- containerNameField.setLayoutData(gd);
- containerNameField.addListener(SWT.Modify, listener);
- containerNameField.setFont(this.getFont());
- } else {
- // filler...
- new Label(this, SWT.NONE);
- }
+ if (allowNewContainerName) {
+ containerNameField = new Text(this, SWT.SINGLE | SWT.BORDER);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.widthHint = widthHint;
+ containerNameField.setLayoutData(gd);
+ containerNameField.addListener(SWT.Modify, listener);
+ containerNameField.setFont(this.getFont());
+ } else {
+ // filler...
+ new Label(this, SWT.NONE);
+ }
- createTreeViewer(heightHint);
- Dialog.applyDialogFont(this);
- }
+ createTreeViewer(heightHint);
+ Dialog.applyDialogFont(this);
+ }
- /**
- * Returns a new drill down viewer for this dialog.
- *
- * @param heightHint
- * height hint for the drill down composite
- */
- private void createTreeViewer(int heightHint) {
- // Create drill down.
- DrillDownComposite drillDown = new DrillDownComposite(this, SWT.BORDER);
- GridData spec = new GridData(SWT.FILL, SWT.FILL, true, true);
- spec.widthHint = SIZING_SELECTION_PANE_WIDTH;
- spec.heightHint = heightHint;
- drillDown.setLayoutData(spec);
+ /**
+ * Returns a new drill down viewer for this dialog.
+ *
+ * @param heightHint
+ * height hint for the drill down composite
+ */
+ private void createTreeViewer(int heightHint) {
+ // Create drill down.
+ DrillDownComposite drillDown = new DrillDownComposite(this, SWT.BORDER);
+ GridData spec = new GridData(SWT.FILL, SWT.FILL, true, true);
+ spec.widthHint = SIZING_SELECTION_PANE_WIDTH;
+ spec.heightHint = heightHint;
+ drillDown.setLayoutData(spec);
- // Create tree viewer inside drill down.
- treeViewer = new TreeViewer(drillDown, SWT.NONE);
- drillDown.setChildTree(treeViewer);
- ChangeLogContainerContentProvider cp = new ChangeLogContainerContentProvider();
- cp.showClosedProjects(showClosedProjects);
- treeViewer.setContentProvider(cp);
- treeViewer.setLabelProvider(WorkbenchLabelProvider
- .getDecoratingWorkbenchLabelProvider());
- treeViewer.setComparator(new ViewerComparator());
- treeViewer.setUseHashlookup(true);
- treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- IStructuredSelection selection = (IStructuredSelection) event
- .getSelection();
- containerSelectionChanged((IContainer) selection
- .getFirstElement()); // allow null
- }
- });
- treeViewer.addDoubleClickListener(new IDoubleClickListener() {
- @Override
- public void doubleClick(DoubleClickEvent event) {
- ISelection selection = event.getSelection();
- if (selection instanceof IStructuredSelection) {
- Object item = ((IStructuredSelection) selection)
- .getFirstElement();
- if (item == null) {
- return;
- }
- if (treeViewer.getExpandedState(item)) {
- treeViewer.collapseToLevel(item, 1);
- } else {
- treeViewer.expandToLevel(item, 1);
- }
- }
- }
- });
+ // Create tree viewer inside drill down.
+ treeViewer = new TreeViewer(drillDown, SWT.NONE);
+ drillDown.setChildTree(treeViewer);
+ ChangeLogContainerContentProvider cp = new ChangeLogContainerContentProvider();
+ cp.showClosedProjects(showClosedProjects);
+ treeViewer.setContentProvider(cp);
+ treeViewer.setLabelProvider(WorkbenchLabelProvider
+ .getDecoratingWorkbenchLabelProvider());
+ treeViewer.setComparator(new ViewerComparator());
+ treeViewer.setUseHashlookup(true);
+ treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ IStructuredSelection selection = (IStructuredSelection) event
+ .getSelection();
+ containerSelectionChanged((IContainer) selection
+ .getFirstElement()); // allow null
+ }
+ });
+ treeViewer.addDoubleClickListener(new IDoubleClickListener() {
+ @Override
+ public void doubleClick(DoubleClickEvent event) {
+ ISelection selection = event.getSelection();
+ if (selection instanceof IStructuredSelection) {
+ Object item = ((IStructuredSelection) selection)
+ .getFirstElement();
+ if (item == null) {
+ return;
+ }
+ if (treeViewer.getExpandedState(item)) {
+ treeViewer.collapseToLevel(item, 1);
+ } else {
+ treeViewer.expandToLevel(item, 1);
+ }
+ }
+ }
+ });
- /*
- * This helps in displaying all folders under the document
- * root as well as the actual root itself.
- */
- ChangeLogRootContainer root = new ChangeLogRootContainer(this.initialSelection.getProject());
- // This has to be done after the viewer has been laid out
- treeViewer.setInput(root);
- }
+ /*
+ * This helps in displaying all folders under the document
+ * root as well as the actual root itself.
+ */
+ ChangeLogRootContainer root = new ChangeLogRootContainer(this.initialSelection.getProject());
+ // This has to be done after the viewer has been laid out
+ treeViewer.setInput(root);
+ }
- /**
- * Returns the currently entered container name. Null if the field is empty.
- * Note that the container may not exist yet if the user entered a new
- * container name in the field.
- *
- * @return IPath
- */
- public IPath getContainerFullPath() {
- if (allowNewContainerName) {
- String pathName = containerNameField.getText();
- if (pathName == null || pathName.isEmpty()) {
- return null;
- }
- // The user may not have made this absolute so do it for them
- return (new Path(TextProcessor.deprocess(pathName))).makeAbsolute();
+ /**
+ * Returns the currently entered container name. Null if the field is empty.
+ * Note that the container may not exist yet if the user entered a new
+ * container name in the field.
+ *
+ * @return IPath
+ */
+ public IPath getContainerFullPath() {
+ if (allowNewContainerName) {
+ String pathName = containerNameField.getText();
+ if (pathName == null || pathName.isEmpty()) {
+ return null;
+ }
+ // The user may not have made this absolute so do it for them
+ return (new Path(TextProcessor.deprocess(pathName))).makeAbsolute();
- }
- if (selectedContainer == null) {
- return null;
- }
- return selectedContainer.getFullPath();
+ }
+ if (selectedContainer == null) {
+ return null;
+ }
+ return selectedContainer.getFullPath();
- }
+ }
- /**
- * Sets the selected existing container.
- *
- * @param container container to set
- */
- public void setSelectedContainer(IContainer container) {
- selectedContainer = container;
+ /**
+ * Sets the selected existing container.
+ *
+ * @param container container to set
+ */
+ public void setSelectedContainer(IContainer container) {
+ selectedContainer = container;
- // expand to and select the specified container
- List<IContainer> itemsToExpand = new ArrayList<>();
- IContainer parent = container.getParent();
- while (parent != null) {
- itemsToExpand.add(0, parent);
- parent = parent.getParent();
- }
- treeViewer.setExpandedElements(itemsToExpand.toArray());
- treeViewer.setSelection(new StructuredSelection(container), true);
- }
+ // expand to and select the specified container
+ List<IContainer> itemsToExpand = new ArrayList<>();
+ IContainer parent = container.getParent();
+ while (parent != null) {
+ itemsToExpand.add(0, parent);
+ parent = parent.getParent();
+ }
+ treeViewer.setExpandedElements(itemsToExpand.toArray());
+ treeViewer.setSelection(new StructuredSelection(container), true);
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogRootContainer.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogRootContainer.java
index 4c2a064468..a3a0facb85 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogRootContainer.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/ChangeLogRootContainer.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -15,13 +15,13 @@ import org.eclipse.core.resources.IResource;
public class ChangeLogRootContainer {
- private IProject proj;
-
- public ChangeLogRootContainer(IProject project) {
- proj = project;
- }
+ private IProject proj;
- public IResource[] members() {
- return new IResource[]{proj};
- }
+ public ChangeLogRootContainer(IProject project) {
+ proj = project;
+ }
+
+ public IResource[] members() {
+ return new IResource[]{proj};
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/FormatChangeLogAction.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/FormatChangeLogAction.java
index 89e90b71b5..60de2ddf38 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/FormatChangeLogAction.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/FormatChangeLogAction.java
@@ -21,19 +21,19 @@ import org.eclipse.ui.handlers.HandlerUtil;
public class FormatChangeLogAction extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) {
- ChangeLogEditor editor = (ChangeLogEditor) HandlerUtil.getActiveEditor(event);
- if (editor == null)
- return null;
+ @Override
+ public Object execute(ExecutionEvent event) {
+ ChangeLogEditor editor = (ChangeLogEditor) HandlerUtil.getActiveEditor(event);
+ if (editor == null)
+ return null;
- SourceViewer srcViewer = (SourceViewer)editor.getMySourceViewer();
- if (srcViewer != null) {
- srcViewer.doOperation(ISourceViewer.FORMAT);
+ SourceViewer srcViewer = (SourceViewer)editor.getMySourceViewer();
+ if (srcViewer != null) {
+ srcViewer.doOperation(ISourceViewer.FORMAT);
- }
+ }
- return null;
- }
+ return null;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/InsertChangeLogKeyHandler.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/InsertChangeLogKeyHandler.java
index e01fd26fbc..0ade53ef82 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/InsertChangeLogKeyHandler.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/InsertChangeLogKeyHandler.java
@@ -32,179 +32,179 @@ import org.eclipse.ui.handlers.HandlerUtil;
* @author pmuldoon (Phil Muldoon)
*/
public class InsertChangeLogKeyHandler extends ChangeLogAction implements
- IHandler, IWorkbenchWindowActionDelegate {
-
- private IEditorPart currentEditor;
-
- private String getEditorName() {
- if (currentEditor != null)
- return returnQualifedEditor(currentEditor.getClass());
- else
- return "";
-
- }
-
- private String getEntryFilePath() {
- if (currentEditor != null)
- return getDocumentLocation(currentEditor, false);
- else
- return "";
- }
-
- private String returnQualifedEditor(Class<?> ClassName) {
- return ClassName.toString().substring(
- ClassName.getPackage().toString().length() - 1,
- ClassName.toString().length());
- }
+ IHandler, IWorkbenchWindowActionDelegate {
+
+ private IEditorPart currentEditor;
+
+ private String getEditorName() {
+ if (currentEditor != null)
+ return returnQualifedEditor(currentEditor.getClass());
+ else
+ return "";
+
+ }
+
+ private String getEntryFilePath() {
+ if (currentEditor != null)
+ return getDocumentLocation(currentEditor, false);
+ else
+ return "";
+ }
+
+ private String returnQualifedEditor(Class<?> ClassName) {
+ return ClassName.toString().substring(
+ ClassName.getPackage().toString().length() - 1,
+ ClassName.toString().length());
+ }
- private IEditorPart getChangelog() {
-
- IConfigurationElement formatterConfigElement = extensionManager
- .getFormatterConfigElement();
- if (formatterConfigElement.getAttribute("inFile").equalsIgnoreCase(
- "true")) {
- return currentEditor;
- // this formatter wants to use an external changelog file
- } else {
- IEditorPart changelog = null;
+ private IEditorPart getChangelog() {
+
+ IConfigurationElement formatterConfigElement = extensionManager
+ .getFormatterConfigElement();
+ if (formatterConfigElement.getAttribute("inFile").equalsIgnoreCase(
+ "true")) {
+ return currentEditor;
+ // this formatter wants to use an external changelog file
+ } else {
+ IEditorPart changelog = null;
- IConfigurationElement nameElement = formatterConfigElement
- .getChildren()[0];
- if (nameElement.getAttribute("name") == null) {
- reportErr("Got non-name child with inFile set to False", null);
- return null;
- } else {
- pref_ChangeLogName = nameElement.getAttribute("name");
- changelog = getChangelog(getDocumentLocation(currentEditor,
- false));
-
- if (changelog == null) {
- changelog = askChangeLogLocation(getDocumentLocation(
- currentEditor, false));
- }
-
- return changelog;
- }
- }
-
- }
+ IConfigurationElement nameElement = formatterConfigElement
+ .getChildren()[0];
+ if (nameElement.getAttribute("name") == null) {
+ reportErr("Got non-name child with inFile set to False", null);
+ return null;
+ } else {
+ pref_ChangeLogName = nameElement.getAttribute("name");
+ changelog = getChangelog(getDocumentLocation(currentEditor,
+ false));
+
+ if (changelog == null) {
+ changelog = askChangeLogLocation(getDocumentLocation(
+ currentEditor, false));
+ }
+
+ return changelog;
+ }
+ }
+
+ }
- private String parseFunctionName(IParserChangeLogContrib parser) {
+ private String parseFunctionName(IParserChangeLogContrib parser) {
- try {
- return parser.parseCurrentFunction(currentEditor);
- } catch (CoreException e) {
- reportErr("Couldn't parse function name with "
- + parser.getClass().toString(), null);
- return "";
- }
+ try {
+ return parser.parseCurrentFunction(currentEditor);
+ } catch (CoreException e) {
+ reportErr("Couldn't parse function name with "
+ + parser.getClass().toString(), null);
+ return "";
+ }
- }
+ }
- @Override
- public Object execute(ExecutionEvent event) {
+ @Override
+ public Object execute(ExecutionEvent event) {
- currentEditor = HandlerUtil.getActiveEditor(event);
+ currentEditor = HandlerUtil.getActiveEditor(event);
- // make sure an editor is selected.
- if (currentEditor == null) {
- return null;
- }
+ // make sure an editor is selected.
+ if (currentEditor == null) {
+ return null;
+ }
- ChangeLogWriter clw = new ChangeLogWriter();
+ ChangeLogWriter clw = new ChangeLogWriter();
- // load settings from extensions + user pref.
- loadPreferences();
+ // load settings from extensions + user pref.
+ loadPreferences();
- // get file path from target file
- clw.setEntryFilePath(getEntryFilePath());
+ // get file path from target file
+ clw.setEntryFilePath(getEntryFilePath());
- // err check. do nothing if no file is being open/edited
- if (clw.getEntryFilePath() == "") {
- return null;
- }
+ // err check. do nothing if no file is being open/edited
+ if (clw.getEntryFilePath() == "") {
+ return null;
+ }
- String editorName = getEditorName();
+ String editorName = getEditorName();
- // get a parser for this file
- IParserChangeLogContrib parser = extensionManager
- .getParserContributor(editorName);
+ // get a parser for this file
+ IParserChangeLogContrib parser = extensionManager
+ .getParserContributor(editorName);
- // if no parser for this type of document, then don't guess function
- // name
- // and set it as "".
- if (parser == null) {
- clw.setGuessedFName("");
- } else {
- // guess function name
- clw.setGuessedFName(parseFunctionName(parser));
- }
+ // if no parser for this type of document, then don't guess function
+ // name
+ // and set it as "".
+ if (parser == null) {
+ clw.setGuessedFName("");
+ } else {
+ // guess function name
+ clw.setGuessedFName(parseFunctionName(parser));
+ }
- // get formatter
- clw.setFormatter(extensionManager.getFormatterContributor(clw
- .getEntryFilePath(), pref_Formatter));
+ // get formatter
+ clw.setFormatter(extensionManager.getFormatterContributor(clw
+ .getEntryFilePath(), pref_Formatter));
- // select changelog
- clw.setChangelog(getChangelog());
- if (clw.getChangelog() == null)
- return null;
+ // select changelog
+ clw.setChangelog(getChangelog());
+ if (clw.getChangelog() == null)
+ return null;
- // write to changelog
- clw.setDateLine(clw.getFormatter().formatDateLine(pref_AuthorName,
- pref_AuthorEmail));
+ // write to changelog
+ clw.setDateLine(clw.getFormatter().formatDateLine(pref_AuthorName,
+ pref_AuthorEmail));
- clw.setChangelogLocation(getDocumentLocation(clw.getChangelog(), true));
+ clw.setChangelogLocation(getDocumentLocation(clw.getChangelog(), true));
- clw.writeChangeLog();
+ clw.writeChangeLog();
- return null;
- }
+ return null;
+ }
- @Override
- public void addHandlerListener(IHandlerListener handlerListener) {
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
- }
+ }
- @Override
- public boolean isEnabled() {
- IEditorReference[] refs = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences();
- for (int i = 0; i < refs.length; ++i) {
- IEditorReference ref = refs[i];
- String id = ref.getId();
- System.out.println(id);
- }
- return true;
- }
+ @Override
+ public boolean isEnabled() {
+ IEditorReference[] refs = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences();
+ for (int i = 0; i < refs.length; ++i) {
+ IEditorReference ref = refs[i];
+ String id = ref.getId();
+ System.out.println(id);
+ }
+ return true;
+ }
- @Override
- public boolean isHandled() {
- return true;
- }
+ @Override
+ public boolean isHandled() {
+ return true;
+ }
- @Override
- public void removeHandlerListener(IHandlerListener handlerListener) {
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
- }
+ }
- @Override
- public void dispose() {
+ @Override
+ public void dispose() {
- }
+ }
- @Override
- public void init(IWorkbenchWindow window) {
+ @Override
+ public void init(IWorkbenchWindow window) {
- }
+ }
- @Override
- public void run(IAction action) {
+ @Override
+ public void run(IAction action) {
- execute(null);
- }
+ execute(null);
+ }
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
+ @Override
+ public void selectionChanged(IAction action, ISelection selection) {
- }
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchFile.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchFile.java
index 3743a2553b..eb6cb83514 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchFile.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchFile.java
@@ -27,127 +27,127 @@ import org.eclipse.core.runtime.IPath;
*/
public class PatchFile {
- private static class EmptyStorage implements IStorage {
+ private static class EmptyStorage implements IStorage {
- public EmptyStorage() {
- }
+ public EmptyStorage() {
+ }
- @Override
- public InputStream getContents() {
- return new ByteArrayInputStream(new byte[0]);
- }
+ @Override
+ public InputStream getContents() {
+ return new ByteArrayInputStream(new byte[0]);
+ }
- @Override
- public IPath getFullPath() {
- return null;
- }
+ @Override
+ public IPath getFullPath() {
+ return null;
+ }
- @Override
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- @Override
- public String getName() {
- return "__emptyStorage__";
- }
-
- @Override
- public boolean isReadOnly() {
- return true;
- }
- }
-
- private IStorage storage = new EmptyStorage();
- private ArrayList<PatchRangeElement> pranges = new ArrayList<>();
-
- private boolean newfile = false;
- private boolean removedfile = false;
- private IResource resource; // required only if dealing with change
-
-
- public boolean isNewfile() {
- return newfile;
- }
-
- public void setNewfile(boolean newfile) {
- this.newfile = newfile;
- }
-
- public boolean isRemovedFile() {
- return removedfile;
- }
-
- public void setRemovedFile(boolean removedfile) {
- this.removedfile = removedfile;
- }
-
- public PatchFile(IResource resource) {
- this.resource = resource;
- }
-
- public void addLineRange(int from, int to, boolean localChange) {
-
- pranges.add(new PatchRangeElement(from, to, localChange));
- }
-
- public PatchRangeElement[] getRanges() {
- Object[] tmpEle = pranges.toArray();
- PatchRangeElement[] ret = new PatchRangeElement[tmpEle.length];
-
- for (int i = 0; i < tmpEle.length; i++) {
- ret[i] = (PatchRangeElement) tmpEle[i];
- }
- return ret;
- }
-
-
- public IPath getPath() {
- return resource.getFullPath();
- }
-
- public IStorage getStorage() {
- return storage;
- }
-
- public void setStorage(IStorage storage) {
- this.storage = storage;
- }
-
- public IResource getResource() {
- return resource;
- }
-
- @Override
- public boolean equals(Object o) {
-
- if (!(o instanceof PatchFile))
- return false;
-
- PatchFile that = (PatchFile) o;
- // check fpath + count
- if (!this.resource.equals(that.resource) ||
- this.pranges.size() != that.pranges.size() ) {
- return false;
- }
-
- // check range elements
- PatchRangeElement[] thatsrange = that.getRanges();
-
- for(int i=0; i<this.pranges.size();i++) {
- if (!thatsrange[i].equals(pranges.get(i))) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- int hash = resource.hashCode();
- for(int i=0; i<this.pranges.size();i++) {
- hash += pranges.get(i).hashCode();
- }
- return hash;
- }
+ @Override
+ public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
+ return null;
+ }
+
+ @Override
+ public String getName() {
+ return "__emptyStorage__";
+ }
+
+ @Override
+ public boolean isReadOnly() {
+ return true;
+ }
+ }
+
+ private IStorage storage = new EmptyStorage();
+ private ArrayList<PatchRangeElement> pranges = new ArrayList<>();
+
+ private boolean newfile = false;
+ private boolean removedfile = false;
+ private IResource resource; // required only if dealing with change
+
+
+ public boolean isNewfile() {
+ return newfile;
+ }
+
+ public void setNewfile(boolean newfile) {
+ this.newfile = newfile;
+ }
+
+ public boolean isRemovedFile() {
+ return removedfile;
+ }
+
+ public void setRemovedFile(boolean removedfile) {
+ this.removedfile = removedfile;
+ }
+
+ public PatchFile(IResource resource) {
+ this.resource = resource;
+ }
+
+ public void addLineRange(int from, int to, boolean localChange) {
+
+ pranges.add(new PatchRangeElement(from, to, localChange));
+ }
+
+ public PatchRangeElement[] getRanges() {
+ Object[] tmpEle = pranges.toArray();
+ PatchRangeElement[] ret = new PatchRangeElement[tmpEle.length];
+
+ for (int i = 0; i < tmpEle.length; i++) {
+ ret[i] = (PatchRangeElement) tmpEle[i];
+ }
+ return ret;
+ }
+
+
+ public IPath getPath() {
+ return resource.getFullPath();
+ }
+
+ public IStorage getStorage() {
+ return storage;
+ }
+
+ public void setStorage(IStorage storage) {
+ this.storage = storage;
+ }
+
+ public IResource getResource() {
+ return resource;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+
+ if (!(o instanceof PatchFile))
+ return false;
+
+ PatchFile that = (PatchFile) o;
+ // check fpath + count
+ if (!this.resource.equals(that.resource) ||
+ this.pranges.size() != that.pranges.size() ) {
+ return false;
+ }
+
+ // check range elements
+ PatchRangeElement[] thatsrange = that.getRanges();
+
+ for(int i=0; i<this.pranges.size();i++) {
+ if (!thatsrange[i].equals(pranges.get(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = resource.hashCode();
+ for(int i=0; i<this.pranges.size();i++) {
+ hash += pranges.get(i).hashCode();
+ }
+ return hash;
+ }
} \ No newline at end of file
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchFileComparator.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchFileComparator.java
index 4d7cee7af2..e6100d48b2 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchFileComparator.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchFileComparator.java
@@ -14,9 +14,9 @@ import java.util.Comparator;
public class PatchFileComparator implements Comparator<PatchFile> {
- @Override
- public int compare(PatchFile p1, PatchFile p2) {
- return p1.getResource().getLocation().toOSString().compareToIgnoreCase(p2.getResource().getLocation().toOSString());
- }
+ @Override
+ public int compare(PatchFile p1, PatchFile p2) {
+ return p1.getResource().getLocation().toOSString().compareToIgnoreCase(p2.getResource().getLocation().toOSString());
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchRangeElement.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchRangeElement.java
index 2c91eee410..73a2432ec5 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchRangeElement.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PatchRangeElement.java
@@ -18,32 +18,32 @@ package org.eclipse.linuxtools.internal.changelog.core.actions;
*/
public class PatchRangeElement {
- public int fromLine;
- public int toLine;
- private boolean localChange;
+ public int fromLine;
+ public int toLine;
+ private boolean localChange;
- public PatchRangeElement(int from, int to, boolean localChange) {
- this.fromLine =from;
- this.toLine= to;
- this.localChange = localChange;
- }
+ public PatchRangeElement(int from, int to, boolean localChange) {
+ this.fromLine =from;
+ this.toLine= to;
+ this.localChange = localChange;
+ }
- public boolean isLocalChange() {
- return localChange;
- }
+ public boolean isLocalChange() {
+ return localChange;
+ }
- @Override
- public boolean equals(Object o) {
- if (o instanceof PatchRangeElement) {
- PatchRangeElement b = (PatchRangeElement)o;
- return b.fromLine == fromLine && b.toLine == toLine && b.localChange == localChange;
- }
- else
- return this == o;
- }
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof PatchRangeElement) {
+ PatchRangeElement b = (PatchRangeElement)o;
+ return b.fromLine == fromLine && b.toLine == toLine && b.localChange == localChange;
+ }
+ else
+ return this == o;
+ }
- @Override
- public int hashCode() {
- return fromLine + toLine + (localChange ? 47 : 83);
- }
+ @Override
+ public int hashCode() {
+ return fromLine + toLine + (localChange ? 47 : 83);
+ }
} \ No newline at end of file
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareChangeLogAction.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareChangeLogAction.java
index dbf91b80da..b3ee36ba1e 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareChangeLogAction.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareChangeLogAction.java
@@ -76,522 +76,522 @@ import org.eclipse.ui.part.FileEditorInput;
*/
public class PrepareChangeLogAction extends ChangeLogAction {
- protected boolean changeLogModified = false;
- protected boolean newEntryWritten = false;
- protected boolean createChangeLog = true;
-
- private static class MyDocumentProvider extends FileDocumentProvider {
-
- @Override
- public IDocument createDocument(Object element) throws CoreException {
- return super.createDocument(element);
- }
- }
-
- private static class MyStorageDocumentProvider extends StorageDocumentProvider {
-
- @Override
- public IDocument createDocument(Object element) throws CoreException {
- return super.createDocument(element);
- }
- }
-
- private IStructuredSelection selected;
-
- public PrepareChangeLogAction() {
- super();
- }
-
- protected void setSelection(IStructuredSelection selection) {
- this.selected = selection;
- }
-
- private String parseCurrentFunctionAtOffset(String editorName,
- IEditorInput input, int offset) {
-
- IParserChangeLogContrib parser = extensionManager
- .getParserContributor(editorName);
-
- // return empty string if function parser for editorName is not present
- if (parser==null)
- return "";
-
- try {
- return parser.parseCurrentFunction(input, offset);
- } catch (CoreException e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
- .getMessage(), e));
- }
- return "";
- }
-
- /**
- * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
- */
- protected void doRun() {
- IRunnableWithProgress code = new IRunnableWithProgress() {
-
- @Override
- public void run(IProgressMonitor monitor) {
- monitor.beginTask(Messages.getString("ChangeLog.PrepareChangeLog"), 1000); // $NON-NLS-1$
- prepareChangeLog(monitor);
- monitor.done();
- }
- };
-
- ProgressMonitorDialog pd = new ProgressMonitorDialog(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getShell());
-
- try {
- pd.run(false /* fork */, false /* cancelable */, code);
- } catch (InvocationTargetException e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
- .getMessage(), e));
- return;
- } catch (InterruptedException e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
- .getMessage(), e));
- }
- }
-
- private void extractSynchronizeModelInfo (ISynchronizeModelElement d, IPath path, Vector<PatchFile> newList, Vector<PatchFile> removeList, Vector<PatchFile> changeList) {
- // Recursively traverse the tree for children and sort leaf elements into their respective change kind sets.
- // Don't add entries for ChangeLog files though.
- if (d.hasChildren()) {
- IPath newPath = path.append(d.getName());
- for (IDiffElement element: d.getChildren()) {
- if (element instanceof ISynchronizeModelElement)
- extractSynchronizeModelInfo((ISynchronizeModelElement)element, newPath, newList, removeList, changeList);
- else {
- if (!(d.getName().equals("ChangeLog"))) { //$NON-NLS-1$
- PatchFile p = new PatchFile(d.getResource());
- int kind = d.getKind() & Differencer.CHANGE_TYPE_MASK;
- if (kind == Differencer.CHANGE) {
- changeList.add(p);
- } else if (kind == Differencer.ADDITION) {
- p.setNewfile(true);
- newList.add(p);
- } else if (kind == Differencer.DELETION) {
- p.setRemovedFile(true);
- removeList.add(p);
- }
- } else {
- this.changeLogModified = true;
- }
- }
- }
- } else {
- if (!(d.getName().equals("ChangeLog"))) { //$NON-NLS-1$
- PatchFile p = new PatchFile(d.getResource());
- int kind = d.getKind() & Differencer.CHANGE_TYPE_MASK;
- if (kind == Differencer.CHANGE) {
- changeList.add(p);
- } else if (kind == Differencer.ADDITION) {
- p.setNewfile(true);
- newList.add(p);
- } else if (kind == Differencer.DELETION) {
- p.setRemovedFile(true);
- removeList.add(p);
- }
- } else {
- this.changeLogModified = true;
- }
- }
- }
-
- private void getChangedLines(Subscriber s, PatchFile p, IProgressMonitor monitor) {
- try {
- // For an outgoing changed resource, find out which lines
- // differ from the local file and its previous local version
- // (i.e. we don't want to force a diff with the repository).
- IDiff d = s.getDiff(p.getResource());
- if (d instanceof IThreeWayDiff
- && ((IThreeWayDiff)d).getDirection() == IThreeWayDiff.OUTGOING) {
- IThreeWayDiff diff = (IThreeWayDiff)d;
- monitor.beginTask(null, 100);
- IResourceDiff localDiff = (IResourceDiff)diff.getLocalChange();
- IResource resource = localDiff.getResource();
- if (resource instanceof IFile) {
- IFile file = (IFile)resource;
- monitor.subTask(Messages.getString("ChangeLog.MergingDiffs")); // $NON-NLS-1$
- String osEncoding = file.getCharset();
- IFileRevision ancestorState = localDiff.getBeforeState();
- IStorage ancestorStorage;
- if (ancestorState != null) {
- ancestorStorage = ancestorState.getStorage(monitor);
- p.setStorage(ancestorStorage);
- }
- else {
- return;
- }
-
- try {
- // We compare using a standard differencer to get ranges
- // of changes. We modify them to be document-based (i.e.
- // first line is line 1) and store them for later parsing.
- LineComparator left = new LineComparator(ancestorStorage.getContents(), osEncoding);
- LineComparator right = new LineComparator(file.getContents(), osEncoding);
- for (RangeDifference tmp: RangeDifferencer.findDifferences(left, right)) {
- if (tmp.kind() == RangeDifference.CHANGE) {
- // Right side of diff are all changes found in local file.
- int rightLength = tmp.rightLength() > 0 ? tmp.rightLength() : tmp.rightLength() + 1;
- // We also want to store left side of the diff which are changes to the ancestor as it may contain
- // functions/methods that have been removed.
- int leftLength = tmp.leftLength() > 0 ? tmp.leftLength() : tmp.leftLength() + 1;
- // Only store left side changes if the storage exists and we add one to the start line number
- if (p.getStorage() != null)
- p.addLineRange(tmp.leftStart(), tmp.leftStart() + leftLength, false);
- p.addLineRange(tmp.rightStart(), tmp.rightStart() + rightLength, true);
- }
- }
- } catch (UnsupportedEncodingException e) {
- // do nothing for now
- }
- }
- monitor.done();
- }
- } catch (CoreException e) {
- // Do nothing if error occurs
- }
- }
-
- private void prepareChangeLog(IProgressMonitor monitor) {
-
- Object element = selected.getFirstElement();
-
- IResource resource = null;
- Vector<PatchFile> newList = new Vector<>();
- Vector<PatchFile> removeList = new Vector<>();
- Vector<PatchFile> changeList = new Vector<>();
- int totalChanges = 0;
-
- if (element instanceof IResource) {
- resource = (IResource)element;
- } else if (element instanceof ISynchronizeModelElement) {
- ISynchronizeModelElement sme = (ISynchronizeModelElement)element;
- resource = sme.getResource();
- } else if (element instanceof IAdaptable) {
- resource = (IResource)((IAdaptable)element).getAdapter(IResource.class);
- }
-
- if (resource == null)
- return;
-
- IProject project = resource.getProject();
- // Get the repository provider so we can support multiple types of
- // code repositories without knowing exactly which (e.g. CVS, SVN, etc..).
- RepositoryProvider r = RepositoryProvider.getProvider(project);
- if (r == null)
- return;
- SyncInfoSet set = new SyncInfoSet();
- Subscriber s = r.getSubscriber();
- if (s == null)
- return;
- if (element instanceof ISynchronizeModelElement) {
- // We can extract the ChangeLog list from the synchronize view which
- // allows us to skip items removed from the view
- ISynchronizeModelElement d = (ISynchronizeModelElement)element;
- while (d.getParent() != null)
- d = (ISynchronizeModelElement)d.getParent();
- extractSynchronizeModelInfo(d, new Path(""), newList, removeList, changeList);
- totalChanges = newList.size() + removeList.size() + changeList.size();
- }
- else {
- // We can then get a list of all out-of-sync resources.
- s.collectOutOfSync(new IResource[] {project}, IResource.DEPTH_INFINITE, set, monitor);
- SyncInfo[] infos = set.getSyncInfos();
- totalChanges = infos.length;
- // Iterate through the list of changed resources and categorize them into
- // New, Removed, and Changed lists.
- for (SyncInfo info : infos) {
- int kind = SyncInfo.getChange(info.getKind());
- PatchFile p = new PatchFile(info.getLocal());
-
- // Check the type of entry and sort into lists. Do not add an entry
- // for ChangeLog files.
- if (!(p.getPath().lastSegment().equals("ChangeLog"))) { // $NON-NLS-1$
- switch (kind) {
- case SyncInfo.ADDITION:
- p.setNewfile(true);
- newList.add(p);
- break;
- case SyncInfo.DELETION:
- p.setRemovedFile(true);
- removeList.add(p);
- break;
- case SyncInfo.CHANGE:
- if (info.getLocal().getType() == IResource.FILE) {
- changeList.add(p);
- }
- break;
- }
- } else {
- this.changeLogModified = true;
- }
- }
- }
-
- if (totalChanges == 0)
- return; // nothing to parse
-
- PatchFile[] patchFileInfoList = new PatchFile[totalChanges];
-
- // Group like changes together and sort them by path name.
- // We want removed files, then new files, then changed files.
- // To get this, we put them in the array in reverse order.
- int index = 0;
- if (changeList.size() > 0) {
- // Get the repository provider so we can support multiple types of
- // code repositories without knowing exactly which (e.g. CVS, SVN, etc..).
- Collections.sort(changeList, new PatchFileComparator());
- int size = changeList.size();
- for (int i = 0; i < size; ++i) {
- PatchFile p = changeList.get(i);
- getChangedLines(s, p, monitor);
- patchFileInfoList[index+(size-i-1)] = p;
- }
- index += size;
- }
-
- if (newList.size() > 0) {
- Collections.sort(newList, new PatchFileComparator());
- int size = newList.size();
- for (int i = 0; i < size; ++i)
- patchFileInfoList[index+(size-i-1)] = newList.get(i);
- index += size;
- }
-
- if (removeList.size() > 0) {
- Collections.sort(removeList, new PatchFileComparator());
- int size = removeList.size();
- for (int i = 0; i < size; ++i)
- patchFileInfoList[index+(size-i-1)] = removeList.get(i);
- }
-
- // now, find out modified functions/classes.
- // try to use the the extension point. so it can be extended easily
- // for all files in patch file info list, get function guesses of each
- // file.
- monitor.subTask(Messages.getString("ChangeLog.WritingMessage")); // $NON-NLS-1$
- int unitwork = 250 / patchFileInfoList.length;
- for (PatchFile pf: patchFileInfoList) {
- // for each file
- if (pf != null) { // any ChangeLog changes will have null entries for them
- String[] funcGuessList = guessFunctionNames(pf);
- outputMultipleEntryChangeLog(pf, funcGuessList);
- }
- monitor.worked(unitwork);
- }
- }
-
- private void outputMultipleEntryChangeLog(PatchFile pf, String[] functionGuess) {
-
- String defaultContent = null;
-
- if (pf.isNewfile())
- defaultContent = Messages.getString("ChangeLog.NewFile"); // $NON-NLS-1$
- else if (pf.isRemovedFile())
- defaultContent = Messages.getString("ChangeLog.RemovedFile"); // $NON-NLS-1$
-
- IPath entryPath = pf.getPath();
- String entryFileName = entryPath.toOSString();
-
- ChangeLogWriter clw = new ChangeLogWriter();
-
- // load settings from extensions + user pref.
- loadPreferences();
-
- // get file path from target file
- clw.setEntryFilePath(entryPath.toOSString());
-
- if (defaultContent != null)
- clw.setDefaultContent(defaultContent);
-
- // err check. do nothing if no file is being open/edited
- if (clw.getEntryFilePath() == "") {
- return;
- }
-
- // Check if formatter is internal or inline..if inline, use the
- // current active editor part, otherwise, we must find the external
- // ChangeLog file.
- IEditorPart changelog = null;
-
- // Before accessing the getFormatterConfigElement, the getFormatContibutor
- // method must be called to initialize.
- extensionManager.getFormatterContributor(clw.getEntryFilePath(),
- pref_Formatter);
- IConfigurationElement formatterConfigElement = extensionManager
+ protected boolean changeLogModified = false;
+ protected boolean newEntryWritten = false;
+ protected boolean createChangeLog = true;
+
+ private static class MyDocumentProvider extends FileDocumentProvider {
+
+ @Override
+ public IDocument createDocument(Object element) throws CoreException {
+ return super.createDocument(element);
+ }
+ }
+
+ private static class MyStorageDocumentProvider extends StorageDocumentProvider {
+
+ @Override
+ public IDocument createDocument(Object element) throws CoreException {
+ return super.createDocument(element);
+ }
+ }
+
+ private IStructuredSelection selected;
+
+ public PrepareChangeLogAction() {
+ super();
+ }
+
+ protected void setSelection(IStructuredSelection selection) {
+ this.selected = selection;
+ }
+
+ private String parseCurrentFunctionAtOffset(String editorName,
+ IEditorInput input, int offset) {
+
+ IParserChangeLogContrib parser = extensionManager
+ .getParserContributor(editorName);
+
+ // return empty string if function parser for editorName is not present
+ if (parser==null)
+ return "";
+
+ try {
+ return parser.parseCurrentFunction(input, offset);
+ } catch (CoreException e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
+ .getMessage(), e));
+ }
+ return "";
+ }
+
+ /**
+ * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
+ */
+ protected void doRun() {
+ IRunnableWithProgress code = new IRunnableWithProgress() {
+
+ @Override
+ public void run(IProgressMonitor monitor) {
+ monitor.beginTask(Messages.getString("ChangeLog.PrepareChangeLog"), 1000); // $NON-NLS-1$
+ prepareChangeLog(monitor);
+ monitor.done();
+ }
+ };
+
+ ProgressMonitorDialog pd = new ProgressMonitorDialog(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getShell());
+
+ try {
+ pd.run(false /* fork */, false /* cancelable */, code);
+ } catch (InvocationTargetException e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
+ .getMessage(), e));
+ return;
+ } catch (InterruptedException e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
+ .getMessage(), e));
+ }
+ }
+
+ private void extractSynchronizeModelInfo (ISynchronizeModelElement d, IPath path, Vector<PatchFile> newList, Vector<PatchFile> removeList, Vector<PatchFile> changeList) {
+ // Recursively traverse the tree for children and sort leaf elements into their respective change kind sets.
+ // Don't add entries for ChangeLog files though.
+ if (d.hasChildren()) {
+ IPath newPath = path.append(d.getName());
+ for (IDiffElement element: d.getChildren()) {
+ if (element instanceof ISynchronizeModelElement)
+ extractSynchronizeModelInfo((ISynchronizeModelElement)element, newPath, newList, removeList, changeList);
+ else {
+ if (!(d.getName().equals("ChangeLog"))) { //$NON-NLS-1$
+ PatchFile p = new PatchFile(d.getResource());
+ int kind = d.getKind() & Differencer.CHANGE_TYPE_MASK;
+ if (kind == Differencer.CHANGE) {
+ changeList.add(p);
+ } else if (kind == Differencer.ADDITION) {
+ p.setNewfile(true);
+ newList.add(p);
+ } else if (kind == Differencer.DELETION) {
+ p.setRemovedFile(true);
+ removeList.add(p);
+ }
+ } else {
+ this.changeLogModified = true;
+ }
+ }
+ }
+ } else {
+ if (!(d.getName().equals("ChangeLog"))) { //$NON-NLS-1$
+ PatchFile p = new PatchFile(d.getResource());
+ int kind = d.getKind() & Differencer.CHANGE_TYPE_MASK;
+ if (kind == Differencer.CHANGE) {
+ changeList.add(p);
+ } else if (kind == Differencer.ADDITION) {
+ p.setNewfile(true);
+ newList.add(p);
+ } else if (kind == Differencer.DELETION) {
+ p.setRemovedFile(true);
+ removeList.add(p);
+ }
+ } else {
+ this.changeLogModified = true;
+ }
+ }
+ }
+
+ private void getChangedLines(Subscriber s, PatchFile p, IProgressMonitor monitor) {
+ try {
+ // For an outgoing changed resource, find out which lines
+ // differ from the local file and its previous local version
+ // (i.e. we don't want to force a diff with the repository).
+ IDiff d = s.getDiff(p.getResource());
+ if (d instanceof IThreeWayDiff
+ && ((IThreeWayDiff)d).getDirection() == IThreeWayDiff.OUTGOING) {
+ IThreeWayDiff diff = (IThreeWayDiff)d;
+ monitor.beginTask(null, 100);
+ IResourceDiff localDiff = (IResourceDiff)diff.getLocalChange();
+ IResource resource = localDiff.getResource();
+ if (resource instanceof IFile) {
+ IFile file = (IFile)resource;
+ monitor.subTask(Messages.getString("ChangeLog.MergingDiffs")); // $NON-NLS-1$
+ String osEncoding = file.getCharset();
+ IFileRevision ancestorState = localDiff.getBeforeState();
+ IStorage ancestorStorage;
+ if (ancestorState != null) {
+ ancestorStorage = ancestorState.getStorage(monitor);
+ p.setStorage(ancestorStorage);
+ }
+ else {
+ return;
+ }
+
+ try {
+ // We compare using a standard differencer to get ranges
+ // of changes. We modify them to be document-based (i.e.
+ // first line is line 1) and store them for later parsing.
+ LineComparator left = new LineComparator(ancestorStorage.getContents(), osEncoding);
+ LineComparator right = new LineComparator(file.getContents(), osEncoding);
+ for (RangeDifference tmp: RangeDifferencer.findDifferences(left, right)) {
+ if (tmp.kind() == RangeDifference.CHANGE) {
+ // Right side of diff are all changes found in local file.
+ int rightLength = tmp.rightLength() > 0 ? tmp.rightLength() : tmp.rightLength() + 1;
+ // We also want to store left side of the diff which are changes to the ancestor as it may contain
+ // functions/methods that have been removed.
+ int leftLength = tmp.leftLength() > 0 ? tmp.leftLength() : tmp.leftLength() + 1;
+ // Only store left side changes if the storage exists and we add one to the start line number
+ if (p.getStorage() != null)
+ p.addLineRange(tmp.leftStart(), tmp.leftStart() + leftLength, false);
+ p.addLineRange(tmp.rightStart(), tmp.rightStart() + rightLength, true);
+ }
+ }
+ } catch (UnsupportedEncodingException e) {
+ // do nothing for now
+ }
+ }
+ monitor.done();
+ }
+ } catch (CoreException e) {
+ // Do nothing if error occurs
+ }
+ }
+
+ private void prepareChangeLog(IProgressMonitor monitor) {
+
+ Object element = selected.getFirstElement();
+
+ IResource resource = null;
+ Vector<PatchFile> newList = new Vector<>();
+ Vector<PatchFile> removeList = new Vector<>();
+ Vector<PatchFile> changeList = new Vector<>();
+ int totalChanges = 0;
+
+ if (element instanceof IResource) {
+ resource = (IResource)element;
+ } else if (element instanceof ISynchronizeModelElement) {
+ ISynchronizeModelElement sme = (ISynchronizeModelElement)element;
+ resource = sme.getResource();
+ } else if (element instanceof IAdaptable) {
+ resource = (IResource)((IAdaptable)element).getAdapter(IResource.class);
+ }
+
+ if (resource == null)
+ return;
+
+ IProject project = resource.getProject();
+ // Get the repository provider so we can support multiple types of
+ // code repositories without knowing exactly which (e.g. CVS, SVN, etc..).
+ RepositoryProvider r = RepositoryProvider.getProvider(project);
+ if (r == null)
+ return;
+ SyncInfoSet set = new SyncInfoSet();
+ Subscriber s = r.getSubscriber();
+ if (s == null)
+ return;
+ if (element instanceof ISynchronizeModelElement) {
+ // We can extract the ChangeLog list from the synchronize view which
+ // allows us to skip items removed from the view
+ ISynchronizeModelElement d = (ISynchronizeModelElement)element;
+ while (d.getParent() != null)
+ d = (ISynchronizeModelElement)d.getParent();
+ extractSynchronizeModelInfo(d, new Path(""), newList, removeList, changeList);
+ totalChanges = newList.size() + removeList.size() + changeList.size();
+ }
+ else {
+ // We can then get a list of all out-of-sync resources.
+ s.collectOutOfSync(new IResource[] {project}, IResource.DEPTH_INFINITE, set, monitor);
+ SyncInfo[] infos = set.getSyncInfos();
+ totalChanges = infos.length;
+ // Iterate through the list of changed resources and categorize them into
+ // New, Removed, and Changed lists.
+ for (SyncInfo info : infos) {
+ int kind = SyncInfo.getChange(info.getKind());
+ PatchFile p = new PatchFile(info.getLocal());
+
+ // Check the type of entry and sort into lists. Do not add an entry
+ // for ChangeLog files.
+ if (!(p.getPath().lastSegment().equals("ChangeLog"))) { // $NON-NLS-1$
+ switch (kind) {
+ case SyncInfo.ADDITION:
+ p.setNewfile(true);
+ newList.add(p);
+ break;
+ case SyncInfo.DELETION:
+ p.setRemovedFile(true);
+ removeList.add(p);
+ break;
+ case SyncInfo.CHANGE:
+ if (info.getLocal().getType() == IResource.FILE) {
+ changeList.add(p);
+ }
+ break;
+ }
+ } else {
+ this.changeLogModified = true;
+ }
+ }
+ }
+
+ if (totalChanges == 0)
+ return; // nothing to parse
+
+ PatchFile[] patchFileInfoList = new PatchFile[totalChanges];
+
+ // Group like changes together and sort them by path name.
+ // We want removed files, then new files, then changed files.
+ // To get this, we put them in the array in reverse order.
+ int index = 0;
+ if (changeList.size() > 0) {
+ // Get the repository provider so we can support multiple types of
+ // code repositories without knowing exactly which (e.g. CVS, SVN, etc..).
+ Collections.sort(changeList, new PatchFileComparator());
+ int size = changeList.size();
+ for (int i = 0; i < size; ++i) {
+ PatchFile p = changeList.get(i);
+ getChangedLines(s, p, monitor);
+ patchFileInfoList[index+(size-i-1)] = p;
+ }
+ index += size;
+ }
+
+ if (newList.size() > 0) {
+ Collections.sort(newList, new PatchFileComparator());
+ int size = newList.size();
+ for (int i = 0; i < size; ++i)
+ patchFileInfoList[index+(size-i-1)] = newList.get(i);
+ index += size;
+ }
+
+ if (removeList.size() > 0) {
+ Collections.sort(removeList, new PatchFileComparator());
+ int size = removeList.size();
+ for (int i = 0; i < size; ++i)
+ patchFileInfoList[index+(size-i-1)] = removeList.get(i);
+ }
+
+ // now, find out modified functions/classes.
+ // try to use the the extension point. so it can be extended easily
+ // for all files in patch file info list, get function guesses of each
+ // file.
+ monitor.subTask(Messages.getString("ChangeLog.WritingMessage")); // $NON-NLS-1$
+ int unitwork = 250 / patchFileInfoList.length;
+ for (PatchFile pf: patchFileInfoList) {
+ // for each file
+ if (pf != null) { // any ChangeLog changes will have null entries for them
+ String[] funcGuessList = guessFunctionNames(pf);
+ outputMultipleEntryChangeLog(pf, funcGuessList);
+ }
+ monitor.worked(unitwork);
+ }
+ }
+
+ private void outputMultipleEntryChangeLog(PatchFile pf, String[] functionGuess) {
+
+ String defaultContent = null;
+
+ if (pf.isNewfile())
+ defaultContent = Messages.getString("ChangeLog.NewFile"); // $NON-NLS-1$
+ else if (pf.isRemovedFile())
+ defaultContent = Messages.getString("ChangeLog.RemovedFile"); // $NON-NLS-1$
+
+ IPath entryPath = pf.getPath();
+ String entryFileName = entryPath.toOSString();
+
+ ChangeLogWriter clw = new ChangeLogWriter();
+
+ // load settings from extensions + user pref.
+ loadPreferences();
+
+ // get file path from target file
+ clw.setEntryFilePath(entryPath.toOSString());
+
+ if (defaultContent != null)
+ clw.setDefaultContent(defaultContent);
+
+ // err check. do nothing if no file is being open/edited
+ if (clw.getEntryFilePath() == "") {
+ return;
+ }
+
+ // Check if formatter is internal or inline..if inline, use the
+ // current active editor part, otherwise, we must find the external
+ // ChangeLog file.
+ IEditorPart changelog = null;
+
+ // Before accessing the getFormatterConfigElement, the getFormatContibutor
+ // method must be called to initialize.
+ extensionManager.getFormatterContributor(clw.getEntryFilePath(),
+ pref_Formatter);
+ IConfigurationElement formatterConfigElement = extensionManager
.getFormatterConfigElement();
- if (formatterConfigElement.getAttribute("inFile").equalsIgnoreCase( //$NON-NLS-1$
- "true")) { //$NON-NLS-1$
- try {
- changelog = openEditor((IFile)pf.getResource());
- clw.setFormatter(extensionManager.getFormatterContributor(
- clw.getEntryFilePath(), pref_Formatter));
- } catch (Exception e) {
- // do nothing changelog will be null
- }
- } else {
- // external changelog
- // get formatter
- clw.setFormatter(extensionManager.getFormatterContributor(
- entryFileName, pref_Formatter));
-
- if (pf.isRemovedFile())
- changelog = getChangelogForRemovePath(entryPath);
- else
- changelog = getChangelog(entryFileName);
-
- // If there isn't a ChangeLog, we will ask for one here.
- // We originally avoided this to prevent a problem for rpm
- // projects whereby the changelog is inlined in a single file
- // and not presented externally. This has been changed in
- // response to bug #347703. If the user cancels the ask
- // dialog, then the prepare operation doesn't try to create
- // one.
- if (createChangeLog && changelog == null)
- changelog = askChangeLogLocation(entryPath.toOSString());
- if (changelog == null) {
- createChangeLog = false;
- return;
- }
- }
- if ((changelog instanceof ChangeLogEditor) && (!this.newEntryWritten)) {
- ChangeLogEditor editor = (ChangeLogEditor) changelog;
- // if the editor is dirty (changes added to the editor without
- // saving), treat it as a change log modification
- if (editor.isDirty())
- this.changeLogModified = true;
- editor.setForceNewLogEntry(!this.changeLogModified);
- this.newEntryWritten = true;
- }
- // select changelog
- clw.setChangelog(changelog);
-
- // write to changelog
- IFormatterChangeLogContrib formatter = clw.getFormatter();
- clw.setDateLine(formatter.formatDateLine(pref_AuthorName,
- pref_AuthorEmail));
-
- clw.setChangelogLocation(getDocumentLocation(clw.getChangelog(), true));
-
- // print multiple changelog entries with different
- // function guess names. We default to an empty guessed name
- // if we have zero function guess names.
- int numFuncs = 0;
- clw.setGuessedFName(""); // $NON-NLS-1$
- if (functionGuess.length > 0) {
- for (String guess : functionGuess) {
- if (!guess.trim().equals("")) { // $NON-NLS-1$
- ++numFuncs;
- clw.setGuessedFName(guess);
- clw.writeChangeLog();
- }
- }
- }
- // Default an empty entry if we did not have any none-empty
- // function guesses.
- if (numFuncs == 0) {
- clw.writeChangeLog();
- }
-
- }
-
-
- /**
- * Guesses the function effected/modified by the patch from local file(newer
- * file).
- *
- * @param patchFileInfo
- * patch file
- * @return array of unique function names
- */
- private String[] guessFunctionNames(PatchFile patchFileInfo) {
-
-
- // if this file is new file or removed file, do not guess function files
- // TODO: create an option to include function names on
- // new files or not
- if (patchFileInfo.isNewfile() || patchFileInfo.isRemovedFile()) {
- return new String[]{""};
- }
-
- String[] fnames = new String[0];
- String editorName = ""; // $NON-NLS-1$
-
- try {
- IEditorDescriptor ed = org.eclipse.ui.ide.IDE
- .getEditorDescriptor(patchFileInfo.getPath().toOSString());
- editorName = ed.getId().substring(ed.getId().lastIndexOf(".") + 1); // $NON-NLS-1$
- } catch (PartInitException e1) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR,
- e1.getMessage(), e1));
- return new String[0];
- }
-
- // check if the file type is supported
-
- // get editor input for target file
-
- IFileEditorInput fei = new FileEditorInput((IFile)patchFileInfo.getResource());
-
- SourceEditorInput sei = new SourceEditorInput(patchFileInfo.getStorage());
-
- MyDocumentProvider mdp = new MyDocumentProvider();
- MyStorageDocumentProvider msdp = new MyStorageDocumentProvider();
-
- try {
- // get document for target file (one for local file, one for repository storage)
- IDocument doc = mdp.createDocument(fei);
- IDocument olddoc = msdp.createDocument(sei);
-
- HashMap<String, String> functionNamesMap = new HashMap<>();
- ArrayList<String> nameList = new ArrayList<>();
-
- // for all the ranges
- for (PatchRangeElement tpre: patchFileInfo.getRanges()) {
-
- for (int j = tpre.fromLine; j <= tpre.toLine; j++) {
-
- String functionGuess = "";
- // add func that determines type of file.
- // right now it assumes it's java file.
- if (tpre.isLocalChange()) {
- if ((j < 0) || (j > doc.getNumberOfLines() - 1))
- continue; // ignore out of bound lines
- functionGuess = parseCurrentFunctionAtOffset(
- editorName, fei, doc.getLineOffset(j));
- } else {
- if ((j < 0) || (j > olddoc.getNumberOfLines() - 1))
- continue; // ignore out of bound lines
- functionGuess = parseCurrentFunctionAtOffset(
- editorName, sei, olddoc.getLineOffset(j));
- }
-
- // putting it in hashmap will eliminate duplicate
- // guesses. We use a list to keep track of ordering which
- // is helpful when trying to document a large set of changes.
- if (functionNamesMap.get(functionGuess) == null)
- nameList.add(functionGuess);
- functionNamesMap.put(functionGuess, functionGuess);
- }
- }
-
- // dump all unique func. guesses in the order found
- fnames = new String[nameList.size()];
- fnames = nameList.toArray(fnames);
-
- } catch (CoreException|BadLocationException e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR,
- e.getMessage(), e));
- }
- return fnames;
- }
+ if (formatterConfigElement.getAttribute("inFile").equalsIgnoreCase( //$NON-NLS-1$
+ "true")) { //$NON-NLS-1$
+ try {
+ changelog = openEditor((IFile)pf.getResource());
+ clw.setFormatter(extensionManager.getFormatterContributor(
+ clw.getEntryFilePath(), pref_Formatter));
+ } catch (Exception e) {
+ // do nothing changelog will be null
+ }
+ } else {
+ // external changelog
+ // get formatter
+ clw.setFormatter(extensionManager.getFormatterContributor(
+ entryFileName, pref_Formatter));
+
+ if (pf.isRemovedFile())
+ changelog = getChangelogForRemovePath(entryPath);
+ else
+ changelog = getChangelog(entryFileName);
+
+ // If there isn't a ChangeLog, we will ask for one here.
+ // We originally avoided this to prevent a problem for rpm
+ // projects whereby the changelog is inlined in a single file
+ // and not presented externally. This has been changed in
+ // response to bug #347703. If the user cancels the ask
+ // dialog, then the prepare operation doesn't try to create
+ // one.
+ if (createChangeLog && changelog == null)
+ changelog = askChangeLogLocation(entryPath.toOSString());
+ if (changelog == null) {
+ createChangeLog = false;
+ return;
+ }
+ }
+ if ((changelog instanceof ChangeLogEditor) && (!this.newEntryWritten)) {
+ ChangeLogEditor editor = (ChangeLogEditor) changelog;
+ // if the editor is dirty (changes added to the editor without
+ // saving), treat it as a change log modification
+ if (editor.isDirty())
+ this.changeLogModified = true;
+ editor.setForceNewLogEntry(!this.changeLogModified);
+ this.newEntryWritten = true;
+ }
+ // select changelog
+ clw.setChangelog(changelog);
+
+ // write to changelog
+ IFormatterChangeLogContrib formatter = clw.getFormatter();
+ clw.setDateLine(formatter.formatDateLine(pref_AuthorName,
+ pref_AuthorEmail));
+
+ clw.setChangelogLocation(getDocumentLocation(clw.getChangelog(), true));
+
+ // print multiple changelog entries with different
+ // function guess names. We default to an empty guessed name
+ // if we have zero function guess names.
+ int numFuncs = 0;
+ clw.setGuessedFName(""); // $NON-NLS-1$
+ if (functionGuess.length > 0) {
+ for (String guess : functionGuess) {
+ if (!guess.trim().equals("")) { // $NON-NLS-1$
+ ++numFuncs;
+ clw.setGuessedFName(guess);
+ clw.writeChangeLog();
+ }
+ }
+ }
+ // Default an empty entry if we did not have any none-empty
+ // function guesses.
+ if (numFuncs == 0) {
+ clw.writeChangeLog();
+ }
+
+ }
+
+
+ /**
+ * Guesses the function effected/modified by the patch from local file(newer
+ * file).
+ *
+ * @param patchFileInfo
+ * patch file
+ * @return array of unique function names
+ */
+ private String[] guessFunctionNames(PatchFile patchFileInfo) {
+
+
+ // if this file is new file or removed file, do not guess function files
+ // TODO: create an option to include function names on
+ // new files or not
+ if (patchFileInfo.isNewfile() || patchFileInfo.isRemovedFile()) {
+ return new String[]{""};
+ }
+
+ String[] fnames = new String[0];
+ String editorName = ""; // $NON-NLS-1$
+
+ try {
+ IEditorDescriptor ed = org.eclipse.ui.ide.IDE
+ .getEditorDescriptor(patchFileInfo.getPath().toOSString());
+ editorName = ed.getId().substring(ed.getId().lastIndexOf(".") + 1); // $NON-NLS-1$
+ } catch (PartInitException e1) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR,
+ e1.getMessage(), e1));
+ return new String[0];
+ }
+
+ // check if the file type is supported
+
+ // get editor input for target file
+
+ IFileEditorInput fei = new FileEditorInput((IFile)patchFileInfo.getResource());
+
+ SourceEditorInput sei = new SourceEditorInput(patchFileInfo.getStorage());
+
+ MyDocumentProvider mdp = new MyDocumentProvider();
+ MyStorageDocumentProvider msdp = new MyStorageDocumentProvider();
+
+ try {
+ // get document for target file (one for local file, one for repository storage)
+ IDocument doc = mdp.createDocument(fei);
+ IDocument olddoc = msdp.createDocument(sei);
+
+ HashMap<String, String> functionNamesMap = new HashMap<>();
+ ArrayList<String> nameList = new ArrayList<>();
+
+ // for all the ranges
+ for (PatchRangeElement tpre: patchFileInfo.getRanges()) {
+
+ for (int j = tpre.fromLine; j <= tpre.toLine; j++) {
+
+ String functionGuess = "";
+ // add func that determines type of file.
+ // right now it assumes it's java file.
+ if (tpre.isLocalChange()) {
+ if ((j < 0) || (j > doc.getNumberOfLines() - 1))
+ continue; // ignore out of bound lines
+ functionGuess = parseCurrentFunctionAtOffset(
+ editorName, fei, doc.getLineOffset(j));
+ } else {
+ if ((j < 0) || (j > olddoc.getNumberOfLines() - 1))
+ continue; // ignore out of bound lines
+ functionGuess = parseCurrentFunctionAtOffset(
+ editorName, sei, olddoc.getLineOffset(j));
+ }
+
+ // putting it in hashmap will eliminate duplicate
+ // guesses. We use a list to keep track of ordering which
+ // is helpful when trying to document a large set of changes.
+ if (functionNamesMap.get(functionGuess) == null)
+ nameList.add(functionGuess);
+ functionNamesMap.put(functionGuess, functionGuess);
+ }
+ }
+
+ // dump all unique func. guesses in the order found
+ fnames = new String[nameList.size()];
+ fnames = nameList.toArray(fnames);
+
+ } catch (CoreException|BadLocationException e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR,
+ e.getMessage(), e));
+ }
+ return fnames;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareChangelogKeyHandler.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareChangelogKeyHandler.java
index dd8ea21f8f..5c3f139e20 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareChangelogKeyHandler.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareChangelogKeyHandler.java
@@ -36,101 +36,101 @@ import org.eclipse.ui.handlers.HandlerUtil;
public class PrepareChangelogKeyHandler extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) {
+ @Override
+ public Object execute(ExecutionEvent event) {
- IStructuredSelection tempResult = null;
+ IStructuredSelection tempResult = null;
- // try getting currently selected project
- IWorkbenchPage ref = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage();
- IWorkbenchPart part = HandlerUtil.getActivePart(event);
- if (part instanceof IEditorPart) {
- // If we are in an editor, check if the file being edited is an IResource
- // that belongs to a project in the workspace
- IEditorPart editorPart = (IEditorPart)part;
- IEditorInput input = editorPart.getEditorInput();
- IResource r = (IResource)input.getAdapter(IResource.class);
- if (r != null) {
- // We have an IResource to work with, so create a selection we can use
- // in PrepareChangeLogAction
- tempResult = new StructuredSelection(r);
- }
- } else {
- // Otherwise, our view is not an editor, see if we have an IResource or something
- // that will lead us to an IResource
- ISelection selected = ref.getSelection();
- if (selected instanceof IStructuredSelection) {
- IResource r = null;
- IStructuredSelection iss = (IStructuredSelection)selected;
- Object o = ((IStructuredSelection)selected).getFirstElement();
- if (o instanceof ISynchronizeModelElement) {
- r = ((ISynchronizeModelElement)o).getResource();
- } else if (o instanceof IAdaptable) {
- r = (IResource)((IAdaptable)o).getAdapter(IResource.class);
- }
- if (r != null)
- tempResult = iss;
- }
- }
- if (tempResult == null) {
- // We don't have an obvious project match in the current active view.
- // Let's search all open views for the Synchronize View which is our first
- // choice to fall back on.
- for (IViewReference view: ref.getViewReferences()) {
- if (view.getId().equals("org.eclipse.team.sync.views.SynchronizeView")) { // $NON-NLS-1$
- IViewPart v = view.getView(false);
- ISelection s = null;
- ISelectionProvider sp = v.getViewSite().getSelectionProvider();
- if (sp != null) {
- s = sp.getSelection();
- }
- if (s instanceof IStructuredSelection) {
- IStructuredSelection ss = (IStructuredSelection)s;
- Object element = ss.getFirstElement();
- IResource r = null;
- if (element instanceof ISynchronizeModelElement) {
- r = ((ISynchronizeModelElement)element).getResource();
- } else if (element instanceof IAdaptable) {
- r = (IResource)((IAdaptable)element).getAdapter(IResource.class);
- }
+ // try getting currently selected project
+ IWorkbenchPage ref = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage();
+ IWorkbenchPart part = HandlerUtil.getActivePart(event);
+ if (part instanceof IEditorPart) {
+ // If we are in an editor, check if the file being edited is an IResource
+ // that belongs to a project in the workspace
+ IEditorPart editorPart = (IEditorPart)part;
+ IEditorInput input = editorPart.getEditorInput();
+ IResource r = (IResource)input.getAdapter(IResource.class);
+ if (r != null) {
+ // We have an IResource to work with, so create a selection we can use
+ // in PrepareChangeLogAction
+ tempResult = new StructuredSelection(r);
+ }
+ } else {
+ // Otherwise, our view is not an editor, see if we have an IResource or something
+ // that will lead us to an IResource
+ ISelection selected = ref.getSelection();
+ if (selected instanceof IStructuredSelection) {
+ IResource r = null;
+ IStructuredSelection iss = (IStructuredSelection)selected;
+ Object o = ((IStructuredSelection)selected).getFirstElement();
+ if (o instanceof ISynchronizeModelElement) {
+ r = ((ISynchronizeModelElement)o).getResource();
+ } else if (o instanceof IAdaptable) {
+ r = (IResource)((IAdaptable)o).getAdapter(IResource.class);
+ }
+ if (r != null)
+ tempResult = iss;
+ }
+ }
+ if (tempResult == null) {
+ // We don't have an obvious project match in the current active view.
+ // Let's search all open views for the Synchronize View which is our first
+ // choice to fall back on.
+ for (IViewReference view: ref.getViewReferences()) {
+ if (view.getId().equals("org.eclipse.team.sync.views.SynchronizeView")) { // $NON-NLS-1$
+ IViewPart v = view.getView(false);
+ ISelection s = null;
+ ISelectionProvider sp = v.getViewSite().getSelectionProvider();
+ if (sp != null) {
+ s = sp.getSelection();
+ }
+ if (s instanceof IStructuredSelection) {
+ IStructuredSelection ss = (IStructuredSelection)s;
+ Object element = ss.getFirstElement();
+ IResource r = null;
+ if (element instanceof ISynchronizeModelElement) {
+ r = ((ISynchronizeModelElement)element).getResource();
+ } else if (element instanceof IAdaptable) {
+ r = (IResource)((IAdaptable)element).getAdapter(IResource.class);
+ }
- if (r != null) {
- tempResult = ss;
- }
- }
- }
- }
- }
+ if (r != null) {
+ tempResult = ss;
+ }
+ }
+ }
+ }
+ }
- // If we can't find the project directly, let the user know.
- if (tempResult == null) {
- MessageDialog.openInformation(getActiveWorkbenchShell(), Messages.getString("ChangeLog.PrepareChangeLog"), // $NON-NLS-1$,
- Messages.getString("PrepareChangeLog.InfoNoProjectFound")); // $NON-NLS-1$
- return null;
- }
+ // If we can't find the project directly, let the user know.
+ if (tempResult == null) {
+ MessageDialog.openInformation(getActiveWorkbenchShell(), Messages.getString("ChangeLog.PrepareChangeLog"), // $NON-NLS-1$,
+ Messages.getString("PrepareChangeLog.InfoNoProjectFound")); // $NON-NLS-1$
+ return null;
+ }
- final IStructuredSelection result = tempResult;
- IAction exampleAction = new PrepareChangeLogAction() {
- @Override
- public void run() {
- setSelection(result);
- doRun();
- }
- };
+ final IStructuredSelection result = tempResult;
+ IAction exampleAction = new PrepareChangeLogAction() {
+ @Override
+ public void run() {
+ setSelection(result);
+ doRun();
+ }
+ };
- exampleAction.run();
+ exampleAction.run();
- return null;
- }
+ return null;
+ }
- /**
- * Returns active shell.
- */
- private Shell getActiveWorkbenchShell() {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window != null) {
- return window.getShell();
- }
- return null;
- }
+ /**
+ * Returns active shell.
+ */
+ private Shell getActiveWorkbenchShell() {
+ IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ if (window != null) {
+ return window.getShell();
+ }
+ return null;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareCommitHandler.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareCommitHandler.java
index 87eeaded11..f751772734 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareCommitHandler.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/PrepareCommitHandler.java
@@ -56,227 +56,227 @@ import org.eclipse.ui.ide.IContributorResourceAdapter2;
public class PrepareCommitHandler extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) {
+ @Override
+ public Object execute(ExecutionEvent event) {
- IRunnableWithProgress code = new IRunnableWithProgress() {
+ IRunnableWithProgress code = new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor) {
- // monitor.beginTask("Loading Clipboard", 1000);
- loadClipboard(monitor);
- // monitor.done();
- }
- };
+ @Override
+ public void run(IProgressMonitor monitor) {
+ // monitor.beginTask("Loading Clipboard", 1000);
+ loadClipboard(monitor);
+ // monitor.done();
+ }
+ };
- ProgressMonitorDialog pd = new ProgressMonitorDialog(PlatformUI
- .getWorkbench().getActiveWorkbenchWindow().getShell());
+ ProgressMonitorDialog pd = new ProgressMonitorDialog(PlatformUI
+ .getWorkbench().getActiveWorkbenchWindow().getShell());
- try {
- pd.run(false /* fork */, false /* cancelable */, code);
- } catch (InvocationTargetException e) {
- ChangelogPlugin
- .getDefault()
- .getLog()
- .log(new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
- IStatus.ERROR, e.getMessage(), e));
- } catch (InterruptedException e) {
- ChangelogPlugin
- .getDefault()
- .getLog()
- .log(new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
- IStatus.ERROR, e.getMessage(), e));
- }
+ try {
+ pd.run(false /* fork */, false /* cancelable */, code);
+ } catch (InvocationTargetException e) {
+ ChangelogPlugin
+ .getDefault()
+ .getLog()
+ .log(new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
+ IStatus.ERROR, e.getMessage(), e));
+ } catch (InterruptedException e) {
+ ChangelogPlugin
+ .getDefault()
+ .getLog()
+ .log(new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
+ IStatus.ERROR, e.getMessage(), e));
+ }
- return null;
- }
+ return null;
+ }
- private ResourceMapping getResourceMapping(Object o) {
- if (o instanceof ResourceMapping) {
- return (ResourceMapping) o;
- }
- if (o instanceof IAdaptable) {
- IAdaptable adaptable = (IAdaptable) o;
- Object adapted = adaptable.getAdapter(ResourceMapping.class);
- if (adapted instanceof ResourceMapping) {
- return (ResourceMapping) adapted;
- }
- adapted = adaptable.getAdapter(IContributorResourceAdapter.class);
- if (adapted instanceof IContributorResourceAdapter2) {
- IContributorResourceAdapter2 cra = (IContributorResourceAdapter2) adapted;
- return cra.getAdaptedResourceMapping(adaptable);
- }
- } else {
- Object adapted = Platform.getAdapterManager().getAdapter(o,
- ResourceMapping.class);
- if (adapted instanceof ResourceMapping) {
- return (ResourceMapping) adapted;
- }
- }
+ private ResourceMapping getResourceMapping(Object o) {
+ if (o instanceof ResourceMapping) {
+ return (ResourceMapping) o;
+ }
+ if (o instanceof IAdaptable) {
+ IAdaptable adaptable = (IAdaptable) o;
+ Object adapted = adaptable.getAdapter(ResourceMapping.class);
+ if (adapted instanceof ResourceMapping) {
+ return (ResourceMapping) adapted;
+ }
+ adapted = adaptable.getAdapter(IContributorResourceAdapter.class);
+ if (adapted instanceof IContributorResourceAdapter2) {
+ IContributorResourceAdapter2 cra = (IContributorResourceAdapter2) adapted;
+ return cra.getAdaptedResourceMapping(adaptable);
+ }
+ } else {
+ Object adapted = Platform.getAdapterManager().getAdapter(o,
+ ResourceMapping.class);
+ if (adapted instanceof ResourceMapping) {
+ return (ResourceMapping) adapted;
+ }
+ }
- return null;
- }
+ return null;
+ }
- private void loadClipboard(IProgressMonitor monitor) {
+ private void loadClipboard(IProgressMonitor monitor) {
- IEditorPart currentEditor;
+ IEditorPart currentEditor;
- try {
- currentEditor = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage()
- .getActiveEditor();
- } catch (Exception e) {
- // no editor is active now so do nothing
+ try {
+ currentEditor = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage()
+ .getActiveEditor();
+ } catch (Exception e) {
+ // no editor is active now so do nothing
- return;
- }
+ return;
+ }
- if (currentEditor == null)
- return;
+ if (currentEditor == null)
+ return;
- // System.out.println(currentEditor.getTitle());
- String diffResult = "";
- IEditorInput input = currentEditor.getEditorInput();
- ResourceMapping mapping = getResourceMapping(input);
- IProject project = null;
- IResource[] resources = new IResource[1];
+ // System.out.println(currentEditor.getTitle());
+ String diffResult = "";
+ IEditorInput input = currentEditor.getEditorInput();
+ ResourceMapping mapping = getResourceMapping(input);
+ IProject project = null;
+ IResource[] resources = new IResource[1];
- if (mapping != null) {
- project = mapping.getProjects()[0];
- resources[0] = (IResource) mapping.getModelObject();
- } else if (input instanceof IFileEditorInput) {
- IFileEditorInput f = (IFileEditorInput) input;
- project = f.getFile().getProject();
- resources[0] = f.getFile();
- } else {
- return; // can't get what we need
- }
+ if (mapping != null) {
+ project = mapping.getProjects()[0];
+ resources[0] = (IResource) mapping.getModelObject();
+ } else if (input instanceof IFileEditorInput) {
+ IFileEditorInput f = (IFileEditorInput) input;
+ project = f.getFile().getProject();
+ resources[0] = f.getFile();
+ } else {
+ return; // can't get what we need
+ }
- RepositoryProvider r = RepositoryProvider.getProvider(project);
- if (r == null) {
- return; // There is no repository provider for this project, i.e
- // it's not shared.
- }
- SyncInfoSet set = new SyncInfoSet();
- Subscriber s = r.getSubscriber();
- s.collectOutOfSync(resources, IResource.DEPTH_ZERO, set, monitor);
- SyncInfo[] infos = set.getSyncInfos();
+ RepositoryProvider r = RepositoryProvider.getProvider(project);
+ if (r == null) {
+ return; // There is no repository provider for this project, i.e
+ // it's not shared.
+ }
+ SyncInfoSet set = new SyncInfoSet();
+ Subscriber s = r.getSubscriber();
+ s.collectOutOfSync(resources, IResource.DEPTH_ZERO, set, monitor);
+ SyncInfo[] infos = set.getSyncInfos();
- if (infos.length == 1) {
- int kind = SyncInfo.getChange(infos[0].getKind());
- if (kind == SyncInfo.CHANGE) {
- try {
- IDiff d = s.getDiff(infos[0].getLocal());
- if (d instanceof IThreeWayDiff
- && ((IThreeWayDiff) d).getDirection() == IThreeWayDiff.OUTGOING) {
- IThreeWayDiff diff = (IThreeWayDiff) d;
- monitor.beginTask(null, 100);
- IResourceDiff localDiff = (IResourceDiff) diff
- .getLocalChange();
- IFile file = (IFile) localDiff.getResource();
- monitor.subTask(Messages
- .getString("ChangeLog.MergingDiffs")); // $NON-NLS-1$
- String osEncoding = file.getCharset();
- IFileRevision ancestorState = localDiff
- .getBeforeState();
- IStorage ancestorStorage;
- if (ancestorState != null)
- ancestorStorage = ancestorState.getStorage(monitor);
- else {
- ancestorStorage = null;
- return;
- }
+ if (infos.length == 1) {
+ int kind = SyncInfo.getChange(infos[0].getKind());
+ if (kind == SyncInfo.CHANGE) {
+ try {
+ IDiff d = s.getDiff(infos[0].getLocal());
+ if (d instanceof IThreeWayDiff
+ && ((IThreeWayDiff) d).getDirection() == IThreeWayDiff.OUTGOING) {
+ IThreeWayDiff diff = (IThreeWayDiff) d;
+ monitor.beginTask(null, 100);
+ IResourceDiff localDiff = (IResourceDiff) diff
+ .getLocalChange();
+ IFile file = (IFile) localDiff.getResource();
+ monitor.subTask(Messages
+ .getString("ChangeLog.MergingDiffs")); // $NON-NLS-1$
+ String osEncoding = file.getCharset();
+ IFileRevision ancestorState = localDiff
+ .getBeforeState();
+ IStorage ancestorStorage;
+ if (ancestorState != null)
+ ancestorStorage = ancestorState.getStorage(monitor);
+ else {
+ ancestorStorage = null;
+ return;
+ }
- try {
- LineComparator left = new LineComparator(
- ancestorStorage.getContents(), osEncoding);
- LineComparator right = new LineComparator(
- file.getContents(), osEncoding);
- for (RangeDifference tmp : RangeDifferencer
- .findDifferences(left, right)) {
- if (tmp.kind() == RangeDifference.CHANGE) {
- LineNumberReader l = new LineNumberReader(
- new InputStreamReader(
- file.getContents()));
- int rightLength = tmp.rightLength() > 0 ? tmp
- .rightLength()
- : tmp.rightLength() + 1;
- String line0 = null;
- String preDiffResult = "";
- for (int i = 0; i < tmp.rightStart(); ++i) {
- // We have equivalence at the start.
- // This could be due to a new entry with
- // the
- // same date stamp as the subsequent
- // entry. In this case, we want the diff
- // to
- // have the date stamp at the top so it
- // forms a complete entry. So, we cache
- // those equivalent lines for later
- // usage if needed.
- try {
- String line = l.readLine();
- if (line0 == null)
- line0 = line;
- preDiffResult += line + "\n";
- } catch (IOException e) {
- break;
- }
- }
- for (int i = 0; i < rightLength; ++i) {
- try {
- String line = l.readLine();
- // If the last line of the diff
- // matches the first line of the old
- // file and
- // there was equivalence at the
- // start of the ChangeLog, then we
- // want to put
- // the equivalent section at top so
- // as to give the best chance of
- // forming
- // a ChangeLog entry that can be
- // used as a commit comment.
- if (i == rightLength
- - tmp.rightStart()) {
- if (tmp.rightStart() != 0
- && line.equals(line0)) {
- diffResult = preDiffResult += diffResult;
- i = rightLength; // stop
- // loop
- } else
- diffResult += line + "\n";
- } else
- diffResult += line + "\n"; // $NON-NLS-1$
- } catch (IOException e) {
- // do nothing
- }
- }
- }
- }
- } catch (UnsupportedEncodingException e) {
- // do nothing for now
- }
- monitor.done();
- }
- } catch (CoreException e) {
- // do nothing
- }
- }
- }
+ try {
+ LineComparator left = new LineComparator(
+ ancestorStorage.getContents(), osEncoding);
+ LineComparator right = new LineComparator(
+ file.getContents(), osEncoding);
+ for (RangeDifference tmp : RangeDifferencer
+ .findDifferences(left, right)) {
+ if (tmp.kind() == RangeDifference.CHANGE) {
+ LineNumberReader l = new LineNumberReader(
+ new InputStreamReader(
+ file.getContents()));
+ int rightLength = tmp.rightLength() > 0 ? tmp
+ .rightLength()
+ : tmp.rightLength() + 1;
+ String line0 = null;
+ String preDiffResult = "";
+ for (int i = 0; i < tmp.rightStart(); ++i) {
+ // We have equivalence at the start.
+ // This could be due to a new entry with
+ // the
+ // same date stamp as the subsequent
+ // entry. In this case, we want the diff
+ // to
+ // have the date stamp at the top so it
+ // forms a complete entry. So, we cache
+ // those equivalent lines for later
+ // usage if needed.
+ try {
+ String line = l.readLine();
+ if (line0 == null)
+ line0 = line;
+ preDiffResult += line + "\n";
+ } catch (IOException e) {
+ break;
+ }
+ }
+ for (int i = 0; i < rightLength; ++i) {
+ try {
+ String line = l.readLine();
+ // If the last line of the diff
+ // matches the first line of the old
+ // file and
+ // there was equivalence at the
+ // start of the ChangeLog, then we
+ // want to put
+ // the equivalent section at top so
+ // as to give the best chance of
+ // forming
+ // a ChangeLog entry that can be
+ // used as a commit comment.
+ if (i == rightLength
+ - tmp.rightStart()) {
+ if (tmp.rightStart() != 0
+ && line.equals(line0)) {
+ diffResult = preDiffResult += diffResult;
+ i = rightLength; // stop
+ // loop
+ } else
+ diffResult += line + "\n";
+ } else
+ diffResult += line + "\n"; // $NON-NLS-1$
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ }
+ }
+ } catch (UnsupportedEncodingException e) {
+ // do nothing for now
+ }
+ monitor.done();
+ }
+ } catch (CoreException e) {
+ // do nothing
+ }
+ }
+ }
- if (!diffResult.equals(""))
- populateClipboardBuffer(diffResult);
- }
+ if (!diffResult.equals(""))
+ populateClipboardBuffer(diffResult);
+ }
- private void populateClipboardBuffer(String input) {
+ private void populateClipboardBuffer(String input) {
- TextTransfer plainTextTransfer = TextTransfer.getInstance();
- Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench()
- .getDisplay());
- clipboard.setContents(new String[] { input },
- new Transfer[] { plainTextTransfer });
- clipboard.dispose();
- }
+ TextTransfer plainTextTransfer = TextTransfer.getInstance();
+ Clipboard clipboard = new Clipboard(PlatformUI.getWorkbench()
+ .getDisplay());
+ clipboard.setContents(new String[] { input },
+ new Transfer[] { plainTextTransfer });
+ clipboard.dispose();
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/SourceEditorInput.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/SourceEditorInput.java
index 5f605a7cb3..314cd13c9a 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/SourceEditorInput.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/SourceEditorInput.java
@@ -17,19 +17,19 @@ import org.eclipse.core.resources.IStorage;
*/
public class SourceEditorInput extends StorageEditorInput {
- /**
- * @param storage that represents a source file
- */
- public SourceEditorInput(IStorage storage) {
- super(storage);
- }
+ /**
+ * @param storage that represents a source file
+ */
+ public SourceEditorInput(IStorage storage) {
+ super(storage);
+ }
- /*
- * @see org.eclipse.ui.IEditorInput#exists()
- */
- @Override
- public boolean exists() {
- return false;
- }
+ /*
+ * @see org.eclipse.ui.IEditorInput#exists()
+ */
+ @Override
+ public boolean exists() {
+ return false;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/StorageEditorInput.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/StorageEditorInput.java
index 95ff2926ee..aa33eb4547 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/StorageEditorInput.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/actions/StorageEditorInput.java
@@ -22,89 +22,89 @@ import org.eclipse.ui.IStorageEditorInput;
*/
public abstract class StorageEditorInput implements IStorageEditorInput {
- /**
- * Storage associated with this editor input
- */
- private IStorage fStorage;
+ /**
+ * Storage associated with this editor input
+ */
+ private IStorage fStorage;
- /**
- * Constructs an editor input on the given storage
- */
- public StorageEditorInput(IStorage storage) {
- fStorage = storage;
- }
+ /**
+ * Constructs an editor input on the given storage
+ */
+ public StorageEditorInput(IStorage storage) {
+ fStorage = storage;
+ }
- /**
- * @see IStorageEditorInput#getStorage()
- */
- @Override
- public IStorage getStorage() {
- return fStorage;
- }
+ /**
+ * @see IStorageEditorInput#getStorage()
+ */
+ @Override
+ public IStorage getStorage() {
+ return fStorage;
+ }
- /**
- * @see IStorageEditorInput#getImageDescriptor()
- */
- @Override
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
+ /**
+ * @see IStorageEditorInput#getImageDescriptor()
+ */
+ @Override
+ public ImageDescriptor getImageDescriptor() {
+ return null;
+ }
- /**
- * @see IStorageEditorInput#getName()
- */
- @Override
- public String getName() {
- return getStorage().getName();
- }
+ /**
+ * @see IStorageEditorInput#getName()
+ */
+ @Override
+ public String getName() {
+ return getStorage().getName();
+ }
- /**
- * @see IStorageEditorInput#getPersistable()
- */
- @Override
- public IPersistableElement getPersistable() {
- return null;
- }
+ /**
+ * @see IStorageEditorInput#getPersistable()
+ */
+ @Override
+ public IPersistableElement getPersistable() {
+ return null;
+ }
- /**
- * @see IStorageEditorInput#getToolTipText()
- */
- @Override
- public String getToolTipText() {
- return getStorage().getFullPath().toOSString();
- }
+ /**
+ * @see IStorageEditorInput#getToolTipText()
+ */
+ @Override
+ public String getToolTipText() {
+ return getStorage().getFullPath().toOSString();
+ }
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object object) {
- if (object == this) {
- return true;
- }
- try {
- return object instanceof IStorageEditorInput
- && getStorage().equals(((IStorageEditorInput)object).getStorage());
- } catch (CoreException e) {
- }
- return false;
- }
+ /**
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object object) {
+ if (object == this) {
+ return true;
+ }
+ try {
+ return object instanceof IStorageEditorInput
+ && getStorage().equals(((IStorageEditorInput)object).getStorage());
+ } catch (CoreException e) {
+ }
+ return false;
+ }
- /**
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
- return getStorage().hashCode();
- }
+ /**
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ return getStorage().hashCode();
+ }
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
- */
- @Override
- @SuppressWarnings({ "rawtypes" })
+ /* (non-Javadoc)
+ * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
+ */
+ @Override
+ @SuppressWarnings({ "rawtypes" })
public Object getAdapter(Class adapter) {
- return null;
- }
+ return null;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogDocumentProvider.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogDocumentProvider.java
index 33c03407eb..e46b3731d7 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogDocumentProvider.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogDocumentProvider.java
@@ -18,8 +18,8 @@ import org.eclipse.ui.editors.text.TextFileDocumentProvider;
*/
public class ChangeLogDocumentProvider extends TextFileDocumentProvider {
- @Override
- public IDocument getDocument(Object element) {
- return super.getDocument(element);
- }
+ @Override
+ public IDocument getDocument(Object element) {
+ return super.getDocument(element);
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogDocumentSetupParticipant.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogDocumentSetupParticipant.java
index 750d3dbea1..818d158c0e 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogDocumentSetupParticipant.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogDocumentSetupParticipant.java
@@ -26,62 +26,62 @@ import org.eclipse.linuxtools.changelog.core.IEditorChangeLogContrib2;
import org.eclipse.linuxtools.internal.changelog.core.ChangelogPlugin;
public class ChangeLogDocumentSetupParticipant implements
- IDocumentSetupParticipant, IDocumentListener {
+ IDocumentSetupParticipant, IDocumentListener {
- @Override
- public void setup(IDocument document) {
- IExtensionPoint editorExtensions = null;
- IEditorChangeLogContrib editorContrib = null;
+ @Override
+ public void setup(IDocument document) {
+ IExtensionPoint editorExtensions = null;
+ IEditorChangeLogContrib editorContrib = null;
- // get editor which is stored in preference.
- IPreferenceStore store = ChangelogPlugin.getDefault()
- .getPreferenceStore();
- String pref_Editor = store
- .getString("IChangeLogConstants.DEFAULT_EDITOR"); // $NON-NLS-1$
+ // get editor which is stored in preference.
+ IPreferenceStore store = ChangelogPlugin.getDefault()
+ .getPreferenceStore();
+ String pref_Editor = store
+ .getString("IChangeLogConstants.DEFAULT_EDITOR"); // $NON-NLS-1$
- editorExtensions = Platform.getExtensionRegistry().getExtensionPoint(
- "org.eclipse.linuxtools.changelog.core", "editorContribution"); //$NON-NLS-1$ //$NON-NLS-2$
+ editorExtensions = Platform.getExtensionRegistry().getExtensionPoint(
+ "org.eclipse.linuxtools.changelog.core", "editorContribution"); //$NON-NLS-1$ //$NON-NLS-2$
- if (editorExtensions != null) {
- IConfigurationElement[] elements = editorExtensions
- .getConfigurationElements();
- for (int i = 0; i < elements.length; i++) {
- if (elements[i].getName().equals("editor") // $NON-NLS-1$
- && (elements[i].getAttribute("name").equals(pref_Editor))) { //$NON-NLS-1$
+ if (editorExtensions != null) {
+ IConfigurationElement[] elements = editorExtensions
+ .getConfigurationElements();
+ for (int i = 0; i < elements.length; i++) {
+ if (elements[i].getName().equals("editor") // $NON-NLS-1$
+ && (elements[i].getAttribute("name").equals(pref_Editor))) { //$NON-NLS-1$
- try {
- // If editor has a special setup routine, use it.
- IConfigurationElement bob = elements[i];
- editorContrib = (IEditorChangeLogContrib) bob
- .createExecutableExtension("class"); // $NON-NLS-1$
+ try {
+ // If editor has a special setup routine, use it.
+ IConfigurationElement bob = elements[i];
+ editorContrib = (IEditorChangeLogContrib) bob
+ .createExecutableExtension("class"); // $NON-NLS-1$
- if (editorContrib instanceof IEditorChangeLogContrib2)
- ((IEditorChangeLogContrib2)editorContrib).setup(document);
- } catch (CoreException e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
- IStatus.ERROR, e.getMessage(), e));
- }
- }
- }
- }
- }
+ if (editorContrib instanceof IEditorChangeLogContrib2)
+ ((IEditorChangeLogContrib2)editorContrib).setup(document);
+ } catch (CoreException e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
+ IStatus.ERROR, e.getMessage(), e));
+ }
+ }
+ }
+ }
+ }
- /*
- * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent)
- */
+ /*
+ * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent)
+ */
- @Override
- public void documentAboutToBeChanged(DocumentEvent e) {
- // do nothing
- }
+ @Override
+ public void documentAboutToBeChanged(DocumentEvent e) {
+ // do nothing
+ }
- /*
- * @see IDocumentListener#documentChanged(DocumentEvent)
- */
- @Override
- public void documentChanged(DocumentEvent e) {
- // do nothing
- }
+ /*
+ * @see IDocumentListener#documentChanged(DocumentEvent)
+ */
+ @Override
+ public void documentChanged(DocumentEvent e) {
+ // do nothing
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogEditor.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogEditor.java
index 63618322ad..1c23bea4d7 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogEditor.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogEditor.java
@@ -35,83 +35,83 @@ import org.eclipse.ui.editors.text.TextEditor;
*/
public class ChangeLogEditor extends TextEditor {
- private boolean forceNewLogEntry;
-
- public ChangeLogEditor() {
- super();
-
- SourceViewerConfiguration config = getConfig();
-
- if (config != null) {
- setSourceViewerConfiguration(config);
- } else {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR,
- Messages.getString("ChangeLogEditor.ErrConfiguration"), // $NON-NLS-1$
- new Exception(Messages.getString("ChangeLogEditor.ErrConfiguration")))); // $NON-NLS-1$
- }
-
- setDocumentProvider(new ChangeLogDocumentProvider());
-
- }
-
- /**
- * Gets appropriate style editor from user pref.
- *
- * @return configuration for the Changelog editor
- */
-
- private SourceViewerConfiguration getConfig() {
-
- IExtensionPoint editorExtensions = null;
- IEditorChangeLogContrib editorContrib = null;
-
- // get editor which is stored in preference.
- IPreferenceStore store = ChangelogPlugin.getDefault()
- .getPreferenceStore();
- String pref_Editor = store
- .getString("IChangeLogConstants.DEFAULT_EDITOR"); // $NON-NLS-1$
-
- editorExtensions = Platform.getExtensionRegistry().getExtensionPoint(
- "org.eclipse.linuxtools.changelog.core", "editorContribution"); //$NON-NLS-1$ //$NON-NLS-2$
-
- if (editorExtensions != null) {
- IConfigurationElement[] elements = editorExtensions
- .getConfigurationElements();
- for (int i = 0; i < elements.length; i++) {
- if (elements[i].getName().equals("editor") // $NON-NLS-1$
- && (elements[i].getAttribute("name").equals(pref_Editor))) { //$NON-NLS-1$
-
- try {
- IConfigurationElement bob = elements[i];
- editorContrib = (IEditorChangeLogContrib) bob
- .createExecutableExtension("class"); // $NON-NLS-1$
-
- editorContrib.setTextEditor(this);
- return (SourceViewerConfiguration) editorContrib;
- } catch (CoreException e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
- IStatus.ERROR, e.getMessage(), e));
- }
-
- }
- }
- }
-
- return null;
- }
-
- public ISourceViewer getMySourceViewer() {
- return this.getSourceViewer();
- }
-
- public boolean isForceNewLogEntry() {
- return forceNewLogEntry;
- }
-
- public void setForceNewLogEntry(boolean forceNewLogEntry) {
- this.forceNewLogEntry = forceNewLogEntry;
- }
+ private boolean forceNewLogEntry;
+
+ public ChangeLogEditor() {
+ super();
+
+ SourceViewerConfiguration config = getConfig();
+
+ if (config != null) {
+ setSourceViewerConfiguration(config);
+ } else {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR,
+ Messages.getString("ChangeLogEditor.ErrConfiguration"), // $NON-NLS-1$
+ new Exception(Messages.getString("ChangeLogEditor.ErrConfiguration")))); // $NON-NLS-1$
+ }
+
+ setDocumentProvider(new ChangeLogDocumentProvider());
+
+ }
+
+ /**
+ * Gets appropriate style editor from user pref.
+ *
+ * @return configuration for the Changelog editor
+ */
+
+ private SourceViewerConfiguration getConfig() {
+
+ IExtensionPoint editorExtensions = null;
+ IEditorChangeLogContrib editorContrib = null;
+
+ // get editor which is stored in preference.
+ IPreferenceStore store = ChangelogPlugin.getDefault()
+ .getPreferenceStore();
+ String pref_Editor = store
+ .getString("IChangeLogConstants.DEFAULT_EDITOR"); // $NON-NLS-1$
+
+ editorExtensions = Platform.getExtensionRegistry().getExtensionPoint(
+ "org.eclipse.linuxtools.changelog.core", "editorContribution"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ if (editorExtensions != null) {
+ IConfigurationElement[] elements = editorExtensions
+ .getConfigurationElements();
+ for (int i = 0; i < elements.length; i++) {
+ if (elements[i].getName().equals("editor") // $NON-NLS-1$
+ && (elements[i].getAttribute("name").equals(pref_Editor))) { //$NON-NLS-1$
+
+ try {
+ IConfigurationElement bob = elements[i];
+ editorContrib = (IEditorChangeLogContrib) bob
+ .createExecutableExtension("class"); // $NON-NLS-1$
+
+ editorContrib.setTextEditor(this);
+ return (SourceViewerConfiguration) editorContrib;
+ } catch (CoreException e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID,
+ IStatus.ERROR, e.getMessage(), e));
+ }
+
+ }
+ }
+ }
+
+ return null;
+ }
+
+ public ISourceViewer getMySourceViewer() {
+ return this.getSourceViewer();
+ }
+
+ public boolean isForceNewLogEntry() {
+ return forceNewLogEntry;
+ }
+
+ public void setForceNewLogEntry(boolean forceNewLogEntry) {
+ this.forceNewLogEntry = forceNewLogEntry;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogFormattingStrategy.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogFormattingStrategy.java
index 2fbc1a6d05..41f2548b91 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogFormattingStrategy.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ChangeLogFormattingStrategy.java
@@ -20,224 +20,224 @@ import org.eclipse.jface.text.formatter.IFormattingStrategy;
public class ChangeLogFormattingStrategy implements IFormattingStrategy {
- private static final String NEW_LINE_CHAR = "\n";
+ private static final String NEW_LINE_CHAR = "\n";
- private static final String WHITE_SPACE_CHAR = " ";
-
- private static final String TAB_SPACE_CHAR = "\t";
-
- @Override
- public String format(String content, boolean isLineStart,
- String indentation, int[] positions) {
+ private static final String WHITE_SPACE_CHAR = " ";
+
+ private static final String TAB_SPACE_CHAR = "\t";
+
+ @Override
+ public String format(String content, boolean isLineStart,
+ String indentation, int[] positions) {
- ArrayList<String> formattedWords = new ArrayList<>();
- int currentLineLength = indentation.length();
- boolean newLineBegin = true;
+ ArrayList<String> formattedWords = new ArrayList<>();
+ int currentLineLength = indentation.length();
+ boolean newLineBegin = true;
- String firstLine = "";
-
- // if first line is not from the start, ignore it
- if (!isLineStart) {
- int eol;
- if ((eol = content.indexOf('\n')) == content.length() - 1) {
- return content;
- } else {
- firstLine = content.substring(0, eol + 1);
- content = content.substring(eol + 1);
- }
- }
+ String firstLine = "";
+
+ // if first line is not from the start, ignore it
+ if (!isLineStart) {
+ int eol;
+ if ((eol = content.indexOf('\n')) == content.length() - 1) {
+ return content;
+ } else {
+ firstLine = content.substring(0, eol + 1);
+ content = content.substring(eol + 1);
+ }
+ }
- StringTokenizer candidateWords = new StringTokenizer(content,
- NEW_LINE_CHAR + WHITE_SPACE_CHAR + TAB_SPACE_CHAR, true);
+ StringTokenizer candidateWords = new StringTokenizer(content,
+ NEW_LINE_CHAR + WHITE_SPACE_CHAR + TAB_SPACE_CHAR, true);
- boolean seenFirstWord = false;
+ boolean seenFirstWord = false;
- boolean addedFirstNL = false;
- while (candidateWords.hasMoreTokens()) {
+ boolean addedFirstNL = false;
+ while (candidateWords.hasMoreTokens()) {
- String cword = candidateWords.nextToken();
+ String cword = candidateWords.nextToken();
- if (!seenFirstWord) {
+ if (!seenFirstWord) {
- if ((cword.indexOf(NEW_LINE_CHAR) < 0
- && cword.indexOf(WHITE_SPACE_CHAR) < 0 && cword
- .indexOf(TAB_SPACE_CHAR) < 0)) {
- seenFirstWord = true;
- } else {
- if (!addedFirstNL && cword.indexOf(NEW_LINE_CHAR) >= 0) {
- firstLine += "\n";
- addedFirstNL = true;
- }
- continue;
- }
-
- } else {
-
- if (cword.indexOf(NEW_LINE_CHAR) >= 0
- || cword.indexOf(WHITE_SPACE_CHAR) >= 0
- || cword.indexOf(TAB_SPACE_CHAR) >= 0) {
- continue;
- }
- }
-
- // if the word is date, start new line and include
- // names, email, then an empty line.
- if (isDate(cword)) {
-
- // see if we are in middle of line and
- // if so, start new line, else continue.
- if (!newLineBegin)
- formattedWords.add(NEW_LINE_CHAR);
-
- if (formattedWords.size() > 0)
- formattedWords.add(NEW_LINE_CHAR);
-
- // insert date
- formattedWords.add(cword + WHITE_SPACE_CHAR);
-
- // insert name
- cword = candidateWords.nextToken();
- while (!isEmail(cword)) {
-
- if (!cword.equals(WHITE_SPACE_CHAR) && !cword.equals(TAB_SPACE_CHAR) && !cword.equals(NEW_LINE_CHAR)) {
- formattedWords.add(WHITE_SPACE_CHAR + cword);
- }
-
-
- cword = candidateWords.nextToken();
- }
-
- // insert email
- formattedWords.add(WHITE_SPACE_CHAR + WHITE_SPACE_CHAR + cword + NEW_LINE_CHAR);
-
- // inserted header, so insert a empty line
- formattedWords.add(NEW_LINE_CHAR);
- newLineBegin = true;
- currentLineLength = indentation.length();
- continue;
- }
-
- // means beginning of file name, so whole filename should be
- // in one line.
- if (isStar(cword)) {
- // see if we are in middle of line and
- // if so, start new line, else continue.
- if (!newLineBegin) {
- formattedWords.add(NEW_LINE_CHAR);
- currentLineLength = indentation.length();
- }
-
- formattedWords.add(TAB_SPACE_CHAR + cword);
- currentLineLength += cword.length() + 1;
-
- // this should be path name
- cword = candidateWords.nextToken();
- cword = candidateWords.nextToken();
-
- formattedWords.add(WHITE_SPACE_CHAR + cword);
- currentLineLength += cword.length() + 1;
- newLineBegin = false;
- continue;
- }
-
- if (cword.startsWith("(")) {
-
- if (formattedWords.size() > 0)
- formattedWords.add(NEW_LINE_CHAR + TAB_SPACE_CHAR);
- else
- formattedWords.add(TAB_SPACE_CHAR);
-
- currentLineLength = 1;
- // add until closing bracket
-
- boolean skipMultiWhiteSpace = false;
-
- while (!cword.endsWith("):")) {
-
- if (cword.equals(WHITE_SPACE_CHAR) && !skipMultiWhiteSpace) {
- formattedWords.add(cword);
- currentLineLength += cword.length();
- skipMultiWhiteSpace = true;
- }
-
- if (!cword.equals(WHITE_SPACE_CHAR)
- && !cword.equals(NEW_LINE_CHAR)
- && !cword.equals(TAB_SPACE_CHAR)) {
- formattedWords.add(cword);
- currentLineLength += cword.length();
- skipMultiWhiteSpace = false;
- }
-
- cword = candidateWords.nextToken();
- }
- formattedWords.add(cword);
- currentLineLength += cword.length();
- newLineBegin = false;
-
- continue;
- }
-
- if (currentLineLength + cword.length() > 80) {
- formattedWords.add(NEW_LINE_CHAR + TAB_SPACE_CHAR + cword);
- currentLineLength = indentation.length() + cword.length();
- newLineBegin = false;
- } else {
- if (newLineBegin) {
- formattedWords.add(TAB_SPACE_CHAR);
- newLineBegin = false;
- } else {
- formattedWords.add(WHITE_SPACE_CHAR);
- }
- formattedWords.add(cword);
- currentLineLength += cword.length() + 1;
-
- }
- }
-
- String finalContent = "";
-
- for (String formattedWord: formattedWords) {
- finalContent +=formattedWord;
- }
-
- return firstLine + finalContent;
- }
-
- private boolean isDate(String inputStr) {
-
- // Set up patterns for looking for the next date in the changelog
- SimpleDateFormat isoDate = new SimpleDateFormat("yyyy-MM-dd");
-
- // Try to find next Date bounded changelog entry by parsing date
- // patterns
- // First start with an ISO date
- try {
- Date ad = isoDate.parse(inputStr);
- if (ad != null)
- return true;
- } catch (ParseException e) {
- // We don't really care on exception; it just means it could not
- // parse a date on that line
- }
- return false;
- }
-
- private boolean isEmail(String inputStr) {
- return inputStr.startsWith("<") && inputStr.endsWith(">");
- }
-
- private boolean isStar(String inputStr) {
- return inputStr.equals("*");
- }
-
- @Override
- public void formatterStarts(String initialIndentation) {
-
- }
-
- @Override
- public void formatterStops() {
-
- }
+ if ((cword.indexOf(NEW_LINE_CHAR) < 0
+ && cword.indexOf(WHITE_SPACE_CHAR) < 0 && cword
+ .indexOf(TAB_SPACE_CHAR) < 0)) {
+ seenFirstWord = true;
+ } else {
+ if (!addedFirstNL && cword.indexOf(NEW_LINE_CHAR) >= 0) {
+ firstLine += "\n";
+ addedFirstNL = true;
+ }
+ continue;
+ }
+
+ } else {
+
+ if (cword.indexOf(NEW_LINE_CHAR) >= 0
+ || cword.indexOf(WHITE_SPACE_CHAR) >= 0
+ || cword.indexOf(TAB_SPACE_CHAR) >= 0) {
+ continue;
+ }
+ }
+
+ // if the word is date, start new line and include
+ // names, email, then an empty line.
+ if (isDate(cword)) {
+
+ // see if we are in middle of line and
+ // if so, start new line, else continue.
+ if (!newLineBegin)
+ formattedWords.add(NEW_LINE_CHAR);
+
+ if (formattedWords.size() > 0)
+ formattedWords.add(NEW_LINE_CHAR);
+
+ // insert date
+ formattedWords.add(cword + WHITE_SPACE_CHAR);
+
+ // insert name
+ cword = candidateWords.nextToken();
+ while (!isEmail(cword)) {
+
+ if (!cword.equals(WHITE_SPACE_CHAR) && !cword.equals(TAB_SPACE_CHAR) && !cword.equals(NEW_LINE_CHAR)) {
+ formattedWords.add(WHITE_SPACE_CHAR + cword);
+ }
+
+
+ cword = candidateWords.nextToken();
+ }
+
+ // insert email
+ formattedWords.add(WHITE_SPACE_CHAR + WHITE_SPACE_CHAR + cword + NEW_LINE_CHAR);
+
+ // inserted header, so insert a empty line
+ formattedWords.add(NEW_LINE_CHAR);
+ newLineBegin = true;
+ currentLineLength = indentation.length();
+ continue;
+ }
+
+ // means beginning of file name, so whole filename should be
+ // in one line.
+ if (isStar(cword)) {
+ // see if we are in middle of line and
+ // if so, start new line, else continue.
+ if (!newLineBegin) {
+ formattedWords.add(NEW_LINE_CHAR);
+ currentLineLength = indentation.length();
+ }
+
+ formattedWords.add(TAB_SPACE_CHAR + cword);
+ currentLineLength += cword.length() + 1;
+
+ // this should be path name
+ cword = candidateWords.nextToken();
+ cword = candidateWords.nextToken();
+
+ formattedWords.add(WHITE_SPACE_CHAR + cword);
+ currentLineLength += cword.length() + 1;
+ newLineBegin = false;
+ continue;
+ }
+
+ if (cword.startsWith("(")) {
+
+ if (formattedWords.size() > 0)
+ formattedWords.add(NEW_LINE_CHAR + TAB_SPACE_CHAR);
+ else
+ formattedWords.add(TAB_SPACE_CHAR);
+
+ currentLineLength = 1;
+ // add until closing bracket
+
+ boolean skipMultiWhiteSpace = false;
+
+ while (!cword.endsWith("):")) {
+
+ if (cword.equals(WHITE_SPACE_CHAR) && !skipMultiWhiteSpace) {
+ formattedWords.add(cword);
+ currentLineLength += cword.length();
+ skipMultiWhiteSpace = true;
+ }
+
+ if (!cword.equals(WHITE_SPACE_CHAR)
+ && !cword.equals(NEW_LINE_CHAR)
+ && !cword.equals(TAB_SPACE_CHAR)) {
+ formattedWords.add(cword);
+ currentLineLength += cword.length();
+ skipMultiWhiteSpace = false;
+ }
+
+ cword = candidateWords.nextToken();
+ }
+ formattedWords.add(cword);
+ currentLineLength += cword.length();
+ newLineBegin = false;
+
+ continue;
+ }
+
+ if (currentLineLength + cword.length() > 80) {
+ formattedWords.add(NEW_LINE_CHAR + TAB_SPACE_CHAR + cword);
+ currentLineLength = indentation.length() + cword.length();
+ newLineBegin = false;
+ } else {
+ if (newLineBegin) {
+ formattedWords.add(TAB_SPACE_CHAR);
+ newLineBegin = false;
+ } else {
+ formattedWords.add(WHITE_SPACE_CHAR);
+ }
+ formattedWords.add(cword);
+ currentLineLength += cword.length() + 1;
+
+ }
+ }
+
+ String finalContent = "";
+
+ for (String formattedWord: formattedWords) {
+ finalContent +=formattedWord;
+ }
+
+ return firstLine + finalContent;
+ }
+
+ private boolean isDate(String inputStr) {
+
+ // Set up patterns for looking for the next date in the changelog
+ SimpleDateFormat isoDate = new SimpleDateFormat("yyyy-MM-dd");
+
+ // Try to find next Date bounded changelog entry by parsing date
+ // patterns
+ // First start with an ISO date
+ try {
+ Date ad = isoDate.parse(inputStr);
+ if (ad != null)
+ return true;
+ } catch (ParseException e) {
+ // We don't really care on exception; it just means it could not
+ // parse a date on that line
+ }
+ return false;
+ }
+
+ private boolean isEmail(String inputStr) {
+ return inputStr.startsWith("<") && inputStr.endsWith(">");
+ }
+
+ private boolean isStar(String inputStr) {
+ return inputStr.equals("*");
+ }
+
+ @Override
+ public void formatterStarts(String initialIndentation) {
+
+ }
+
+ @Override
+ public void formatterStops() {
+
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ColorManager.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ColorManager.java
index 861069d335..c00e41cc56 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ColorManager.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/ColorManager.java
@@ -26,20 +26,20 @@ import org.eclipse.swt.widgets.Display;
*/
public class ColorManager {
- protected Map<RGB, Color> fColorTable = new HashMap<>(10);
+ protected Map<RGB, Color> fColorTable = new HashMap<>(10);
- public void dispose() {
- for (Color color: fColorTable.values()){
- color.dispose();
- }
- }
+ public void dispose() {
+ for (Color color: fColorTable.values()){
+ color.dispose();
+ }
+ }
- public Color getColor(RGB rgb) {
- Color color = fColorTable.get(rgb);
- if (color == null) {
- color = new Color(Display.getCurrent(), rgb);
- fColorTable.put(rgb, color);
- }
- return color;
- }
+ public Color getColor(RGB rgb) {
+ Color color = fColorTable.get(rgb);
+ if (color == null) {
+ color = new Color(Display.getCurrent(), rgb);
+ fColorTable.put(rgb, color);
+ }
+ return color;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/FileHyperlink.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/FileHyperlink.java
index 756e2314ad..f0e111e548 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/FileHyperlink.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/FileHyperlink.java
@@ -25,43 +25,43 @@ import org.eclipse.ui.PlatformUI;
*/
public class FileHyperlink implements IHyperlink {
- private IFile fileLoc;
+ private IFile fileLoc;
- private IRegion region;
+ private IRegion region;
- public FileHyperlink(IRegion regionIn, IFile fileIn) {
- fileLoc = fileIn;
- region = regionIn;
- }
+ public FileHyperlink(IRegion regionIn, IFile fileIn) {
+ fileLoc = fileIn;
+ region = regionIn;
+ }
- @Override
- public IRegion getHyperlinkRegion() {
- return region;
- }
+ @Override
+ public IRegion getHyperlinkRegion() {
+ return region;
+ }
- @Override
- public String getTypeLabel() {
- return null;
- }
+ @Override
+ public String getTypeLabel() {
+ return null;
+ }
- @Override
- public String getHyperlinkText() {
- return null;
- }
+ @Override
+ public String getHyperlinkText() {
+ return null;
+ }
- /**
- * Opens the hyperlink in new editor window.
- */
- @Override
- public void open() {
- IWorkbench ws = PlatformUI.getWorkbench();
- try {
- org.eclipse.ui.ide.IDE.openEditor(ws.getActiveWorkbenchWindow()
- .getActivePage(), fileLoc, true);
- } catch (PartInitException e) {
- e.printStackTrace();
+ /**
+ * Opens the hyperlink in new editor window.
+ */
+ @Override
+ public void open() {
+ IWorkbench ws = PlatformUI.getWorkbench();
+ try {
+ org.eclipse.ui.ide.IDE.openEditor(ws.getActiveWorkbenchWindow()
+ .getActivePage(), fileLoc, true);
+ } catch (PartInitException e) {
+ e.printStackTrace();
- }
+ }
- }
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUEditorConfiguration.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUEditorConfiguration.java
index c673a26259..df6b6c7f55 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUEditorConfiguration.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUEditorConfiguration.java
@@ -36,144 +36,144 @@ import org.eclipse.ui.editors.text.TextSourceViewerConfiguration;
* @author klee (Kyu Lee)
*/
public class GNUEditorConfiguration extends TextSourceViewerConfiguration implements
- IEditorChangeLogContrib, IEditorChangeLogContrib2 {
-
- public static final String CHANGELOG_PARTITIONING= "gnu_changelog_partitioning"; //$NON-NLS-1$
-
- private GNUElementScanner scanner;
-
- private ColorManager colorManager;
-
- private TextEditor parentEditor;
-
- /**
- * Prepares configuration.
- */
- public GNUEditorConfiguration() {
- this.colorManager = new ColorManager();
-
- }
-
- /**
- * Sets TextEditor that this configuration is going to be applied.
- */
- @Override
- public void setTextEditor(TextEditor editor) {
- parentEditor = editor;
- }
-
- /**
- * Get configured content types.
- *
- * @return array of configured content types.
- */
- @Override
- public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
- return new String[] { IDocument.DEFAULT_CONTENT_TYPE,
- GNUPartitionScanner.CHANGELOG_EMAIL,
- GNUPartitionScanner.CHANGELOG_SRC_ENTRY};
- }
-
- private GNUElementScanner getChangeLogFileScanner() {
- if (scanner == null) {
- scanner = new GNUElementScanner(colorManager);
- scanner.setDefaultReturnToken(new Token(new TextAttribute(
- colorManager.getColor(IChangeLogColorConstants.TEXT))));
- }
- return scanner;
- }
-
- /**
- * Detects hyperlinks in GNU formatted changelogs.
- *
- * @return link detector for GNU format.
- */
- @Override
- public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) {
- if (sourceViewer == null)
- return null;
-
- return getRegisteredHyperlinkDetectors(sourceViewer);
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer)
- */
- @Override
- public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) {
- return CHANGELOG_PARTITIONING;
- }
-
- /**
- * Set content formatter. For ChangeLog, it just wraps lines.
- */
- @Override
- public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
-
- ContentFormatter cf = new ContentFormatter();
-
- // no partitions
- cf.enablePartitionAwareFormatting(false);
-
- ChangeLogFormattingStrategy cfs = new ChangeLogFormattingStrategy();
-
- cf.setFormattingStrategy(cfs, IDocument.DEFAULT_CONTENT_TYPE);
-
-
- return cf;
- }
-
-
- /**
- * Highlights GNU format changelog syntaxes.
- *
- * @return reconciler for GNU format changelog.
- */
- @Override
- public IPresentationReconciler getPresentationReconciler(
- ISourceViewer sourceViewer) {
- PresentationReconciler reconciler = new PresentationReconciler();
-
- DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getChangeLogFileScanner());
- reconciler.setDamager(dr, GNUPartitionScanner.CHANGELOG_EMAIL);
- reconciler.setRepairer(dr, GNUPartitionScanner.CHANGELOG_EMAIL);
-
- dr= new GNUFileEntryDamagerRepairer(getChangeLogFileScanner());
- reconciler.setDamager(dr, GNUPartitionScanner.CHANGELOG_SRC_ENTRY);
- reconciler.setRepairer(dr, GNUPartitionScanner.CHANGELOG_SRC_ENTRY);
-
- dr= new MultilineRuleDamagerRepairer(getChangeLogFileScanner());
- reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
- reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
-
- return reconciler;
- }
-
- /**
- * Perform documentation setup to set up partitioning.
- *
- * @param document to set up partitioning on.
- */
- @Override
- public void setup(IDocument document) {
- FastPartitioner partitioner =
- new FastPartitioner(
- new GNUPartitionScanner(),
- GNUPartitionScanner.CHANGELOG_PARTITION_TYPES);
- partitioner.connect(document);
- if (document instanceof IDocumentExtension3) {
- IDocumentExtension3 extension3= (IDocumentExtension3) document;
- extension3.setDocumentPartitioner(CHANGELOG_PARTITIONING, partitioner);
- } else {
- document.setDocumentPartitioner(partitioner);
- }
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Override
- protected Map getHyperlinkDetectorTargets(ISourceViewer sourceViewer) {
- Map targets = super.getHyperlinkDetectorTargets(sourceViewer);
- targets.put("org.eclipse.changelog.editor.target", parentEditor); //$NON-NLS-1$
- targets.put("org.eclipse.ui.DefaultTextEditor", parentEditor); //$NON-NLS-1$
- return targets;
- }}
+ IEditorChangeLogContrib, IEditorChangeLogContrib2 {
+
+ public static final String CHANGELOG_PARTITIONING= "gnu_changelog_partitioning"; //$NON-NLS-1$
+
+ private GNUElementScanner scanner;
+
+ private ColorManager colorManager;
+
+ private TextEditor parentEditor;
+
+ /**
+ * Prepares configuration.
+ */
+ public GNUEditorConfiguration() {
+ this.colorManager = new ColorManager();
+
+ }
+
+ /**
+ * Sets TextEditor that this configuration is going to be applied.
+ */
+ @Override
+ public void setTextEditor(TextEditor editor) {
+ parentEditor = editor;
+ }
+
+ /**
+ * Get configured content types.
+ *
+ * @return array of configured content types.
+ */
+ @Override
+ public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
+ return new String[] { IDocument.DEFAULT_CONTENT_TYPE,
+ GNUPartitionScanner.CHANGELOG_EMAIL,
+ GNUPartitionScanner.CHANGELOG_SRC_ENTRY};
+ }
+
+ private GNUElementScanner getChangeLogFileScanner() {
+ if (scanner == null) {
+ scanner = new GNUElementScanner(colorManager);
+ scanner.setDefaultReturnToken(new Token(new TextAttribute(
+ colorManager.getColor(IChangeLogColorConstants.TEXT))));
+ }
+ return scanner;
+ }
+
+ /**
+ * Detects hyperlinks in GNU formatted changelogs.
+ *
+ * @return link detector for GNU format.
+ */
+ @Override
+ public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) {
+ if (sourceViewer == null)
+ return null;
+
+ return getRegisteredHyperlinkDetectors(sourceViewer);
+ }
+
+ /*
+ * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer)
+ */
+ @Override
+ public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) {
+ return CHANGELOG_PARTITIONING;
+ }
+
+ /**
+ * Set content formatter. For ChangeLog, it just wraps lines.
+ */
+ @Override
+ public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
+
+ ContentFormatter cf = new ContentFormatter();
+
+ // no partitions
+ cf.enablePartitionAwareFormatting(false);
+
+ ChangeLogFormattingStrategy cfs = new ChangeLogFormattingStrategy();
+
+ cf.setFormattingStrategy(cfs, IDocument.DEFAULT_CONTENT_TYPE);
+
+
+ return cf;
+ }
+
+
+ /**
+ * Highlights GNU format changelog syntaxes.
+ *
+ * @return reconciler for GNU format changelog.
+ */
+ @Override
+ public IPresentationReconciler getPresentationReconciler(
+ ISourceViewer sourceViewer) {
+ PresentationReconciler reconciler = new PresentationReconciler();
+
+ DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getChangeLogFileScanner());
+ reconciler.setDamager(dr, GNUPartitionScanner.CHANGELOG_EMAIL);
+ reconciler.setRepairer(dr, GNUPartitionScanner.CHANGELOG_EMAIL);
+
+ dr= new GNUFileEntryDamagerRepairer(getChangeLogFileScanner());
+ reconciler.setDamager(dr, GNUPartitionScanner.CHANGELOG_SRC_ENTRY);
+ reconciler.setRepairer(dr, GNUPartitionScanner.CHANGELOG_SRC_ENTRY);
+
+ dr= new MultilineRuleDamagerRepairer(getChangeLogFileScanner());
+ reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
+ reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
+
+ return reconciler;
+ }
+
+ /**
+ * Perform documentation setup to set up partitioning.
+ *
+ * @param document to set up partitioning on.
+ */
+ @Override
+ public void setup(IDocument document) {
+ FastPartitioner partitioner =
+ new FastPartitioner(
+ new GNUPartitionScanner(),
+ GNUPartitionScanner.CHANGELOG_PARTITION_TYPES);
+ partitioner.connect(document);
+ if (document instanceof IDocumentExtension3) {
+ IDocumentExtension3 extension3= (IDocumentExtension3) document;
+ extension3.setDocumentPartitioner(CHANGELOG_PARTITIONING, partitioner);
+ } else {
+ document.setDocumentPartitioner(partitioner);
+ }
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ @Override
+ protected Map getHyperlinkDetectorTargets(ISourceViewer sourceViewer) {
+ Map targets = super.getHyperlinkDetectorTargets(sourceViewer);
+ targets.put("org.eclipse.changelog.editor.target", parentEditor); //$NON-NLS-1$
+ targets.put("org.eclipse.ui.DefaultTextEditor", parentEditor); //$NON-NLS-1$
+ return targets;
+ }}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUElementScanner.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUElementScanner.java
index 2d921b92f8..1707f941d8 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUElementScanner.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUElementScanner.java
@@ -16,94 +16,94 @@ import org.eclipse.jface.text.rules.*;
/**
* Recognizes GNU format changelog. Can be configured to return different types
* of tokens.
- *
+ *
* @author klee (Kyu Lee)
*/
public class GNUElementScanner extends RuleBasedScanner {
- public static final String FILE_NAME = "_file_name"; // $NON-NLS-1$
+ public static final String FILE_NAME = "_file_name"; // $NON-NLS-1$
public static final String TEXT = "_text_content"; // $NON-NLS-1$
- public static final String EMAIL = "_author_email"; // $NON-NLS-1$
- public static final String DATE = "_entry_date"; // $NON-NLS-1$
- public static final String AUTHOR = "_author_name"; // $NON-NLS-1$
- public static final String FUNC_NAME = "_function_name"; // $NON-NLS-1$
- public static final String OTHER = "_other"; // $NON-NLS-1$
- /**
- * Build a scanner for syntax highlighting.
- *
- * @param manager Color scheme to use.
- */
- public GNUElementScanner(ColorManager manager) {
- IToken file = new Token(new TextAttribute(manager
- .getColor(IChangeLogColorConstants.FILE_NAME)));
-
- IToken func = new Token(new TextAttribute(manager
- .getColor(IChangeLogColorConstants.FUNC_NAME)));
-
- IToken email = new Token(new TextAttribute(manager
- .getColor(IChangeLogColorConstants.EMAIL)));
-
- IToken other = new Token(new TextAttribute(manager
- .getColor(IChangeLogColorConstants.TEXT)));
-
- IRule[] rules = new IRule[3];
-
- // Add rule for file path
- rules[0] = new GNUFileEntryRule(file);
-
- // function
- rules[1] = new SingleLineRule("(", ")", func); // $NON-NLS-1$ // $NON-NLS-2$
- // email
- rules[2] = new SingleLineRule("<", ">\n", email); // $NON-NLS-1$ // $NON-NLS-2$
-
- setDefaultReturnToken(other);
-
- setRules(rules);
- }
-
- /**
- * Build a scanner for hyperlink.
- *
- */
- public GNUElementScanner() {
- IToken file = new Token(FILE_NAME);
-
- IToken func = new Token(FUNC_NAME);
-
- IToken email = new Token(EMAIL);
-
- IToken other = new Token(OTHER);
-
- IRule[] rules = new IRule[3];
-
- // Add rule for file path
- rules[0] = new GNUFileEntryRule(file);
-
- // function
- rules[1] = new SingleLineRule("(", "):", func); // $NON-NLS-1$ // $NON-NLS-2$
- // email
- rules[2]= new SingleLineRule("<", ">", email); // $NON-NLS-1$ // $NON-NLS-2$
-
- setDefaultReturnToken(other);
-
- setRules(rules);
- }
-
- /**
- * Get the file offset.
- *
- * @return the file offset.
- */
- public int getOffset() {
- return fOffset;
- }
-
- /**
- * Get the default token.
- *
- * @return the default token.
- */
- public IToken getDefaultToken() {
- return fDefaultReturnToken;
- }
+ public static final String EMAIL = "_author_email"; // $NON-NLS-1$
+ public static final String DATE = "_entry_date"; // $NON-NLS-1$
+ public static final String AUTHOR = "_author_name"; // $NON-NLS-1$
+ public static final String FUNC_NAME = "_function_name"; // $NON-NLS-1$
+ public static final String OTHER = "_other"; // $NON-NLS-1$
+ /**
+ * Build a scanner for syntax highlighting.
+ *
+ * @param manager Color scheme to use.
+ */
+ public GNUElementScanner(ColorManager manager) {
+ IToken file = new Token(new TextAttribute(manager
+ .getColor(IChangeLogColorConstants.FILE_NAME)));
+
+ IToken func = new Token(new TextAttribute(manager
+ .getColor(IChangeLogColorConstants.FUNC_NAME)));
+
+ IToken email = new Token(new TextAttribute(manager
+ .getColor(IChangeLogColorConstants.EMAIL)));
+
+ IToken other = new Token(new TextAttribute(manager
+ .getColor(IChangeLogColorConstants.TEXT)));
+
+ IRule[] rules = new IRule[3];
+
+ // Add rule for file path
+ rules[0] = new GNUFileEntryRule(file);
+
+ // function
+ rules[1] = new SingleLineRule("(", ")", func); // $NON-NLS-1$ // $NON-NLS-2$
+ // email
+ rules[2] = new SingleLineRule("<", ">\n", email); // $NON-NLS-1$ // $NON-NLS-2$
+
+ setDefaultReturnToken(other);
+
+ setRules(rules);
+ }
+
+ /**
+ * Build a scanner for hyperlink.
+ *
+ */
+ public GNUElementScanner() {
+ IToken file = new Token(FILE_NAME);
+
+ IToken func = new Token(FUNC_NAME);
+
+ IToken email = new Token(EMAIL);
+
+ IToken other = new Token(OTHER);
+
+ IRule[] rules = new IRule[3];
+
+ // Add rule for file path
+ rules[0] = new GNUFileEntryRule(file);
+
+ // function
+ rules[1] = new SingleLineRule("(", "):", func); // $NON-NLS-1$ // $NON-NLS-2$
+ // email
+ rules[2]= new SingleLineRule("<", ">", email); // $NON-NLS-1$ // $NON-NLS-2$
+
+ setDefaultReturnToken(other);
+
+ setRules(rules);
+ }
+
+ /**
+ * Get the file offset.
+ *
+ * @return the file offset.
+ */
+ public int getOffset() {
+ return fOffset;
+ }
+
+ /**
+ * Get the default token.
+ *
+ * @return the default token.
+ */
+ public IToken getDefaultToken() {
+ return fDefaultReturnToken;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUFileEntryDamagerRepairer.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUFileEntryDamagerRepairer.java
index 035271c177..95deab2bcb 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUFileEntryDamagerRepairer.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUFileEntryDamagerRepairer.java
@@ -18,26 +18,26 @@ import org.eclipse.jface.text.rules.ITokenScanner;
public class GNUFileEntryDamagerRepairer extends DefaultDamagerRepairer {
- /**
- * Creates a damager/repairer that uses the given scanner. The scanner may not be <code>null</code>
- * and is assumed to return only token that carry text attributes.
- *
- * @param scanner the token scanner to be used, may not be <code>null</code>
- */
- public GNUFileEntryDamagerRepairer(ITokenScanner scanner) {
- super(scanner);
- }
+ /**
+ * Creates a damager/repairer that uses the given scanner. The scanner may not be <code>null</code>
+ * and is assumed to return only token that carry text attributes.
+ *
+ * @param scanner the token scanner to be used, may not be <code>null</code>
+ */
+ public GNUFileEntryDamagerRepairer(ITokenScanner scanner) {
+ super(scanner);
+ }
- /*
- * @see IPresentationDamager#getDamageRegion(ITypedRegion, DocumentEvent, boolean)
- */
- @Override
- public IRegion getDamageRegion(ITypedRegion partition, DocumentEvent e, boolean documentPartitioningChanged) {
- // In the case of a partition with multiline rules, we will punt to
- // reparse the entire partition because we don't know if the line being
- // edited is in the middle of an area covered by a multiline rule. In
- // such a case, we need to back up and find the start sequence of the
- // rule. It is easiest to just reparse the whole partition.
- return partition;
- }
+ /*
+ * @see IPresentationDamager#getDamageRegion(ITypedRegion, DocumentEvent, boolean)
+ */
+ @Override
+ public IRegion getDamageRegion(ITypedRegion partition, DocumentEvent e, boolean documentPartitioningChanged) {
+ // In the case of a partition with multiline rules, we will punt to
+ // reparse the entire partition because we don't know if the line being
+ // edited is in the middle of an area covered by a multiline rule. In
+ // such a case, we need to back up and find the start sequence of the
+ // rule. It is easiest to just reparse the whole partition.
+ return partition;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUFileEntryRule.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUFileEntryRule.java
index 539e8dba8f..a2c9d04193 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUFileEntryRule.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUFileEntryRule.java
@@ -18,128 +18,128 @@ import org.eclipse.jface.text.rules.IWordDetector;
import org.eclipse.jface.text.rules.Token;
public class GNUFileEntryRule implements IPredicateRule {
- /**
- * The default token to be returned on success and if nothing else has been
- * specified.
- */
- protected IToken fileToken;
-
- protected IWordDetector fDetector = new IWordDetector() {
-
- @Override
- public boolean isWordPart(char c) {
- return Character.isJavaIdentifierPart(c) || c == '/' || c == '.' || c == '-';
- }
-
- @Override
- public boolean isWordStart(char c) {
- return Character.isJavaIdentifierPart(c) || c == '/' || c == '.';
- }
-
- };
-
- private boolean started = false;
-
- private IWhitespaceDetector fWsDetector = new IWhitespaceDetector() {
- @Override
- public boolean isWhitespace(char character) {
- return Character.isWhitespace(character);
- }
- };
-
- /** The column constraint */
- protected int fColumn = UNDEFINED;
-
- /** Internal setting for the un-initialized column constraint */
- protected static final int UNDEFINED = -1;
-
- /** Buffer used for pattern detection */
- private StringBuffer fBuffer = new StringBuffer();
-
- private String fStartingSequence = "* ";
-
- public GNUFileEntryRule(IToken fileToken) {
- this.fileToken = fileToken;
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner) {
- return evaluate(scanner, false);
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner, boolean resume) {
- int c = scanner.read();
- fBuffer.setLength(0);
- if (started == false) {
- for (int i = 0; i < fStartingSequence.length(); i++) {
- fBuffer.append((char) c);
- if (fStartingSequence.charAt(i) != c) {
- unreadBuffer(scanner);
- return Token.UNDEFINED;
- }
- c = scanner.read();
- }
- } else if (c == ',') { // we are continuing after a comma (perhaps we have multiple entries
- fBuffer.append((char) c);
- c = scanner.read();
- while (c != ICharacterScanner.EOF && fWsDetector.isWhitespace((char)c)) {
- fBuffer.append((char) c);
- c = scanner.read();
- }
- scanner.unread();
- return ((GNUElementScanner)scanner).getDefaultToken();
- }
-
- boolean haveFilePart = false;
-
- while (c != ICharacterScanner.EOF) {
- if (fDetector.isWordPart((char) c)) {
- fBuffer.append((char) c);
- haveFilePart = true;
- }
- else if (c == '\\') {
- fBuffer.append((char) c);
- c = scanner.read();
- if (c == ICharacterScanner.EOF) {
- unreadBuffer(scanner);
- return Token.UNDEFINED;
- }
- fBuffer.append((char) c);
- } else {
- break;
- }
- c = scanner.read();
- }
-
- if (!haveFilePart) {
- unreadBuffer(scanner);
- return Token.UNDEFINED;
- }
-
- if (c == ',')
- started = true;
-
- scanner.unread();
- return fileToken;
- }
-
- /**
- * Returns the characters in the buffer to the scanner.
- *
- * @param scanner
- * the scanner to be used
- */
- private void unreadBuffer(ICharacterScanner scanner) {
- for (int i = fBuffer.length() - 1; i >= 0; i--) {
- scanner.unread();
- }
- started = false;
- }
-
- @Override
- public IToken getSuccessToken() {
- return fileToken;
- }
+ /**
+ * The default token to be returned on success and if nothing else has been
+ * specified.
+ */
+ protected IToken fileToken;
+
+ protected IWordDetector fDetector = new IWordDetector() {
+
+ @Override
+ public boolean isWordPart(char c) {
+ return Character.isJavaIdentifierPart(c) || c == '/' || c == '.' || c == '-';
+ }
+
+ @Override
+ public boolean isWordStart(char c) {
+ return Character.isJavaIdentifierPart(c) || c == '/' || c == '.';
+ }
+
+ };
+
+ private boolean started = false;
+
+ private IWhitespaceDetector fWsDetector = new IWhitespaceDetector() {
+ @Override
+ public boolean isWhitespace(char character) {
+ return Character.isWhitespace(character);
+ }
+ };
+
+ /** The column constraint */
+ protected int fColumn = UNDEFINED;
+
+ /** Internal setting for the un-initialized column constraint */
+ protected static final int UNDEFINED = -1;
+
+ /** Buffer used for pattern detection */
+ private StringBuffer fBuffer = new StringBuffer();
+
+ private String fStartingSequence = "* ";
+
+ public GNUFileEntryRule(IToken fileToken) {
+ this.fileToken = fileToken;
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner) {
+ return evaluate(scanner, false);
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner, boolean resume) {
+ int c = scanner.read();
+ fBuffer.setLength(0);
+ if (started == false) {
+ for (int i = 0; i < fStartingSequence.length(); i++) {
+ fBuffer.append((char) c);
+ if (fStartingSequence.charAt(i) != c) {
+ unreadBuffer(scanner);
+ return Token.UNDEFINED;
+ }
+ c = scanner.read();
+ }
+ } else if (c == ',') { // we are continuing after a comma (perhaps we have multiple entries
+ fBuffer.append((char) c);
+ c = scanner.read();
+ while (c != ICharacterScanner.EOF && fWsDetector.isWhitespace((char)c)) {
+ fBuffer.append((char) c);
+ c = scanner.read();
+ }
+ scanner.unread();
+ return ((GNUElementScanner)scanner).getDefaultToken();
+ }
+
+ boolean haveFilePart = false;
+
+ while (c != ICharacterScanner.EOF) {
+ if (fDetector.isWordPart((char) c)) {
+ fBuffer.append((char) c);
+ haveFilePart = true;
+ }
+ else if (c == '\\') {
+ fBuffer.append((char) c);
+ c = scanner.read();
+ if (c == ICharacterScanner.EOF) {
+ unreadBuffer(scanner);
+ return Token.UNDEFINED;
+ }
+ fBuffer.append((char) c);
+ } else {
+ break;
+ }
+ c = scanner.read();
+ }
+
+ if (!haveFilePart) {
+ unreadBuffer(scanner);
+ return Token.UNDEFINED;
+ }
+
+ if (c == ',')
+ started = true;
+
+ scanner.unread();
+ return fileToken;
+ }
+
+ /**
+ * Returns the characters in the buffer to the scanner.
+ *
+ * @param scanner
+ * the scanner to be used
+ */
+ private void unreadBuffer(ICharacterScanner scanner) {
+ for (int i = fBuffer.length() - 1; i >= 0; i--) {
+ scanner.unread();
+ }
+ started = false;
+ }
+
+ @Override
+ public IToken getSuccessToken() {
+ return fileToken;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUHyperlinkDetector.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUHyperlinkDetector.java
index 8779d30211..889a657fa3 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUHyperlinkDetector.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUHyperlinkDetector.java
@@ -39,172 +39,172 @@ import org.eclipse.ui.texteditor.ITextEditor;
*/
public class GNUHyperlinkDetector extends AbstractHyperlinkDetector {
- private IPath documentLocation;
-
- public GNUHyperlinkDetector() {
- }
-
- /**
- * Creates a new URL hyperlink detector for GNU Format changelogs.
- *
- * NOTE: It assumes that the path this ChangeLog is in, is root
- * directory of path names in this ChangeLog.
- *
- * ex) ChangeLog is in /some/project and in ChangeLog, path names are like
- * abc/file.java ghi/file2.java
- *
- * then absolute path of file.java and file2.java are
- * /some/project/abc/file.java and /some/project/ghi/file2.java
- *
- * @param textViewer The text viewer in which to detect the hyperlink.
- */
- public GNUHyperlinkDetector(ITextViewer textViewer, TextEditor editor) {
- Assert.isNotNull(textViewer);
-
- documentLocation = getDocumentLocation(editor);
-
- }
-
- /**
- * Detector using RuleBasedScanner.
- */
- @Override
- public IHyperlink[] detectHyperlinks(ITextViewer textViewer,
- IRegion region, boolean canShowMultipleHyperlinks) {
- if (documentLocation == null) {
- ITextEditor ed = (ITextEditor) this.getAdapter(ITextEditor.class);
- documentLocation = getDocumentLocation(ed);
- }
-
- IDocument thisDoc = textViewer.getDocument();
-
- GNUElementScanner scanner = new GNUElementScanner();
-
- scanner.setDefaultReturnToken(new Token("default"));
-
- ITypedRegion partitionInfo = null;
-
- try {
- partitionInfo = thisDoc.getPartition(region.getOffset());
- } catch (org.eclipse.jface.text.BadLocationException e1) {
- e1.printStackTrace();
- return null;
- }
-
- scanner.setRange(thisDoc, partitionInfo.getOffset(), partitionInfo.getLength());
-
- Token tmpToken = (Token) scanner.nextToken();
-
- String tokenStr = (String) tmpToken.getData();
-
- if (tokenStr == null) {
- return null;
- }
-
- // try to find non-default token containing region..if none, return null.
- while (region.getOffset() < scanner.getTokenOffset() ||
- region.getOffset() > scanner.getOffset() ||
- tokenStr.equals("default")) {
- tmpToken = (Token) scanner.nextToken();
- tokenStr = (String) tmpToken.getData();
- if (tokenStr == null)
- return null;
- }
-
- Region tokenRegion = new Region(scanner.getTokenOffset(), scanner
- .getTokenLength());
-
- String line = "";
- try {
- line = thisDoc
- .get(tokenRegion.getOffset(), tokenRegion.getLength());
- } catch (org.eclipse.jface.text.BadLocationException e1) {
- e1.printStackTrace();
- return null;
- }
-
- // process file link
- if (tokenStr.equals(GNUElementScanner.FILE_NAME)) {
-
- Region pathRegion = null;
-
- int lineOffset = 0;
-
- // cut "* " if necessary
- if (line.startsWith("* ")) {
- lineOffset = 2;
- line = line.substring(2);
- }
-// int trailingWhiteSpace;
-// if (((trailingWhiteSpace = line.indexOf(":")) > 0)
-// || ((trailingWhiteSpace = line.indexOf(" ")) > 0)) {
+ private IPath documentLocation;
+
+ public GNUHyperlinkDetector() {
+ }
+
+ /**
+ * Creates a new URL hyperlink detector for GNU Format changelogs.
+ *
+ * NOTE: It assumes that the path this ChangeLog is in, is root
+ * directory of path names in this ChangeLog.
+ *
+ * ex) ChangeLog is in /some/project and in ChangeLog, path names are like
+ * abc/file.java ghi/file2.java
+ *
+ * then absolute path of file.java and file2.java are
+ * /some/project/abc/file.java and /some/project/ghi/file2.java
+ *
+ * @param textViewer The text viewer in which to detect the hyperlink.
+ */
+ public GNUHyperlinkDetector(ITextViewer textViewer, TextEditor editor) {
+ Assert.isNotNull(textViewer);
+
+ documentLocation = getDocumentLocation(editor);
+
+ }
+
+ /**
+ * Detector using RuleBasedScanner.
+ */
+ @Override
+ public IHyperlink[] detectHyperlinks(ITextViewer textViewer,
+ IRegion region, boolean canShowMultipleHyperlinks) {
+ if (documentLocation == null) {
+ ITextEditor ed = (ITextEditor) this.getAdapter(ITextEditor.class);
+ documentLocation = getDocumentLocation(ed);
+ }
+
+ IDocument thisDoc = textViewer.getDocument();
+
+ GNUElementScanner scanner = new GNUElementScanner();
+
+ scanner.setDefaultReturnToken(new Token("default"));
+
+ ITypedRegion partitionInfo = null;
+
+ try {
+ partitionInfo = thisDoc.getPartition(region.getOffset());
+ } catch (org.eclipse.jface.text.BadLocationException e1) {
+ e1.printStackTrace();
+ return null;
+ }
+
+ scanner.setRange(thisDoc, partitionInfo.getOffset(), partitionInfo.getLength());
+
+ Token tmpToken = (Token) scanner.nextToken();
+
+ String tokenStr = (String) tmpToken.getData();
+
+ if (tokenStr == null) {
+ return null;
+ }
+
+ // try to find non-default token containing region..if none, return null.
+ while (region.getOffset() < scanner.getTokenOffset() ||
+ region.getOffset() > scanner.getOffset() ||
+ tokenStr.equals("default")) {
+ tmpToken = (Token) scanner.nextToken();
+ tokenStr = (String) tmpToken.getData();
+ if (tokenStr == null)
+ return null;
+ }
+
+ Region tokenRegion = new Region(scanner.getTokenOffset(), scanner
+ .getTokenLength());
+
+ String line = "";
+ try {
+ line = thisDoc
+ .get(tokenRegion.getOffset(), tokenRegion.getLength());
+ } catch (org.eclipse.jface.text.BadLocationException e1) {
+ e1.printStackTrace();
+ return null;
+ }
+
+ // process file link
+ if (tokenStr.equals(GNUElementScanner.FILE_NAME)) {
+
+ Region pathRegion = null;
+
+ int lineOffset = 0;
+
+ // cut "* " if necessary
+ if (line.startsWith("* ")) {
+ lineOffset = 2;
+ line = line.substring(2);
+ }
+// int trailingWhiteSpace;
+// if (((trailingWhiteSpace = line.indexOf(":")) > 0)
+// || ((trailingWhiteSpace = line.indexOf(" ")) > 0)) {
//
-// line = line.substring(0, trailingWhiteSpace);
-// pathRegion = new Region(tokenRegion.getOffset() + lineOffset,
-// trailingWhiteSpace);
-// } else {
- pathRegion = new Region(tokenRegion.getOffset() + lineOffset, line
- .length());
-// }
+// line = line.substring(0, trailingWhiteSpace);
+// pathRegion = new Region(tokenRegion.getOffset() + lineOffset,
+// trailingWhiteSpace);
+// } else {
+ pathRegion = new Region(tokenRegion.getOffset() + lineOffset, line
+ .length());
+// }
- if (documentLocation == null)
- return null;
+ if (documentLocation == null)
+ return null;
- // Replace any escape characters added to name
- line = line.replaceAll("\\\\(.)", "$1");
+ // Replace any escape characters added to name
+ line = line.replaceAll("\\\\(.)", "$1");
- IPath filePath = documentLocation.append(line);
+ IPath filePath = documentLocation.append(line);
- return new IHyperlink[] { new FileHyperlink(pathRegion,
- ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(
- filePath)) };
+ return new IHyperlink[] { new FileHyperlink(pathRegion,
+ ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(
+ filePath)) };
- }
+ }
- return null;
- }
+ return null;
+ }
- private IWorkspaceRoot getWorkspaceRoot() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
+ private IWorkspaceRoot getWorkspaceRoot() {
+ return ResourcesPlugin.getWorkspace().getRoot();
+ }
- /**
- * Get current directory that ChangeLog is in.
- *
- * @param currentEditor
- * @return path that this ChangeLog is in
- */
- private IPath getDocumentLocation(IEditorPart currentEditor) {
- IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
- String WorkspaceRoot = myWorkspaceRoot.getLocation().toOSString();
- IEditorInput cc = currentEditor.getEditorInput();
+ /**
+ * Get current directory that ChangeLog is in.
+ *
+ * @param currentEditor
+ * @return path that this ChangeLog is in
+ */
+ private IPath getDocumentLocation(IEditorPart currentEditor) {
+ IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
+ String WorkspaceRoot = myWorkspaceRoot.getLocation().toOSString();
+ IEditorInput cc = currentEditor.getEditorInput();
- if (cc instanceof IFileEditorInput) {
- IFileEditorInput test = (IFileEditorInput) cc;
- IFile loc = test.getFile();
+ if (cc instanceof IFileEditorInput) {
+ IFileEditorInput test = (IFileEditorInput) cc;
+ IFile loc = test.getFile();
- IPath docLoc = loc.getLocation();
- docLoc = docLoc.removeLastSegments(1);
- return docLoc;
+ IPath docLoc = loc.getLocation();
+ docLoc = docLoc.removeLastSegments(1);
+ return docLoc;
- }
+ }
- if ((cc instanceof SyncInfoCompareInput)
- || (cc instanceof CompareEditorInput)) {
+ if ((cc instanceof SyncInfoCompareInput)
+ || (cc instanceof CompareEditorInput)) {
- CompareEditorInput test = (CompareEditorInput) cc;
- if (test.getCompareResult() == null)
- return null;
+ CompareEditorInput test = (CompareEditorInput) cc;
+ if (test.getCompareResult() == null)
+ return null;
- IPath docLoc = new Path(WorkspaceRoot
- + test.getCompareResult().toString());
- docLoc = docLoc.removeLastSegments(1);
- return docLoc;
+ IPath docLoc = new Path(WorkspaceRoot
+ + test.getCompareResult().toString());
+ docLoc = docLoc.removeLastSegments(1);
+ return docLoc;
- }
+ }
- return null;
- }
+ return null;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUPartitionScanner.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUPartitionScanner.java
index d29dd770c5..c479fd8978 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUPartitionScanner.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/GNUPartitionScanner.java
@@ -20,31 +20,31 @@ import org.eclipse.jface.text.rules.SingleLineRule;
import org.eclipse.jface.text.rules.Token;
public class GNUPartitionScanner extends RuleBasedPartitionScanner {
- // We partition into sections we want to parse from the beginning every time
- // a change occurs within the area. In this case, we are only interested in
- // email entries which are surrounded by < and > and source entries which
- // have one or more file names which may extend across lines.
- public static final String CHANGELOG_EMAIL = "changelog_email"; //$NON-NLS-1$
- public static final String CHANGELOG_SRC_ENTRY = "changelog_src_entry"; //$NON-NLS-1$
- public static final String[] CHANGELOG_PARTITION_TYPES=
- new String[] { CHANGELOG_EMAIL, CHANGELOG_SRC_ENTRY };
-
- /**
- * Creates the partitioner and sets up the appropriate rules.
- */
- public GNUPartitionScanner() {
- super();
-
- List<IPredicateRule> rules= new ArrayList<>();
- Token email = new Token(CHANGELOG_EMAIL);
- Token srcEntry = new Token(CHANGELOG_SRC_ENTRY);
-
- rules.add(new SingleLineRule("<", ">", email, '\\'));
- rules.add(new MultiLineRule("* ", ":", srcEntry, '\\', true));
-
- IPredicateRule[] result= new IPredicateRule[rules.size()];
- rules.toArray(result);
- setPredicateRules(result);
- }
+ // We partition into sections we want to parse from the beginning every time
+ // a change occurs within the area. In this case, we are only interested in
+ // email entries which are surrounded by < and > and source entries which
+ // have one or more file names which may extend across lines.
+ public static final String CHANGELOG_EMAIL = "changelog_email"; //$NON-NLS-1$
+ public static final String CHANGELOG_SRC_ENTRY = "changelog_src_entry"; //$NON-NLS-1$
+ public static final String[] CHANGELOG_PARTITION_TYPES=
+ new String[] { CHANGELOG_EMAIL, CHANGELOG_SRC_ENTRY };
+
+ /**
+ * Creates the partitioner and sets up the appropriate rules.
+ */
+ public GNUPartitionScanner() {
+ super();
+
+ List<IPredicateRule> rules= new ArrayList<>();
+ Token email = new Token(CHANGELOG_EMAIL);
+ Token srcEntry = new Token(CHANGELOG_SRC_ENTRY);
+
+ rules.add(new SingleLineRule("<", ">", email, '\\'));
+ rules.add(new MultiLineRule("* ", ":", srcEntry, '\\', true));
+
+ IPredicateRule[] result= new IPredicateRule[rules.size()];
+ rules.toArray(result);
+ setPredicateRules(result);
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/IChangeLogColorConstants.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/IChangeLogColorConstants.java
index 28d5cf5137..10eae4e6c4 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/IChangeLogColorConstants.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/IChangeLogColorConstants.java
@@ -14,20 +14,20 @@ import org.eclipse.swt.graphics.RGB;
/**
* Color scheme to use for syntax highlighting.
- *
+ *
* @author klee (Kyu Lee)
- *
+ *
*/
public interface IChangeLogColorConstants {
- RGB FILE_NAME = new RGB(128, 0, 0);
+ RGB FILE_NAME = new RGB(128, 0, 0);
- RGB FUNC_NAME = new RGB(0, 128, 0);
+ RGB FUNC_NAME = new RGB(0, 128, 0);
- RGB TEXT = new RGB(0, 0, 0);
+ RGB TEXT = new RGB(0, 0, 0);
- RGB EMAIL = new RGB(0, 0, 128);
+ RGB EMAIL = new RGB(0, 0, 128);
- RGB DATE = new RGB(64, 64, 0);
+ RGB DATE = new RGB(64, 64, 0);
- RGB AUTHOR = new RGB(0, 64, 64);
+ RGB AUTHOR = new RGB(0, 64, 64);
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/MultilineRuleDamagerRepairer.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/MultilineRuleDamagerRepairer.java
index d56d77d8de..b3d100b3cb 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/MultilineRuleDamagerRepairer.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/editors/MultilineRuleDamagerRepairer.java
@@ -17,29 +17,29 @@ import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.ITokenScanner;
public class MultilineRuleDamagerRepairer extends DefaultDamagerRepairer {
-
-
- /**
- * Creates a damager/repairer that uses the given scanner. The scanner may not be <code>null</code>
- * and is assumed to return only token that carry text attributes.
- *
- * @param scanner the token scanner to be used, may not be <code>null</code>
- */
- public MultilineRuleDamagerRepairer(ITokenScanner scanner) {
- super(scanner);
- }
- /*
- * @see IPresentationDamager#getDamageRegion(ITypedRegion, DocumentEvent, boolean)
- */
- @Override
- public IRegion getDamageRegion(ITypedRegion partition, DocumentEvent e, boolean documentPartitioningChanged) {
- // In the case of a partition with multiline rules, we will punt to
- // reparse the entire partition because we don't know if the line being
- // edited is in the middle of an area covered by a multiline rule. In
- // such a case, we need to back up and find the start sequence of the
- // rule. It is easiest to just reparse the whole partition.
- return partition;
- }
-
+
+ /**
+ * Creates a damager/repairer that uses the given scanner. The scanner may not be <code>null</code>
+ * and is assumed to return only token that carry text attributes.
+ *
+ * @param scanner the token scanner to be used, may not be <code>null</code>
+ */
+ public MultilineRuleDamagerRepairer(ITokenScanner scanner) {
+ super(scanner);
+ }
+
+ /*
+ * @see IPresentationDamager#getDamageRegion(ITypedRegion, DocumentEvent, boolean)
+ */
+ @Override
+ public IRegion getDamageRegion(ITypedRegion partition, DocumentEvent e, boolean documentPartitioningChanged) {
+ // In the case of a partition with multiline rules, we will punt to
+ // reparse the entire partition because we don't know if the line being
+ // edited is in the middle of an area covered by a multiline rule. In
+ // such a case, we need to back up and find the start sequence of the
+ // rule. It is easiest to just reparse the whole partition.
+ return partition;
+ }
+
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/formatters/GNUFormat.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/formatters/GNUFormat.java
index 0ef4f965d9..8ed9be02c8 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/formatters/GNUFormat.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/formatters/GNUFormat.java
@@ -37,374 +37,374 @@ import org.eclipse.ui.texteditor.ITextEditor;
*/
public class GNUFormat implements IFormatterChangeLogContrib {
- final String line_sep = System.getProperty("line.separator"); //$NON-NLS-1$
-
- final static String TAB = "\t"; // $NON-NLS-1$
-
-
- @Override
- public String formatDateLine(String authorName, String authorEmail) {
- String detail = returnDate() + " " + //$NON-NLS-1$
- authorName + " " + "<" + authorEmail + ">" + line_sep + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- line_sep;
- return detail;
- }
-
-
- @Override
- public String mergeChangelog(String dateLine, String functionGuess,String defaultContent,
- IEditorPart changelog, String changeLogLocation, String fileLocation) {
-
- String fileDetail = formatFileDetail(changeLogLocation, fileLocation);
- IDocument changelog_doc = getDocument(changelog);
- String function = formatFunction(functionGuess);
- boolean multipleEntrySuccess = false;
- boolean forceNewEntry = false;
- String functionSpacer = " "; // $NON-NLS-1$
- if (function.equals(": ")) // $NON-NLS-1$
- functionSpacer = ""; // $NON-NLS-1$
-
- /* Fix Bz #366854. Make sure that forceNewEntry is used only
- * once and then cleared even when the ChangeLog is empty to start with.
- */
- if(changelog instanceof ChangeLogEditor) {
- ChangeLogEditor editor = (ChangeLogEditor)changelog;
- forceNewEntry = editor.isForceNewLogEntry();
- editor.setForceNewLogEntry(false);
- }
-
- if (changelog_doc.getLength() > 0) {
-
- int offset_start = findChangeLogEntry(changelog_doc, dateLine);
- int offset_end = dateLine.length();
- boolean foundFunction = false;
- //if the prepare change action determines it requires a new entry, we force
- //a new entry by changing the offset_start and change the corresponding field
- //of the editor back to false to prevent subsequent function change log being
- //written to a new entry again.
- if (forceNewEntry)
- offset_start = -1;
-
- if (offset_start != -1) {
- int nextChangeEntry = findChangeLogPattern(changelog_doc,
- offset_start + dateLine.length());
- int functLogEntry = offset_start + dateLine.length();
-
- while (functLogEntry < nextChangeEntry) {
- int line_length = 0;
- String entry = ""; // $NON-NLS-1$
- try {
- line_length = changelog_doc
- .getLineOfOffset(functLogEntry);
- entry = changelog_doc.get(functLogEntry, changelog_doc
- .getLineLength(line_length));
- } catch (BadLocationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- // Look to see if entry already exists for file (will be preceded by "*")
- if (entry.lastIndexOf("* " + fileDetail) > 0) {
- foundFunction = true;
- // Check for the case where the default content (e.g. new or removed file)
- // is being caught again because user has prepared the ChangeLog more than once.
- // In such a case, just return. We don't need to repeat ourselves.
- if (defaultContent.length() > 0 && entry.lastIndexOf(defaultContent) > 0) {
- return ""; // $NON-NLS-1$
- }
- int nextFunctLoc = functLogEntry + fileDetail.length() + 2;
- String nextFunc = ""; // $NON-NLS-1$
- try {
- nextFunc = changelog_doc.get(nextFunctLoc,
- nextChangeEntry - nextFunctLoc);
- } catch (BadLocationException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- int foundFunc = nextFunc.indexOf("* "); // $NON-NLS-1$
- if (foundFunc > 0) {
- foundFunc--;
- try {
- while (changelog_doc.get(
- nextFunctLoc + foundFunc, 1).equals(
- "\t") // $NON-NLS-1$
- || changelog_doc.get(
- nextFunctLoc + foundFunc, 1)
- .equals("\n")) { // $NON-NLS-1$
- foundFunc--;
- }
- } catch (BadLocationException e2) {
- // TODO Auto-generated catch block
- e2.printStackTrace();
- }
- functLogEntry = nextFunctLoc + foundFunc + 1;
- break;
- }
-
- }
- try {
- functLogEntry += changelog_doc
- .getLineLength(line_length);
- } catch (BadLocationException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- if (functLogEntry >= nextChangeEntry) {
- functLogEntry = nextChangeEntry - 1;
- try {
- // Get rid of some potential lines containing whitespace only.
- functLogEntry = removeWhitespaceOnlyLines(changelog_doc, functLogEntry);
- while (changelog_doc.get(functLogEntry, 1).equals("\n")) // $NON-NLS-1$
- functLogEntry--;
- } catch (BadLocationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- functLogEntry++;
- }
-
- if (offset_start != -1) {
- if (foundFunction) {
- try {
- if (!function.equals(": ")) // $NON-NLS-1$
- changelog_doc.replace(functLogEntry, 0, "\n" + TAB // $NON-NLS-1$
- + function + " "); // $NON-NLS-1$
- else
- changelog_doc.replace(functLogEntry, 0, "\n" + TAB // $NON-NLS-1$
- );
- } catch (BadLocationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- ITextEditor edit = (ITextEditor) changelog;
- if (!function.equals(": ")) // $NON-NLS-1$
- edit.selectAndReveal(functLogEntry + function.length()
- + 3, 0);
- else
- edit.selectAndReveal(functLogEntry + function.length()
- , 0);
- multipleEntrySuccess = true;
- } else {
- try {
- changelog_doc.replace(offset_end, 0, TAB
- + "* " + fileDetail + functionSpacer // $NON-NLS-1$
- + function + functionSpacer + defaultContent + "\n"); //$NON-NLS-1$
- } catch (BadLocationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- ITextEditor edit = (ITextEditor) changelog;
- edit.selectAndReveal(offset_end + fileDetail.length()
- + function.length() +functionSpacer.length()*2 + 3 + defaultContent.length(), 0);
- multipleEntrySuccess = true;
- }
-
- }
- }
- }
-
- if (!multipleEntrySuccess) {
- try {
- if (changelog_doc.getLength() > 0)
- changelog_doc.replace(0, 0, "\n\n"); //$NON-NLS-1$
- changelog_doc.replace(0, 0, dateLine + TAB + "* " + fileDetail // $NON-NLS-1$
- + functionSpacer+function+functionSpacer+defaultContent);
-
- ITextEditor edit = (ITextEditor) changelog;
- edit.selectAndReveal(dateLine.length() + fileDetail.length()
- + function.length() + functionSpacer.length()*2 + 3 + defaultContent.length(), 0);
- } catch (BadLocationException e) {
- e.printStackTrace();
-
- }
-
- }
-
- return ""; // $NON-NLS-1$
-
- }
-
- /**
- * Remove any empty lines (i.e. lines only containing whitespace) between
- * <code>offset</code> and index backed-up until a '\n' preceded by some non-whitespace
- * character is reached. Whitespace will be merged to '\n\n'. For example
- * consider the following string "(main): Removed.\n\t\ \n\n\t\n" and
- * <code>offset</code> pointing to the last '\n'. This string would be
- * changed to: "(main): Removed.\n\n".
- *
- * @param changelog_doc
- * @param offset
- * @return The new offset.
- */
- private int removeWhitespaceOnlyLines(IDocument changelog_doc, int offset) {
- int initialOffset = offset;
- int backedUpOffset = offset;
- char charAtOffset;
- try {
- charAtOffset = changelog_doc.get(offset, 1).charAt(0);
- } catch (BadLocationException e) {
- e.printStackTrace();
- return offset;
- }
- while( backedUpOffset > 0 && (charAtOffset == '\n' || charAtOffset == '\t' || charAtOffset == ' ') ) {
- backedUpOffset--;
- try {
- charAtOffset = changelog_doc.get(backedUpOffset, 1).charAt(0);
- } catch (BadLocationException e) {
- e.printStackTrace();
- break;
- }
- }
- if ( (initialOffset - backedUpOffset) > 2 ) {
- try {
- int replaceLength = (initialOffset - backedUpOffset - 2);
- changelog_doc.replace(backedUpOffset + 2, replaceLength, "");
- // change offset accordingly
- offset -= replaceLength;
- } catch (BadLocationException e) {
- // exception should have been thrown earlier if that's
- // really a bad location...
- }
- }
- return offset;
- }
-
- private IWorkspaceRoot getWorkspaceRoot() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
- private String formatFileDetail(String changeLogLocation,
- String editorFileLocation) {
- // Format Path. Is a full path specified, or just file name?
- IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
- String WorkspaceRoot = myWorkspaceRoot.getLocation().toOSString();
- String changeLogLocNoRoot = ""; // $NON-NLS-1$
- String editorFileLocNoRoot = ""; // $NON-NLS-1$
- if (changeLogLocation.lastIndexOf(WorkspaceRoot) >= 0) {
- changeLogLocNoRoot = changeLogLocation.substring(changeLogLocation
- .lastIndexOf(WorkspaceRoot)
- + WorkspaceRoot.length(), changeLogLocation.length());
- } else
- changeLogLocNoRoot = changeLogLocation;
-
- if (editorFileLocation.lastIndexOf(WorkspaceRoot) >= 0) {
- editorFileLocNoRoot = editorFileLocation.substring(
- editorFileLocation.lastIndexOf(WorkspaceRoot),
- editorFileLocation.lastIndexOf(WorkspaceRoot)
- + WorkspaceRoot.length());
- } else
- editorFileLocNoRoot = editorFileLocation;
-
- File changelogLocation = new File(changeLogLocNoRoot);
- File fileLocation = new File(editorFileLocNoRoot);
- File reversePath = fileLocation.getParentFile();
- String reversePathb = ""; // $NON-NLS-1$
-
- while (reversePath.getParentFile() != null) {
- if (reversePath.compareTo(changelogLocation.getParentFile()) == 0)
- break;
- reversePath = reversePath.getParentFile();
- }
- if (reversePath != null)
- reversePathb = fileLocation.toString().substring(
- reversePath.toString().length() + 1,
- fileLocation.toString().length());
- return reversePathb;
- }
-
- private int findChangeLogPattern(IDocument changelog_doc, int startOffset) {
- // find the "pattern" of a changelog entry. Not a specific one,
- // but one that "looks" like an entry
- int nextEntry = startOffset;
- int line_length = 0;
- String entry = ""; // $NON-NLS-1$
- while (nextEntry < changelog_doc.getLength()) {
- try {
- // Get the line of interest in the changelog document
- line_length = changelog_doc.getLineOfOffset(nextEntry);
- entry = changelog_doc.get(nextEntry, changelog_doc
- .getLineLength(line_length));
- // Attempt to find date pattern on line
- if (matchDatePattern(entry)) {
- //nextDate -= entry.length()+1;
- break;
- }
- // If no date matches, move to the next line
- nextEntry += changelog_doc.getLineLength(line_length);
- } catch (BadLocationException e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
- .getMessage(), e
-
- ));
- }
-
- }
- return nextEntry;
- }
-
- private boolean matchDatePattern(String text) {
-
- // Set up patterns for looking for the next date in the changelog
- SimpleDateFormat isoDate = new SimpleDateFormat("yyyy-MM-dd"); // $NON-NLS-1$
-
- // Try to find next Date bounded changelog entry by parsing date patterns
- // First start with an ISO date
- try {
- Date ad = isoDate.parse(text);
- if (ad != null)
- return true;
- } catch (ParseException e) {
- // We don't really care on exception; it just means it could not parse a date on that line
- }
-
- return false;
- }
-
- private int findChangeLogEntry(IDocument changelog_doc, String entry) {
- FindReplaceDocumentAdapter findDocumentAptd = new FindReplaceDocumentAdapter(
- changelog_doc);
- IRegion region = null;
- try {
- region = findDocumentAptd.find(0, entry, true, false,/*whole world */ false, true);
- } catch (BadLocationException e) {
- ChangelogPlugin.getDefault().getLog().log(
- new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
- .getMessage(), e
-
- ));
- return -1;
- }
- if (region != null) {
- // If the user's entry is not at the beginning of the file,
- // make a new entry.
- return region.getOffset() > 0 ? -1 : 0;
- }
- else
- return -1;
- }
-
- private String formatFunction(String function) {
-
- // If Function Guess is true, and Function Guess has found something
- if (function.length() > 0)
- return "(" + function + "):"; // $NON-NLS-1$ // $NON-NLS-2$
- else
- return ": "; //$NON-NLS-1$
-
- }
-
- public IDocument getDocument(IEditorPart currentEditor) {
- AbstractTextEditor castEditor = (AbstractTextEditor) currentEditor;
- IDocumentProvider provider = castEditor.getDocumentProvider();
-
- return provider.getDocument(castEditor.getEditorInput());
- }
-
- private String returnDate() {
- SimpleDateFormat date_Format = new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
- return date_Format.format(new Date());
- }
+ final String line_sep = System.getProperty("line.separator"); //$NON-NLS-1$
+
+ final static String TAB = "\t"; // $NON-NLS-1$
+
+
+ @Override
+ public String formatDateLine(String authorName, String authorEmail) {
+ String detail = returnDate() + " " + //$NON-NLS-1$
+ authorName + " " + "<" + authorEmail + ">" + line_sep + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ line_sep;
+ return detail;
+ }
+
+
+ @Override
+ public String mergeChangelog(String dateLine, String functionGuess,String defaultContent,
+ IEditorPart changelog, String changeLogLocation, String fileLocation) {
+
+ String fileDetail = formatFileDetail(changeLogLocation, fileLocation);
+ IDocument changelog_doc = getDocument(changelog);
+ String function = formatFunction(functionGuess);
+ boolean multipleEntrySuccess = false;
+ boolean forceNewEntry = false;
+ String functionSpacer = " "; // $NON-NLS-1$
+ if (function.equals(": ")) // $NON-NLS-1$
+ functionSpacer = ""; // $NON-NLS-1$
+
+ /* Fix Bz #366854. Make sure that forceNewEntry is used only
+ * once and then cleared even when the ChangeLog is empty to start with.
+ */
+ if(changelog instanceof ChangeLogEditor) {
+ ChangeLogEditor editor = (ChangeLogEditor)changelog;
+ forceNewEntry = editor.isForceNewLogEntry();
+ editor.setForceNewLogEntry(false);
+ }
+
+ if (changelog_doc.getLength() > 0) {
+
+ int offset_start = findChangeLogEntry(changelog_doc, dateLine);
+ int offset_end = dateLine.length();
+ boolean foundFunction = false;
+ //if the prepare change action determines it requires a new entry, we force
+ //a new entry by changing the offset_start and change the corresponding field
+ //of the editor back to false to prevent subsequent function change log being
+ //written to a new entry again.
+ if (forceNewEntry)
+ offset_start = -1;
+
+ if (offset_start != -1) {
+ int nextChangeEntry = findChangeLogPattern(changelog_doc,
+ offset_start + dateLine.length());
+ int functLogEntry = offset_start + dateLine.length();
+
+ while (functLogEntry < nextChangeEntry) {
+ int line_length = 0;
+ String entry = ""; // $NON-NLS-1$
+ try {
+ line_length = changelog_doc
+ .getLineOfOffset(functLogEntry);
+ entry = changelog_doc.get(functLogEntry, changelog_doc
+ .getLineLength(line_length));
+ } catch (BadLocationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ // Look to see if entry already exists for file (will be preceded by "*")
+ if (entry.lastIndexOf("* " + fileDetail) > 0) {
+ foundFunction = true;
+ // Check for the case where the default content (e.g. new or removed file)
+ // is being caught again because user has prepared the ChangeLog more than once.
+ // In such a case, just return. We don't need to repeat ourselves.
+ if (defaultContent.length() > 0 && entry.lastIndexOf(defaultContent) > 0) {
+ return ""; // $NON-NLS-1$
+ }
+ int nextFunctLoc = functLogEntry + fileDetail.length() + 2;
+ String nextFunc = ""; // $NON-NLS-1$
+ try {
+ nextFunc = changelog_doc.get(nextFunctLoc,
+ nextChangeEntry - nextFunctLoc);
+ } catch (BadLocationException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+ int foundFunc = nextFunc.indexOf("* "); // $NON-NLS-1$
+ if (foundFunc > 0) {
+ foundFunc--;
+ try {
+ while (changelog_doc.get(
+ nextFunctLoc + foundFunc, 1).equals(
+ "\t") // $NON-NLS-1$
+ || changelog_doc.get(
+ nextFunctLoc + foundFunc, 1)
+ .equals("\n")) { // $NON-NLS-1$
+ foundFunc--;
+ }
+ } catch (BadLocationException e2) {
+ // TODO Auto-generated catch block
+ e2.printStackTrace();
+ }
+ functLogEntry = nextFunctLoc + foundFunc + 1;
+ break;
+ }
+
+ }
+ try {
+ functLogEntry += changelog_doc
+ .getLineLength(line_length);
+ } catch (BadLocationException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+ }
+ if (functLogEntry >= nextChangeEntry) {
+ functLogEntry = nextChangeEntry - 1;
+ try {
+ // Get rid of some potential lines containing whitespace only.
+ functLogEntry = removeWhitespaceOnlyLines(changelog_doc, functLogEntry);
+ while (changelog_doc.get(functLogEntry, 1).equals("\n")) // $NON-NLS-1$
+ functLogEntry--;
+ } catch (BadLocationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ functLogEntry++;
+ }
+
+ if (offset_start != -1) {
+ if (foundFunction) {
+ try {
+ if (!function.equals(": ")) // $NON-NLS-1$
+ changelog_doc.replace(functLogEntry, 0, "\n" + TAB // $NON-NLS-1$
+ + function + " "); // $NON-NLS-1$
+ else
+ changelog_doc.replace(functLogEntry, 0, "\n" + TAB // $NON-NLS-1$
+ );
+ } catch (BadLocationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ ITextEditor edit = (ITextEditor) changelog;
+ if (!function.equals(": ")) // $NON-NLS-1$
+ edit.selectAndReveal(functLogEntry + function.length()
+ + 3, 0);
+ else
+ edit.selectAndReveal(functLogEntry + function.length()
+ , 0);
+ multipleEntrySuccess = true;
+ } else {
+ try {
+ changelog_doc.replace(offset_end, 0, TAB
+ + "* " + fileDetail + functionSpacer // $NON-NLS-1$
+ + function + functionSpacer + defaultContent + "\n"); //$NON-NLS-1$
+ } catch (BadLocationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ ITextEditor edit = (ITextEditor) changelog;
+ edit.selectAndReveal(offset_end + fileDetail.length()
+ + function.length() +functionSpacer.length()*2 + 3 + defaultContent.length(), 0);
+ multipleEntrySuccess = true;
+ }
+
+ }
+ }
+ }
+
+ if (!multipleEntrySuccess) {
+ try {
+ if (changelog_doc.getLength() > 0)
+ changelog_doc.replace(0, 0, "\n\n"); //$NON-NLS-1$
+ changelog_doc.replace(0, 0, dateLine + TAB + "* " + fileDetail // $NON-NLS-1$
+ + functionSpacer+function+functionSpacer+defaultContent);
+
+ ITextEditor edit = (ITextEditor) changelog;
+ edit.selectAndReveal(dateLine.length() + fileDetail.length()
+ + function.length() + functionSpacer.length()*2 + 3 + defaultContent.length(), 0);
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+
+ }
+
+ }
+
+ return ""; // $NON-NLS-1$
+
+ }
+
+ /**
+ * Remove any empty lines (i.e. lines only containing whitespace) between
+ * <code>offset</code> and index backed-up until a '\n' preceded by some non-whitespace
+ * character is reached. Whitespace will be merged to '\n\n'. For example
+ * consider the following string "(main): Removed.\n\t\ \n\n\t\n" and
+ * <code>offset</code> pointing to the last '\n'. This string would be
+ * changed to: "(main): Removed.\n\n".
+ *
+ * @param changelog_doc
+ * @param offset
+ * @return The new offset.
+ */
+ private int removeWhitespaceOnlyLines(IDocument changelog_doc, int offset) {
+ int initialOffset = offset;
+ int backedUpOffset = offset;
+ char charAtOffset;
+ try {
+ charAtOffset = changelog_doc.get(offset, 1).charAt(0);
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ return offset;
+ }
+ while( backedUpOffset > 0 && (charAtOffset == '\n' || charAtOffset == '\t' || charAtOffset == ' ') ) {
+ backedUpOffset--;
+ try {
+ charAtOffset = changelog_doc.get(backedUpOffset, 1).charAt(0);
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ break;
+ }
+ }
+ if ( (initialOffset - backedUpOffset) > 2 ) {
+ try {
+ int replaceLength = (initialOffset - backedUpOffset - 2);
+ changelog_doc.replace(backedUpOffset + 2, replaceLength, "");
+ // change offset accordingly
+ offset -= replaceLength;
+ } catch (BadLocationException e) {
+ // exception should have been thrown earlier if that's
+ // really a bad location...
+ }
+ }
+ return offset;
+ }
+
+ private IWorkspaceRoot getWorkspaceRoot() {
+ return ResourcesPlugin.getWorkspace().getRoot();
+ }
+
+ private String formatFileDetail(String changeLogLocation,
+ String editorFileLocation) {
+ // Format Path. Is a full path specified, or just file name?
+ IWorkspaceRoot myWorkspaceRoot = getWorkspaceRoot();
+ String WorkspaceRoot = myWorkspaceRoot.getLocation().toOSString();
+ String changeLogLocNoRoot = ""; // $NON-NLS-1$
+ String editorFileLocNoRoot = ""; // $NON-NLS-1$
+ if (changeLogLocation.lastIndexOf(WorkspaceRoot) >= 0) {
+ changeLogLocNoRoot = changeLogLocation.substring(changeLogLocation
+ .lastIndexOf(WorkspaceRoot)
+ + WorkspaceRoot.length(), changeLogLocation.length());
+ } else
+ changeLogLocNoRoot = changeLogLocation;
+
+ if (editorFileLocation.lastIndexOf(WorkspaceRoot) >= 0) {
+ editorFileLocNoRoot = editorFileLocation.substring(
+ editorFileLocation.lastIndexOf(WorkspaceRoot),
+ editorFileLocation.lastIndexOf(WorkspaceRoot)
+ + WorkspaceRoot.length());
+ } else
+ editorFileLocNoRoot = editorFileLocation;
+
+ File changelogLocation = new File(changeLogLocNoRoot);
+ File fileLocation = new File(editorFileLocNoRoot);
+ File reversePath = fileLocation.getParentFile();
+ String reversePathb = ""; // $NON-NLS-1$
+
+ while (reversePath.getParentFile() != null) {
+ if (reversePath.compareTo(changelogLocation.getParentFile()) == 0)
+ break;
+ reversePath = reversePath.getParentFile();
+ }
+ if (reversePath != null)
+ reversePathb = fileLocation.toString().substring(
+ reversePath.toString().length() + 1,
+ fileLocation.toString().length());
+ return reversePathb;
+ }
+
+ private int findChangeLogPattern(IDocument changelog_doc, int startOffset) {
+ // find the "pattern" of a changelog entry. Not a specific one,
+ // but one that "looks" like an entry
+ int nextEntry = startOffset;
+ int line_length = 0;
+ String entry = ""; // $NON-NLS-1$
+ while (nextEntry < changelog_doc.getLength()) {
+ try {
+ // Get the line of interest in the changelog document
+ line_length = changelog_doc.getLineOfOffset(nextEntry);
+ entry = changelog_doc.get(nextEntry, changelog_doc
+ .getLineLength(line_length));
+ // Attempt to find date pattern on line
+ if (matchDatePattern(entry)) {
+ //nextDate -= entry.length()+1;
+ break;
+ }
+ // If no date matches, move to the next line
+ nextEntry += changelog_doc.getLineLength(line_length);
+ } catch (BadLocationException e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
+ .getMessage(), e
+
+ ));
+ }
+
+ }
+ return nextEntry;
+ }
+
+ private boolean matchDatePattern(String text) {
+
+ // Set up patterns for looking for the next date in the changelog
+ SimpleDateFormat isoDate = new SimpleDateFormat("yyyy-MM-dd"); // $NON-NLS-1$
+
+ // Try to find next Date bounded changelog entry by parsing date patterns
+ // First start with an ISO date
+ try {
+ Date ad = isoDate.parse(text);
+ if (ad != null)
+ return true;
+ } catch (ParseException e) {
+ // We don't really care on exception; it just means it could not parse a date on that line
+ }
+
+ return false;
+ }
+
+ private int findChangeLogEntry(IDocument changelog_doc, String entry) {
+ FindReplaceDocumentAdapter findDocumentAptd = new FindReplaceDocumentAdapter(
+ changelog_doc);
+ IRegion region = null;
+ try {
+ region = findDocumentAptd.find(0, entry, true, false,/*whole world */ false, true);
+ } catch (BadLocationException e) {
+ ChangelogPlugin.getDefault().getLog().log(
+ new Status(IStatus.ERROR, ChangelogPlugin.PLUGIN_ID, IStatus.ERROR, e
+ .getMessage(), e
+
+ ));
+ return -1;
+ }
+ if (region != null) {
+ // If the user's entry is not at the beginning of the file,
+ // make a new entry.
+ return region.getOffset() > 0 ? -1 : 0;
+ }
+ else
+ return -1;
+ }
+
+ private String formatFunction(String function) {
+
+ // If Function Guess is true, and Function Guess has found something
+ if (function.length() > 0)
+ return "(" + function + "):"; // $NON-NLS-1$ // $NON-NLS-2$
+ else
+ return ": "; //$NON-NLS-1$
+
+ }
+
+ public IDocument getDocument(IEditorPart currentEditor) {
+ AbstractTextEditor castEditor = (AbstractTextEditor) currentEditor;
+ IDocumentProvider provider = castEditor.getDocumentProvider();
+
+ return provider.getDocument(castEditor.getEditorInput());
+ }
+
+ private String returnDate() {
+ SimpleDateFormat date_Format = new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
+ return date_Format.format(new Date());
+ }
} \ No newline at end of file
diff --git a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ui/ChangeLogActionProvider.java b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ui/ChangeLogActionProvider.java
index db2990f2a0..79d40db6c1 100644
--- a/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ui/ChangeLogActionProvider.java
+++ b/changelog/org.eclipse.linuxtools.changelog.core/src/org/eclipse/linuxtools/internal/changelog/core/ui/ChangeLogActionProvider.java
@@ -20,32 +20,32 @@ import org.eclipse.ui.navigator.ICommonActionConstants;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
public class ChangeLogActionProvider extends CommonActionProvider {
- private Action exampleAction;
-
- @Override
- public void init(ICommonActionExtensionSite aSite) {
- super.init(aSite);
- exampleAction = new PrepareChangeLogAction() {
- @Override
- public void run() {
- setSelection((IStructuredSelection) getContext().getSelection());
- doRun();
- }
-
- };
-
- }
-
- @Override
- public void fillContextMenu(IMenuManager menu) {
- super.fillContextMenu(menu);
- menu.add(exampleAction);
- }
-
- @Override
- public void fillActionBars(IActionBars actionBars) {
-
- actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN,
- exampleAction);
- }
+ private Action exampleAction;
+
+ @Override
+ public void init(ICommonActionExtensionSite aSite) {
+ super.init(aSite);
+ exampleAction = new PrepareChangeLogAction() {
+ @Override
+ public void run() {
+ setSelection((IStructuredSelection) getContext().getSelection());
+ doRun();
+ }
+
+ };
+
+ }
+
+ @Override
+ public void fillContextMenu(IMenuManager menu) {
+ super.fillContextMenu(menu);
+ menu.add(exampleAction);
+ }
+
+ @Override
+ public void fillActionBars(IActionBars actionBars) {
+
+ actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN,
+ exampleAction);
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.cparser/src/org/eclipse/linuxtools/internal/changelog/parsers/CParser.java b/changelog/org.eclipse.linuxtools.changelog.cparser/src/org/eclipse/linuxtools/internal/changelog/parsers/CParser.java
index 496abe7117..72050762ac 100644
--- a/changelog/org.eclipse.linuxtools.changelog.cparser/src/org/eclipse/linuxtools/internal/changelog/parsers/CParser.java
+++ b/changelog/org.eclipse.linuxtools.changelog.cparser/src/org/eclipse/linuxtools/internal/changelog/parsers/CParser.java
@@ -44,171 +44,171 @@ import org.eclipse.ui.texteditor.AbstractTextEditor;
*/
public class CParser implements IParserChangeLogContrib {
- public CParser() {
- super();
- }
-
- /**
- * @see IParserChangeLogContrib#parseCurrentFunction(IEditorInput, int)
- */
- @Override
- public String parseCurrentFunction(IEditorInput input, int offset)
- throws CoreException {
-
- String currentElementName;
-
- if (input instanceof IFileEditorInput) {
- // Get the working copy and connect to input.
- IWorkingCopyManager manager = CUIPlugin.getDefault()
- .getWorkingCopyManager();
- manager.connect(input);
-
- // Retrieve the C/C++ Element in question.
- IWorkingCopy workingCopy = manager.getWorkingCopy(input);
- ICElement method = workingCopy.getElementAtOffset(offset);
-
- manager.disconnect(input);
-
- // no element selected
- if (method == null)
- return "";
-
- // Get the current element name, to test it.
- currentElementName = method.getElementName();
-
- // Element doesn't have a name. Can go no further.
- if (currentElementName == null) {
- // element doesn't have a name
- return "";
- }
-
- // Get the Element Type to test.
- int elementType = method.getElementType();
-
- switch (elementType) {
- case ICElement.C_FIELD:
- case ICElement.C_METHOD:
- case ICElement.C_FUNCTION:
- break;
- case ICElement.C_MODEL:
- return "";
-
- // So it's not a method, field, function, or model. Where are we?
- default:
- ICElement tmpMethodType;
- if (((tmpMethodType = method.getAncestor(ICElement.C_FUNCTION)) == null)
- && ((tmpMethodType = method.getAncestor(ICElement.C_METHOD)) == null)
- && ((tmpMethodType = method.getAncestor(ICElement.C_CLASS)) == null)) {
- return "";
- } else {
- // In a class, but not in a method. Return class name instead.
- method = tmpMethodType;
- currentElementName = method.getElementName();
- }
-
- }
-
- // Build all ancestor classes.
- // Append all ancestor class names to string
- ICElement tmpParent = method.getParent();
-
- while (tmpParent != null) {
- ICElement tmpParentClass = tmpParent.getAncestor(ICElement.C_CLASS);
- if (tmpParentClass != null) {
- String tmpParentClassName = tmpParentClass.getElementName();
- if (tmpParentClassName == null)
- return currentElementName;
- currentElementName = tmpParentClassName + "."
- + currentElementName;
- } else
- return currentElementName;
- tmpParent = tmpParentClass.getParent();
-
- }
- return currentElementName;
- }
- else if (input instanceof IStorageEditorInput) {
- // Get the working copy and connect to input.
- // don't follow inclusions
- currentElementName = "";
- IStorageEditorInput sei = (IStorageEditorInput)input;
- // don't follow inclusions
- IncludeFileContentProvider contentProvider = IncludeFileContentProvider.getEmptyFilesProvider();
-
- // empty scanner info
- IScannerInfo scanInfo= new ScannerInfo();
- IStorage ancestorStorage = sei.getStorage();
- if (ancestorStorage == null)
- return "";
- InputStream stream = ancestorStorage.getContents();
- byte buffer[] = new byte[100];
- String data = "";
- int read = 0;
- try {
- do {
- read = stream.read(buffer);
- if (read > 0) {
- String tmp = new String(buffer, 0, read);
- data = data.concat(tmp);
- }
- } while (read == 100);
- stream.close();
- } catch (IOException e) {
- // do nothing
- }
-
- FileContent content = FileContent.create("<text>", data.toCharArray()); //$NON-NLS-1$
-
- // determine the language
- boolean isSource[]= {false};
- ILanguage language= GPPLanguage.getDefault();
-
- try {
- IASTTranslationUnit ast;
- int options= isSource[0] ? ILanguage.OPTION_IS_SOURCE_UNIT : 0;
- ast= language.getASTTranslationUnit(content, scanInfo, contentProvider, null, options, ParserUtil.getParserLogService());
- IASTNodeSelector n = ast.getNodeSelector(null);
- IASTNode node = n.findFirstContainedNode(offset, 100);
- while (node != null && !(node instanceof IASTTranslationUnit)) {
- if (node instanceof IASTFunctionDefinition) {
- IASTFunctionDefinition fd = (IASTFunctionDefinition)node;
- IASTFunctionDeclarator d = fd.getDeclarator();
- currentElementName = new String(d.getName().getSimpleID());
- break;
- }
- node = node.getParent();
- }
-// System.out.println(currentElementName);
- } catch (CoreException exc) {
- currentElementName = "";
- CUIPlugin.log(exc);
- }
-
- return currentElementName;
- }
-
- return "";
- }
-
- /**
- * @see IParserChangeLogContrib#parseCurrentFunction(IEditorPart)
- */
- @Override
- public String parseCurrentFunction(IEditorPart editor) throws CoreException {
-
- // Check for correct editor type
- if (!(editor instanceof AbstractTextEditor))
- return "";
-
- // Get the editor, test selection and input.
- AbstractTextEditor a_editor = (AbstractTextEditor) editor;
- ITextSelection selection = (ITextSelection) (a_editor)
- .getSelectionProvider().getSelection();
- IEditorInput input = a_editor.getEditorInput();
-
- // Parse it and return the function.
- return parseCurrentFunction(input, selection.getOffset());
- }
+ public CParser() {
+ super();
+ }
+
+ /**
+ * @see IParserChangeLogContrib#parseCurrentFunction(IEditorInput, int)
+ */
+ @Override
+ public String parseCurrentFunction(IEditorInput input, int offset)
+ throws CoreException {
+
+ String currentElementName;
+
+ if (input instanceof IFileEditorInput) {
+ // Get the working copy and connect to input.
+ IWorkingCopyManager manager = CUIPlugin.getDefault()
+ .getWorkingCopyManager();
+ manager.connect(input);
+
+ // Retrieve the C/C++ Element in question.
+ IWorkingCopy workingCopy = manager.getWorkingCopy(input);
+ ICElement method = workingCopy.getElementAtOffset(offset);
+
+ manager.disconnect(input);
+
+ // no element selected
+ if (method == null)
+ return "";
+
+ // Get the current element name, to test it.
+ currentElementName = method.getElementName();
+
+ // Element doesn't have a name. Can go no further.
+ if (currentElementName == null) {
+ // element doesn't have a name
+ return "";
+ }
+
+ // Get the Element Type to test.
+ int elementType = method.getElementType();
+
+ switch (elementType) {
+ case ICElement.C_FIELD:
+ case ICElement.C_METHOD:
+ case ICElement.C_FUNCTION:
+ break;
+ case ICElement.C_MODEL:
+ return "";
+
+ // So it's not a method, field, function, or model. Where are we?
+ default:
+ ICElement tmpMethodType;
+ if (((tmpMethodType = method.getAncestor(ICElement.C_FUNCTION)) == null)
+ && ((tmpMethodType = method.getAncestor(ICElement.C_METHOD)) == null)
+ && ((tmpMethodType = method.getAncestor(ICElement.C_CLASS)) == null)) {
+ return "";
+ } else {
+ // In a class, but not in a method. Return class name instead.
+ method = tmpMethodType;
+ currentElementName = method.getElementName();
+ }
+
+ }
+
+ // Build all ancestor classes.
+ // Append all ancestor class names to string
+ ICElement tmpParent = method.getParent();
+
+ while (tmpParent != null) {
+ ICElement tmpParentClass = tmpParent.getAncestor(ICElement.C_CLASS);
+ if (tmpParentClass != null) {
+ String tmpParentClassName = tmpParentClass.getElementName();
+ if (tmpParentClassName == null)
+ return currentElementName;
+ currentElementName = tmpParentClassName + "."
+ + currentElementName;
+ } else
+ return currentElementName;
+ tmpParent = tmpParentClass.getParent();
+
+ }
+ return currentElementName;
+ }
+ else if (input instanceof IStorageEditorInput) {
+ // Get the working copy and connect to input.
+ // don't follow inclusions
+ currentElementName = "";
+ IStorageEditorInput sei = (IStorageEditorInput)input;
+ // don't follow inclusions
+ IncludeFileContentProvider contentProvider = IncludeFileContentProvider.getEmptyFilesProvider();
+
+ // empty scanner info
+ IScannerInfo scanInfo= new ScannerInfo();
+ IStorage ancestorStorage = sei.getStorage();
+ if (ancestorStorage == null)
+ return "";
+ InputStream stream = ancestorStorage.getContents();
+ byte buffer[] = new byte[100];
+ String data = "";
+ int read = 0;
+ try {
+ do {
+ read = stream.read(buffer);
+ if (read > 0) {
+ String tmp = new String(buffer, 0, read);
+ data = data.concat(tmp);
+ }
+ } while (read == 100);
+ stream.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+
+ FileContent content = FileContent.create("<text>", data.toCharArray()); //$NON-NLS-1$
+
+ // determine the language
+ boolean isSource[]= {false};
+ ILanguage language= GPPLanguage.getDefault();
+
+ try {
+ IASTTranslationUnit ast;
+ int options= isSource[0] ? ILanguage.OPTION_IS_SOURCE_UNIT : 0;
+ ast= language.getASTTranslationUnit(content, scanInfo, contentProvider, null, options, ParserUtil.getParserLogService());
+ IASTNodeSelector n = ast.getNodeSelector(null);
+ IASTNode node = n.findFirstContainedNode(offset, 100);
+ while (node != null && !(node instanceof IASTTranslationUnit)) {
+ if (node instanceof IASTFunctionDefinition) {
+ IASTFunctionDefinition fd = (IASTFunctionDefinition)node;
+ IASTFunctionDeclarator d = fd.getDeclarator();
+ currentElementName = new String(d.getName().getSimpleID());
+ break;
+ }
+ node = node.getParent();
+ }
+// System.out.println(currentElementName);
+ } catch (CoreException exc) {
+ currentElementName = "";
+ CUIPlugin.log(exc);
+ }
+
+ return currentElementName;
+ }
+
+ return "";
+ }
+
+ /**
+ * @see IParserChangeLogContrib#parseCurrentFunction(IEditorPart)
+ */
+ @Override
+ public String parseCurrentFunction(IEditorPart editor) throws CoreException {
+
+ // Check for correct editor type
+ if (!(editor instanceof AbstractTextEditor))
+ return "";
+
+ // Get the editor, test selection and input.
+ AbstractTextEditor a_editor = (AbstractTextEditor) editor;
+ ITextSelection selection = (ITextSelection) (a_editor)
+ .getSelectionProvider().getSelection();
+ IEditorInput input = a_editor.getEditorInput();
+
+ // Parse it and return the function.
+ return parseCurrentFunction(input, selection.getOffset());
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.doc/build-helper.xml b/changelog/org.eclipse.linuxtools.changelog.doc/build-helper.xml
index 83891d8fd1..0062c117ce 100644
--- a/changelog/org.eclipse.linuxtools.changelog.doc/build-helper.xml
+++ b/changelog/org.eclipse.linuxtools.changelog.doc/build-helper.xml
@@ -1,61 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="org.eclipse.linuxtools.changelog.doc" default="all">
- <description>
+ <description>
Generate Eclipse help content for the Linux Tools changelog user guide
</description>
- <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
+ <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
- <path id="tasks.classpath" path="bin" />
- <path id="wikitext.tasks.classpath">
- <!-- Replace dir with the dir you have wikitext installed into.-->
- <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
- <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
- </fileset>
- </path>
+ <path id="tasks.classpath" path="bin" />
+ <path id="wikitext.tasks.classpath">
+ <!-- Replace dir with the dir you have wikitext installed into.-->
+ <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
+ <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
+ </fileset>
+ </path>
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
- <target name="all" description="Generate Eclipse help content for the Linux Tools changelog user guide">
- <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="ChangeLog Editor User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*,Linux_Tools">
+ <target name="all" description="Generate Eclipse help content for the Linux Tools changelog user guide">
+ <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="ChangeLog Editor User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*,Linux_Tools">
- <path name="Linux_Tools_Project/ChangeLog/User_Guide" title="ChangeLog Editor User Guide" generateToc="false" />
- <stylesheet url="book.css" />
- <pageAppendum>
- = Updating This Document =
+ <path name="Linux_Tools_Project/ChangeLog/User_Guide" title="ChangeLog Editor User Guide" generateToc="false" />
+ <stylesheet url="book.css" />
+ <pageAppendum>
+ = Updating This Document =
- This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
- http://wiki.eclipse.org/Linux_Tools_Project/ChangeLog/User_Guide .
- </pageAppendum>
- </mediawiki-to-eclipse-help>
- <antcall target="test" />
- </target>
+ This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
+ http://wiki.eclipse.org/Linux_Tools_Project/ChangeLog/User_Guide .
+ </pageAppendum>
+ </mediawiki-to-eclipse-help>
+ <antcall target="test" />
+ </target>
- <target name="test" description="verify that all of the HTML files are well-formed XML">
- <echo level="info">
+ <target name="test" description="verify that all of the HTML files are well-formed XML">
+ <echo level="info">
Validating help content XML and HTML files: The Eclipse help system expects well-formed XML
-
+
If validation fails it is because either:
-
+
* the userguide source code is poorly formed, or
* the WikiText MediaWiki parser has a bug
-
+
Problems with userguide source are usually caused by improper use of HTML markup in the MediaWiki source,
or inadvertently starting a line with a space character (in MediaWiki this starts a preformatted block)
- </echo>
-
- <!--
- Don't bother with DTD validation: we only care if the files are well-formed.
- We therefore provide an empty DTD
- -->
- <echo file="tmp/__empty.dtd" message="" />
- <xmlvalidate lenient="true">
- <fileset dir="Linux_Tools_Project">
- <include name="**/*.html" />
- </fileset>
- <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
- </xmlvalidate>
- <delete dir="tmp" />
- </target>
+ </echo>
+
+ <!--
+ Don't bother with DTD validation: we only care if the files are well-formed.
+ We therefore provide an empty DTD
+ -->
+ <echo file="tmp/__empty.dtd" message="" />
+ <xmlvalidate lenient="true">
+ <fileset dir="Linux_Tools_Project">
+ <include name="**/*.html" />
+ </fileset>
+ <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
+ </xmlvalidate>
+ <delete dir="tmp" />
+ </target>
</project>
diff --git a/changelog/org.eclipse.linuxtools.changelog.doc/toc-doc.xml b/changelog/org.eclipse.linuxtools.changelog.doc/toc-doc.xml
index 53a2102920..e63c786aee 100644
--- a/changelog/org.eclipse.linuxtools.changelog.doc/toc-doc.xml
+++ b/changelog/org.eclipse.linuxtools.changelog.doc/toc-doc.xml
@@ -1,5 +1,5 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/ChangeLog/User_Guide/User-Guide.html" label="ChangeLog Editor User Guide">
-<link toc="toc.xml" />
+<link toc="toc.xml" />
<topic href="doc/notices.html" label="Legal"> </topic>
</toc>
diff --git a/changelog/org.eclipse.linuxtools.changelog.doc/toc.xml b/changelog/org.eclipse.linuxtools.changelog.doc/toc.xml
index ae39864308..14c002890a 100644
--- a/changelog/org.eclipse.linuxtools.changelog.doc/toc.xml
+++ b/changelog/org.eclipse.linuxtools.changelog.doc/toc.xml
@@ -1,14 +1,14 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/ChangeLog/User_Guide/User-Guide.html" label="ChangeLog Editor User Guide">
- <topic href="Linux_Tools_Project/ChangeLog/User_Guide/User-Guide.html" label="ChangeLog Editor User Guide">
- <topic href="Linux_Tools_Project/ChangeLog/User_Guide/User-Guide.html" label="Overview"></topic>
- <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Preferences.html" label="ChangeLog Preferences"></topic>
- <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Editor.html" label="ChangeLog Editor"></topic>
- <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Plug-in-Functions.html" label="ChangeLog Plug-in Functions">
- <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Plug-in-Functions.html#Insert_ChangeLog" label="Insert ChangeLog"></topic>
- <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Plug-in-Functions.html#Prepare_ChangeLog" label="Prepare ChangeLog"></topic>
- <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Plug-in-Functions.html#Format_ChangeLog" label="Format ChangeLog"></topic>
- </topic>
- <topic href="Linux_Tools_Project/ChangeLog/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
- </topic>
+ <topic href="Linux_Tools_Project/ChangeLog/User_Guide/User-Guide.html" label="ChangeLog Editor User Guide">
+ <topic href="Linux_Tools_Project/ChangeLog/User_Guide/User-Guide.html" label="Overview"></topic>
+ <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Preferences.html" label="ChangeLog Preferences"></topic>
+ <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Editor.html" label="ChangeLog Editor"></topic>
+ <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Plug-in-Functions.html" label="ChangeLog Plug-in Functions">
+ <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Plug-in-Functions.html#Insert_ChangeLog" label="Insert ChangeLog"></topic>
+ <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Plug-in-Functions.html#Prepare_ChangeLog" label="Prepare ChangeLog"></topic>
+ <topic href="Linux_Tools_Project/ChangeLog/User_Guide/ChangeLog-Plug-in-Functions.html#Format_ChangeLog" label="Format ChangeLog"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/ChangeLog/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
+ </topic>
</toc> \ No newline at end of file
diff --git a/changelog/org.eclipse.linuxtools.changelog.javaparser/src/org/eclipse/linuxtools/internal/changelog/parsers/java/JavaParser.java b/changelog/org.eclipse.linuxtools.changelog.javaparser/src/org/eclipse/linuxtools/internal/changelog/parsers/java/JavaParser.java
index d10bbacef0..2d5be01fbe 100644
--- a/changelog/org.eclipse.linuxtools.changelog.javaparser/src/org/eclipse/linuxtools/internal/changelog/parsers/java/JavaParser.java
+++ b/changelog/org.eclipse.linuxtools.changelog.javaparser/src/org/eclipse/linuxtools/internal/changelog/parsers/java/JavaParser.java
@@ -30,137 +30,137 @@ import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
@SuppressWarnings("restriction")
public class JavaParser implements IParserChangeLogContrib {
- public static final String STATIC_INITIALIZER_NAME = "static initializer";
-
- /**
- * @see IParserChangeLogContrib#parseCurrentFunction(IEditorPart)
- */
- @Override
- public String parseCurrentFunction(IEditorInput input, int offset)
- throws CoreException {
-
- String currentElementName;
- int elementType;
-
- // Get the working copy and connect to input.
- IWorkingCopyManager manager = JavaUI.getWorkingCopyManager();
- manager.connect(input);
-
- // Retrieve the Java Element in question.
- // The following internal access is done because the getWorkingCopy()
- // method
- // for the WorkingCopyManager returns null for StorageEditorInput,
- // however,
- // there is a working copy available through the
- // ICompilationUnitDocumentProvider.
- ICompilationUnitDocumentProvider x = (ICompilationUnitDocumentProvider) JavaUI
- .getDocumentProvider();
- // Retrieve the Java Element in question.
- ICompilationUnit workingCopy = x.getWorkingCopy(input);
-
- if (workingCopy == null) {
- return "";
- }
-
- IJavaElement method = workingCopy.getElementAt(offset);
-
- manager.disconnect(input);
-
- // no element selected
- if (method == null) {
- return "";
- }
-
- // Get the current element name, to test it.
- currentElementName = method.getElementName();
-
- // Element doesn't have a name. Can go no further.
- if (currentElementName == null) {
- return "";
- }
-
- // Get the Element Type to test.
- elementType = method.getElementType();
-
- switch (elementType) {
- case IJavaElement.METHOD:
- case IJavaElement.FIELD:
- break;
- case IJavaElement.COMPILATION_UNIT:
- return "";
- case IJavaElement.INITIALIZER:
- return STATIC_INITIALIZER_NAME;
-
- // So it's not a method, field, type, or static initializer. Where
- // are we?
- default:
- IJavaElement tmpMethodType;
- if (((tmpMethodType = method.getAncestor(IJavaElement.METHOD)) == null)
- && ((tmpMethodType = method.getAncestor(IJavaElement.TYPE)) == null)) {
- return "";
- } else {
- // In a class, but not in a method. Return class name instead.
- method = tmpMethodType;
- currentElementName = method.getElementName();
- }
- }
-
- // Build all ancestor classes.
- // Append all ancestor class names to string
-
- IJavaElement tmpParent = method.getParent();
- boolean firstLoop = true;
-
- while (tmpParent != null) {
- IJavaElement tmpParentClass = tmpParent
- .getAncestor(IJavaElement.TYPE);
- if (tmpParentClass != null) {
- String tmpParentClassName = tmpParentClass.getElementName();
- if (tmpParentClassName == null) {
- return "";
- }
- currentElementName = tmpParentClassName + "."
- + currentElementName;
- } else {
- // cut root class name
- int rootClassPos = currentElementName.indexOf('.');
- if (rootClassPos >= 0) {
- currentElementName = currentElementName
- .substring(rootClassPos + 1);
- }
- if (firstLoop) {
- return "";
- } else {
- return currentElementName;
- }
- }
- tmpParent = tmpParentClass.getParent();
- firstLoop = false;
-
- }
-
- return "";
- }
-
- /**
- * @see IParserChangeLogContrib#parseCurrentFunction(IEditorInput, int)
- */
- @Override
- public String parseCurrentFunction(IEditorPart editor) throws CoreException {
-
- // Check for correct editor type
- if (!(editor instanceof AbstractDecoratedTextEditor)) {
- return "";
- }
-
- // Get the editor, test selection and input.
- AbstractDecoratedTextEditor java_editor = (AbstractDecoratedTextEditor) editor;
- ITextSelection selection = (ITextSelection) (java_editor
- .getSelectionProvider().getSelection());
- IEditorInput input = java_editor.getEditorInput();
-
- // Parse it and return the function.
- return parseCurrentFunction(input, selection.getOffset());
- }
+ public static final String STATIC_INITIALIZER_NAME = "static initializer";
+
+ /**
+ * @see IParserChangeLogContrib#parseCurrentFunction(IEditorPart)
+ */
+ @Override
+ public String parseCurrentFunction(IEditorInput input, int offset)
+ throws CoreException {
+
+ String currentElementName;
+ int elementType;
+
+ // Get the working copy and connect to input.
+ IWorkingCopyManager manager = JavaUI.getWorkingCopyManager();
+ manager.connect(input);
+
+ // Retrieve the Java Element in question.
+ // The following internal access is done because the getWorkingCopy()
+ // method
+ // for the WorkingCopyManager returns null for StorageEditorInput,
+ // however,
+ // there is a working copy available through the
+ // ICompilationUnitDocumentProvider.
+ ICompilationUnitDocumentProvider x = (ICompilationUnitDocumentProvider) JavaUI
+ .getDocumentProvider();
+ // Retrieve the Java Element in question.
+ ICompilationUnit workingCopy = x.getWorkingCopy(input);
+
+ if (workingCopy == null) {
+ return "";
+ }
+
+ IJavaElement method = workingCopy.getElementAt(offset);
+
+ manager.disconnect(input);
+
+ // no element selected
+ if (method == null) {
+ return "";
+ }
+
+ // Get the current element name, to test it.
+ currentElementName = method.getElementName();
+
+ // Element doesn't have a name. Can go no further.
+ if (currentElementName == null) {
+ return "";
+ }
+
+ // Get the Element Type to test.
+ elementType = method.getElementType();
+
+ switch (elementType) {
+ case IJavaElement.METHOD:
+ case IJavaElement.FIELD:
+ break;
+ case IJavaElement.COMPILATION_UNIT:
+ return "";
+ case IJavaElement.INITIALIZER:
+ return STATIC_INITIALIZER_NAME;
+
+ // So it's not a method, field, type, or static initializer. Where
+ // are we?
+ default:
+ IJavaElement tmpMethodType;
+ if (((tmpMethodType = method.getAncestor(IJavaElement.METHOD)) == null)
+ && ((tmpMethodType = method.getAncestor(IJavaElement.TYPE)) == null)) {
+ return "";
+ } else {
+ // In a class, but not in a method. Return class name instead.
+ method = tmpMethodType;
+ currentElementName = method.getElementName();
+ }
+ }
+
+ // Build all ancestor classes.
+ // Append all ancestor class names to string
+
+ IJavaElement tmpParent = method.getParent();
+ boolean firstLoop = true;
+
+ while (tmpParent != null) {
+ IJavaElement tmpParentClass = tmpParent
+ .getAncestor(IJavaElement.TYPE);
+ if (tmpParentClass != null) {
+ String tmpParentClassName = tmpParentClass.getElementName();
+ if (tmpParentClassName == null) {
+ return "";
+ }
+ currentElementName = tmpParentClassName + "."
+ + currentElementName;
+ } else {
+ // cut root class name
+ int rootClassPos = currentElementName.indexOf('.');
+ if (rootClassPos >= 0) {
+ currentElementName = currentElementName
+ .substring(rootClassPos + 1);
+ }
+ if (firstLoop) {
+ return "";
+ } else {
+ return currentElementName;
+ }
+ }
+ tmpParent = tmpParentClass.getParent();
+ firstLoop = false;
+
+ }
+
+ return "";
+ }
+
+ /**
+ * @see IParserChangeLogContrib#parseCurrentFunction(IEditorInput, int)
+ */
+ @Override
+ public String parseCurrentFunction(IEditorPart editor) throws CoreException {
+
+ // Check for correct editor type
+ if (!(editor instanceof AbstractDecoratedTextEditor)) {
+ return "";
+ }
+
+ // Get the editor, test selection and input.
+ AbstractDecoratedTextEditor java_editor = (AbstractDecoratedTextEditor) editor;
+ ITextSelection selection = (ITextSelection) (java_editor
+ .getSelectionProvider().getSelection());
+ IEditorInput input = java_editor.getEditorInput();
+
+ // Parse it and return the function.
+ return parseCurrentFunction(input, selection.getOffset());
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.tests/pom.xml b/changelog/org.eclipse.linuxtools.changelog.tests/pom.xml
index f684b0d25c..30c86db3d6 100644
--- a/changelog/org.eclipse.linuxtools.changelog.tests/pom.xml
+++ b/changelog/org.eclipse.linuxtools.changelog.tests/pom.xml
@@ -36,7 +36,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.changelog.tests</testSuite>
<testClass>org.eclipse.linuxtools.changelog.core.tests.AllTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.platform.ide</product>
<dependencies>
diff --git a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/formatters/tests/GNUFormatTest.java b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/formatters/tests/GNUFormatTest.java
index d44efd68c3..d8069b14c2 100644
--- a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/formatters/tests/GNUFormatTest.java
+++ b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/formatters/tests/GNUFormatTest.java
@@ -33,479 +33,479 @@ import org.eclipse.jface.text.IDocument;
public class GNUFormatTest {
- // The instance under test
- private GNUFormat gnuFormatter;
- // A faked project
- private ChangeLogTestProject project;
- // The IEditorPart corresponding to the ChangeLog file
- private IEditorPart changelogEditorPart = null;
-
- // Tokens for the GNU format
- private static final String TWO_SPACES = " ";
- private static final String SPACE = " ";
- private static final String TAB = "\t";
- private static final String LEFT_EMAIL_BRACKET = "<";
- private static final String RIGHT_EMAIL_BRACKET = ">";
- private static final String FILE_ENTRY_START_MARKER = "* ";
- private static final String FILE_ENTRY_END_MARKER = ": ";
- private static final String FUNCTION_START_MARKER = "(";
- private static final String FUNCTION_END_MARKER = ")";
- private static final String NEW_LINE = "\n";
-
- @Before
- public void setUp() throws Exception {
- gnuFormatter = new GNUFormat();
- project = new ChangeLogTestProject("GNUFormatterTest");
- }
-
- @After
- public void tearDown() throws Exception {
- // Most tests in this class use changelogEditorPart. In order to avoid
- // spill-over from previous runs, truncate content (i.e. manually set
- // content to the empty string).
- if (changelogEditorPart != null) { // testFormatDateLine does not use it
- AbstractTextEditor castEditor = (AbstractTextEditor) changelogEditorPart;
- IDocumentProvider iDocProvider = castEditor.getDocumentProvider();
- IDocument changelogContentDoc = iDocProvider.getDocument(castEditor.getEditorInput());
- changelogContentDoc.set(""); // empty content
- changelogEditorPart.doSave(null);
- // Also close open editor in order for default content to work.
- // I.e. avoid spill over from previous test runs
- closeEditor(changelogEditorPart);
- }
- project.getTestProject().delete(true, true, null); // dispose
- }
-
- /**
- * GNU ChangeLog style date lines are of the following format
- *
- * YYYY-MM-DD Author Name <author.email@domain.com>
- */
- @Test
- public void testFormatDateLine() {
- // Today's date in ISO format
- Calendar c = new GregorianCalendar();
- String isoDate = String.format("%1$tY-%1$tm-%1$td", c);
- String authorName = "William Shakespeare";
- String authorEmail = "william.shakespeare@medieval.com";
- final String expectedDateFormatting = isoDate +
- TWO_SPACES +
- authorName +
- TWO_SPACES +
- LEFT_EMAIL_BRACKET +
- authorEmail +
- RIGHT_EMAIL_BRACKET +
- "\n\n";
- assertEquals(expectedDateFormatting,
- gnuFormatter.formatDateLine(authorName, authorEmail));
- }
-
- /**
- * Assume the following initial content of ChangeLog:
- *
- * <code>
- * 2010-11-26 Severin Gehwolf <sgehwolf@redhat.com>
- *
- * * src/org/eclipse/linuxtools/changelog/parsers/java/HelloWorld.java (test): New Method\n\t\n
- * </code>
- *
- * Note the trailing new-line, tab, new-line combination. If another change in the same file but
- * in a different method (or function) is merged, the empty line containing a tab only should be
- * removed.
- *
- */
- @Test
- public void twoChangesInSameFileAreProperlyMergedWhenThereIsATrailingTabNewLine() throws Exception {
- // set date/author line
- String authorName = "Test Foo";
- String email = "test@example.com";
- final String dateLine = gnuFormatter.formatDateLine(authorName, email);
-
- // full absolute path to ChangeLog file (relative to project root)
- String changelogPath = "/" + project.getTestProject().getName() + "/path/to";
- final String changelogFilePath = changelogPath + "/ChangeLog";
-
- // entry file path (need overlap with changelogPath)
- String fileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
- final String entryFilePath = changelogPath + "/" + fileEntryRelPath;
-
- final String firstMethodName = "main";
- final String firstChangeComment = "Fix args parsing.";
- // Setup proper pre-existing content
- String content = dateLine + NEW_LINE + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
- fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
- firstMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
- firstChangeComment + NEW_LINE +
- TAB + NEW_LINE; // produces an empty line which should be removed
-
- assertNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
-
- // add a ChangeLog file to our test project
- InputStream newFileInputStream = new ByteArrayInputStream(
- content.getBytes());
- IFile changelogFile = project.addFileToProject( "/path/to", "ChangeLog",
- newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
-
- // Open a document and get the IEditorPart
- changelogEditorPart = EditorHelper.openEditor(changelogFile);
-
- // make sure changelog editor content is right before merging
- assertEquals(content, getContent(changelogEditorPart));
-
- final String secondMethodName = "toString";
-
- // Do the merge with the existing content
- gnuFormatter.mergeChangelog(dateLine, secondMethodName,
- "" /* no default content */, changelogEditorPart,
- changelogFilePath, entryFilePath);
-
- final String actualMergeResult = getContent(changelogEditorPart);
-
- // Expect trailing tab+newline combination to not show up in merge
- final String expectedResult = dateLine + NEW_LINE + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
- fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
- firstMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
- firstChangeComment + NEW_LINE + TAB + FUNCTION_START_MARKER +
- secondMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
- NEW_LINE + NEW_LINE;
- assertEquals(expectedResult, actualMergeResult);
- }
-
- /**
- * Test merge of two separate changes to an existing file within the same changelog entry.
- * I.e. test for
- *
- * * path/to/file (method1): First change.
- * (method2): Another change in same file but different function/method.
- */
- @Test
- public void twoChangesInSameFileAreProperlyMerged() throws Exception {
- // set date/author line
- String authorName = "Test Author";
- String email = "test@example.com";
- final String dateLine = gnuFormatter.formatDateLine(authorName, email);
-
- // full absolute path to ChangeLog file (relative to project root)
- String changelogPath = "/" + project.getTestProject().getName() + "/path/to";
- final String changelogFilePath = changelogPath + "/ChangeLog";
-
- // entry file path (need overlap with changelogPath)
- String fileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
- final String entryFilePath = changelogPath + "/" + fileEntryRelPath;
-
- final String firstMethodName = "main";
- final String firstChangeComment = "Fix args parsing.";
- // Setup proper pre-existing content
- String content = dateLine + NEW_LINE + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
- fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
- firstMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
- firstChangeComment + NEW_LINE;
-
- assertNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
-
- // add a ChangeLog file to our test project
- InputStream newFileInputStream = new ByteArrayInputStream(
- content.getBytes());
- IFile changelogFile = project.addFileToProject( "/path/to", "ChangeLog",
- newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
-
- // Open a document and get the IEditorPart
- changelogEditorPart = openEditor(changelogFile);
- // make sure changelog editor content is right before merging
- assertEquals(content, getContent(changelogEditorPart));
-
- final String secondMethodName = "toString";
-
- // Do the merge with the existing content
- gnuFormatter.mergeChangelog(dateLine, secondMethodName,
- "" /* no default content */, changelogEditorPart,
- changelogFilePath, entryFilePath);
-
- final String actualMergeResult = getContent(changelogEditorPart);
-
- final String expectedResult = dateLine + NEW_LINE + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
- fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
- firstMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
- firstChangeComment + NEW_LINE + TAB + FUNCTION_START_MARKER +
- secondMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
- NEW_LINE;
-
- assertEquals(expectedResult, actualMergeResult);
- }
-
- /**
- * If two different authors make modifications on the same day, both modifications must
- * show up as separate changelog entries for that day.
- */
- @Test
- public void newChangeLogEntryForNewAuthorOnSameDay() throws Exception {
- // first author
- String authorName = "Test Author";
- String email = "test@example.com";
- final String firstDateLine = gnuFormatter.formatDateLine(authorName, email);
- // second author
- authorName = "William Shakespeare";
- email = "will@pear.com";
- final String secondDateLine = gnuFormatter.formatDateLine(authorName, email);
-
- // full absolute path to ChangeLog file
- String changelogPath = "/" + project.getTestProject().getName() + "/path/to";
- final String changelogFilePath = changelogPath + "/ChangeLog";
-
- // No existing content in ChangeLog file
- String content = "";
-
- assertNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
-
- // add a ChangeLog file to our test project
- InputStream newFileInputStream = new ByteArrayInputStream(
- content.getBytes());
- IFile changelogFile = project.addFileToProject( changelogPath, "ChangeLog",
- newFileInputStream);
- // Open a document and get the IEditorPart
- changelogEditorPart = openEditor(changelogFile);
-
- // entry file path (needs overlap with changelogPath)
- String fileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
- final String entryFilePath = changelogPath + "/" + fileEntryRelPath;
-
- final String guessedFunctionName = "bazinga";
-
- // merge first changelog entry with empty content
- gnuFormatter.mergeChangelog(firstDateLine, guessedFunctionName,
- "" /* empty default content */, changelogEditorPart,
- changelogFilePath, entryFilePath);
-
- String actualMergeResult = getContent(changelogEditorPart);
-
- String expectedResult = firstDateLine + TAB + FILE_ENTRY_START_MARKER +
- fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
- guessedFunctionName + FUNCTION_END_MARKER +
- FILE_ENTRY_END_MARKER;
-
- assertEquals(expectedResult, actualMergeResult);
-
- // add second changelog entry on same date but by different author
- gnuFormatter.mergeChangelog(secondDateLine, guessedFunctionName,
- "" /* empty default content */, changelogEditorPart,
- changelogFilePath, entryFilePath);
-
- actualMergeResult = getContent(changelogEditorPart);
-
- expectedResult = secondDateLine + TAB + FILE_ENTRY_START_MARKER +
- fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
- guessedFunctionName + FUNCTION_END_MARKER +
- FILE_ENTRY_END_MARKER + NEW_LINE + NEW_LINE +
- expectedResult;
-
- assertEquals(expectedResult, actualMergeResult);
- }
-
- /**
- * Basic format check.
- */
- @Test
- public void mergeChangeLogHasProperFormat() throws Exception {
- // set date/author line
- String authorName = "Test Author";
- String email = "test@example.com";
- final String dateLine = gnuFormatter.formatDateLine(authorName, email);
-
- // full absolute path to ChangeLog file (relative to project root)
- String changelogPath = "/" + project.getTestProject().getName() + "/path/to";
- final String changelogFilePath = changelogPath + "/ChangeLog";
-
- // Content to merge into
- String content = "";
-
- assertNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
-
- // add a ChangeLog file to our test project
- InputStream newFileInputStream = new ByteArrayInputStream(
- content.getBytes());
- IFile changelogFile = project.addFileToProject( "/path/to", "ChangeLog",
- newFileInputStream);
- // Open a document and get the IEditorPart
- changelogEditorPart = openEditor(changelogFile);
-
- // make sure changelog editor content is empty
- assertEquals(content, getContent(changelogEditorPart));
-
- // entry file path (need overlap with changelogPath)
- String fileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
- final String entryFilePath = changelogPath + "/" + fileEntryRelPath;
-
- // Will show up surrounded by "(" and ")" in ChangeLog
- final String guessedFunctionName = "bazinga";
-
- // This always returns an empty String (should probably be changed...)
- // merge result will be written to editorContent
- gnuFormatter.mergeChangelog(dateLine, guessedFunctionName,
- "" /* empty default content */, changelogEditorPart,
- changelogFilePath, entryFilePath);
-
- final String actualMergeResult = getContent(changelogEditorPart);
-
- final String expectedResult = dateLine + TAB + FILE_ENTRY_START_MARKER +
- fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
- guessedFunctionName + FUNCTION_END_MARKER +
- FILE_ENTRY_END_MARKER;
-
- assertEquals(expectedResult, actualMergeResult);
- }
-
- /**
- * Here's the scenario for this test. It may be that there are only files removed and
- * new files added for a commit. This should yield to changelog entries for the following
- * form:
- *
- *<code>
- * 2010-11-26 Some Author <some.author@example.com>
- *
- * * path/to/deleted/file.c: Removed.
- * * path/to/new/file.c: New file.
- *</code>
- *
- * Prior to the fix for Eclipse Bz #331244 the result was:
- *
- *<code>
- * 2010-11-26 Some Author <some.author@example.com>
- *
- * * path/to/deleted/file.c: Removed.
- * * path/to/new/file.c:
- *</code>
- *
- * This regression test should catch this.
- */
- @Test
- public void canHaveEntriesWithDefaultTextOnly() throws Exception {
- // set date/author line
- String authorName = "Test Author";
- String email = "test@example.com";
- final String dateLine = gnuFormatter.formatDateLine(authorName, email);
-
- // full absolute path to ChangeLog file (relative to project root)
- String changelogPath = "/" + project.getTestProject().getName() + "/path/example";
- final String changelogFilePath = changelogPath + "/ChangeLog";
-
- // Content to merge into
- String content = "";
-
- // add a ChangeLog file to our test project
- InputStream newFileInputStream = new ByteArrayInputStream(
- content.getBytes());
- IFile changelogFile = project.addFileToProject( "/path/example", "ChangeLog",
- newFileInputStream);
- // Open a document and get the IEditorPart
- changelogEditorPart = openEditor(changelogFile);
-
- // make sure changelog editor content is empty
- assertEquals(content, getContent(changelogEditorPart));
-
- // entry file path (need overlap with changelogPath)
- final String firstFileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
- String entryFilePath = changelogPath + "/" + firstFileEntryRelPath;
-
- final String firstDefaultContent = "New file.";
-
- // Note: This always returns an empty String (should probably be changed...)
- // merge result will be written to editorContent.
- //
- // Create a line with default text "New file"
- gnuFormatter.mergeChangelog(dateLine, "" /* no guessed function name */,
- firstDefaultContent, changelogEditorPart,
- changelogFilePath, entryFilePath);
- final String secondFileEntryRelPath = "eclipse/example/test/OldCoffeeMaker.java";
- entryFilePath = changelogPath + "/" + secondFileEntryRelPath;
- final String secondDefaultContent = "Removed.";
- // Add entry for removed file
- gnuFormatter.mergeChangelog(dateLine, "" /* no guessed function name */,
- secondDefaultContent, changelogEditorPart,
- changelogFilePath, entryFilePath);
-
- final String actualMergeResult = getContent(changelogEditorPart);
-
- // Note: Removed files occur in the list first, new file items come after that.
- final String expectedResult = dateLine + TAB + FILE_ENTRY_START_MARKER +
- secondFileEntryRelPath+ FILE_ENTRY_END_MARKER +
- secondDefaultContent + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
- firstFileEntryRelPath + FILE_ENTRY_END_MARKER +
- firstDefaultContent;
-
- assertEquals(expectedResult, actualMergeResult);
- }
-
- /**
- * Test for a changelog entry with items for removed files, new files and modified
- * existing files. This test differs from the previous in that the ChangeLog is
- * empty to start with. This verifies Bz #366854 fix.
- *
- * @throws Exception
- */
- @Test
- public void canHaveEntriesWithDefaultTextAndSomeModificationToAnExistingFile2() throws Exception {
- // set date/author line
- String authorName = "Test Author";
- String email = "test@example.com";
- final String dateLine = gnuFormatter.formatDateLine(authorName, email);
-
- // full absolute path to ChangeLog file (relative to project root)
- String changelogPath = "/" + project.getTestProject().getName() + "/test/example";
- final String changelogFilePath = changelogPath + "/ChangeLog";
-
- // add a new empty ChangeLog file to our test project
- InputStream newFileInputStream = new ByteArrayInputStream(new byte[0]);
- IFile changelogFile = project.addFileToProject( "/test/example", "ChangeLog",
- newFileInputStream);
- // Open a document and get the IEditorPart
- changelogEditorPart = openEditor(changelogFile);
-
- // entry file path (need overlap with changelogPath)
- final String firstFileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
- String entryFilePath = changelogPath + "/" + firstFileEntryRelPath;
-
- final String firstDefaultContent = "New file.";
-
- // Note: This always returns an empty String (should probably be changed...)
- // merge result will be written to editorContent.
- //
- // Create an item with default text "New file"
- gnuFormatter.mergeChangelog(dateLine, "" /* no guessed function name */,
- firstDefaultContent, changelogEditorPart,
- changelogFilePath, entryFilePath);
- final String secondFileEntryRelPath = "eclipse/example/test/OldCoffeeMaker.java";
- entryFilePath = changelogPath + "/" + secondFileEntryRelPath;
- final String secondDefaultContent = "Removed.";
- // Add entry for removed file
- gnuFormatter.mergeChangelog(dateLine, "" /* no guessed function name */,
- secondDefaultContent, changelogEditorPart,
- changelogFilePath, entryFilePath);
- final String thirdFileEntryRelPath = "eclipse/example/test/ModifiedFile.java";
- entryFilePath = changelogPath + "/" + thirdFileEntryRelPath;
- final String guessedFunctionName = "main";
- // Create a bullet point describing a change in some existing file
- gnuFormatter.mergeChangelog(dateLine, guessedFunctionName,
- "" /* no default content */, changelogEditorPart,
- changelogFilePath, entryFilePath);
-
- final String actualMergeResult = getContent(changelogEditorPart);
-
- // Note that changes to existing files appear first in the changelog entries.
- // Second are removed files and new files are last.
- final String expectedResult = dateLine + TAB + FILE_ENTRY_START_MARKER +
- thirdFileEntryRelPath + SPACE + FUNCTION_START_MARKER +
- guessedFunctionName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
- NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
- secondFileEntryRelPath+ FILE_ENTRY_END_MARKER +
- secondDefaultContent + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
- firstFileEntryRelPath + FILE_ENTRY_END_MARKER +
- firstDefaultContent;
-
- assertEquals(expectedResult, actualMergeResult);
- }
+ // The instance under test
+ private GNUFormat gnuFormatter;
+ // A faked project
+ private ChangeLogTestProject project;
+ // The IEditorPart corresponding to the ChangeLog file
+ private IEditorPart changelogEditorPart = null;
+
+ // Tokens for the GNU format
+ private static final String TWO_SPACES = " ";
+ private static final String SPACE = " ";
+ private static final String TAB = "\t";
+ private static final String LEFT_EMAIL_BRACKET = "<";
+ private static final String RIGHT_EMAIL_BRACKET = ">";
+ private static final String FILE_ENTRY_START_MARKER = "* ";
+ private static final String FILE_ENTRY_END_MARKER = ": ";
+ private static final String FUNCTION_START_MARKER = "(";
+ private static final String FUNCTION_END_MARKER = ")";
+ private static final String NEW_LINE = "\n";
+
+ @Before
+ public void setUp() throws Exception {
+ gnuFormatter = new GNUFormat();
+ project = new ChangeLogTestProject("GNUFormatterTest");
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ // Most tests in this class use changelogEditorPart. In order to avoid
+ // spill-over from previous runs, truncate content (i.e. manually set
+ // content to the empty string).
+ if (changelogEditorPart != null) { // testFormatDateLine does not use it
+ AbstractTextEditor castEditor = (AbstractTextEditor) changelogEditorPart;
+ IDocumentProvider iDocProvider = castEditor.getDocumentProvider();
+ IDocument changelogContentDoc = iDocProvider.getDocument(castEditor.getEditorInput());
+ changelogContentDoc.set(""); // empty content
+ changelogEditorPart.doSave(null);
+ // Also close open editor in order for default content to work.
+ // I.e. avoid spill over from previous test runs
+ closeEditor(changelogEditorPart);
+ }
+ project.getTestProject().delete(true, true, null); // dispose
+ }
+
+ /**
+ * GNU ChangeLog style date lines are of the following format
+ *
+ * YYYY-MM-DD Author Name <author.email@domain.com>
+ */
+ @Test
+ public void testFormatDateLine() {
+ // Today's date in ISO format
+ Calendar c = new GregorianCalendar();
+ String isoDate = String.format("%1$tY-%1$tm-%1$td", c);
+ String authorName = "William Shakespeare";
+ String authorEmail = "william.shakespeare@medieval.com";
+ final String expectedDateFormatting = isoDate +
+ TWO_SPACES +
+ authorName +
+ TWO_SPACES +
+ LEFT_EMAIL_BRACKET +
+ authorEmail +
+ RIGHT_EMAIL_BRACKET +
+ "\n\n";
+ assertEquals(expectedDateFormatting,
+ gnuFormatter.formatDateLine(authorName, authorEmail));
+ }
+
+ /**
+ * Assume the following initial content of ChangeLog:
+ *
+ * <code>
+ * 2010-11-26 Severin Gehwolf <sgehwolf@redhat.com>
+ *
+ * * src/org/eclipse/linuxtools/changelog/parsers/java/HelloWorld.java (test): New Method\n\t\n
+ * </code>
+ *
+ * Note the trailing new-line, tab, new-line combination. If another change in the same file but
+ * in a different method (or function) is merged, the empty line containing a tab only should be
+ * removed.
+ *
+ */
+ @Test
+ public void twoChangesInSameFileAreProperlyMergedWhenThereIsATrailingTabNewLine() throws Exception {
+ // set date/author line
+ String authorName = "Test Foo";
+ String email = "test@example.com";
+ final String dateLine = gnuFormatter.formatDateLine(authorName, email);
+
+ // full absolute path to ChangeLog file (relative to project root)
+ String changelogPath = "/" + project.getTestProject().getName() + "/path/to";
+ final String changelogFilePath = changelogPath + "/ChangeLog";
+
+ // entry file path (need overlap with changelogPath)
+ String fileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
+ final String entryFilePath = changelogPath + "/" + fileEntryRelPath;
+
+ final String firstMethodName = "main";
+ final String firstChangeComment = "Fix args parsing.";
+ // Setup proper pre-existing content
+ String content = dateLine + NEW_LINE + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
+ fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
+ firstMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
+ firstChangeComment + NEW_LINE +
+ TAB + NEW_LINE; // produces an empty line which should be removed
+
+ assertNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
+
+ // add a ChangeLog file to our test project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ content.getBytes());
+ IFile changelogFile = project.addFileToProject( "/path/to", "ChangeLog",
+ newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
+
+ // Open a document and get the IEditorPart
+ changelogEditorPart = EditorHelper.openEditor(changelogFile);
+
+ // make sure changelog editor content is right before merging
+ assertEquals(content, getContent(changelogEditorPart));
+
+ final String secondMethodName = "toString";
+
+ // Do the merge with the existing content
+ gnuFormatter.mergeChangelog(dateLine, secondMethodName,
+ "" /* no default content */, changelogEditorPart,
+ changelogFilePath, entryFilePath);
+
+ final String actualMergeResult = getContent(changelogEditorPart);
+
+ // Expect trailing tab+newline combination to not show up in merge
+ final String expectedResult = dateLine + NEW_LINE + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
+ fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
+ firstMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
+ firstChangeComment + NEW_LINE + TAB + FUNCTION_START_MARKER +
+ secondMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
+ NEW_LINE + NEW_LINE;
+ assertEquals(expectedResult, actualMergeResult);
+ }
+
+ /**
+ * Test merge of two separate changes to an existing file within the same changelog entry.
+ * I.e. test for
+ *
+ * * path/to/file (method1): First change.
+ * (method2): Another change in same file but different function/method.
+ */
+ @Test
+ public void twoChangesInSameFileAreProperlyMerged() throws Exception {
+ // set date/author line
+ String authorName = "Test Author";
+ String email = "test@example.com";
+ final String dateLine = gnuFormatter.formatDateLine(authorName, email);
+
+ // full absolute path to ChangeLog file (relative to project root)
+ String changelogPath = "/" + project.getTestProject().getName() + "/path/to";
+ final String changelogFilePath = changelogPath + "/ChangeLog";
+
+ // entry file path (need overlap with changelogPath)
+ String fileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
+ final String entryFilePath = changelogPath + "/" + fileEntryRelPath;
+
+ final String firstMethodName = "main";
+ final String firstChangeComment = "Fix args parsing.";
+ // Setup proper pre-existing content
+ String content = dateLine + NEW_LINE + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
+ fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
+ firstMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
+ firstChangeComment + NEW_LINE;
+
+ assertNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
+
+ // add a ChangeLog file to our test project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ content.getBytes());
+ IFile changelogFile = project.addFileToProject( "/path/to", "ChangeLog",
+ newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
+
+ // Open a document and get the IEditorPart
+ changelogEditorPart = openEditor(changelogFile);
+ // make sure changelog editor content is right before merging
+ assertEquals(content, getContent(changelogEditorPart));
+
+ final String secondMethodName = "toString";
+
+ // Do the merge with the existing content
+ gnuFormatter.mergeChangelog(dateLine, secondMethodName,
+ "" /* no default content */, changelogEditorPart,
+ changelogFilePath, entryFilePath);
+
+ final String actualMergeResult = getContent(changelogEditorPart);
+
+ final String expectedResult = dateLine + NEW_LINE + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
+ fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
+ firstMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
+ firstChangeComment + NEW_LINE + TAB + FUNCTION_START_MARKER +
+ secondMethodName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
+ NEW_LINE;
+
+ assertEquals(expectedResult, actualMergeResult);
+ }
+
+ /**
+ * If two different authors make modifications on the same day, both modifications must
+ * show up as separate changelog entries for that day.
+ */
+ @Test
+ public void newChangeLogEntryForNewAuthorOnSameDay() throws Exception {
+ // first author
+ String authorName = "Test Author";
+ String email = "test@example.com";
+ final String firstDateLine = gnuFormatter.formatDateLine(authorName, email);
+ // second author
+ authorName = "William Shakespeare";
+ email = "will@pear.com";
+ final String secondDateLine = gnuFormatter.formatDateLine(authorName, email);
+
+ // full absolute path to ChangeLog file
+ String changelogPath = "/" + project.getTestProject().getName() + "/path/to";
+ final String changelogFilePath = changelogPath + "/ChangeLog";
+
+ // No existing content in ChangeLog file
+ String content = "";
+
+ assertNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
+
+ // add a ChangeLog file to our test project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ content.getBytes());
+ IFile changelogFile = project.addFileToProject( changelogPath, "ChangeLog",
+ newFileInputStream);
+ // Open a document and get the IEditorPart
+ changelogEditorPart = openEditor(changelogFile);
+
+ // entry file path (needs overlap with changelogPath)
+ String fileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
+ final String entryFilePath = changelogPath + "/" + fileEntryRelPath;
+
+ final String guessedFunctionName = "bazinga";
+
+ // merge first changelog entry with empty content
+ gnuFormatter.mergeChangelog(firstDateLine, guessedFunctionName,
+ "" /* empty default content */, changelogEditorPart,
+ changelogFilePath, entryFilePath);
+
+ String actualMergeResult = getContent(changelogEditorPart);
+
+ String expectedResult = firstDateLine + TAB + FILE_ENTRY_START_MARKER +
+ fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
+ guessedFunctionName + FUNCTION_END_MARKER +
+ FILE_ENTRY_END_MARKER;
+
+ assertEquals(expectedResult, actualMergeResult);
+
+ // add second changelog entry on same date but by different author
+ gnuFormatter.mergeChangelog(secondDateLine, guessedFunctionName,
+ "" /* empty default content */, changelogEditorPart,
+ changelogFilePath, entryFilePath);
+
+ actualMergeResult = getContent(changelogEditorPart);
+
+ expectedResult = secondDateLine + TAB + FILE_ENTRY_START_MARKER +
+ fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
+ guessedFunctionName + FUNCTION_END_MARKER +
+ FILE_ENTRY_END_MARKER + NEW_LINE + NEW_LINE +
+ expectedResult;
+
+ assertEquals(expectedResult, actualMergeResult);
+ }
+
+ /**
+ * Basic format check.
+ */
+ @Test
+ public void mergeChangeLogHasProperFormat() throws Exception {
+ // set date/author line
+ String authorName = "Test Author";
+ String email = "test@example.com";
+ final String dateLine = gnuFormatter.formatDateLine(authorName, email);
+
+ // full absolute path to ChangeLog file (relative to project root)
+ String changelogPath = "/" + project.getTestProject().getName() + "/path/to";
+ final String changelogFilePath = changelogPath + "/ChangeLog";
+
+ // Content to merge into
+ String content = "";
+
+ assertNull(project.getTestProject().findMember(new Path("/path/to/ChangeLog")));
+
+ // add a ChangeLog file to our test project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ content.getBytes());
+ IFile changelogFile = project.addFileToProject( "/path/to", "ChangeLog",
+ newFileInputStream);
+ // Open a document and get the IEditorPart
+ changelogEditorPart = openEditor(changelogFile);
+
+ // make sure changelog editor content is empty
+ assertEquals(content, getContent(changelogEditorPart));
+
+ // entry file path (need overlap with changelogPath)
+ String fileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
+ final String entryFilePath = changelogPath + "/" + fileEntryRelPath;
+
+ // Will show up surrounded by "(" and ")" in ChangeLog
+ final String guessedFunctionName = "bazinga";
+
+ // This always returns an empty String (should probably be changed...)
+ // merge result will be written to editorContent
+ gnuFormatter.mergeChangelog(dateLine, guessedFunctionName,
+ "" /* empty default content */, changelogEditorPart,
+ changelogFilePath, entryFilePath);
+
+ final String actualMergeResult = getContent(changelogEditorPart);
+
+ final String expectedResult = dateLine + TAB + FILE_ENTRY_START_MARKER +
+ fileEntryRelPath + SPACE + FUNCTION_START_MARKER +
+ guessedFunctionName + FUNCTION_END_MARKER +
+ FILE_ENTRY_END_MARKER;
+
+ assertEquals(expectedResult, actualMergeResult);
+ }
+
+ /**
+ * Here's the scenario for this test. It may be that there are only files removed and
+ * new files added for a commit. This should yield to changelog entries for the following
+ * form:
+ *
+ *<code>
+ * 2010-11-26 Some Author <some.author@example.com>
+ *
+ * * path/to/deleted/file.c: Removed.
+ * * path/to/new/file.c: New file.
+ *</code>
+ *
+ * Prior to the fix for Eclipse Bz #331244 the result was:
+ *
+ *<code>
+ * 2010-11-26 Some Author <some.author@example.com>
+ *
+ * * path/to/deleted/file.c: Removed.
+ * * path/to/new/file.c:
+ *</code>
+ *
+ * This regression test should catch this.
+ */
+ @Test
+ public void canHaveEntriesWithDefaultTextOnly() throws Exception {
+ // set date/author line
+ String authorName = "Test Author";
+ String email = "test@example.com";
+ final String dateLine = gnuFormatter.formatDateLine(authorName, email);
+
+ // full absolute path to ChangeLog file (relative to project root)
+ String changelogPath = "/" + project.getTestProject().getName() + "/path/example";
+ final String changelogFilePath = changelogPath + "/ChangeLog";
+
+ // Content to merge into
+ String content = "";
+
+ // add a ChangeLog file to our test project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ content.getBytes());
+ IFile changelogFile = project.addFileToProject( "/path/example", "ChangeLog",
+ newFileInputStream);
+ // Open a document and get the IEditorPart
+ changelogEditorPart = openEditor(changelogFile);
+
+ // make sure changelog editor content is empty
+ assertEquals(content, getContent(changelogEditorPart));
+
+ // entry file path (need overlap with changelogPath)
+ final String firstFileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
+ String entryFilePath = changelogPath + "/" + firstFileEntryRelPath;
+
+ final String firstDefaultContent = "New file.";
+
+ // Note: This always returns an empty String (should probably be changed...)
+ // merge result will be written to editorContent.
+ //
+ // Create a line with default text "New file"
+ gnuFormatter.mergeChangelog(dateLine, "" /* no guessed function name */,
+ firstDefaultContent, changelogEditorPart,
+ changelogFilePath, entryFilePath);
+ final String secondFileEntryRelPath = "eclipse/example/test/OldCoffeeMaker.java";
+ entryFilePath = changelogPath + "/" + secondFileEntryRelPath;
+ final String secondDefaultContent = "Removed.";
+ // Add entry for removed file
+ gnuFormatter.mergeChangelog(dateLine, "" /* no guessed function name */,
+ secondDefaultContent, changelogEditorPart,
+ changelogFilePath, entryFilePath);
+
+ final String actualMergeResult = getContent(changelogEditorPart);
+
+ // Note: Removed files occur in the list first, new file items come after that.
+ final String expectedResult = dateLine + TAB + FILE_ENTRY_START_MARKER +
+ secondFileEntryRelPath+ FILE_ENTRY_END_MARKER +
+ secondDefaultContent + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
+ firstFileEntryRelPath + FILE_ENTRY_END_MARKER +
+ firstDefaultContent;
+
+ assertEquals(expectedResult, actualMergeResult);
+ }
+
+ /**
+ * Test for a changelog entry with items for removed files, new files and modified
+ * existing files. This test differs from the previous in that the ChangeLog is
+ * empty to start with. This verifies Bz #366854 fix.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canHaveEntriesWithDefaultTextAndSomeModificationToAnExistingFile2() throws Exception {
+ // set date/author line
+ String authorName = "Test Author";
+ String email = "test@example.com";
+ final String dateLine = gnuFormatter.formatDateLine(authorName, email);
+
+ // full absolute path to ChangeLog file (relative to project root)
+ String changelogPath = "/" + project.getTestProject().getName() + "/test/example";
+ final String changelogFilePath = changelogPath + "/ChangeLog";
+
+ // add a new empty ChangeLog file to our test project
+ InputStream newFileInputStream = new ByteArrayInputStream(new byte[0]);
+ IFile changelogFile = project.addFileToProject( "/test/example", "ChangeLog",
+ newFileInputStream);
+ // Open a document and get the IEditorPart
+ changelogEditorPart = openEditor(changelogFile);
+
+ // entry file path (need overlap with changelogPath)
+ final String firstFileEntryRelPath = "eclipse/example/test/NewCoffeeMaker.java";
+ String entryFilePath = changelogPath + "/" + firstFileEntryRelPath;
+
+ final String firstDefaultContent = "New file.";
+
+ // Note: This always returns an empty String (should probably be changed...)
+ // merge result will be written to editorContent.
+ //
+ // Create an item with default text "New file"
+ gnuFormatter.mergeChangelog(dateLine, "" /* no guessed function name */,
+ firstDefaultContent, changelogEditorPart,
+ changelogFilePath, entryFilePath);
+ final String secondFileEntryRelPath = "eclipse/example/test/OldCoffeeMaker.java";
+ entryFilePath = changelogPath + "/" + secondFileEntryRelPath;
+ final String secondDefaultContent = "Removed.";
+ // Add entry for removed file
+ gnuFormatter.mergeChangelog(dateLine, "" /* no guessed function name */,
+ secondDefaultContent, changelogEditorPart,
+ changelogFilePath, entryFilePath);
+ final String thirdFileEntryRelPath = "eclipse/example/test/ModifiedFile.java";
+ entryFilePath = changelogPath + "/" + thirdFileEntryRelPath;
+ final String guessedFunctionName = "main";
+ // Create a bullet point describing a change in some existing file
+ gnuFormatter.mergeChangelog(dateLine, guessedFunctionName,
+ "" /* no default content */, changelogEditorPart,
+ changelogFilePath, entryFilePath);
+
+ final String actualMergeResult = getContent(changelogEditorPart);
+
+ // Note that changes to existing files appear first in the changelog entries.
+ // Second are removed files and new files are last.
+ final String expectedResult = dateLine + TAB + FILE_ENTRY_START_MARKER +
+ thirdFileEntryRelPath + SPACE + FUNCTION_START_MARKER +
+ guessedFunctionName + FUNCTION_END_MARKER + FILE_ENTRY_END_MARKER +
+ NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
+ secondFileEntryRelPath+ FILE_ENTRY_END_MARKER +
+ secondDefaultContent + NEW_LINE + TAB + FILE_ENTRY_START_MARKER +
+ firstFileEntryRelPath + FILE_ENTRY_END_MARKER +
+ firstDefaultContent;
+
+ assertEquals(expectedResult, actualMergeResult);
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/tests/AllTests.java b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/tests/AllTests.java
index 329c4cc799..fba24ddc5e 100644
--- a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/tests/AllTests.java
+++ b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/tests/AllTests.java
@@ -20,15 +20,15 @@ import org.junit.runners.Suite.SuiteClasses;
*/
@RunWith(Suite.class)
@SuiteClasses({
- ChangeLogWriterTest.class,
- GNUFormatTest.class,
- JavaParserTest.class,
- CParserTest.class,
- // A small test for the fixture
- TestChangeLogTestProject.class
- }
+ ChangeLogWriterTest.class,
+ GNUFormatTest.class,
+ JavaParserTest.class,
+ CParserTest.class,
+ // A small test for the fixture
+ TestChangeLogTestProject.class
+ }
)
public class AllTests {
- // empty
+ // empty
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/tests/ChangeLogWriterTest.java b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/tests/ChangeLogWriterTest.java
index d366b3c2f5..74206bef4f 100644
--- a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/tests/ChangeLogWriterTest.java
+++ b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/core/tests/ChangeLogWriterTest.java
@@ -31,266 +31,266 @@ import org.eclipse.linuxtools.internal.changelog.core.formatters.GNUFormat;
/**
* @author Severin Gehwolf <sgehwolf@redhat.com>
- *
+ *
*/
public class ChangeLogWriterTest {
- // The instance of the class under test
- private ChangeLogWriter clogWriter;
- // A fake project
- private ChangeLogTestProject project;
- // the path elements to the ChangeLog file, absolute to the project root
- private final String CHANGELOG_FILE_PATH = "/project-name/src/org/";
- private final String CHANGELOG_FILE_NAME = "ChangeLog";
- private String changelogFilePath;
- // IFile handle to '/path/changelog/ChangeLog'
- private IFile changelogFile;
- // Current content of the ChangeLog file
- private final String changeLogContent = "2009-10-14 Some Author <some.author@example.com>\n\n" +
- "\t* this/file/does/not/really/exist/SpringRoll.java: new file\n\n";
-
-
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- clogWriter = new ChangeLogWriter();
- // create a testproject and add a file to it
- project = new ChangeLogTestProject("changelogWriterProject");
- // Generate full path to ChangeLog file
- changelogFilePath = CHANGELOG_FILE_PATH + CHANGELOG_FILE_NAME;
- // add a ChangeLog file to the project at the path specified by
- // CHANGELOG_FILE_PATH_SEGMENTS
- InputStream newFileInputStream = new ByteArrayInputStream(
- changeLogContent.getBytes());
- changelogFile = project.addFileToProject(CHANGELOG_FILE_PATH + CHANGELOG_FILE_NAME, CHANGELOG_FILE_NAME,
- newFileInputStream);
- }
-
- /**
- * @throws java.lang.Exception
- */
- @After
- public void tearDown() throws CoreException {
- // dispose testproject
- project.getTestProject().delete(true, null);
- }
-
- /**
- * Test for setting and getting the content of the ChangeLog
- * file.
- */
- @Test
- public void testGetSetChangelog() {
- // Open the ChangeLog file and get the IEdiorPart
- final IEditorPart currentContent = EditorHelper.openEditor(changelogFile);
- clogWriter.setChangelog(currentContent);
- assertEquals(currentContent, clogWriter.getChangelog());
- EditorHelper.closeEditor(currentContent);
- }
-
- @Test
- public void testGetSetChangelogLocation() {
- final String path = "/path/to/changelog/file/ChangeLog";
- clogWriter.setChangelogLocation(path);
- assertEquals(path, clogWriter.getChangelogLocation());
- }
-
- @Test
- public void testGetSetDateLine() {
- String authorName = "Test Author";
- String email = "spongebob@commedycentral.com";
- clogWriter.setDateLine(new GNUFormat().formatDateLine(
- authorName, email));
-
- // Today's date in ISO format
- Calendar c = new GregorianCalendar();
- String isoDate = String.format("%1$tY-%1$tm-%1$td", c);
-
- // expected date/author line
- String expectedDateLine = isoDate + " " + authorName + " <" + email + ">\n\n";
- assertEquals(expectedDateLine, clogWriter.getDateLine());
- }
-
- @Test
- public void testGetSetEntryFilePath() {
- final String entryFilePath = "/some/path/to/some/File.java";
- clogWriter.setEntryFilePath(entryFilePath);
- assertEquals(entryFilePath, clogWriter.getEntryFilePath());
- }
-
- @Test
- public void testGetSetFormatter() {
- IFormatterChangeLogContrib formatter = new GNUFormat();
- clogWriter.setFormatter(formatter);
- assertEquals(formatter, clogWriter.getFormatter());
- }
-
- @Test
- public void testGetSetGuessedFName() {
- final String guessedFunctionName = "getInstance";
- clogWriter.setGuessedFName(guessedFunctionName);
- assertEquals(guessedFunctionName, clogWriter.getGuessedFName());
- }
-
- /**
- * Note that there can be several Changelogs inside a directory tree.
- * The {@link ChangeLogWriter#writeChangeLog()} code assumes that the full path to
- * the ChangeLog file and the full path to the file for which to generate a ChangeLog
- * entry have the same ancestor (with some potential overlap).
- *
- * Consider the following example:
- *
- * 1. The ChangeLog file is <project-root>/src/ChangeLog
- * 2. The currently open editor contains code of <project-root>/src/org/eclipse/example/Test.java
- *
- * In the above case entries in <project-root>/src/ChangeLog *should* be of the form:
- *
- * <code>
- *
- * YYYY-MM-DD Author Name <email@example.com>
- *
- * * org/eclipse/example/Test.java: new File
- *
- * </code>
- *
- * Similarly, if the ChangeLog file is in <project-root>/ChangeLog and the currently open
- * file is <project-root>/src/org/eclipse/example/Sun.java, generated entries in
- * <project-root>/ChangeLog would look like (note the "src" path is added in this case):
- *
- * <code>
- *
- * YYYY-MM-DD Author Name <email@example.com>
- *
- * * src/org/eclipse/example/Sun.java: new File
- *
- * </code>
- *
- * Test for method {@link org.eclipse.linuxtools.internal.changelog.core.ChangeLogWriter#writeChangeLog()}
- */
- @Test
- public void testWriteChangeLog() throws Exception {
- // We want paths up to the ChangeLog file to overlap
-
- final String pathRelativeToChangeLog = "eclipse/example/test/NewCoffeeMaker.java";
- clogWriter.setEntryFilePath( CHANGELOG_FILE_PATH + pathRelativeToChangeLog );
-
- // Will show up surrounded by "(" and ")" in ChangeLog
- String guessedFunctionName = "bazinga";
- clogWriter.setGuessedFName(guessedFunctionName);
-
- // set GNU formatter
- clogWriter.setFormatter(new GNUFormat());
-
- // Open a document and get the IEditorPart
- IEditorPart editorContent = EditorHelper.openEditor(changelogFile);
- clogWriter.setChangelog(editorContent);
-
- // set date/author line
- String authorName = "Test Author";
- String email = "test@example.com";
- clogWriter.setDateLine(clogWriter.getFormatter().formatDateLine(
- authorName, email));
-
- // full absolute path to ChangeLog file (relative to project root)
- clogWriter.setChangelogLocation(changelogFilePath);
-
- // Write changelog to buffer - need to save for persistence
- clogWriter.writeChangeLog();
-
- // above written content is not persistent yet; save it to make it persistent
- clogWriter.getChangelog().doSave(null);
-
- // Today's date in ISO format
- Calendar c = new GregorianCalendar();
- String isoDate = String.format("%1$tY-%1$tm-%1$td", c);
-
- // Construct the changelog entry by hand and match it with what has been written
- String expectedChangeLogEntry = isoDate + " " + authorName + " <" + email + ">\n\n";
- expectedChangeLogEntry += "\t* " + pathRelativeToChangeLog + " (" + guessedFunctionName + "): \n\n";
-
- String expectedContent = expectedChangeLogEntry + changeLogContent;
-
- // Read in content written to file
- StringBuffer actualContent = new StringBuffer();
- try (BufferedReader br = new BufferedReader(new InputStreamReader(
- new FileInputStream(changelogFile.getLocation().toFile())))) {
- String line;
- while ((line = br.readLine()) != null) {
- actualContent.append(line + "\n");
- }
- }
- // Assert proper content has been added
- assertEquals(expectedContent, actualContent.toString());
- EditorHelper.closeEditor(editorContent);
- }
-
- @Test
- public void testGetSetDefaultContent() {
- final String defaultContent = "DISCLAIMER: default ChangeLog content for new files?";
- clogWriter.setDefaultContent(defaultContent);
- assertEquals(defaultContent, clogWriter.getDefaultContent());
- }
-
-
- /**
- * Test the use of default text.
- *
- * @throws Exception
- */
- @Test
- public void canWriteChangeLogToEmptyChangeLogButWithSomeDefaultContent() throws Exception {
- // set GNU formatter
- clogWriter.setFormatter(new GNUFormat());
-
- // Open up a new ChangeLog file at newPathToChangeLog with empty content
- // and get the IEditorPart
- InputStream newFileInputStream = new ByteArrayInputStream(
- "".getBytes()); // no content
- String destinationPath = "/this/is/some/random/path";
- IFile emptyChangeLogFile = project.addFileToProject(destinationPath, CHANGELOG_FILE_NAME,
- newFileInputStream);
- IEditorPart editorContent = EditorHelper.openEditor(emptyChangeLogFile);
- clogWriter.setChangelog(editorContent);
-
- String authorName = "Test Author";
- String email = "test@example.com";
- clogWriter.setDateLine(clogWriter.getFormatter().formatDateLine(
- authorName, email));
- clogWriter.setChangelogLocation(destinationPath + "/" + CHANGELOG_FILE_NAME);
-
- // Set some default content
- String defaultContent = "Removed.";
- clogWriter.setDefaultContent(defaultContent);
-
- String relativePathOfChangedFile = "path/to/file/for/new/entry/test.c";
- clogWriter.setEntryFilePath( destinationPath + "/" + relativePathOfChangedFile );
-
- clogWriter.setGuessedFName("");
-
- // Write changelog to buffer - need to save for persistence
- clogWriter.writeChangeLog();
-
- // above written content is not persistent yet; save it to make it persistent
- clogWriter.getChangelog().doSave(null);
-
- // Construct the changelog entry by hand and match it with what has been written
- String expectedChangeLogEntry = new GNUFormat().formatDateLine(authorName, email);
- expectedChangeLogEntry += "\t* " + relativePathOfChangedFile + ": "
- + defaultContent + "\n";
-
- // Read in content written to file
- StringBuffer actualContent = new StringBuffer();
- try (BufferedReader br = new BufferedReader(new InputStreamReader(
- new FileInputStream(emptyChangeLogFile.getLocation().toFile())))) {
- String line;
- while ((line = br.readLine()) != null) {
- actualContent.append(line + "\n");
- }
- }
- // Assert proper content has been added
- assertEquals(expectedChangeLogEntry, actualContent.toString());
- EditorHelper.closeEditor(editorContent);
- }
+ // The instance of the class under test
+ private ChangeLogWriter clogWriter;
+ // A fake project
+ private ChangeLogTestProject project;
+ // the path elements to the ChangeLog file, absolute to the project root
+ private final String CHANGELOG_FILE_PATH = "/project-name/src/org/";
+ private final String CHANGELOG_FILE_NAME = "ChangeLog";
+ private String changelogFilePath;
+ // IFile handle to '/path/changelog/ChangeLog'
+ private IFile changelogFile;
+ // Current content of the ChangeLog file
+ private final String changeLogContent = "2009-10-14 Some Author <some.author@example.com>\n\n" +
+ "\t* this/file/does/not/really/exist/SpringRoll.java: new file\n\n";
+
+
+ /**
+ * @throws java.lang.Exception
+ */
+ @Before
+ public void setUp() throws Exception {
+ clogWriter = new ChangeLogWriter();
+ // create a testproject and add a file to it
+ project = new ChangeLogTestProject("changelogWriterProject");
+ // Generate full path to ChangeLog file
+ changelogFilePath = CHANGELOG_FILE_PATH + CHANGELOG_FILE_NAME;
+ // add a ChangeLog file to the project at the path specified by
+ // CHANGELOG_FILE_PATH_SEGMENTS
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ changeLogContent.getBytes());
+ changelogFile = project.addFileToProject(CHANGELOG_FILE_PATH + CHANGELOG_FILE_NAME, CHANGELOG_FILE_NAME,
+ newFileInputStream);
+ }
+
+ /**
+ * @throws java.lang.Exception
+ */
+ @After
+ public void tearDown() throws CoreException {
+ // dispose testproject
+ project.getTestProject().delete(true, null);
+ }
+
+ /**
+ * Test for setting and getting the content of the ChangeLog
+ * file.
+ */
+ @Test
+ public void testGetSetChangelog() {
+ // Open the ChangeLog file and get the IEdiorPart
+ final IEditorPart currentContent = EditorHelper.openEditor(changelogFile);
+ clogWriter.setChangelog(currentContent);
+ assertEquals(currentContent, clogWriter.getChangelog());
+ EditorHelper.closeEditor(currentContent);
+ }
+
+ @Test
+ public void testGetSetChangelogLocation() {
+ final String path = "/path/to/changelog/file/ChangeLog";
+ clogWriter.setChangelogLocation(path);
+ assertEquals(path, clogWriter.getChangelogLocation());
+ }
+
+ @Test
+ public void testGetSetDateLine() {
+ String authorName = "Test Author";
+ String email = "spongebob@commedycentral.com";
+ clogWriter.setDateLine(new GNUFormat().formatDateLine(
+ authorName, email));
+
+ // Today's date in ISO format
+ Calendar c = new GregorianCalendar();
+ String isoDate = String.format("%1$tY-%1$tm-%1$td", c);
+
+ // expected date/author line
+ String expectedDateLine = isoDate + " " + authorName + " <" + email + ">\n\n";
+ assertEquals(expectedDateLine, clogWriter.getDateLine());
+ }
+
+ @Test
+ public void testGetSetEntryFilePath() {
+ final String entryFilePath = "/some/path/to/some/File.java";
+ clogWriter.setEntryFilePath(entryFilePath);
+ assertEquals(entryFilePath, clogWriter.getEntryFilePath());
+ }
+
+ @Test
+ public void testGetSetFormatter() {
+ IFormatterChangeLogContrib formatter = new GNUFormat();
+ clogWriter.setFormatter(formatter);
+ assertEquals(formatter, clogWriter.getFormatter());
+ }
+
+ @Test
+ public void testGetSetGuessedFName() {
+ final String guessedFunctionName = "getInstance";
+ clogWriter.setGuessedFName(guessedFunctionName);
+ assertEquals(guessedFunctionName, clogWriter.getGuessedFName());
+ }
+
+ /**
+ * Note that there can be several Changelogs inside a directory tree.
+ * The {@link ChangeLogWriter#writeChangeLog()} code assumes that the full path to
+ * the ChangeLog file and the full path to the file for which to generate a ChangeLog
+ * entry have the same ancestor (with some potential overlap).
+ *
+ * Consider the following example:
+ *
+ * 1. The ChangeLog file is <project-root>/src/ChangeLog
+ * 2. The currently open editor contains code of <project-root>/src/org/eclipse/example/Test.java
+ *
+ * In the above case entries in <project-root>/src/ChangeLog *should* be of the form:
+ *
+ * <code>
+ *
+ * YYYY-MM-DD Author Name <email@example.com>
+ *
+ * * org/eclipse/example/Test.java: new File
+ *
+ * </code>
+ *
+ * Similarly, if the ChangeLog file is in <project-root>/ChangeLog and the currently open
+ * file is <project-root>/src/org/eclipse/example/Sun.java, generated entries in
+ * <project-root>/ChangeLog would look like (note the "src" path is added in this case):
+ *
+ * <code>
+ *
+ * YYYY-MM-DD Author Name <email@example.com>
+ *
+ * * src/org/eclipse/example/Sun.java: new File
+ *
+ * </code>
+ *
+ * Test for method {@link org.eclipse.linuxtools.internal.changelog.core.ChangeLogWriter#writeChangeLog()}
+ */
+ @Test
+ public void testWriteChangeLog() throws Exception {
+ // We want paths up to the ChangeLog file to overlap
+
+ final String pathRelativeToChangeLog = "eclipse/example/test/NewCoffeeMaker.java";
+ clogWriter.setEntryFilePath( CHANGELOG_FILE_PATH + pathRelativeToChangeLog );
+
+ // Will show up surrounded by "(" and ")" in ChangeLog
+ String guessedFunctionName = "bazinga";
+ clogWriter.setGuessedFName(guessedFunctionName);
+
+ // set GNU formatter
+ clogWriter.setFormatter(new GNUFormat());
+
+ // Open a document and get the IEditorPart
+ IEditorPart editorContent = EditorHelper.openEditor(changelogFile);
+ clogWriter.setChangelog(editorContent);
+
+ // set date/author line
+ String authorName = "Test Author";
+ String email = "test@example.com";
+ clogWriter.setDateLine(clogWriter.getFormatter().formatDateLine(
+ authorName, email));
+
+ // full absolute path to ChangeLog file (relative to project root)
+ clogWriter.setChangelogLocation(changelogFilePath);
+
+ // Write changelog to buffer - need to save for persistence
+ clogWriter.writeChangeLog();
+
+ // above written content is not persistent yet; save it to make it persistent
+ clogWriter.getChangelog().doSave(null);
+
+ // Today's date in ISO format
+ Calendar c = new GregorianCalendar();
+ String isoDate = String.format("%1$tY-%1$tm-%1$td", c);
+
+ // Construct the changelog entry by hand and match it with what has been written
+ String expectedChangeLogEntry = isoDate + " " + authorName + " <" + email + ">\n\n";
+ expectedChangeLogEntry += "\t* " + pathRelativeToChangeLog + " (" + guessedFunctionName + "): \n\n";
+
+ String expectedContent = expectedChangeLogEntry + changeLogContent;
+
+ // Read in content written to file
+ StringBuffer actualContent = new StringBuffer();
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(
+ new FileInputStream(changelogFile.getLocation().toFile())))) {
+ String line;
+ while ((line = br.readLine()) != null) {
+ actualContent.append(line + "\n");
+ }
+ }
+ // Assert proper content has been added
+ assertEquals(expectedContent, actualContent.toString());
+ EditorHelper.closeEditor(editorContent);
+ }
+
+ @Test
+ public void testGetSetDefaultContent() {
+ final String defaultContent = "DISCLAIMER: default ChangeLog content for new files?";
+ clogWriter.setDefaultContent(defaultContent);
+ assertEquals(defaultContent, clogWriter.getDefaultContent());
+ }
+
+
+ /**
+ * Test the use of default text.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canWriteChangeLogToEmptyChangeLogButWithSomeDefaultContent() throws Exception {
+ // set GNU formatter
+ clogWriter.setFormatter(new GNUFormat());
+
+ // Open up a new ChangeLog file at newPathToChangeLog with empty content
+ // and get the IEditorPart
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ "".getBytes()); // no content
+ String destinationPath = "/this/is/some/random/path";
+ IFile emptyChangeLogFile = project.addFileToProject(destinationPath, CHANGELOG_FILE_NAME,
+ newFileInputStream);
+ IEditorPart editorContent = EditorHelper.openEditor(emptyChangeLogFile);
+ clogWriter.setChangelog(editorContent);
+
+ String authorName = "Test Author";
+ String email = "test@example.com";
+ clogWriter.setDateLine(clogWriter.getFormatter().formatDateLine(
+ authorName, email));
+ clogWriter.setChangelogLocation(destinationPath + "/" + CHANGELOG_FILE_NAME);
+
+ // Set some default content
+ String defaultContent = "Removed.";
+ clogWriter.setDefaultContent(defaultContent);
+
+ String relativePathOfChangedFile = "path/to/file/for/new/entry/test.c";
+ clogWriter.setEntryFilePath( destinationPath + "/" + relativePathOfChangedFile );
+
+ clogWriter.setGuessedFName("");
+
+ // Write changelog to buffer - need to save for persistence
+ clogWriter.writeChangeLog();
+
+ // above written content is not persistent yet; save it to make it persistent
+ clogWriter.getChangelog().doSave(null);
+
+ // Construct the changelog entry by hand and match it with what has been written
+ String expectedChangeLogEntry = new GNUFormat().formatDateLine(authorName, email);
+ expectedChangeLogEntry += "\t* " + relativePathOfChangedFile + ": "
+ + defaultContent + "\n";
+
+ // Read in content written to file
+ StringBuffer actualContent = new StringBuffer();
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(
+ new FileInputStream(emptyChangeLogFile.getLocation().toFile())))) {
+ String line;
+ while ((line = br.readLine()) != null) {
+ actualContent.append(line + "\n");
+ }
+ }
+ // Assert proper content has been added
+ assertEquals(expectedChangeLogEntry, actualContent.toString());
+ EditorHelper.closeEditor(editorContent);
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/parsers/tests/CParserTest.java b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/parsers/tests/CParserTest.java
index a94897c82f..afe5b3cd3d 100644
--- a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/parsers/tests/CParserTest.java
+++ b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/parsers/tests/CParserTest.java
@@ -38,395 +38,395 @@ import org.junit.Test;
/**
* CParser test suite.
- *
+ *
*/
public class CParserTest {
- // A unique string to mark the place of current selection in source code
- private static final String OFFSET_MARKER = "<# selection #>";
- // The parser under test
- private IParserChangeLogContrib cParser;
- // A faked project
- private ChangeLogTestProject project;
- // The IEditorPart corresponding to the ChangeLog file
- private IEditorPart cppSourceEditorPart = null;
-
- @Before
- public void setUp() throws Exception {
- cParser = ChangeLogExtensionManager.getExtensionManager().getParserContributor("CEditor");
- project = new ChangeLogTestProject("c-parser-test-project");
- }
-
- @After
- public void tearDown() throws Exception {
- // Tests in this class use javaSourceEditorPart. In order to avoid
- // spill-over from previous runs, truncate content (i.e. manually set
- // content to the empty string).
- if (cppSourceEditorPart != null) {
- AbstractTextEditor castEditor = (AbstractTextEditor) cppSourceEditorPart;
- IDocumentProvider iDocProvider = castEditor.getDocumentProvider();
- IDocument changelogContentDoc = iDocProvider.getDocument(castEditor.getEditorInput());
- changelogContentDoc.set("");
- cppSourceEditorPart.doSave(null);
- // Also close open editor in order for default content to work.
- // I.e. avoid spill over from previous test runs
- closeEditor(cppSourceEditorPart);
- }
- project.getTestProject().delete(true, true, null); // dispose
- }
-
- /**
- * Given an IEditorPart we should be able to retrieve the currently
- * function active C function inside a C source file.
- *
- * @throws Exception
- */
- @Test
- public void canParseCurrentFunctionFromCFile() throws Exception {
- // make testproject a C project
- project.addCNature();
-
- final String expectedFunctionName = "doSomething";
- final String cSourceCode = "static int " + expectedFunctionName + "(char *test)\n"
- + "{\n"
- + "int index = 0;\n"
- + "// " + OFFSET_MARKER + "\n"
- + "return 0;\n"
- + "}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/some_c_file.c")));
-
- // Add some_c_file.c to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- cSourceCode.getBytes());
- IFile cSourceFile = project.addFileToProject(
- "/src",
- "some_c_file.c", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/some_c_file.c")));
-
- // Open a source file and get the IEditorPart
- cppSourceEditorPart = openEditor(cSourceFile);
- assertEquals(cSourceCode, getContent(cppSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
-
- // Select the snippet we want
- int selectionStart = cSourceCode.indexOf(OFFSET_MARKER);
- assertTrue(selectionStart >= 0);
- int selectionLength = OFFSET_MARKER.length();
- AbstractTextEditor cEditor = (AbstractTextEditor) cppSourceEditorPart;
- cEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String actualFunctionName = cParser.parseCurrentFunction(cppSourceEditorPart);
-
- assertEquals(expectedFunctionName, actualFunctionName);
- }
-
- /**
- * Given an IEditorPart and not being inside any function within a C
- * source file, no function should be determined.
- *
- * @throws Exception
- */
- @Test
- public void canDetermineThatInNoFunctionInCFile() throws Exception {
- // make test project a C project
- project.addCNature();
-
- final String cSourceCode = "// Prototype " + OFFSET_MARKER + "\n"
- + "static int doSomething(char *test);\n\n"
- + "static int doSomething(char *test)\n"
- + "{\n"
- + "int index = 0;\n"
- + "return 0;\n"
- + "}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/some_c_file.c")));
-
- // Add some_c_file.c to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- cSourceCode.getBytes());
- IFile cSourceFile = project.addFileToProject(
- "/src",
- "some_c_file.c", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/some_c_file.c")));
-
- // Open a source file and get the IEditorPart
- cppSourceEditorPart = openEditor(cSourceFile);
- assertEquals(cSourceCode, getContent(cppSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
-
- // Select the snippet we want
- int selectionStart = cSourceCode.indexOf(OFFSET_MARKER);
- assertTrue(selectionStart >= 0);
- int selectionLength = OFFSET_MARKER.length();
- AbstractTextEditor cEditor = (AbstractTextEditor) cppSourceEditorPart;
- cEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String actualFunctionName = cParser.parseCurrentFunction(cppSourceEditorPart);
-
- assertEquals("" /* expect empty function name */, actualFunctionName);
- }
-
- /**
- * Given an IEditorPart we should be able to retrieve the currently selected
- * variable identifier inside a C++ file.
- *
- * @throws Exception
- */
- @Test
- public void canParseCurrentlySelectedVariableIdentifierInCppFile() throws Exception {
- // make test project a C++ project
- project.addCCNature();
-
- final String expectedIdentifier = "myIdentifier";
- final String className = "shape";
- final String cppSourceCode = "class " + className + " {\n"
- + "int x;\n"
- + "int y;\n"
- + "private:\n"
- + "int color;\n"
- + "float " + expectedIdentifier + ";\n"
- + "void set_color(int color);\n"
- +"}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/shape.h")));
-
- // Add shape.h to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- cppSourceCode.getBytes());
- IFile cppSourceFile = project.addFileToProject(
- "/src",
- "shape.h", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/shape.h")));
-
- // Open a source file and get the IEditorPart
- cppSourceEditorPart = openEditor(cppSourceFile);
- // make sure editor content is correct
- assertEquals(cppSourceCode, getContent(cppSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
-
- // Select the snippet we want
- int selectionStart = cppSourceCode.indexOf(expectedIdentifier);
- assertTrue(selectionStart >= 0);
- // shouldn't need to mark whole length of identifier.
- int selectionLength = expectedIdentifier.length() - 3;
- AbstractTextEditor cppEditor = (AbstractTextEditor) cppSourceEditorPart;
- cppEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String actualIdentifier = cParser.parseCurrentFunction(cppSourceEditorPart);
-
- assertEquals(className + "." + expectedIdentifier, actualIdentifier);
- }
-
- /**
- * Given an IEditorPart and not selected any variable identifier in a class, we should
- * get the class name as selected function name only.
- *
- * @throws Exception
- */
- @Test
- public void canParseClassNameIfNoVariableIdentifierSelectedInCppFile() throws Exception {
- // make test project a C++ project
- project.addCCNature();
-
- final String className = "shape";
- final String cppSourceCode = "class " + className + " {\n"
- + "int x;\n"
- + "int y;\n"
- + "// " + OFFSET_MARKER + "\n"
- + "private:\n"
- + "int color;\n"
- + "void set_color(int color);\n"
- +"}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/shape.h")));
-
- // Add shape.h to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- cppSourceCode.getBytes());
- IFile cppSourceFile = project.addFileToProject(
- "/src",
- "shape.h", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/shape.h")));
-
- // Open a source file and get the IEditorPart
- cppSourceEditorPart = openEditor(cppSourceFile);
- // make sure editor content is correct
- assertEquals(cppSourceCode, getContent(cppSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
-
- // Select the snippet we want
- int selectionStart = cppSourceCode.indexOf(OFFSET_MARKER);
- assertTrue(selectionStart >= 0);
- int selectionLength = OFFSET_MARKER.length();
- AbstractTextEditor cppEditor = (AbstractTextEditor) cppSourceEditorPart;
- cppEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String actualFunction = cParser.parseCurrentFunction(cppSourceEditorPart);
-
- assertEquals(className, actualFunction);
- }
-
- /**
- * Given an IEditorPart and current selection is inside a method,
- * CParser should be able to figure that out.
- *
- * @throws Exception
- */
- @Test
- public void canParseCurrentMethodNameInCppFile() throws Exception {
- // make test project a C++ project
- project.addCCNature();
-
- final String expectedMethodName = "circle::area";
- final String cppSourceCode = "#include \"circle.h\"\n"
- + "#include <math.h>\n"
- + "float " + expectedMethodName + "() {\n"
- + "// " + OFFSET_MARKER + "\n"
- + "return this->radius * this-> radius * M_PI\n"
- + "}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/circle.cpp")));
-
- // Add shape.h to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- cppSourceCode.getBytes());
- IFile cppSourceFile = project.addFileToProject(
- "/src",
- "circle.cpp", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/circle.cpp")));
-
- // Open a source file and get the IEditorPart
- cppSourceEditorPart = openEditor(cppSourceFile);
- // make sure editor content is correct
- assertEquals(cppSourceCode, getContent(cppSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
-
- // Select the snippet we want
- int selectionStart = cppSourceCode.indexOf(OFFSET_MARKER);
- assertTrue(selectionStart >= 0);
- int selectionLength = OFFSET_MARKER.length();
- AbstractTextEditor cppEditor = (AbstractTextEditor) cppSourceEditorPart;
- cppEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String actualMethodName = cParser.parseCurrentFunction(cppSourceEditorPart);
-
- assertEquals(expectedMethodName, actualMethodName);
- }
-
- /**
- * Given an IEditorPart and current selection is inside a method,
- * CParser should be able to figure that out.
- *
- * @throws Exception
- */
- @Test
- public void canParseCurrentFunctionInCppFile() throws Exception {
- // make test project a C++ project
- project.addCCNature();
-
- final String expectedFunction = "main";
- final String cppSourceCode = "#include \"circle.h\"\n"
- + "#include <math.h>\n"
- + "float circle::area() {\n"
- + "return this->radius * this-> radius * M_PI\n"
- + "}\n"
- + "int " + expectedFunction + "() {\n"
- + "int some_var = 0;\n"
- + "// " + OFFSET_MARKER + "\n"
- + "return 0;\n"
- + "}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/circle.cpp")));
-
- // Add shape.h to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- cppSourceCode.getBytes());
- IFile cppSourceFile = project.addFileToProject(
- "/src",
- "circle.cpp", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/circle.cpp")));
-
- // Open a source file and get the IEditorPart
- cppSourceEditorPart = openEditor(cppSourceFile);
- // make sure editor content is correct
- assertEquals(cppSourceCode, getContent(cppSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
-
- // Select the snippet we want
- int selectionStart = cppSourceCode.indexOf(OFFSET_MARKER);
- assertTrue(selectionStart >= 0);
- int selectionLength = OFFSET_MARKER.length();
- AbstractTextEditor cppEditor = (AbstractTextEditor) cppSourceEditorPart;
- cppEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String actualFunction = cParser.parseCurrentFunction(cppSourceEditorPart);
-
- assertEquals(expectedFunction, actualFunction);
- }
-
- /**
- * Given an IStorageEditorInput we should be able to retrieve the currently
- * active C function.
- *
- * @throws Exception
- */
- @Test
- public void canParseCurrentFunctionFromCStringInIStorageEditorInput() throws Exception {
- final String expectedFunctionName = "doSomething";
- final String cSourceCode = "static int " + expectedFunctionName + "(char *test)\n"
- + "{\n"
- + "int index = 0;\n"
- + "// " + OFFSET_MARKER + "\n"
- + "return 0;\n"
- + "}\n";
-
- // prepare IStorageEditorInput
- IStorage cStringStorage = new CStringStorage(cSourceCode);
- IStorageEditorInput cStringStorageEditorInput = new CStringStorageInput(cStringStorage);
-
- // Figure out the desired offset
- int selectOffset = cSourceCode.indexOf(OFFSET_MARKER);
- assertTrue(selectOffset >= 0);
-
- final String actualFunctionName = cParser.parseCurrentFunction(cStringStorageEditorInput, selectOffset);
-
- assertEquals(expectedFunctionName, actualFunctionName);
- }
+ // A unique string to mark the place of current selection in source code
+ private static final String OFFSET_MARKER = "<# selection #>";
+ // The parser under test
+ private IParserChangeLogContrib cParser;
+ // A faked project
+ private ChangeLogTestProject project;
+ // The IEditorPart corresponding to the ChangeLog file
+ private IEditorPart cppSourceEditorPart = null;
+
+ @Before
+ public void setUp() throws Exception {
+ cParser = ChangeLogExtensionManager.getExtensionManager().getParserContributor("CEditor");
+ project = new ChangeLogTestProject("c-parser-test-project");
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ // Tests in this class use javaSourceEditorPart. In order to avoid
+ // spill-over from previous runs, truncate content (i.e. manually set
+ // content to the empty string).
+ if (cppSourceEditorPart != null) {
+ AbstractTextEditor castEditor = (AbstractTextEditor) cppSourceEditorPart;
+ IDocumentProvider iDocProvider = castEditor.getDocumentProvider();
+ IDocument changelogContentDoc = iDocProvider.getDocument(castEditor.getEditorInput());
+ changelogContentDoc.set("");
+ cppSourceEditorPart.doSave(null);
+ // Also close open editor in order for default content to work.
+ // I.e. avoid spill over from previous test runs
+ closeEditor(cppSourceEditorPart);
+ }
+ project.getTestProject().delete(true, true, null); // dispose
+ }
+
+ /**
+ * Given an IEditorPart we should be able to retrieve the currently
+ * function active C function inside a C source file.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canParseCurrentFunctionFromCFile() throws Exception {
+ // make testproject a C project
+ project.addCNature();
+
+ final String expectedFunctionName = "doSomething";
+ final String cSourceCode = "static int " + expectedFunctionName + "(char *test)\n"
+ + "{\n"
+ + "int index = 0;\n"
+ + "// " + OFFSET_MARKER + "\n"
+ + "return 0;\n"
+ + "}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/some_c_file.c")));
+
+ // Add some_c_file.c to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ cSourceCode.getBytes());
+ IFile cSourceFile = project.addFileToProject(
+ "/src",
+ "some_c_file.c", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/some_c_file.c")));
+
+ // Open a source file and get the IEditorPart
+ cppSourceEditorPart = openEditor(cSourceFile);
+ assertEquals(cSourceCode, getContent(cppSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = cSourceCode.indexOf(OFFSET_MARKER);
+ assertTrue(selectionStart >= 0);
+ int selectionLength = OFFSET_MARKER.length();
+ AbstractTextEditor cEditor = (AbstractTextEditor) cppSourceEditorPart;
+ cEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String actualFunctionName = cParser.parseCurrentFunction(cppSourceEditorPart);
+
+ assertEquals(expectedFunctionName, actualFunctionName);
+ }
+
+ /**
+ * Given an IEditorPart and not being inside any function within a C
+ * source file, no function should be determined.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canDetermineThatInNoFunctionInCFile() throws Exception {
+ // make test project a C project
+ project.addCNature();
+
+ final String cSourceCode = "// Prototype " + OFFSET_MARKER + "\n"
+ + "static int doSomething(char *test);\n\n"
+ + "static int doSomething(char *test)\n"
+ + "{\n"
+ + "int index = 0;\n"
+ + "return 0;\n"
+ + "}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/some_c_file.c")));
+
+ // Add some_c_file.c to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ cSourceCode.getBytes());
+ IFile cSourceFile = project.addFileToProject(
+ "/src",
+ "some_c_file.c", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/some_c_file.c")));
+
+ // Open a source file and get the IEditorPart
+ cppSourceEditorPart = openEditor(cSourceFile);
+ assertEquals(cSourceCode, getContent(cppSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = cSourceCode.indexOf(OFFSET_MARKER);
+ assertTrue(selectionStart >= 0);
+ int selectionLength = OFFSET_MARKER.length();
+ AbstractTextEditor cEditor = (AbstractTextEditor) cppSourceEditorPart;
+ cEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String actualFunctionName = cParser.parseCurrentFunction(cppSourceEditorPart);
+
+ assertEquals("" /* expect empty function name */, actualFunctionName);
+ }
+
+ /**
+ * Given an IEditorPart we should be able to retrieve the currently selected
+ * variable identifier inside a C++ file.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canParseCurrentlySelectedVariableIdentifierInCppFile() throws Exception {
+ // make test project a C++ project
+ project.addCCNature();
+
+ final String expectedIdentifier = "myIdentifier";
+ final String className = "shape";
+ final String cppSourceCode = "class " + className + " {\n"
+ + "int x;\n"
+ + "int y;\n"
+ + "private:\n"
+ + "int color;\n"
+ + "float " + expectedIdentifier + ";\n"
+ + "void set_color(int color);\n"
+ +"}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/shape.h")));
+
+ // Add shape.h to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ cppSourceCode.getBytes());
+ IFile cppSourceFile = project.addFileToProject(
+ "/src",
+ "shape.h", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/shape.h")));
+
+ // Open a source file and get the IEditorPart
+ cppSourceEditorPart = openEditor(cppSourceFile);
+ // make sure editor content is correct
+ assertEquals(cppSourceCode, getContent(cppSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = cppSourceCode.indexOf(expectedIdentifier);
+ assertTrue(selectionStart >= 0);
+ // shouldn't need to mark whole length of identifier.
+ int selectionLength = expectedIdentifier.length() - 3;
+ AbstractTextEditor cppEditor = (AbstractTextEditor) cppSourceEditorPart;
+ cppEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String actualIdentifier = cParser.parseCurrentFunction(cppSourceEditorPart);
+
+ assertEquals(className + "." + expectedIdentifier, actualIdentifier);
+ }
+
+ /**
+ * Given an IEditorPart and not selected any variable identifier in a class, we should
+ * get the class name as selected function name only.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canParseClassNameIfNoVariableIdentifierSelectedInCppFile() throws Exception {
+ // make test project a C++ project
+ project.addCCNature();
+
+ final String className = "shape";
+ final String cppSourceCode = "class " + className + " {\n"
+ + "int x;\n"
+ + "int y;\n"
+ + "// " + OFFSET_MARKER + "\n"
+ + "private:\n"
+ + "int color;\n"
+ + "void set_color(int color);\n"
+ +"}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/shape.h")));
+
+ // Add shape.h to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ cppSourceCode.getBytes());
+ IFile cppSourceFile = project.addFileToProject(
+ "/src",
+ "shape.h", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/shape.h")));
+
+ // Open a source file and get the IEditorPart
+ cppSourceEditorPart = openEditor(cppSourceFile);
+ // make sure editor content is correct
+ assertEquals(cppSourceCode, getContent(cppSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = cppSourceCode.indexOf(OFFSET_MARKER);
+ assertTrue(selectionStart >= 0);
+ int selectionLength = OFFSET_MARKER.length();
+ AbstractTextEditor cppEditor = (AbstractTextEditor) cppSourceEditorPart;
+ cppEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String actualFunction = cParser.parseCurrentFunction(cppSourceEditorPart);
+
+ assertEquals(className, actualFunction);
+ }
+
+ /**
+ * Given an IEditorPart and current selection is inside a method,
+ * CParser should be able to figure that out.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canParseCurrentMethodNameInCppFile() throws Exception {
+ // make test project a C++ project
+ project.addCCNature();
+
+ final String expectedMethodName = "circle::area";
+ final String cppSourceCode = "#include \"circle.h\"\n"
+ + "#include <math.h>\n"
+ + "float " + expectedMethodName + "() {\n"
+ + "// " + OFFSET_MARKER + "\n"
+ + "return this->radius * this-> radius * M_PI\n"
+ + "}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/circle.cpp")));
+
+ // Add shape.h to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ cppSourceCode.getBytes());
+ IFile cppSourceFile = project.addFileToProject(
+ "/src",
+ "circle.cpp", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/circle.cpp")));
+
+ // Open a source file and get the IEditorPart
+ cppSourceEditorPart = openEditor(cppSourceFile);
+ // make sure editor content is correct
+ assertEquals(cppSourceCode, getContent(cppSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = cppSourceCode.indexOf(OFFSET_MARKER);
+ assertTrue(selectionStart >= 0);
+ int selectionLength = OFFSET_MARKER.length();
+ AbstractTextEditor cppEditor = (AbstractTextEditor) cppSourceEditorPart;
+ cppEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String actualMethodName = cParser.parseCurrentFunction(cppSourceEditorPart);
+
+ assertEquals(expectedMethodName, actualMethodName);
+ }
+
+ /**
+ * Given an IEditorPart and current selection is inside a method,
+ * CParser should be able to figure that out.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canParseCurrentFunctionInCppFile() throws Exception {
+ // make test project a C++ project
+ project.addCCNature();
+
+ final String expectedFunction = "main";
+ final String cppSourceCode = "#include \"circle.h\"\n"
+ + "#include <math.h>\n"
+ + "float circle::area() {\n"
+ + "return this->radius * this-> radius * M_PI\n"
+ + "}\n"
+ + "int " + expectedFunction + "() {\n"
+ + "int some_var = 0;\n"
+ + "// " + OFFSET_MARKER + "\n"
+ + "return 0;\n"
+ + "}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/circle.cpp")));
+
+ // Add shape.h to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ cppSourceCode.getBytes());
+ IFile cppSourceFile = project.addFileToProject(
+ "/src",
+ "circle.cpp", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/circle.cpp")));
+
+ // Open a source file and get the IEditorPart
+ cppSourceEditorPart = openEditor(cppSourceFile);
+ // make sure editor content is correct
+ assertEquals(cppSourceCode, getContent(cppSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( cppSourceEditorPart instanceof AbstractTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = cppSourceCode.indexOf(OFFSET_MARKER);
+ assertTrue(selectionStart >= 0);
+ int selectionLength = OFFSET_MARKER.length();
+ AbstractTextEditor cppEditor = (AbstractTextEditor) cppSourceEditorPart;
+ cppEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String actualFunction = cParser.parseCurrentFunction(cppSourceEditorPart);
+
+ assertEquals(expectedFunction, actualFunction);
+ }
+
+ /**
+ * Given an IStorageEditorInput we should be able to retrieve the currently
+ * active C function.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canParseCurrentFunctionFromCStringInIStorageEditorInput() throws Exception {
+ final String expectedFunctionName = "doSomething";
+ final String cSourceCode = "static int " + expectedFunctionName + "(char *test)\n"
+ + "{\n"
+ + "int index = 0;\n"
+ + "// " + OFFSET_MARKER + "\n"
+ + "return 0;\n"
+ + "}\n";
+
+ // prepare IStorageEditorInput
+ IStorage cStringStorage = new CStringStorage(cSourceCode);
+ IStorageEditorInput cStringStorageEditorInput = new CStringStorageInput(cStringStorage);
+
+ // Figure out the desired offset
+ int selectOffset = cSourceCode.indexOf(OFFSET_MARKER);
+ assertTrue(selectOffset >= 0);
+
+ final String actualFunctionName = cParser.parseCurrentFunction(cStringStorageEditorInput, selectOffset);
+
+ assertEquals(expectedFunctionName, actualFunctionName);
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/parsers/tests/JavaParserTest.java b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/parsers/tests/JavaParserTest.java
index d57462adc5..3687d149c3 100644
--- a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/parsers/tests/JavaParserTest.java
+++ b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/parsers/tests/JavaParserTest.java
@@ -35,429 +35,429 @@ import org.junit.Test;
/**
* JavaParser test suite.
- *
+ *
*/
public class JavaParserTest {
- // A unique string to mark the place of current selection in source code
- private static final String OFFSET_MARKER = "<# selection #>";
- // The parser under test
- private IParserChangeLogContrib javaParser;
- // A faked project
- private ChangeLogTestProject project;
- // The IEditorPart corresponding to the ChangeLog file
- private IEditorPart javaSourceEditorPart = null;
-
- @Before
- public void setUp() throws Exception {
- javaParser = ChangeLogExtensionManager.getExtensionManager().getParserContributor("CompilationUnitEditor");
- project = new ChangeLogTestProject("java-parser-test-project");
- // make it a Java project
- project.addJavaNature();
- }
-
- @After
- public void tearDown() throws Exception {
- // Tests in this class use javaSourceEditorPart. In order to avoid
- // spill-over from previous runs, truncate content (i.e. manually set
- // content to the empty string).
- if (javaSourceEditorPart != null) {
- AbstractTextEditor castEditor = (AbstractTextEditor) javaSourceEditorPart;
- IDocumentProvider iDocProvider = castEditor.getDocumentProvider();
- IDocument changelogContentDoc = iDocProvider.getDocument(castEditor.getEditorInput());
- changelogContentDoc.set("");
- javaSourceEditorPart.doSave(null);
- // Also close open editor in order for default content to work.
- // I.e. avoid spill over from previous test runs
- closeEditor(javaSourceEditorPart);
- }
- project.getTestProject().delete(true, true, null); // dispose
- }
-
- /**
- * Given an IEditorPart we should be able to retrieve the current function
- * we are in.
- *
- * @throws Exception
- */
- @Test
- public void canParseCurrentMethod() throws Exception {
- final String expectedMethodName = "doSomething";
- final String javaSourceCode = "public class JavaParserExampleClass {\n"
- + "private void " + expectedMethodName + "(String param) {\n"
- + "// " + OFFSET_MARKER + "\n"
- + "}\n"
- + "}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Add JavaParserExampleClass.java to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- javaSourceCode.getBytes());
- IFile javaSourceFile = project.addFileToProject(
- "/src/org/eclipse/changelog/tests",
- "JavaParserExampleClass.java", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Open a source file and get the IEditorPart
- javaSourceEditorPart = openEditor(javaSourceFile);
- // make sure changelog editor content is right before merging
- assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
-
- // Select the snippet we want
- int selectionStart = javaSourceCode.indexOf(OFFSET_MARKER);
- assertTrue(selectionStart >= 0);
- int selectionLength = OFFSET_MARKER.length();
- AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
- javaEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String actualMethodName = javaParser.parseCurrentFunction(javaSourceEditorPart);
-
- assertEquals(expectedMethodName, actualMethodName);
- }
-
- /**
- * Given an IEditorPart we should be able to retrieve the currently selected
- * field.
- *
- * @throws Exception
- */
- @Test
- public void canParseSelectedField() throws Exception {
- final String expectedFieldName = "testVar";
- final String javaSourceCode = "public class JavaParserExampleClass {\n"
- + "private String " + expectedFieldName + " = null;\n"
- + "private void someMethod(String param) {\n"
- + "// empty \n"
- + "}\n"
- + "}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Add JavaParserExampleClass.java to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- javaSourceCode.getBytes());
- IFile javaSourceFile = project.addFileToProject(
- "/src/org/eclipse/changelog/tests",
- "JavaParserExampleClass.java", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Open a source file and get the IEditorPart
- javaSourceEditorPart = openEditor(javaSourceFile);
- // make sure changelog editor content is right before merging
- assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
-
- // Select the snippet we want
- int selectionStart = javaSourceCode.indexOf(expectedFieldName);
- assertTrue(selectionStart >= 0);
- int selectionLength = expectedFieldName.length() - 3; // Shouldn't need to select the entire field
- AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
- javaEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String actualFieldName = javaParser.parseCurrentFunction(javaSourceEditorPart);
-
- assertEquals(expectedFieldName, actualFieldName);
- }
-
- /**
- * Given an IEditorPart and current selection is in a static instance initializer
- * block, JavaParser should be able to figure out that we were in an static
- * initializer block.
- *
- * @throws Exception
- */
- @Test
- public void canIdentifyStaticInitializerWhenInStaticInstanceInitializer() throws Exception {
- final String javaSourceCode = "public class JavaParserExampleClass {\n"
- + "private String someStrVariable = null;\n"
- // create static instance initializer block
- + "{\n"
- + "// " + OFFSET_MARKER + "\n"
- + "}\n"
- + "private void someMethod(String param) {\n"
- + "// empty \n"
- + "}\n"
- + "}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Add JavaParserExampleClass.java to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- javaSourceCode.getBytes());
- IFile javaSourceFile = project.addFileToProject(
- "/src/org/eclipse/changelog/tests",
- "JavaParserExampleClass.java", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Open a source file and get the IEditorPart
- javaSourceEditorPart = openEditor(javaSourceFile);
- // make sure changelog editor content is right before merging
- assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
-
- // Select the snippet we want
- int selectionStart = javaSourceCode.indexOf(OFFSET_MARKER);
- assertTrue(selectionStart >= 0);
- int selectionLength = OFFSET_MARKER.length();
- AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
- javaEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String actualFunctionName = javaParser.parseCurrentFunction(javaSourceEditorPart);
-
- assertEquals("static initializer", actualFunctionName);
- }
-
- /**
- * Given an IEditorPart and current selection is in a static class initializer
- * block, JavaParser should be able to figure out that we were in an static
- * initializer block.
- *
- * @throws Exception
- */
- @Test
- public void canIdentifyStaticInitializerWhenInStaticClassInitializer() throws Exception {
- final String javaSourceCode = "public class JavaParserExampleClass {\n"
- + "private String someStrVariable = null;\n"
- // create static class initializer block
- + "static {\n"
- + "// " + OFFSET_MARKER + "\n"
- + "}\n"
- + "private void someMethod(String param) {\n"
- + "// empty \n"
- + "}\n"
- + "}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Add JavaParserExampleClass.java to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- javaSourceCode.getBytes());
- IFile javaSourceFile = project.addFileToProject(
- "/src/org/eclipse/changelog/tests",
- "JavaParserExampleClass.java", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Open a source file and get the IEditorPart
- javaSourceEditorPart = openEditor(javaSourceFile);
- // make sure changelog editor content is right before merging
- assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
-
- // Select the snippet we want
- int selectionStart = javaSourceCode.indexOf(OFFSET_MARKER);
- assertTrue(selectionStart >= 0);
- int selectionLength = OFFSET_MARKER.length();
- AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
- javaEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String actualFunctionName = javaParser.parseCurrentFunction(javaSourceEditorPart);
-
- assertEquals("static initializer", actualFunctionName);
- }
-
- /**
- * Given an IEditorPart and current selection is inside a method within a nested
- * class, JavaParser should return a "nestedClass.methodName" construct for the
- * current function.
- *
- * @throws Exception
- */
- @Test
- public void canIdentifyMethodWithinNestedClass() throws Exception {
- final String nestedClassName = "Encapsulated";
- final String currentMethodName = "getString";
- final String javaSourceCode = "public class JavaParserExampleClass {\n"
- + "private String someStrVariable = null;\n"
- + "static {\n"
- + "// empty \n"
- + "}\n"
- + "private void someMethod(String param) {\n"
- + "// empty \n"
- + "}\n"
- + "private class " + nestedClassName + "{\n"
- + "public String " + currentMethodName + "() throws Exception {\n"
- + "// " + OFFSET_MARKER + "\n"
- + "return \"returnString\";\n"
- + "}\n"
- + "}\n"
- + "}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Add JavaParserExampleClass.java to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- javaSourceCode.getBytes());
- IFile javaSourceFile = project.addFileToProject(
- "/src/org/eclipse/changelog/tests",
- "JavaParserExampleClass.java", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Open a source file and get the IEditorPart
- javaSourceEditorPart = openEditor(javaSourceFile);
- // make sure changelog editor content is right before merging
- assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
-
- // Select the snippet we want
- int selectionStart = javaSourceCode.indexOf(OFFSET_MARKER);
- assertTrue(selectionStart >= 0);
- int selectionLength = OFFSET_MARKER.length();
- AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
- javaEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String expectedFunctionName = nestedClassName + "." + currentMethodName;
- final String actualFunctionName = javaParser.parseCurrentFunction(javaSourceEditorPart);
-
- assertEquals(expectedFunctionName, actualFunctionName);
- }
-
- /**
- * Given an IEditorPart and currently a field within a nested
- * class is selected, JavaParser should return a "nestedClass.fieldName"
- * construct for the current function.
- *
- * @throws Exception
- */
- @Test
- public void canIdentifyFieldWithinNestedClass() throws Exception {
- final String nestedClassName = "Encapsulated";
- final String currentFieldName = "variableInNestedClass";
- final String javaSourceCode = "public class JavaParserExampleClass {\n"
- + "private String someStrVariable = null;\n"
- + "static {\n"
- + "// empty \n"
- + "}\n"
- + "private void someMethod(String param) {\n"
- + "// empty \n"
- + "}\n"
- + "private class " + nestedClassName + "{\n"
- + "private int " + currentFieldName + " = 10;\n"
- + "public String getString() throws Exception {\n"
- + "// return a String, yay ;-)\n"
- + "return \"returnString\";\n"
- + "}\n"
- + "}\n"
- + "}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Add JavaParserExampleClass.java to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- javaSourceCode.getBytes());
- IFile javaSourceFile = project.addFileToProject(
- "/src/org/eclipse/changelog/tests",
- "JavaParserExampleClass.java", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Open a source file and get the IEditorPart
- javaSourceEditorPart = openEditor(javaSourceFile);
- // make sure changelog editor content is right before merging
- assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
-
- // Select the snippet we want
- int selectionStart = javaSourceCode.indexOf(currentFieldName);
- assertTrue(selectionStart >= 0);
- // select only a part of field name, as this should be sufficient
- int selectionLength = currentFieldName.length() - 3;
- AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
- javaEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String expectedFunctionName = nestedClassName + "." + currentFieldName;
- final String actualFunctionName = javaParser.parseCurrentFunction(javaSourceEditorPart);
-
- assertEquals(expectedFunctionName, actualFunctionName);
- }
-
- /**
- * Given an IEditorPart and current selection is inside a class but not within a
- * method, not selecting a field and not in a nested class (somewhere else in the
- * class) it should return an empty string for the function.
- *
- * @throws Exception
- */
- @Test
- public void canDetermineThatSelectionIsJustInClass() throws Exception {
- // Apparently comments don't show up in the compilation units. Makes
- // sense, right? But we can't use the OFFSET_MARKER trick in this case.
- final String javaSourceCode = "public class JavaParserExampleClass {\n"
- + "private String someStrVariable = null;\n"
- + "\n" // want to select this line indexOf(';') + 2
- + "\n"
- + "private void someMethod(String param) {\n"
- + "// empty \n"
- + "}\n"
- + "}\n";
-
- assertNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Add JavaParserExampleClass.java to project
- InputStream newFileInputStream = new ByteArrayInputStream(
- javaSourceCode.getBytes());
- IFile javaSourceFile = project.addFileToProject(
- "/src/org/eclipse/changelog/tests",
- "JavaParserExampleClass.java", newFileInputStream);
-
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
-
- // Open a source file and get the IEditorPart
- javaSourceEditorPart = openEditor(javaSourceFile);
- // make sure changelog editor content is right before merging
- assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
-
- // make sure we have the proper editor type
- assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
-
- // Select the right point
- int selectionStart = javaSourceCode.indexOf(';') + 2;
- assertTrue(selectionStart >= 2);
- int selectionLength = 0;
- AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
- javaEditor.getSelectionProvider().setSelection(
- new TextSelection(selectionStart, selectionLength));
-
- final String actualFunctionName = javaParser.parseCurrentFunction(javaSourceEditorPart);
-
- assertEquals("" /* expect empty string */, actualFunctionName);
- }
+ // A unique string to mark the place of current selection in source code
+ private static final String OFFSET_MARKER = "<# selection #>";
+ // The parser under test
+ private IParserChangeLogContrib javaParser;
+ // A faked project
+ private ChangeLogTestProject project;
+ // The IEditorPart corresponding to the ChangeLog file
+ private IEditorPart javaSourceEditorPart = null;
+
+ @Before
+ public void setUp() throws Exception {
+ javaParser = ChangeLogExtensionManager.getExtensionManager().getParserContributor("CompilationUnitEditor");
+ project = new ChangeLogTestProject("java-parser-test-project");
+ // make it a Java project
+ project.addJavaNature();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ // Tests in this class use javaSourceEditorPart. In order to avoid
+ // spill-over from previous runs, truncate content (i.e. manually set
+ // content to the empty string).
+ if (javaSourceEditorPart != null) {
+ AbstractTextEditor castEditor = (AbstractTextEditor) javaSourceEditorPart;
+ IDocumentProvider iDocProvider = castEditor.getDocumentProvider();
+ IDocument changelogContentDoc = iDocProvider.getDocument(castEditor.getEditorInput());
+ changelogContentDoc.set("");
+ javaSourceEditorPart.doSave(null);
+ // Also close open editor in order for default content to work.
+ // I.e. avoid spill over from previous test runs
+ closeEditor(javaSourceEditorPart);
+ }
+ project.getTestProject().delete(true, true, null); // dispose
+ }
+
+ /**
+ * Given an IEditorPart we should be able to retrieve the current function
+ * we are in.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canParseCurrentMethod() throws Exception {
+ final String expectedMethodName = "doSomething";
+ final String javaSourceCode = "public class JavaParserExampleClass {\n"
+ + "private void " + expectedMethodName + "(String param) {\n"
+ + "// " + OFFSET_MARKER + "\n"
+ + "}\n"
+ + "}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Add JavaParserExampleClass.java to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ javaSourceCode.getBytes());
+ IFile javaSourceFile = project.addFileToProject(
+ "/src/org/eclipse/changelog/tests",
+ "JavaParserExampleClass.java", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Open a source file and get the IEditorPart
+ javaSourceEditorPart = openEditor(javaSourceFile);
+ // make sure changelog editor content is right before merging
+ assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = javaSourceCode.indexOf(OFFSET_MARKER);
+ assertTrue(selectionStart >= 0);
+ int selectionLength = OFFSET_MARKER.length();
+ AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
+ javaEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String actualMethodName = javaParser.parseCurrentFunction(javaSourceEditorPart);
+
+ assertEquals(expectedMethodName, actualMethodName);
+ }
+
+ /**
+ * Given an IEditorPart we should be able to retrieve the currently selected
+ * field.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canParseSelectedField() throws Exception {
+ final String expectedFieldName = "testVar";
+ final String javaSourceCode = "public class JavaParserExampleClass {\n"
+ + "private String " + expectedFieldName + " = null;\n"
+ + "private void someMethod(String param) {\n"
+ + "// empty \n"
+ + "}\n"
+ + "}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Add JavaParserExampleClass.java to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ javaSourceCode.getBytes());
+ IFile javaSourceFile = project.addFileToProject(
+ "/src/org/eclipse/changelog/tests",
+ "JavaParserExampleClass.java", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Open a source file and get the IEditorPart
+ javaSourceEditorPart = openEditor(javaSourceFile);
+ // make sure changelog editor content is right before merging
+ assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = javaSourceCode.indexOf(expectedFieldName);
+ assertTrue(selectionStart >= 0);
+ int selectionLength = expectedFieldName.length() - 3; // Shouldn't need to select the entire field
+ AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
+ javaEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String actualFieldName = javaParser.parseCurrentFunction(javaSourceEditorPart);
+
+ assertEquals(expectedFieldName, actualFieldName);
+ }
+
+ /**
+ * Given an IEditorPart and current selection is in a static instance initializer
+ * block, JavaParser should be able to figure out that we were in an static
+ * initializer block.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canIdentifyStaticInitializerWhenInStaticInstanceInitializer() throws Exception {
+ final String javaSourceCode = "public class JavaParserExampleClass {\n"
+ + "private String someStrVariable = null;\n"
+ // create static instance initializer block
+ + "{\n"
+ + "// " + OFFSET_MARKER + "\n"
+ + "}\n"
+ + "private void someMethod(String param) {\n"
+ + "// empty \n"
+ + "}\n"
+ + "}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Add JavaParserExampleClass.java to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ javaSourceCode.getBytes());
+ IFile javaSourceFile = project.addFileToProject(
+ "/src/org/eclipse/changelog/tests",
+ "JavaParserExampleClass.java", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Open a source file and get the IEditorPart
+ javaSourceEditorPart = openEditor(javaSourceFile);
+ // make sure changelog editor content is right before merging
+ assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = javaSourceCode.indexOf(OFFSET_MARKER);
+ assertTrue(selectionStart >= 0);
+ int selectionLength = OFFSET_MARKER.length();
+ AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
+ javaEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String actualFunctionName = javaParser.parseCurrentFunction(javaSourceEditorPart);
+
+ assertEquals("static initializer", actualFunctionName);
+ }
+
+ /**
+ * Given an IEditorPart and current selection is in a static class initializer
+ * block, JavaParser should be able to figure out that we were in an static
+ * initializer block.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canIdentifyStaticInitializerWhenInStaticClassInitializer() throws Exception {
+ final String javaSourceCode = "public class JavaParserExampleClass {\n"
+ + "private String someStrVariable = null;\n"
+ // create static class initializer block
+ + "static {\n"
+ + "// " + OFFSET_MARKER + "\n"
+ + "}\n"
+ + "private void someMethod(String param) {\n"
+ + "// empty \n"
+ + "}\n"
+ + "}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Add JavaParserExampleClass.java to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ javaSourceCode.getBytes());
+ IFile javaSourceFile = project.addFileToProject(
+ "/src/org/eclipse/changelog/tests",
+ "JavaParserExampleClass.java", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Open a source file and get the IEditorPart
+ javaSourceEditorPart = openEditor(javaSourceFile);
+ // make sure changelog editor content is right before merging
+ assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = javaSourceCode.indexOf(OFFSET_MARKER);
+ assertTrue(selectionStart >= 0);
+ int selectionLength = OFFSET_MARKER.length();
+ AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
+ javaEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String actualFunctionName = javaParser.parseCurrentFunction(javaSourceEditorPart);
+
+ assertEquals("static initializer", actualFunctionName);
+ }
+
+ /**
+ * Given an IEditorPart and current selection is inside a method within a nested
+ * class, JavaParser should return a "nestedClass.methodName" construct for the
+ * current function.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canIdentifyMethodWithinNestedClass() throws Exception {
+ final String nestedClassName = "Encapsulated";
+ final String currentMethodName = "getString";
+ final String javaSourceCode = "public class JavaParserExampleClass {\n"
+ + "private String someStrVariable = null;\n"
+ + "static {\n"
+ + "// empty \n"
+ + "}\n"
+ + "private void someMethod(String param) {\n"
+ + "// empty \n"
+ + "}\n"
+ + "private class " + nestedClassName + "{\n"
+ + "public String " + currentMethodName + "() throws Exception {\n"
+ + "// " + OFFSET_MARKER + "\n"
+ + "return \"returnString\";\n"
+ + "}\n"
+ + "}\n"
+ + "}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Add JavaParserExampleClass.java to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ javaSourceCode.getBytes());
+ IFile javaSourceFile = project.addFileToProject(
+ "/src/org/eclipse/changelog/tests",
+ "JavaParserExampleClass.java", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Open a source file and get the IEditorPart
+ javaSourceEditorPart = openEditor(javaSourceFile);
+ // make sure changelog editor content is right before merging
+ assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = javaSourceCode.indexOf(OFFSET_MARKER);
+ assertTrue(selectionStart >= 0);
+ int selectionLength = OFFSET_MARKER.length();
+ AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
+ javaEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String expectedFunctionName = nestedClassName + "." + currentMethodName;
+ final String actualFunctionName = javaParser.parseCurrentFunction(javaSourceEditorPart);
+
+ assertEquals(expectedFunctionName, actualFunctionName);
+ }
+
+ /**
+ * Given an IEditorPart and currently a field within a nested
+ * class is selected, JavaParser should return a "nestedClass.fieldName"
+ * construct for the current function.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canIdentifyFieldWithinNestedClass() throws Exception {
+ final String nestedClassName = "Encapsulated";
+ final String currentFieldName = "variableInNestedClass";
+ final String javaSourceCode = "public class JavaParserExampleClass {\n"
+ + "private String someStrVariable = null;\n"
+ + "static {\n"
+ + "// empty \n"
+ + "}\n"
+ + "private void someMethod(String param) {\n"
+ + "// empty \n"
+ + "}\n"
+ + "private class " + nestedClassName + "{\n"
+ + "private int " + currentFieldName + " = 10;\n"
+ + "public String getString() throws Exception {\n"
+ + "// return a String, yay ;-)\n"
+ + "return \"returnString\";\n"
+ + "}\n"
+ + "}\n"
+ + "}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Add JavaParserExampleClass.java to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ javaSourceCode.getBytes());
+ IFile javaSourceFile = project.addFileToProject(
+ "/src/org/eclipse/changelog/tests",
+ "JavaParserExampleClass.java", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Open a source file and get the IEditorPart
+ javaSourceEditorPart = openEditor(javaSourceFile);
+ // make sure changelog editor content is right before merging
+ assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
+
+ // Select the snippet we want
+ int selectionStart = javaSourceCode.indexOf(currentFieldName);
+ assertTrue(selectionStart >= 0);
+ // select only a part of field name, as this should be sufficient
+ int selectionLength = currentFieldName.length() - 3;
+ AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
+ javaEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String expectedFunctionName = nestedClassName + "." + currentFieldName;
+ final String actualFunctionName = javaParser.parseCurrentFunction(javaSourceEditorPart);
+
+ assertEquals(expectedFunctionName, actualFunctionName);
+ }
+
+ /**
+ * Given an IEditorPart and current selection is inside a class but not within a
+ * method, not selecting a field and not in a nested class (somewhere else in the
+ * class) it should return an empty string for the function.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canDetermineThatSelectionIsJustInClass() throws Exception {
+ // Apparently comments don't show up in the compilation units. Makes
+ // sense, right? But we can't use the OFFSET_MARKER trick in this case.
+ final String javaSourceCode = "public class JavaParserExampleClass {\n"
+ + "private String someStrVariable = null;\n"
+ + "\n" // want to select this line indexOf(';') + 2
+ + "\n"
+ + "private void someMethod(String param) {\n"
+ + "// empty \n"
+ + "}\n"
+ + "}\n";
+
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Add JavaParserExampleClass.java to project
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ javaSourceCode.getBytes());
+ IFile javaSourceFile = project.addFileToProject(
+ "/src/org/eclipse/changelog/tests",
+ "JavaParserExampleClass.java", newFileInputStream);
+
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/org/eclipse/changelog/tests/JavaParserExampleClass.java")));
+
+ // Open a source file and get the IEditorPart
+ javaSourceEditorPart = openEditor(javaSourceFile);
+ // make sure changelog editor content is right before merging
+ assertEquals(javaSourceCode, getContent(javaSourceEditorPart));
+
+ // make sure we have the proper editor type
+ assertTrue( javaSourceEditorPart instanceof AbstractDecoratedTextEditor );
+
+ // Select the right point
+ int selectionStart = javaSourceCode.indexOf(';') + 2;
+ assertTrue(selectionStart >= 2);
+ int selectionLength = 0;
+ AbstractDecoratedTextEditor javaEditor = (AbstractDecoratedTextEditor) javaSourceEditorPart;
+ javaEditor.getSelectionProvider().setSelection(
+ new TextSelection(selectionStart, selectionLength));
+
+ final String actualFunctionName = javaParser.parseCurrentFunction(javaSourceEditorPart);
+
+ assertEquals("" /* expect empty string */, actualFunctionName);
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/CStringStorage.java b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/CStringStorage.java
index 136f57c653..9f16aace40 100644
--- a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/CStringStorage.java
+++ b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/CStringStorage.java
@@ -18,35 +18,35 @@ import org.eclipse.core.runtime.IPath;
*
*/
public class CStringStorage implements IStorage {
- private String string;
-
- public CStringStorage(String input) {
- this.string = input;
- }
-
- @Override
- public InputStream getContents() {
- return new ByteArrayInputStream(string.getBytes());
- }
-
- @Override
- public IPath getFullPath() {
- return null;
- }
-
- @Override
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
-
- @Override
- public String getName() {
- int len = Math.min(5, string.length());
- return string.substring(0, len).concat("..."); //$NON-NLS-1$
- }
-
- @Override
- public boolean isReadOnly() {
- return true;
- }
+ private String string;
+
+ public CStringStorage(String input) {
+ this.string = input;
+ }
+
+ @Override
+ public InputStream getContents() {
+ return new ByteArrayInputStream(string.getBytes());
+ }
+
+ @Override
+ public IPath getFullPath() {
+ return null;
+ }
+
+ @Override
+ public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
+ return null;
+ }
+
+ @Override
+ public String getName() {
+ int len = Math.min(5, string.length());
+ return string.substring(0, len).concat("..."); //$NON-NLS-1$
+ }
+
+ @Override
+ public boolean isReadOnly() {
+ return true;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/CStringStorageInput.java b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/CStringStorageInput.java
index 117e8f1f40..9f3e638d5e 100644
--- a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/CStringStorageInput.java
+++ b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/CStringStorageInput.java
@@ -17,46 +17,46 @@ import org.eclipse.ui.IStorageEditorInput;
*
*/
public class CStringStorageInput implements IStorageEditorInput {
-
- private IStorage storage;
-
- public CStringStorageInput(IStorage storage) {
- this.storage = storage;
- }
-
- @Override
- public boolean exists() {
- return true;
- }
-
- @Override
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- @Override
- public String getName() {
- return storage.getName();
- }
-
- @Override
- public IPersistableElement getPersistable() {
- return null;
- }
-
- @Override
- public IStorage getStorage() {
- return storage;
- }
-
- @Override
- public String getToolTipText() {
- return "String-based file: " + storage.getName();
- }
-
- @Override
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- return null;
- }
+
+ private IStorage storage;
+
+ public CStringStorageInput(IStorage storage) {
+ this.storage = storage;
+ }
+
+ @Override
+ public boolean exists() {
+ return true;
+ }
+
+ @Override
+ public ImageDescriptor getImageDescriptor() {
+ return null;
+ }
+
+ @Override
+ public String getName() {
+ return storage.getName();
+ }
+
+ @Override
+ public IPersistableElement getPersistable() {
+ return null;
+ }
+
+ @Override
+ public IStorage getStorage() {
+ return storage;
+ }
+
+ @Override
+ public String getToolTipText() {
+ return "String-based file: " + storage.getName();
+ }
+
+ @Override
+ public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
+ return null;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/ChangeLogTestProject.java b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/ChangeLogTestProject.java
index 144e31409d..455fd3b3b4 100644
--- a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/ChangeLogTestProject.java
+++ b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/ChangeLogTestProject.java
@@ -25,124 +25,124 @@ import org.eclipse.jdt.core.JavaCore;
/**
* Test fixture for the changelog plug-in tests.
- *
+ *
* Functionality:
* - Create a new project in the current workspace
*
*/
public class ChangeLogTestProject {
- private IProject testProject;
-
- /**
- * Create a new ChangelogTestProject
- *
- * @param projectName The name of the project to be created.
- * @throws Exception
- */
- public ChangeLogTestProject(String projectName) throws Exception {
- testProject = createNewProject(projectName);
- }
-
- /**
- * @return the testProject
- */
- public IProject getTestProject() {
- return testProject;
- }
+ private IProject testProject;
+
+ /**
+ * Create a new ChangelogTestProject
+ *
+ * @param projectName The name of the project to be created.
+ * @throws Exception
+ */
+ public ChangeLogTestProject(String projectName) throws Exception {
+ testProject = createNewProject(projectName);
+ }
+
+ /**
+ * @return the testProject
+ */
+ public IProject getTestProject() {
+ return testProject;
+ }
+
+ /**
+ * @param testProject the testProject to set
+ */
+ public void setTestProject(IProject testProject) {
+ this.testProject = testProject;
+ }
+
+ /**
+ * Adds a file to this project at the specified <code>path</code>
+ * and the provided <code>filename</code>. If segments of <code>path</code>
+ * do not exist, they will be created.
+ *
+ * @param destPath The path relative to the project (use '/' as path separator).
+ * @param filename The name of the to be created file
+ * @param fileInputStream A stream to the new files content.
+ */
+ public IFile addFileToProject(String destPath, String filename, InputStream fileInputStream) throws CoreException {
+ String[] pathSegments = destPath.split("/");
+
+ IContainer parent = this.testProject;
+ for (String segment: pathSegments) {
+ if (segment.equals("")) {
+ continue; // ignore
+ }
+ IResource segmentResource = parent.findMember(new Path(IPath.SEPARATOR + segment));
+ if (segmentResource == null) {
+ // create folder
+ IFolder newFolder = parent.getFolder(new Path(segment));
+ newFolder.create(false, true, null);
+ parent = newFolder;
+ } else {
+ // resource existed
+ parent = (IContainer)segmentResource;
+ }
+ }
+ // Finally add the file
+ IFile newFile = parent.getFile(new Path(filename));
+ if (fileInputStream == null) {
+ throw new IllegalStateException("fileInputStream must not be null");
+ }
+ newFile.create(fileInputStream, false, null);
+
+ // refresh project
+ this.testProject.refreshLocal(IResource.DEPTH_INFINITE, null);
+
+ return newFile;
+ }
+
+ /**
+ * Add the Java nature to this project. I.e. make it a Java project.
+ */
+ public IJavaProject addJavaNature() throws CoreException {
+ IProjectDescription description = this.testProject.getDescription();
+ String[] natures = description.getNatureIds();
+ String[] newNatures = new String[natures.length + 1];
+ System.arraycopy(natures, 0, newNatures, 0, natures.length);
+ newNatures[natures.length] = JavaCore.NATURE_ID;
+ description.setNatureIds(newNatures);
+ this.testProject.setDescription(description, null);
+ return JavaCore.create(this.testProject);
+ }
- /**
- * @param testProject the testProject to set
- */
- public void setTestProject(IProject testProject) {
- this.testProject = testProject;
- }
-
- /**
- * Adds a file to this project at the specified <code>path</code>
- * and the provided <code>filename</code>. If segments of <code>path</code>
- * do not exist, they will be created.
- *
- * @param destPath The path relative to the project (use '/' as path separator).
- * @param filename The name of the to be created file
- * @param fileInputStream A stream to the new files content.
- */
- public IFile addFileToProject(String destPath, String filename, InputStream fileInputStream) throws CoreException {
- String[] pathSegments = destPath.split("/");
-
- IContainer parent = this.testProject;
- for (String segment: pathSegments) {
- if (segment.equals("")) {
- continue; // ignore
- }
- IResource segmentResource = parent.findMember(new Path(IPath.SEPARATOR + segment));
- if (segmentResource == null) {
- // create folder
- IFolder newFolder = parent.getFolder(new Path(segment));
- newFolder.create(false, true, null);
- parent = newFolder;
- } else {
- // resource existed
- parent = (IContainer)segmentResource;
- }
- }
- // Finally add the file
- IFile newFile = parent.getFile(new Path(filename));
- if (fileInputStream == null) {
- throw new IllegalStateException("fileInputStream must not be null");
- }
- newFile.create(fileInputStream, false, null);
-
- // refresh project
- this.testProject.refreshLocal(IResource.DEPTH_INFINITE, null);
-
- return newFile;
- }
-
- /**
- * Add the Java nature to this project. I.e. make it a Java project.
- */
- public IJavaProject addJavaNature() throws CoreException {
- IProjectDescription description = this.testProject.getDescription();
- String[] natures = description.getNatureIds();
- String[] newNatures = new String[natures.length + 1];
- System.arraycopy(natures, 0, newNatures, 0, natures.length);
- newNatures[natures.length] = JavaCore.NATURE_ID;
- description.setNatureIds(newNatures);
- this.testProject.setDescription(description, null);
- return JavaCore.create(this.testProject);
- }
+ /**
+ * Add the C nature to this project. I.e. make it a C project.
+ * @throws CoreException
+ */
+ public void addCNature() throws CoreException {
+ this.testProject = CCorePlugin.getDefault().createCDTProject(
+ testProject.getDescription(), testProject, null);
+ }
- /**
- * Add the C nature to this project. I.e. make it a C project.
- * @throws CoreException
- */
- public void addCNature() throws CoreException {
- this.testProject = CCorePlugin.getDefault().createCDTProject(
- testProject.getDescription(), testProject, null);
- }
-
- /**
- * Add the C++ nature to this project. I.e. make it a C++ project.
- * @throws CoreException
- */
- public void addCCNature() throws CoreException {
- addCNature();
- CCorePlugin.getDefault().convertProjectFromCtoCC(testProject, null);
- }
+ /**
+ * Add the C++ nature to this project. I.e. make it a C++ project.
+ * @throws CoreException
+ */
+ public void addCCNature() throws CoreException {
+ addCNature();
+ CCorePlugin.getDefault().convertProjectFromCtoCC(testProject, null);
+ }
- /**
- * Create a new Eclipse project in the current workspace
- *
- * @param name
- * @throws CoreException if project creation fails for some reason.
- * @return The newly created project.
- */
- private IProject createNewProject(String name) throws CoreException {
- IProject newProject = ResourcesPlugin.getWorkspace().getRoot()
- .getProject(name);
- newProject.create(null);
- newProject.open(null); // needs to be open
- return newProject;
- }
+ /**
+ * Create a new Eclipse project in the current workspace
+ *
+ * @param name
+ * @throws CoreException if project creation fails for some reason.
+ * @return The newly created project.
+ */
+ private IProject createNewProject(String name) throws CoreException {
+ IProject newProject = ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(name);
+ newProject.create(null);
+ newProject.open(null); // needs to be open
+ return newProject;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/TestChangeLogTestProject.java b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/TestChangeLogTestProject.java
index 522f99f2a8..d9b19a6836 100644
--- a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/TestChangeLogTestProject.java
+++ b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/fixtures/TestChangeLogTestProject.java
@@ -27,124 +27,124 @@ import org.eclipse.cdt.core.model.CoreModel;
/**
* @author Redhat Inc.
- *
+ *
*/
public class TestChangeLogTestProject {
- private ChangeLogTestProject project;
-
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- project = new ChangeLogTestProject("com.redhat.testchangelog.project");
- }
-
- /**
- * @throws java.lang.Exception
- */
- @After
- public void tearDown() throws Exception {
- // dispose
- project.getTestProject().delete(true, null);
- }
-
- /**
- * Test method for
- * {@link org.eclipse.linuxtools.changelog.tests.fixtures.ChangeLogTestProject#addFileToProject(java.lang.String, java.lang.String, java.io.InputStream)}
- * .
- */
- @Test
- public void testAddFileToProject() throws Exception {
- String fileContent = "some content";
- InputStream newFileInputStream = new ByteArrayInputStream(
- fileContent.getBytes());
- // Create file "testfile.txt" with content "some content" at
- // "/this/is/a/testpath"
- project.addFileToProject("/this/is/a/testpath", "testfile.txt",
- newFileInputStream);
- IProject p = project.getTestProject();
-
- // Paths along the way should have been created
- IResource member = p.findMember(new Path("/this"));
- assertNotNull(member);
- assertEquals("this", member.getName());
- member = p.findMember(new Path("/this/is"));
- assertNotNull(member);
- assertEquals("is", member.getName());
- member = p.findMember(new Path("/this/is/a"));
- assertNotNull(member);
- assertEquals("a", member.getName());
- member = p.findMember(new Path("/this/is/a/testpath"));
- assertNotNull(member);
- assertEquals("testpath", member.getName());
-
- // Testfile should be around
- IResource createdFile = p.findMember(new Path("/this/is/a/testpath/testfile.txt"));
- assertNotNull(createdFile);
- assertEquals("this/is/a/testpath/testfile.txt", createdFile.getProjectRelativePath().toString());
- assertEquals("testfile.txt", createdFile.getName());
- assertTrue(createdFile instanceof IFile);
-
- // Content should be "some content"
- try (BufferedReader br = new BufferedReader(new InputStreamReader(
- new FileInputStream(createdFile.getLocation().toFile())))) {
- String actualContent = br.readLine();
- assertEquals(fileContent, actualContent);
- }
-
- // this should throw an IllegalStateException
- boolean exceptionTrown = false;
- try {
- project.addFileToProject("donnot/care", "not_important.java",
- null /* should cause exception */);
- } catch (IllegalStateException e) {
- // pass
- exceptionTrown = true;
- }
- assertTrue(exceptionTrown);
- }
-
- /**
- * We should be able to add a Java nature to a project.
- *
- * @throws Exception
- */
- @Test
- public void canAddJavaNature() throws Exception {
- IJavaProject javaProject = this.project.addJavaNature();
- assertNotNull(javaProject);
- }
-
- /**
- * We should be able to add a C nature to a project.
- *
- * @throws Exception
- */
- @Test
- public void canAddCNature() throws Exception {
- IProject cProject = this.project.getTestProject();
- assertFalse(CoreModel.hasCNature(cProject));
- // Add C nature
- this.project.addCNature();
- cProject = this.project.getTestProject();
- assertTrue(CoreModel.hasCNature(cProject));
- }
-
- /**
- * We should be able to add a C++ nature to a project.
- *
- * @throws Exception
- */
- @Test
- public void canAddCCNature() throws Exception {
- IProject ccProject = this.project.getTestProject();
- assertFalse(CoreModel.hasCCNature(ccProject));
- // Add C++ nature
- this.project.addCCNature();
- ccProject = this.project.getTestProject();
- assertTrue(CoreModel.hasCCNature(ccProject));
- }
+ private ChangeLogTestProject project;
+
+ /**
+ * @throws java.lang.Exception
+ */
+ @Before
+ public void setUp() throws Exception {
+ project = new ChangeLogTestProject("com.redhat.testchangelog.project");
+ }
+
+ /**
+ * @throws java.lang.Exception
+ */
+ @After
+ public void tearDown() throws Exception {
+ // dispose
+ project.getTestProject().delete(true, null);
+ }
+
+ /**
+ * Test method for
+ * {@link org.eclipse.linuxtools.changelog.tests.fixtures.ChangeLogTestProject#addFileToProject(java.lang.String, java.lang.String, java.io.InputStream)}
+ * .
+ */
+ @Test
+ public void testAddFileToProject() throws Exception {
+ String fileContent = "some content";
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ fileContent.getBytes());
+ // Create file "testfile.txt" with content "some content" at
+ // "/this/is/a/testpath"
+ project.addFileToProject("/this/is/a/testpath", "testfile.txt",
+ newFileInputStream);
+ IProject p = project.getTestProject();
+
+ // Paths along the way should have been created
+ IResource member = p.findMember(new Path("/this"));
+ assertNotNull(member);
+ assertEquals("this", member.getName());
+ member = p.findMember(new Path("/this/is"));
+ assertNotNull(member);
+ assertEquals("is", member.getName());
+ member = p.findMember(new Path("/this/is/a"));
+ assertNotNull(member);
+ assertEquals("a", member.getName());
+ member = p.findMember(new Path("/this/is/a/testpath"));
+ assertNotNull(member);
+ assertEquals("testpath", member.getName());
+
+ // Testfile should be around
+ IResource createdFile = p.findMember(new Path("/this/is/a/testpath/testfile.txt"));
+ assertNotNull(createdFile);
+ assertEquals("this/is/a/testpath/testfile.txt", createdFile.getProjectRelativePath().toString());
+ assertEquals("testfile.txt", createdFile.getName());
+ assertTrue(createdFile instanceof IFile);
+
+ // Content should be "some content"
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(
+ new FileInputStream(createdFile.getLocation().toFile())))) {
+ String actualContent = br.readLine();
+ assertEquals(fileContent, actualContent);
+ }
+
+ // this should throw an IllegalStateException
+ boolean exceptionTrown = false;
+ try {
+ project.addFileToProject("donnot/care", "not_important.java",
+ null /* should cause exception */);
+ } catch (IllegalStateException e) {
+ // pass
+ exceptionTrown = true;
+ }
+ assertTrue(exceptionTrown);
+ }
+
+ /**
+ * We should be able to add a Java nature to a project.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canAddJavaNature() throws Exception {
+ IJavaProject javaProject = this.project.addJavaNature();
+ assertNotNull(javaProject);
+ }
+
+ /**
+ * We should be able to add a C nature to a project.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canAddCNature() throws Exception {
+ IProject cProject = this.project.getTestProject();
+ assertFalse(CoreModel.hasCNature(cProject));
+ // Add C nature
+ this.project.addCNature();
+ cProject = this.project.getTestProject();
+ assertTrue(CoreModel.hasCNature(cProject));
+ }
+
+ /**
+ * We should be able to add a C++ nature to a project.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canAddCCNature() throws Exception {
+ IProject ccProject = this.project.getTestProject();
+ assertFalse(CoreModel.hasCCNature(ccProject));
+ // Add C++ nature
+ this.project.addCCNature();
+ ccProject = this.project.getTestProject();
+ assertTrue(CoreModel.hasCCNature(ccProject));
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/helpers/EditorHelper.java b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/helpers/EditorHelper.java
index 3f22957e0b..e3ffb389fd 100644
--- a/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/helpers/EditorHelper.java
+++ b/changelog/org.eclipse.linuxtools.changelog.tests/src/org/eclipse/linuxtools/changelog/tests/helpers/EditorHelper.java
@@ -18,52 +18,52 @@ import org.eclipse.ui.texteditor.IDocumentProvider;
public class EditorHelper {
- /**
- * Open file associated with <code>diskresource</code> in current
- * workspace.
- *
- * @param diskresource The file to be opened in the current workspace.
- * @return The IEditorPart associated with the opened file in the current workspace
- * or null if opening fails.
- */
- public static IEditorPart openEditor(IFile diskresource) {
- IWorkbench ws = PlatformUI.getWorkbench();
- try {
- return org.eclipse.ui.ide.IDE.openEditor(ws
- .getActiveWorkbenchWindow().getActivePage(), diskresource,
- true);
- } catch (PartInitException e) {
- e.printStackTrace();
+ /**
+ * Open file associated with <code>diskresource</code> in current
+ * workspace.
+ *
+ * @param diskresource The file to be opened in the current workspace.
+ * @return The IEditorPart associated with the opened file in the current workspace
+ * or null if opening fails.
+ */
+ public static IEditorPart openEditor(IFile diskresource) {
+ IWorkbench ws = PlatformUI.getWorkbench();
+ try {
+ return org.eclipse.ui.ide.IDE.openEditor(ws
+ .getActiveWorkbenchWindow().getActivePage(), diskresource,
+ true);
+ } catch (PartInitException e) {
+ e.printStackTrace();
- return null;
- }
- }
-
- /**
- * Close editor if it is active.
- */
- public static void closeEditor(final IEditorPart editor) {
- if (editor.getSite().getWorkbenchWindow().getActivePage() != null) {
- PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
- @Override
- public void run() {
- // close editor
- editor.getSite().getWorkbenchWindow().getActivePage()
- .closeEditor(editor, false);
- }
- });
- }
- }
-
- /**
- * Return the content of the given IEditorPart as String.
- * @param editorPart
- * @return Content of editorPart.
- */
- public static String getContent(IEditorPart editorPart) {
- AbstractTextEditor castEditor = (AbstractTextEditor) editorPart;
- IDocumentProvider provider = castEditor.getDocumentProvider();
- IDocument document = provider.getDocument(castEditor.getEditorInput());
- return document.get();
- }
+ return null;
+ }
+ }
+
+ /**
+ * Close editor if it is active.
+ */
+ public static void closeEditor(final IEditorPart editor) {
+ if (editor.getSite().getWorkbenchWindow().getActivePage() != null) {
+ PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ // close editor
+ editor.getSite().getWorkbenchWindow().getActivePage()
+ .closeEditor(editor, false);
+ }
+ });
+ }
+ }
+
+ /**
+ * Return the content of the given IEditorPart as String.
+ * @param editorPart
+ * @return Content of editorPart.
+ */
+ public static String getContent(IEditorPart editorPart) {
+ AbstractTextEditor castEditor = (AbstractTextEditor) editorPart;
+ IDocumentProvider provider = castEditor.getDocumentProvider();
+ IDocument document = provider.getDocument(castEditor.getEditorInput());
+ return document.get();
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/pom.xml b/changelog/org.eclipse.linuxtools.changelog.ui.tests/pom.xml
index 18dfe8f0de..68d5d44284 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/pom.xml
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/pom.xml
@@ -36,7 +36,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.changelog.ui.tests</testSuite>
<testClass>org.eclipse.linuxtools.changelog.ui.tests.swtbot.AllSWTBotTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>false</useUIThread>
<product>org.eclipse.platform.ide</product>
<surefire.timeout>1800</surefire.timeout>
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/log4j.xml b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/log4j.xml
index 87414d37ef..9bbb32c295 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/log4j.xml
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/log4j.xml
@@ -1,60 +1,60 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
- debug="false">
-
- <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
- <param name="Target" value="System.out" />
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern"
- value="%d{dd MMM yyyy HH:mm:ss.SSS} - %25t - %-5p - %30c{1} - (%C{1}.java:%L) - %m%n" />
- </layout>
- </appender>
-
- <appender name="fileAppender" class="org.apache.log4j.FileAppender">
- <param name="File" value="swtbot_tests.log" />
- <param name="Append" value="false" />
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern"
- value="%d{dd MMM yyyy HH:mm:ss.SSS} - %25t - %-5p - %30c{1} - (%C{1}.java:%L) - %m%n" />
- </layout>
- </appender>
-
- <appender name="asyncAppender" class="org.apache.log4j.AsyncAppender">
- <!-- appender-ref ref="consoleAppender" / -->
- <appender-ref ref="fileAppender" />
- </appender>
-
- <!-- don't log matchers, this is very high amount of chatter -->
- <category name="org.eclipse.swtbot.swt.finder.matchers">
- <priority value="OFF" />
- </category>
-
- <!--
- don't log widget notification events, this is moderately high chatter
- -->
- <category name="org.eclipse.swtbot.swt.finder.widgets">
- <priority value="DEBUG" />
- </category>
-
- <!-- don't log finders, this is moderate chatter -->
- <category name="org.eclipse.swtbot.swt.finder.finders">
- <priority value="DEBUG" />
- </category>
-
- <category name="org.eclipse.swtbot.swt.finder.keyboard">
- <!-- set to a value higher than debug to turn on. -->
- <priority value="DEBUG" />
- </category>
-
- <category name="org.eclipse.swtbot">
- <priority value="ALL" />
- </category>
-
- <root>
- <priority value="INFO" />
- <appender-ref ref="consoleAppender" />
- <appender-ref ref="fileAppender" />
- </root>
+ debug="false">
+
+ <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
+ <param name="Target" value="System.out" />
+ <layout class="org.apache.log4j.PatternLayout">
+ <param name="ConversionPattern"
+ value="%d{dd MMM yyyy HH:mm:ss.SSS} - %25t - %-5p - %30c{1} - (%C{1}.java:%L) - %m%n" />
+ </layout>
+ </appender>
+
+ <appender name="fileAppender" class="org.apache.log4j.FileAppender">
+ <param name="File" value="swtbot_tests.log" />
+ <param name="Append" value="false" />
+ <layout class="org.apache.log4j.PatternLayout">
+ <param name="ConversionPattern"
+ value="%d{dd MMM yyyy HH:mm:ss.SSS} - %25t - %-5p - %30c{1} - (%C{1}.java:%L) - %m%n" />
+ </layout>
+ </appender>
+
+ <appender name="asyncAppender" class="org.apache.log4j.AsyncAppender">
+ <!-- appender-ref ref="consoleAppender" / -->
+ <appender-ref ref="fileAppender" />
+ </appender>
+
+ <!-- don't log matchers, this is very high amount of chatter -->
+ <category name="org.eclipse.swtbot.swt.finder.matchers">
+ <priority value="OFF" />
+ </category>
+
+ <!--
+ don't log widget notification events, this is moderately high chatter
+ -->
+ <category name="org.eclipse.swtbot.swt.finder.widgets">
+ <priority value="DEBUG" />
+ </category>
+
+ <!-- don't log finders, this is moderate chatter -->
+ <category name="org.eclipse.swtbot.swt.finder.finders">
+ <priority value="DEBUG" />
+ </category>
+
+ <category name="org.eclipse.swtbot.swt.finder.keyboard">
+ <!-- set to a value higher than debug to turn on. -->
+ <priority value="DEBUG" />
+ </category>
+
+ <category name="org.eclipse.swtbot">
+ <priority value="ALL" />
+ </category>
+
+ <root>
+ <priority value="INFO" />
+ <appender-ref ref="consoleAppender" />
+ <appender-ref ref="fileAppender" />
+ </root>
</log4j:configuration> \ No newline at end of file
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/AddChangelogEntrySWTBotTest.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/AddChangelogEntrySWTBotTest.java
index 2ae9a4b6b4..f9c4d03ff0 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/AddChangelogEntrySWTBotTest.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/AddChangelogEntrySWTBotTest.java
@@ -50,213 +50,213 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class AddChangelogEntrySWTBotTest {
- private static SWTWorkbenchBot bot;
- private static SWTBotTree projectExplorerViewTree;
- private ChangeLogTestProject project;
- private static final String OFFSET_MARKER = "<-- SELECT -->";
- // The name of the test project, we create
- private final String PROJECT_NAME = "changelog-java-project";
+ private static SWTWorkbenchBot bot;
+ private static SWTBotTree projectExplorerViewTree;
+ private ChangeLogTestProject project;
+ private static final String OFFSET_MARKER = "<-- SELECT -->";
+ // The name of the test project, we create
+ private final String PROJECT_NAME = "changelog-java-project";
- @BeforeClass
- public static void beforeClass() throws Exception {
- // delay click speed; with this turned on things get flaky
- //System.setProperty("org.eclipse.swtbot.playback.delay", "200");
- bot = new SWTWorkbenchBot();
- try {
- bot.viewByTitle("Welcome").close();
- // hide Subclipse Usage stats popup if present/installed
- bot.shell("Subclipse Usage").activate();
- bot.button("Cancel").click();
- } catch (WidgetNotFoundException e) {
- // ignore
- }
- // Make sure project explorer is open and tree available
- ProjectExplorer.openView();
- projectExplorerViewTree = ProjectExplorer.getTree();
- }
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ // delay click speed; with this turned on things get flaky
+ //System.setProperty("org.eclipse.swtbot.playback.delay", "200");
+ bot = new SWTWorkbenchBot();
+ try {
+ bot.viewByTitle("Welcome").close();
+ // hide Subclipse Usage stats popup if present/installed
+ bot.shell("Subclipse Usage").activate();
+ bot.button("Cancel").click();
+ } catch (WidgetNotFoundException e) {
+ // ignore
+ }
+ // Make sure project explorer is open and tree available
+ ProjectExplorer.openView();
+ projectExplorerViewTree = ProjectExplorer.getTree();
+ }
- @Before
- public void setUp() throws Exception {
- // Create an empty test project
- project = new ChangeLogTestProject(PROJECT_NAME);
- project.addJavaNature(); // make it a Java project
- }
+ @Before
+ public void setUp() throws Exception {
+ // Create an empty test project
+ project = new ChangeLogTestProject(PROJECT_NAME);
+ project.addJavaNature(); // make it a Java project
+ }
- @After
- public void tearDown() throws Exception {
- this.project.getTestProject().delete(true, null);
- }
+ @After
+ public void tearDown() throws Exception {
+ this.project.getTestProject().delete(true, null);
+ }
- /**
- * ChangeLog editor should pop-up if inside an active editor
- * and a ChangeLog file exists in the project. Tests the CTRL+ALT+c
- * shortcut.
- *
- * @throws Exception
- */
- @SuppressWarnings("unchecked")
- @Test
- public void canAddChangeLogEntryUsingShortCutIfSourceIsActive() throws Exception {
- // Add a Java source file
- String sourceCode = "package src;\n" +
- "public class JavaTest {\n" +
- "public static void main(String args[]) {\n" +
- "//" + OFFSET_MARKER + "\n" +
- "System.out.println(\"Hello World!\");\n" +
- "}\n" +
- "}\n";
+ /**
+ * ChangeLog editor should pop-up if inside an active editor
+ * and a ChangeLog file exists in the project. Tests the CTRL+ALT+c
+ * shortcut.
+ *
+ * @throws Exception
+ */
+ @SuppressWarnings("unchecked")
+ @Test
+ public void canAddChangeLogEntryUsingShortCutIfSourceIsActive() throws Exception {
+ // Add a Java source file
+ String sourceCode = "package src;\n" +
+ "public class JavaTest {\n" +
+ "public static void main(String args[]) {\n" +
+ "//" + OFFSET_MARKER + "\n" +
+ "System.out.println(\"Hello World!\");\n" +
+ "}\n" +
+ "}\n";
- assertNull(project.getTestProject().findMember( new Path(
- "/src/JavaTest.java")));
- InputStream newFileInputStream = new ByteArrayInputStream(
- sourceCode.getBytes());
- project.addFileToProject("/src", "JavaTest.java", newFileInputStream);
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/JavaTest.java")));
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ sourceCode.getBytes());
+ project.addFileToProject("/src", "JavaTest.java", newFileInputStream);
- // Add a changelog file
- newFileInputStream = new ByteArrayInputStream(
- "".getBytes());
- project.addFileToProject("/", "ChangeLog", newFileInputStream);
+ // Add a changelog file
+ newFileInputStream = new ByteArrayInputStream(
+ "".getBytes());
+ project.addFileToProject("/", "ChangeLog", newFileInputStream);
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/JavaTest.java")));
- assertNotNull(project.getTestProject().findMember( new Path(
- "/ChangeLog")));
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/JavaTest.java")));
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/ChangeLog")));
- // Open JavaTest.java in an editor
- projectExplorerViewTree.expandNode(PROJECT_NAME).expandNode("src").expandNode("JavaTest.java").doubleClick();
+ // Open JavaTest.java in an editor
+ projectExplorerViewTree.expandNode(PROJECT_NAME).expandNode("src").expandNode("JavaTest.java").doubleClick();
- Matcher<?> editorMatcher = allOf(
- IsInstanceOf.instanceOf(IEditorReference.class),
- withPartName("JavaTest.java")
- );
- // Wait for Java editor to open
- bot.waitUntil(Conditions.waitForEditor((Matcher<IEditorReference>) editorMatcher));
- SWTBotEditor swtBoteditor = bot.editorByTitle("JavaTest.java");
- SWTBotEclipseEditor eclipseEditor = swtBoteditor.toTextEditor();
- eclipseEditor.selectLine(getLineOfOffsetMarker(sourceCode));
+ Matcher<?> editorMatcher = allOf(
+ IsInstanceOf.instanceOf(IEditorReference.class),
+ withPartName("JavaTest.java")
+ );
+ // Wait for Java editor to open
+ bot.waitUntil(Conditions.waitForEditor((Matcher<IEditorReference>) editorMatcher));
+ SWTBotEditor swtBoteditor = bot.editorByTitle("JavaTest.java");
+ SWTBotEclipseEditor eclipseEditor = swtBoteditor.toTextEditor();
+ eclipseEditor.selectLine(getLineOfOffsetMarker(sourceCode));
- // Press: CTRL + ALT + c
- eclipseEditor.pressShortcut(Keystrokes.CTRL, Keystrokes.ALT, KeyStroke.getInstance("C"));
- // Wait for ChangeLog editor to open
- editorMatcher = allOf(
- IsInstanceOf.instanceOf(IEditorReference.class),
- withPartName("ChangeLog")
- );
- bot.waitUntil(Conditions.waitForEditor((Matcher<IEditorReference>) editorMatcher));
- swtBoteditor = bot.activeEditor();
- swtBoteditor.save(); // save to avoid "save changes"-pop-up
- assertEquals("ChangeLog", swtBoteditor.getTitle());
- eclipseEditor = swtBoteditor.toTextEditor();
- // make sure expected entry has been added.
- assertTrue(eclipseEditor.getText().contains("\t* src/JavaTest.java (main):"));
- }
+ // Press: CTRL + ALT + c
+ eclipseEditor.pressShortcut(Keystrokes.CTRL, Keystrokes.ALT, KeyStroke.getInstance("C"));
+ // Wait for ChangeLog editor to open
+ editorMatcher = allOf(
+ IsInstanceOf.instanceOf(IEditorReference.class),
+ withPartName("ChangeLog")
+ );
+ bot.waitUntil(Conditions.waitForEditor((Matcher<IEditorReference>) editorMatcher));
+ swtBoteditor = bot.activeEditor();
+ swtBoteditor.save(); // save to avoid "save changes"-pop-up
+ assertEquals("ChangeLog", swtBoteditor.getTitle());
+ eclipseEditor = swtBoteditor.toTextEditor();
+ // make sure expected entry has been added.
+ assertTrue(eclipseEditor.getText().contains("\t* src/JavaTest.java (main):"));
+ }
- /**
- * ChangeLog editor should pop-up if inside an active editor
- * and a ChangeLog file exists in the project. Tests the "Edit" => "ChangeLog Entry"
- * menu item.
- *
- * @throws Exception
- */
- @SuppressWarnings("unchecked")
- @Test
- public void canAddChangeLogEntryUsingEditMenuIfSourceIsActive() throws Exception {
- // Add a Java source file
- String sourceCode = "package src;\n" +
- "public class JavaTest {\n" +
- "public static void main(String args[]) {\n" +
- "//" + OFFSET_MARKER + "\n" +
- "System.out.println(\"Hello World!\");\n" +
- "}\n" +
- "}\n";
+ /**
+ * ChangeLog editor should pop-up if inside an active editor
+ * and a ChangeLog file exists in the project. Tests the "Edit" => "ChangeLog Entry"
+ * menu item.
+ *
+ * @throws Exception
+ */
+ @SuppressWarnings("unchecked")
+ @Test
+ public void canAddChangeLogEntryUsingEditMenuIfSourceIsActive() throws Exception {
+ // Add a Java source file
+ String sourceCode = "package src;\n" +
+ "public class JavaTest {\n" +
+ "public static void main(String args[]) {\n" +
+ "//" + OFFSET_MARKER + "\n" +
+ "System.out.println(\"Hello World!\");\n" +
+ "}\n" +
+ "}\n";
- assertNull(project.getTestProject().findMember( new Path(
- "/src/JavaTest.java")));
- InputStream newFileInputStream = new ByteArrayInputStream(
- sourceCode.getBytes());
- project.addFileToProject("/src", "JavaTest.java", newFileInputStream);
+ assertNull(project.getTestProject().findMember( new Path(
+ "/src/JavaTest.java")));
+ InputStream newFileInputStream = new ByteArrayInputStream(
+ sourceCode.getBytes());
+ project.addFileToProject("/src", "JavaTest.java", newFileInputStream);
- // Add a changelog file
- newFileInputStream = new ByteArrayInputStream(
- "".getBytes());
- project.addFileToProject("/", "ChangeLog", newFileInputStream);
+ // Add a changelog file
+ newFileInputStream = new ByteArrayInputStream(
+ "".getBytes());
+ project.addFileToProject("/", "ChangeLog", newFileInputStream);
- assertNotNull(project.getTestProject().findMember( new Path(
- "/src/JavaTest.java")));
- assertNotNull(project.getTestProject().findMember( new Path(
- "/ChangeLog")));
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/src/JavaTest.java")));
+ assertNotNull(project.getTestProject().findMember( new Path(
+ "/ChangeLog")));
- // Open JavaTest.java in an editor
- SWTBotTreeItem projectItem = projectExplorerViewTree.expandNode(PROJECT_NAME);
- projectItem.expandNode("src").expandNode("JavaTest.java").doubleClick();
+ // Open JavaTest.java in an editor
+ SWTBotTreeItem projectItem = projectExplorerViewTree.expandNode(PROJECT_NAME);
+ projectItem.expandNode("src").expandNode("JavaTest.java").doubleClick();
- Matcher<?> editorMatcher = allOf(
- IsInstanceOf.instanceOf(IEditorReference.class),
- withPartName("JavaTest.java")
- );
- // Wait for editor to open
- bot.waitUntil(Conditions.waitForEditor((Matcher<IEditorReference>) editorMatcher));
- SWTBotEditor swtBoteditor = bot.editorByTitle("JavaTest.java");
- SWTBotEclipseEditor eclipseEditor = swtBoteditor.toTextEditor();
- eclipseEditor.selectLine(getLineOfOffsetMarker(sourceCode));
+ Matcher<?> editorMatcher = allOf(
+ IsInstanceOf.instanceOf(IEditorReference.class),
+ withPartName("JavaTest.java")
+ );
+ // Wait for editor to open
+ bot.waitUntil(Conditions.waitForEditor((Matcher<IEditorReference>) editorMatcher));
+ SWTBotEditor swtBoteditor = bot.editorByTitle("JavaTest.java");
+ SWTBotEclipseEditor eclipseEditor = swtBoteditor.toTextEditor();
+ eclipseEditor.selectLine(getLineOfOffsetMarker(sourceCode));
- // Click menu item.
- bot.menu("Edit").menu("ChangeLog Entry").click();
- // Wait for ChangeLog editor to open
- editorMatcher = allOf(
- IsInstanceOf.instanceOf(IEditorReference.class),
- withPartName("ChangeLog")
- );
- bot.waitUntil(Conditions.waitForEditor((Matcher<IEditorReference>) editorMatcher));
- swtBoteditor = bot.activeEditor();
- swtBoteditor.save(); // save to avoid "save changes"-pop-up
- assertEquals("ChangeLog", swtBoteditor.getTitle());
- eclipseEditor = swtBoteditor.toTextEditor();
- // make sure expected entry has been added.
- assertTrue(eclipseEditor.getText().contains("\t* src/JavaTest.java (main):"));
- }
+ // Click menu item.
+ bot.menu("Edit").menu("ChangeLog Entry").click();
+ // Wait for ChangeLog editor to open
+ editorMatcher = allOf(
+ IsInstanceOf.instanceOf(IEditorReference.class),
+ withPartName("ChangeLog")
+ );
+ bot.waitUntil(Conditions.waitForEditor((Matcher<IEditorReference>) editorMatcher));
+ swtBoteditor = bot.activeEditor();
+ swtBoteditor.save(); // save to avoid "save changes"-pop-up
+ assertEquals("ChangeLog", swtBoteditor.getTitle());
+ eclipseEditor = swtBoteditor.toTextEditor();
+ // make sure expected entry has been added.
+ assertTrue(eclipseEditor.getText().contains("\t* src/JavaTest.java (main):"));
+ }
- /**
- * FIXME: Disable menu item instead of showing it and doing nothing.
- *
- * This test throws WidgetNotFountException (i.e. shouldn't open any editor).
- */
- @Test(expected=WidgetNotFoundException.class)
- public void shouldDoNothingIfNoEditorIsActive() {
- assertNull(project.getTestProject().findMember( new Path("/src/dummy")));
- try {
- project.addFileToProject("src", "dummy", new ByteArrayInputStream("".getBytes()));
- } catch (CoreException e) {
- fail("Could not add /src/dummy file to project");
- }
- assertNotNull(project.getTestProject().findMember( new Path("/src/dummy")));
- // Make sure we are in the project explorer view and no editors are open
- bot.closeAllEditors();
- projectExplorerViewTree.expandNode(PROJECT_NAME).expandNode("src");
- // Try to create ChangeLog
- bot.menu("Edit").menu("ChangeLog Entry").click();
- // Don't wait 5 secs
- long oldTimeout = SWTBotPreferences.TIMEOUT;
- SWTBotPreferences.TIMEOUT = 1000; // give it a full second :)
- bot.activeEditor();
- SWTBotPreferences.TIMEOUT = oldTimeout;
- }
+ /**
+ * FIXME: Disable menu item instead of showing it and doing nothing.
+ *
+ * This test throws WidgetNotFountException (i.e. shouldn't open any editor).
+ */
+ @Test(expected=WidgetNotFoundException.class)
+ public void shouldDoNothingIfNoEditorIsActive() {
+ assertNull(project.getTestProject().findMember( new Path("/src/dummy")));
+ try {
+ project.addFileToProject("src", "dummy", new ByteArrayInputStream("".getBytes()));
+ } catch (CoreException e) {
+ fail("Could not add /src/dummy file to project");
+ }
+ assertNotNull(project.getTestProject().findMember( new Path("/src/dummy")));
+ // Make sure we are in the project explorer view and no editors are open
+ bot.closeAllEditors();
+ projectExplorerViewTree.expandNode(PROJECT_NAME).expandNode("src");
+ // Try to create ChangeLog
+ bot.menu("Edit").menu("ChangeLog Entry").click();
+ // Don't wait 5 secs
+ long oldTimeout = SWTBotPreferences.TIMEOUT;
+ SWTBotPreferences.TIMEOUT = 1000; // give it a full second :)
+ bot.activeEditor();
+ SWTBotPreferences.TIMEOUT = oldTimeout;
+ }
- /**
- * @param The source text.
- * @return The index of the first line containing the OFFSET_MARKER string in sourceCode.
- * -1 if not found.
- */
- private int getLineOfOffsetMarker(String sourceCode) {
- // select line containing the println() statement.
- int offset = -1, i = 0;
- for (String line: sourceCode.split("\n")) {
- if (line.indexOf(OFFSET_MARKER) >= 0) {
- offset = i;
- break;
- }
- i++;
- }
- return offset;
- }
+ /**
+ * @param The source text.
+ * @return The index of the first line containing the OFFSET_MARKER string in sourceCode.
+ * -1 if not found.
+ */
+ private int getLineOfOffsetMarker(String sourceCode) {
+ // select line containing the println() statement.
+ int offset = -1, i = 0;
+ for (String line: sourceCode.split("\n")) {
+ if (line.indexOf(OFFSET_MARKER) >= 0) {
+ offset = i;
+ break;
+ }
+ i++;
+ }
+ return offset;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/AllSWTBotTests.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/AllSWTBotTests.java
index 49e60230ae..165298c244 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/AllSWTBotTests.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/AllSWTBotTests.java
@@ -17,14 +17,14 @@ import org.junit.runners.Suite.SuiteClasses;
*/
@RunWith(Suite.class)
@SuiteClasses({
- AddChangelogEntrySWTBotTest.class,
- PrepareChangelogSWTBotTest.class,
- DisabledPrepareChangelogSWTBotTest.class,
- CreateChangeLogFromHistorySWTBotTest.class,
- FormatChangeLogSWTBotTest.class
- }
+ AddChangelogEntrySWTBotTest.class,
+ PrepareChangelogSWTBotTest.class,
+ DisabledPrepareChangelogSWTBotTest.class,
+ CreateChangeLogFromHistorySWTBotTest.class,
+ FormatChangeLogSWTBotTest.class
+ }
)
public class AllSWTBotTests {
- // empty
+ // empty
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/CreateChangeLogFromHistorySWTBotTest.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/CreateChangeLogFromHistorySWTBotTest.java
index 5cc35ef759..c53c717b44 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/CreateChangeLogFromHistorySWTBotTest.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/CreateChangeLogFromHistorySWTBotTest.java
@@ -55,140 +55,140 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class CreateChangeLogFromHistorySWTBotTest {
- private static SWTWorkbenchBot bot;
- private static SWTBotTree projectExplorerViewTree;
- private IProject project;
- private SVNProject subversionProject;
- // The name of the test project, we create
- private final String PROJECT_NAME = "org.eclipse.linuxtools.changelog.tests";
- // An available SVN repo
- private final String SVN_PROJECT_URL = "svn://dev.eclipse.org/svnroot/technology/" +
- "org.eclipse.linuxtools/changelog/trunk";
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- // delay click speed
- //System.setProperty("org.eclipse.swtbot.playback.delay", "200");
- bot = new SWTWorkbenchBot();
- try {
- bot.viewByTitle("Welcome").close();
- // hide Subclipse Usage stats popup if present/installed
- bot.shell("Subclipse Usage").activate();
- bot.button("Cancel").click();
- } catch (WidgetNotFoundException e) {
- // ignore
- }
- // Make sure project explorer is open and tree available
- ProjectExplorer.openView();
- projectExplorerViewTree = ProjectExplorer.getTree();
- }
-
- @Before
- public void setUp() throws Exception {
- // Do an SVN checkout of the changelog.tests plugin
- subversionProject = new SVNProject(bot);
- project = subversionProject.setProjectName(PROJECT_NAME).setRepoURL(SVN_PROJECT_URL).checkoutProject();
- bot.waitUntil(new SVNProjectCreatedCondition(PROJECT_NAME));
- ProjectExplorer.openView();
- }
-
- @After
- public void tearDown() throws Exception {
- this.project.delete(true, null);
- // discard existing repo from previous test runs
- try {
- subversionProject.discardRepositoryLocation();
- } catch (WidgetNotFoundException e) {
- // Ignore case if repository not existing
- }
- }
-
- /**
- * Create changelog from SVN history (commit messages).
- *
- * @throws Exception
- */
- @Test
- public void canPrepareChangeLogFromSVNHistory() throws Exception {
- // select ChangeLog file
- String teamProviderString = "[changelog/trunk/" + PROJECT_NAME + "]";
- SWTBotTreeItem projectItem = ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME, teamProviderString);
- long oldTimeout = SWTBotPreferences.TIMEOUT;
- SWTBotPreferences.TIMEOUT = 5000;
- bot.waitUntil(new ProjectExplorerTreeItemAppearsCondition(projectExplorerViewTree, PROJECT_NAME, teamProviderString, "ChangeLog"));
- SWTBotPreferences.TIMEOUT = oldTimeout;
- SWTBotTreeItem changeLogItem = ProjectExplorer.getProjectItem(projectItem, "ChangeLog");
- changeLogItem.select();
-
- // open history for ChangeLog file
- clickOnShowHistory(projectExplorerViewTree);
- SWTBot historyViewBot = bot.viewByTitle("History").bot();
- // wait for SVN revision table to appear
- oldTimeout = SWTBotPreferences.TIMEOUT;
- SWTBotPreferences.TIMEOUT = 3 * 5000;
- historyViewBot.waitUntil(new TableAppearsCondition());
- SWTBotPreferences.TIMEOUT = oldTimeout;
- SWTBotTable historyTable = historyViewBot.table();
- historyTable.select(0); // select the first row
-
- // right-click => Generate Changelog...
- clickOnGenerateChangeLog(historyTable);
- bot.waitUntil(Conditions.shellIsActive("Generate ChangeLog"));
- SWTBotShell shell = bot.shell("Generate ChangeLog");
-
- SWTBot generateChangelogBot = shell.bot();
- generateChangelogBot.radio("Clipboard").click();
- generateChangelogBot.button("OK").click();
-
- // create and open a new file for pasting
- String pasteFile = "newFile";
- IFile newFile = project.getFile(new Path(pasteFile));
- newFile.create(new ByteArrayInputStream("".getBytes()) /* empty content */, false, null);
- project.refreshLocal(IResource.DEPTH_INFINITE, null);
-
- assertNotNull(project.findMember(new Path(pasteFile)));
-
- ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME,
- teamProviderString).expandNode(pasteFile).select().doubleClick();
- Matcher<IEditorReference> editorMatcher = allOf(
- IsInstanceOf.instanceOf(IEditorReference.class),
- withPartName(pasteFile)
- );
- bot.waitUntil(Conditions.waitForEditor(editorMatcher));
- oldTimeout = SWTBotPreferences.TIMEOUT;
- SWTBotPreferences.TIMEOUT = oldTimeout;
- SWTBotEditor swtBoteditor = bot.activeEditor();
- assertEquals(pasteFile, swtBoteditor.getTitle());
- SWTBotEclipseEditor eclipseEditor = swtBoteditor.toTextEditor();
-
- // go to beginning of editor
- eclipseEditor.selectRange(0, 0, 0);
- // paste
- eclipseEditor.pressShortcut(Keystrokes.CTRL, KeyStroke.getInstance("V"));
- swtBoteditor.save();
- // make sure some changelog like text was pasted
- String text = eclipseEditor.getText();
- assertFalse(text.isEmpty());
- }
-
- /**
- * Helper method for right-clicking => Generate ChangeLog in History
- * view table.
- *
- * Pre: History view table row selected.
- */
- private void clickOnGenerateChangeLog(SWTBotTable table) {
- String menuItem = "Generate ChangeLog...";
- ContextMenuHelper.clickContextMenu(table, menuItem);
- }
-
- /**
- * Helper method for right-click => Team => Show History.
- */
- private void clickOnShowHistory(SWTBotTree tree) {
- String menuItem = "Team";
- String subMenuItem = "Show History";
- ContextMenuHelper.clickContextMenu(tree, menuItem, subMenuItem);
- }
+ private static SWTWorkbenchBot bot;
+ private static SWTBotTree projectExplorerViewTree;
+ private IProject project;
+ private SVNProject subversionProject;
+ // The name of the test project, we create
+ private final String PROJECT_NAME = "org.eclipse.linuxtools.changelog.tests";
+ // An available SVN repo
+ private final String SVN_PROJECT_URL = "svn://dev.eclipse.org/svnroot/technology/" +
+ "org.eclipse.linuxtools/changelog/trunk";
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ // delay click speed
+ //System.setProperty("org.eclipse.swtbot.playback.delay", "200");
+ bot = new SWTWorkbenchBot();
+ try {
+ bot.viewByTitle("Welcome").close();
+ // hide Subclipse Usage stats popup if present/installed
+ bot.shell("Subclipse Usage").activate();
+ bot.button("Cancel").click();
+ } catch (WidgetNotFoundException e) {
+ // ignore
+ }
+ // Make sure project explorer is open and tree available
+ ProjectExplorer.openView();
+ projectExplorerViewTree = ProjectExplorer.getTree();
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ // Do an SVN checkout of the changelog.tests plugin
+ subversionProject = new SVNProject(bot);
+ project = subversionProject.setProjectName(PROJECT_NAME).setRepoURL(SVN_PROJECT_URL).checkoutProject();
+ bot.waitUntil(new SVNProjectCreatedCondition(PROJECT_NAME));
+ ProjectExplorer.openView();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ this.project.delete(true, null);
+ // discard existing repo from previous test runs
+ try {
+ subversionProject.discardRepositoryLocation();
+ } catch (WidgetNotFoundException e) {
+ // Ignore case if repository not existing
+ }
+ }
+
+ /**
+ * Create changelog from SVN history (commit messages).
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canPrepareChangeLogFromSVNHistory() throws Exception {
+ // select ChangeLog file
+ String teamProviderString = "[changelog/trunk/" + PROJECT_NAME + "]";
+ SWTBotTreeItem projectItem = ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME, teamProviderString);
+ long oldTimeout = SWTBotPreferences.TIMEOUT;
+ SWTBotPreferences.TIMEOUT = 5000;
+ bot.waitUntil(new ProjectExplorerTreeItemAppearsCondition(projectExplorerViewTree, PROJECT_NAME, teamProviderString, "ChangeLog"));
+ SWTBotPreferences.TIMEOUT = oldTimeout;
+ SWTBotTreeItem changeLogItem = ProjectExplorer.getProjectItem(projectItem, "ChangeLog");
+ changeLogItem.select();
+
+ // open history for ChangeLog file
+ clickOnShowHistory(projectExplorerViewTree);
+ SWTBot historyViewBot = bot.viewByTitle("History").bot();
+ // wait for SVN revision table to appear
+ oldTimeout = SWTBotPreferences.TIMEOUT;
+ SWTBotPreferences.TIMEOUT = 3 * 5000;
+ historyViewBot.waitUntil(new TableAppearsCondition());
+ SWTBotPreferences.TIMEOUT = oldTimeout;
+ SWTBotTable historyTable = historyViewBot.table();
+ historyTable.select(0); // select the first row
+
+ // right-click => Generate Changelog...
+ clickOnGenerateChangeLog(historyTable);
+ bot.waitUntil(Conditions.shellIsActive("Generate ChangeLog"));
+ SWTBotShell shell = bot.shell("Generate ChangeLog");
+
+ SWTBot generateChangelogBot = shell.bot();
+ generateChangelogBot.radio("Clipboard").click();
+ generateChangelogBot.button("OK").click();
+
+ // create and open a new file for pasting
+ String pasteFile = "newFile";
+ IFile newFile = project.getFile(new Path(pasteFile));
+ newFile.create(new ByteArrayInputStream("".getBytes()) /* empty content */, false, null);
+ project.refreshLocal(IResource.DEPTH_INFINITE, null);
+
+ assertNotNull(project.findMember(new Path(pasteFile)));
+
+ ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME,
+ teamProviderString).expandNode(pasteFile).select().doubleClick();
+ Matcher<IEditorReference> editorMatcher = allOf(
+ IsInstanceOf.instanceOf(IEditorReference.class),
+ withPartName(pasteFile)
+ );
+ bot.waitUntil(Conditions.waitForEditor(editorMatcher));
+ oldTimeout = SWTBotPreferences.TIMEOUT;
+ SWTBotPreferences.TIMEOUT = oldTimeout;
+ SWTBotEditor swtBoteditor = bot.activeEditor();
+ assertEquals(pasteFile, swtBoteditor.getTitle());
+ SWTBotEclipseEditor eclipseEditor = swtBoteditor.toTextEditor();
+
+ // go to beginning of editor
+ eclipseEditor.selectRange(0, 0, 0);
+ // paste
+ eclipseEditor.pressShortcut(Keystrokes.CTRL, KeyStroke.getInstance("V"));
+ swtBoteditor.save();
+ // make sure some changelog like text was pasted
+ String text = eclipseEditor.getText();
+ assertFalse(text.isEmpty());
+ }
+
+ /**
+ * Helper method for right-clicking => Generate ChangeLog in History
+ * view table.
+ *
+ * Pre: History view table row selected.
+ */
+ private void clickOnGenerateChangeLog(SWTBotTable table) {
+ String menuItem = "Generate ChangeLog...";
+ ContextMenuHelper.clickContextMenu(table, menuItem);
+ }
+
+ /**
+ * Helper method for right-click => Team => Show History.
+ */
+ private void clickOnShowHistory(SWTBotTree tree) {
+ String menuItem = "Team";
+ String subMenuItem = "Show History";
+ ContextMenuHelper.clickContextMenu(tree, menuItem, subMenuItem);
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/DisabledPrepareChangelogSWTBotTest.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/DisabledPrepareChangelogSWTBotTest.java
index ef232caabd..27982171ed 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/DisabledPrepareChangelogSWTBotTest.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/DisabledPrepareChangelogSWTBotTest.java
@@ -39,69 +39,69 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class DisabledPrepareChangelogSWTBotTest {
- private static SWTWorkbenchBot bot;
- private static SWTBotTree projectExplorerViewTree;
- private final String projectName = "not-shared";
- private ChangeLogTestProject project;
+ private static SWTWorkbenchBot bot;
+ private static SWTBotTree projectExplorerViewTree;
+ private final String projectName = "not-shared";
+ private ChangeLogTestProject project;
- @BeforeClass
- public static void beforeClass() throws Exception {
- // delay click speed
- //System.setProperty("org.eclipse.swtbot.playback.delay", "200");
- bot = new SWTWorkbenchBot();
- try {
- bot.viewByTitle("Welcome").close();
- // hide Subclipse Usage stats popup if present/installed
- bot.shell("Subclipse Usage").activate();
- bot.button("Cancel").click();
- } catch (WidgetNotFoundException e) {
- // ignore
- }
- // Make sure project explorer is open and tree available
- ProjectExplorer.openView();
- projectExplorerViewTree = ProjectExplorer.getTree();
- }
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ // delay click speed
+ //System.setProperty("org.eclipse.swtbot.playback.delay", "200");
+ bot = new SWTWorkbenchBot();
+ try {
+ bot.viewByTitle("Welcome").close();
+ // hide Subclipse Usage stats popup if present/installed
+ bot.shell("Subclipse Usage").activate();
+ bot.button("Cancel").click();
+ } catch (WidgetNotFoundException e) {
+ // ignore
+ }
+ // Make sure project explorer is open and tree available
+ ProjectExplorer.openView();
+ projectExplorerViewTree = ProjectExplorer.getTree();
+ }
- @Before
- public void setUp() throws Exception {
- project = new ChangeLogTestProject(projectName);
- }
+ @Before
+ public void setUp() throws Exception {
+ project = new ChangeLogTestProject(projectName);
+ }
- @After
- public void tearDown() throws Exception {
- this.project.getTestProject().delete(true, null);
- }
+ @After
+ public void tearDown() throws Exception {
+ this.project.getTestProject().delete(true, null);
+ }
- /**
- * If the project is not shared by any CVS or SVN team provider, "Prepare ChangeLog"
- * should be disabled.
- *
- * @throws Exception
- */
- @Test
- public void cannotPrepareChangeLogOnNonCVSOrSVNProject() throws Exception {
- assertNull(project.getTestProject().findMember(new Path("/ChangeLog")));
+ /**
+ * If the project is not shared by any CVS or SVN team provider, "Prepare ChangeLog"
+ * should be disabled.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void cannotPrepareChangeLogOnNonCVSOrSVNProject() throws Exception {
+ assertNull(project.getTestProject().findMember(new Path("/ChangeLog")));
- final String changeLogContent = "2010-12-08 Will Probe <will@example.com>\n\n" +
- "\t* path/to/some/non-existing/file.c: New file.\n";
- project.addFileToProject("/", "ChangeLog", new ByteArrayInputStream(changeLogContent.getBytes()));
+ final String changeLogContent = "2010-12-08 Will Probe <will@example.com>\n\n" +
+ "\t* path/to/some/non-existing/file.c: New file.\n";
+ project.addFileToProject("/", "ChangeLog", new ByteArrayInputStream(changeLogContent.getBytes()));
- assertNotNull(project.getTestProject().findMember(new Path("/ChangeLog")));
+ assertNotNull(project.getTestProject().findMember(new Path("/ChangeLog")));
- // select ChangeLog file
- String teamProviderString = "n/a";
- SWTBotTreeItem projectItem = ProjectExplorer.expandProject(projectExplorerViewTree, projectName, teamProviderString);
- SWTBotTreeItem changeLogItem = ProjectExplorer.getProjectItem(projectItem, "ChangeLog");
- changeLogItem.select();
- long oldTimeout = SWTBotPreferences.TIMEOUT;
- SWTBotPreferences.TIMEOUT = 100;
- try {
- bot.menu("Prepare ChangeLog").click(); // Should be disabled (throws exception)
- fail("'Prepare ChangeLog' should be disabled");
- } catch (TimeoutException e) {
- assertTrue(e.getMessage().contains("The widget with mnemonic 'Prepare ChangeLog' was not enabled."));
- }
- SWTBotPreferences.TIMEOUT = oldTimeout;
- }
+ // select ChangeLog file
+ String teamProviderString = "n/a";
+ SWTBotTreeItem projectItem = ProjectExplorer.expandProject(projectExplorerViewTree, projectName, teamProviderString);
+ SWTBotTreeItem changeLogItem = ProjectExplorer.getProjectItem(projectItem, "ChangeLog");
+ changeLogItem.select();
+ long oldTimeout = SWTBotPreferences.TIMEOUT;
+ SWTBotPreferences.TIMEOUT = 100;
+ try {
+ bot.menu("Prepare ChangeLog").click(); // Should be disabled (throws exception)
+ fail("'Prepare ChangeLog' should be disabled");
+ } catch (TimeoutException e) {
+ assertTrue(e.getMessage().contains("The widget with mnemonic 'Prepare ChangeLog' was not enabled."));
+ }
+ SWTBotPreferences.TIMEOUT = oldTimeout;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/FormatChangeLogSWTBotTest.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/FormatChangeLogSWTBotTest.java
index 7d8b7192fa..061c02e73c 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/FormatChangeLogSWTBotTest.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/FormatChangeLogSWTBotTest.java
@@ -48,100 +48,100 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class FormatChangeLogSWTBotTest {
- private static SWTWorkbenchBot bot;
- private static SWTBotTree projectExplorerViewTree;
- private ChangeLogTestProject project;
- // The name of the test project, we create
- private final String PROJECT_NAME = "org.eclipse.linuxtools.changelog.ui.formattestproject";
+ private static SWTWorkbenchBot bot;
+ private static SWTBotTree projectExplorerViewTree;
+ private ChangeLogTestProject project;
+ // The name of the test project, we create
+ private final String PROJECT_NAME = "org.eclipse.linuxtools.changelog.ui.formattestproject";
- @BeforeClass
- public static void beforeClass() throws Exception {
- // delay click speed
- //System.setProperty("org.eclipse.swtbot.playback.delay", "200");
- bot = new SWTWorkbenchBot();
- try {
- bot.viewByTitle("Welcome").close();
- // hide Subclipse Usage stats popup if present/installed
- bot.shell("Subclipse Usage").activate();
- bot.button("Cancel").click();
- } catch (WidgetNotFoundException e) {
- // ignore
- }
- // Make sure project explorer is open and tree available
- ProjectExplorer.openView();
- projectExplorerViewTree = ProjectExplorer.getTree();
- }
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ // delay click speed
+ //System.setProperty("org.eclipse.swtbot.playback.delay", "200");
+ bot = new SWTWorkbenchBot();
+ try {
+ bot.viewByTitle("Welcome").close();
+ // hide Subclipse Usage stats popup if present/installed
+ bot.shell("Subclipse Usage").activate();
+ bot.button("Cancel").click();
+ } catch (WidgetNotFoundException e) {
+ // ignore
+ }
+ // Make sure project explorer is open and tree available
+ ProjectExplorer.openView();
+ projectExplorerViewTree = ProjectExplorer.getTree();
+ }
- @Before
- public void setUp() throws Exception {
- project = new ChangeLogTestProject(PROJECT_NAME);
- ProjectExplorer.openView();
- }
+ @Before
+ public void setUp() throws Exception {
+ project = new ChangeLogTestProject(PROJECT_NAME);
+ ProjectExplorer.openView();
+ }
- @After
- public void tearDown() throws Exception {
- this.project.getTestProject().delete(true, null);
- }
+ @After
+ public void tearDown() throws Exception {
+ this.project.getTestProject().delete(true, null);
+ }
- /**
- * Simple test for ChangeLog formatting.
- *
- * @throws Exception
- */
- @Test
- public void canFormatChangeLogFile() throws Exception {
- // add a ChangeLog file
- assertNull(project.getTestProject().findMember(new Path("/ChangeLog")));
- final String changelogContent = "2010-12-14 Severin Gehwolf <sgehwolf@redhat.com>\n\n" +
- "\tAdded org.eclipse.linuxtools.changelog.tests.ui plug-in.\n" +
- "\t* .classpath: New file.\n" +
- "\t* .project: New file.\n" +
- "\t* .settings/org.eclipse.jdt.core.prefs: New file.\n" +
- "\t* build.properties: New file.\n" +
- "\t* src/log4j.xml: New file.\n" +
- "\t* src/org/eclipse/linuxtools/changelog/tests/ui/utils/ContextMenuHelper.java: New file.\n" +
- "\t* src/org/eclipse/linuxtools/changelog/tests/ui/utils/ProjectExplorer.java: New file.\n" +
- "\t* src/org/eclipse/linuxtools/changelog/tests/ui/utils/ProjectExplorerTreeItemAppearsCondition.java: New file.\n";
- project.addFileToProject("/", "ChangeLog", new ByteArrayInputStream(changelogContent.getBytes()));
- assertNotNull(project.getTestProject().findMember(new Path("/ChangeLog")));
+ /**
+ * Simple test for ChangeLog formatting.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canFormatChangeLogFile() throws Exception {
+ // add a ChangeLog file
+ assertNull(project.getTestProject().findMember(new Path("/ChangeLog")));
+ final String changelogContent = "2010-12-14 Severin Gehwolf <sgehwolf@redhat.com>\n\n" +
+ "\tAdded org.eclipse.linuxtools.changelog.tests.ui plug-in.\n" +
+ "\t* .classpath: New file.\n" +
+ "\t* .project: New file.\n" +
+ "\t* .settings/org.eclipse.jdt.core.prefs: New file.\n" +
+ "\t* build.properties: New file.\n" +
+ "\t* src/log4j.xml: New file.\n" +
+ "\t* src/org/eclipse/linuxtools/changelog/tests/ui/utils/ContextMenuHelper.java: New file.\n" +
+ "\t* src/org/eclipse/linuxtools/changelog/tests/ui/utils/ProjectExplorer.java: New file.\n" +
+ "\t* src/org/eclipse/linuxtools/changelog/tests/ui/utils/ProjectExplorerTreeItemAppearsCondition.java: New file.\n";
+ project.addFileToProject("/", "ChangeLog", new ByteArrayInputStream(changelogContent.getBytes()));
+ assertNotNull(project.getTestProject().findMember(new Path("/ChangeLog")));
- // select ChangeLog file
- String teamProviderString = "n/a";
- SWTBotTreeItem projectItem = ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME, teamProviderString);
- long oldTimeout = SWTBotPreferences.TIMEOUT;
- SWTBotPreferences.TIMEOUT = 5000;
- bot.waitUntil(new ProjectExplorerTreeItemAppearsCondition(projectExplorerViewTree, PROJECT_NAME, teamProviderString, "ChangeLog"));
- SWTBotPreferences.TIMEOUT = oldTimeout;
- SWTBotTreeItem changeLogItem = ProjectExplorer.getProjectItem(projectItem, "ChangeLog");
- changeLogItem.doubleClick(); // should open ChangeLog file
+ // select ChangeLog file
+ String teamProviderString = "n/a";
+ SWTBotTreeItem projectItem = ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME, teamProviderString);
+ long oldTimeout = SWTBotPreferences.TIMEOUT;
+ SWTBotPreferences.TIMEOUT = 5000;
+ bot.waitUntil(new ProjectExplorerTreeItemAppearsCondition(projectExplorerViewTree, PROJECT_NAME, teamProviderString, "ChangeLog"));
+ SWTBotPreferences.TIMEOUT = oldTimeout;
+ SWTBotTreeItem changeLogItem = ProjectExplorer.getProjectItem(projectItem, "ChangeLog");
+ changeLogItem.doubleClick(); // should open ChangeLog file
- oldTimeout = SWTBotPreferences.TIMEOUT;
- SWTBotPreferences.TIMEOUT = 3 * 5000;
- // Wait for ChangeLog editor to open
- Matcher<IEditorReference> editorMatcher = allOf(
- IsInstanceOf.instanceOf(IEditorReference.class),
- withPartName("ChangeLog")
- );
- bot.waitUntil(Conditions.waitForEditor(editorMatcher));
- SWTBotEditor swtBoteditor = bot.activeEditor();
- assertEquals("ChangeLog", swtBoteditor.getTitle());
+ oldTimeout = SWTBotPreferences.TIMEOUT;
+ SWTBotPreferences.TIMEOUT = 3 * 5000;
+ // Wait for ChangeLog editor to open
+ Matcher<IEditorReference> editorMatcher = allOf(
+ IsInstanceOf.instanceOf(IEditorReference.class),
+ withPartName("ChangeLog")
+ );
+ bot.waitUntil(Conditions.waitForEditor(editorMatcher));
+ SWTBotEditor swtBoteditor = bot.activeEditor();
+ assertEquals("ChangeLog", swtBoteditor.getTitle());
- SWTBotEclipseEditor swtBotEclipseEditor = swtBoteditor.toTextEditor();
+ SWTBotEclipseEditor swtBotEclipseEditor = swtBoteditor.toTextEditor();
- // Add two extra lines after the first date line
- swtBotEclipseEditor.insertText(1, 0, "\n\n");
- // Should have 3 empty lines between date-line and first file entry
- swtBotEclipseEditor.selectRange(1, 0, 3);
+ // Add two extra lines after the first date line
+ swtBotEclipseEditor.insertText(1, 0, "\n\n");
+ // Should have 3 empty lines between date-line and first file entry
+ swtBotEclipseEditor.selectRange(1, 0, 3);
- // format: ESC CTRL+F
- swtBotEclipseEditor.pressShortcut(Keystrokes.ESC);
- swtBotEclipseEditor.pressShortcut(Keystrokes.CTRL, KeyStroke.getInstance("F"));
- swtBoteditor.save();
- String secondLine = swtBotEclipseEditor.getTextOnLine(1);
- String thirdLine = swtBotEclipseEditor.getTextOnLine(2);
- // FIXME: These assertions are lame.
- assertTrue(secondLine.isEmpty());
- assertFalse(thirdLine.isEmpty());
- }
+ // format: ESC CTRL+F
+ swtBotEclipseEditor.pressShortcut(Keystrokes.ESC);
+ swtBotEclipseEditor.pressShortcut(Keystrokes.CTRL, KeyStroke.getInstance("F"));
+ swtBoteditor.save();
+ String secondLine = swtBotEclipseEditor.getTextOnLine(1);
+ String thirdLine = swtBotEclipseEditor.getTextOnLine(2);
+ // FIXME: These assertions are lame.
+ assertTrue(secondLine.isEmpty());
+ assertFalse(thirdLine.isEmpty());
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/PrepareChangelogSWTBotTest.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/PrepareChangelogSWTBotTest.java
index 530f65cb6c..2aae0e4a9d 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/PrepareChangelogSWTBotTest.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/swtbot/PrepareChangelogSWTBotTest.java
@@ -52,200 +52,200 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class PrepareChangelogSWTBotTest {
- private static SWTWorkbenchBot bot;
- private static SWTBotTree projectExplorerViewTree;
- private SVNProject subversionProject;
- private IProject project;
- // The name of the test project, we create
- private final String PROJECT_NAME = "org.eclipse.linuxtools.changelog.tests";
- // An available SVN repo
- private final String SVN_PROJECT_URL = "svn://dev.eclipse.org/svnroot/technology/" +
- "org.eclipse.linuxtools/changelog/trunk";
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- // delay click speed
- //System.setProperty("org.eclipse.swtbot.playback.delay", "200");
- bot = new SWTWorkbenchBot();
- try {
- bot.viewByTitle("Welcome").close();
- // hide Subclipse Usage stats popup if present/installed
- bot.shell("Subclipse Usage").activate();
- bot.button("Cancel").click();
- } catch (WidgetNotFoundException e) {
- // ignore
- }
- // Make sure project explorer is open and tree available
- ProjectExplorer.openView();
- projectExplorerViewTree = ProjectExplorer.getTree();
- }
-
- @Before
- public void setUp() throws Exception {
- // Do an SVN checkout of the changelog.tests plugin
- subversionProject = new SVNProject(bot);
- project = subversionProject.setProjectName(PROJECT_NAME).setRepoURL(SVN_PROJECT_URL).checkoutProject();
- bot.waitUntil(new SVNProjectCreatedCondition(PROJECT_NAME));
- ProjectExplorer.openView();
- }
-
- @After
- public void tearDown() throws Exception {
- this.project.delete(true, null);
- // discard existing repo from previous test runs
- try {
- subversionProject.discardRepositoryLocation();
- } catch (WidgetNotFoundException e) {
- // Ignore case if repository not existing
- }
- }
-
- /**
- * Basic prepare changelog test.
- *
- * @throws Exception
- */
- @SuppressWarnings("unchecked")
- @Test
- public void canPrepareChangeLog() throws Exception {
- // Find manifest file
- IResource manifest = project.findMember(new Path("/META-INF/MANIFEST.MF"));
- assertNotNull(manifest);
- // delete it
- manifest.delete(true, null);
- project.refreshLocal(IResource.DEPTH_INFINITE, null);
-
- // select ChangeLog file
- String teamProviderString = "[changelog/trunk/" + PROJECT_NAME + "]";
- SWTBotTreeItem projectItem = ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME, teamProviderString);
- SWTBotTreeItem changeLogItem = ProjectExplorer.getProjectItem(projectItem, "ChangeLog");
- changeLogItem.select();
- bot.menu("Prepare ChangeLog").click(); // Should be unique
-
- long oldTimeout = SWTBotPreferences.TIMEOUT;
- SWTBotPreferences.TIMEOUT = 3 * 5000;
- // Wait for ChangeLog editor to open
- Matcher<?> editorMatcher = allOf(
- IsInstanceOf.instanceOf(IEditorReference.class),
- withPartName("ChangeLog")
- );
- bot.waitUntil(Conditions.waitForEditor((Matcher<IEditorReference>) editorMatcher));
- SWTBotPreferences.TIMEOUT = oldTimeout;
-
- SWTBotEditor swtBoteditor = bot.activeEditor();
- swtBoteditor.save(); // save to avoid "save changes"-pop-up
- assertEquals("ChangeLog", swtBoteditor.getTitle());
- SWTBotEclipseEditor eclipseEditor = swtBoteditor.toTextEditor();
- // make sure expected entry has been added.
- assertTrue(matchHead(eclipseEditor.getText(), "\t* META-INF/MANIFEST.MF:", 3));
- }
-
- /**
- * Should be able to save changes to ChangeLog file in clipboard.
- * Tests CTRL + ALT + V functionality.
- *
- * @throws Exception
- */
- @Test
- public void canPrepareChangeLogAndSaveChangesInChangeLogFileToClipboard() throws Exception {
- // Find manifest file
- IResource manifest = project.findMember(new Path("/META-INF/MANIFEST.MF"));
- assertNotNull(manifest);
- // delete it
- manifest.delete(true, null);
- project.refreshLocal(IResource.DEPTH_INFINITE, null);
-
- // select ChangeLog file
- String teamProviderString = "[changelog/trunk/" + PROJECT_NAME + "]";
- SWTBotTreeItem projectItem = ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME, teamProviderString);
- long oldTimeout = SWTBotPreferences.TIMEOUT;
- SWTBotPreferences.TIMEOUT = 5000;
- bot.waitUntil(new ProjectExplorerTreeItemAppearsCondition(projectExplorerViewTree, PROJECT_NAME, teamProviderString, "ChangeLog"));
- SWTBotPreferences.TIMEOUT = oldTimeout;
- SWTBotTreeItem changeLogItem = ProjectExplorer.getProjectItem(projectItem, "ChangeLog");
- changeLogItem.select();
- // CTRL + ALT + P
- bot.activeShell().pressShortcut(Keystrokes.CTRL, Keystrokes.ALT, KeyStroke.getInstance("P"));
-
- oldTimeout = SWTBotPreferences.TIMEOUT;
- SWTBotPreferences.TIMEOUT = 3 * 5000;
- // Wait for ChangeLog editor to open
- Matcher<IEditorReference> editorMatcher = allOf(
- IsInstanceOf.instanceOf(IEditorReference.class),
- withPartName("ChangeLog")
- );
- bot.waitUntil(Conditions.waitForEditor(editorMatcher));
- SWTBotEditor swtBoteditor = bot.activeEditor();
- swtBoteditor.save(); // save to avoid "save changes"-pop-up
- assertEquals("ChangeLog", swtBoteditor.getTitle());
- SWTBotEclipseEditor eclipseEditor = swtBoteditor.toTextEditor();
- // make sure expected entry has been added.
- assertTrue(matchHead(eclipseEditor.getText(), "\t* META-INF/MANIFEST.MF:", 3));
- eclipseEditor.selectLine(0); // select first line
- final String expectedFirstLineContent = eclipseEditor.getSelection();
-
- // save changes to clipboard: CTRL + ALT + V
- eclipseEditor.pressShortcut(Keystrokes.CTRL, Keystrokes.ALT, KeyStroke.getInstance("V"));
-
- // create and open a new file for pasting
- String pasteFile = "newFile";
- IFile newFile = project.getFile(new Path(pasteFile));
- newFile.create(new ByteArrayInputStream("".getBytes()) /* empty content */, false, null);
- project.refreshLocal(IResource.DEPTH_INFINITE, null);
-
- assertNotNull(project.findMember(new Path(pasteFile)));
-
- ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME,
- teamProviderString).expandNode(pasteFile).select().doubleClick();
- //bot.activeShell().pressShortcut(Keystrokes.F3); // open file
- editorMatcher = allOf(
- IsInstanceOf.instanceOf(IEditorReference.class),
- withPartName(pasteFile)
- );
- bot.waitUntil(Conditions.waitForEditor(editorMatcher));
- SWTBotPreferences.TIMEOUT = oldTimeout;
- swtBoteditor = bot.activeEditor();
- assertEquals(pasteFile, swtBoteditor.getTitle());
- eclipseEditor = swtBoteditor.toTextEditor();
-
- // go to beginning of editor
- eclipseEditor.selectRange(0, 0, 0);
- // paste
- eclipseEditor.pressShortcut(Keystrokes.CTRL, KeyStroke.getInstance("V"));
- swtBoteditor.save();
- // make sure proper content was pasted
- assertTrue(matchHead(eclipseEditor.getText(), "\t* META-INF/MANIFEST.MF:", 3));
- eclipseEditor.selectLine(0); // select first line
- final String actualFirstLineContent = eclipseEditor.getSelection();
- assertEquals(expectedFirstLineContent, actualFirstLineContent);
- }
-
- /**
- * Determine if first <code>i</code> lines in <code>text</code> contain
- * the string <code>matchText</code>.
- *
- * @param text The text to compare to.
- * @param matchText The match string to look for.
- * @param i The number of lines in text to consider.
- * @return
- *
- * @throws IllegalArgumentException if <code>i</code> is invalid.
- */
- private boolean matchHead(String text, String matchText, int i) throws IllegalArgumentException {
- if ( i < 0 ) {
- throw new IllegalArgumentException();
- }
- String[] lines = text.split("\n");
- if ( lines.length < i ) {
- throw new IllegalArgumentException();
- }
- // arguments appear to be good
- for (int j = 0; j < i; j++) {
- if (lines[j].contains(matchText)) {
- return true;
- }
- }
- return false; // no match
- }
+ private static SWTWorkbenchBot bot;
+ private static SWTBotTree projectExplorerViewTree;
+ private SVNProject subversionProject;
+ private IProject project;
+ // The name of the test project, we create
+ private final String PROJECT_NAME = "org.eclipse.linuxtools.changelog.tests";
+ // An available SVN repo
+ private final String SVN_PROJECT_URL = "svn://dev.eclipse.org/svnroot/technology/" +
+ "org.eclipse.linuxtools/changelog/trunk";
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ // delay click speed
+ //System.setProperty("org.eclipse.swtbot.playback.delay", "200");
+ bot = new SWTWorkbenchBot();
+ try {
+ bot.viewByTitle("Welcome").close();
+ // hide Subclipse Usage stats popup if present/installed
+ bot.shell("Subclipse Usage").activate();
+ bot.button("Cancel").click();
+ } catch (WidgetNotFoundException e) {
+ // ignore
+ }
+ // Make sure project explorer is open and tree available
+ ProjectExplorer.openView();
+ projectExplorerViewTree = ProjectExplorer.getTree();
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ // Do an SVN checkout of the changelog.tests plugin
+ subversionProject = new SVNProject(bot);
+ project = subversionProject.setProjectName(PROJECT_NAME).setRepoURL(SVN_PROJECT_URL).checkoutProject();
+ bot.waitUntil(new SVNProjectCreatedCondition(PROJECT_NAME));
+ ProjectExplorer.openView();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ this.project.delete(true, null);
+ // discard existing repo from previous test runs
+ try {
+ subversionProject.discardRepositoryLocation();
+ } catch (WidgetNotFoundException e) {
+ // Ignore case if repository not existing
+ }
+ }
+
+ /**
+ * Basic prepare changelog test.
+ *
+ * @throws Exception
+ */
+ @SuppressWarnings("unchecked")
+ @Test
+ public void canPrepareChangeLog() throws Exception {
+ // Find manifest file
+ IResource manifest = project.findMember(new Path("/META-INF/MANIFEST.MF"));
+ assertNotNull(manifest);
+ // delete it
+ manifest.delete(true, null);
+ project.refreshLocal(IResource.DEPTH_INFINITE, null);
+
+ // select ChangeLog file
+ String teamProviderString = "[changelog/trunk/" + PROJECT_NAME + "]";
+ SWTBotTreeItem projectItem = ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME, teamProviderString);
+ SWTBotTreeItem changeLogItem = ProjectExplorer.getProjectItem(projectItem, "ChangeLog");
+ changeLogItem.select();
+ bot.menu("Prepare ChangeLog").click(); // Should be unique
+
+ long oldTimeout = SWTBotPreferences.TIMEOUT;
+ SWTBotPreferences.TIMEOUT = 3 * 5000;
+ // Wait for ChangeLog editor to open
+ Matcher<?> editorMatcher = allOf(
+ IsInstanceOf.instanceOf(IEditorReference.class),
+ withPartName("ChangeLog")
+ );
+ bot.waitUntil(Conditions.waitForEditor((Matcher<IEditorReference>) editorMatcher));
+ SWTBotPreferences.TIMEOUT = oldTimeout;
+
+ SWTBotEditor swtBoteditor = bot.activeEditor();
+ swtBoteditor.save(); // save to avoid "save changes"-pop-up
+ assertEquals("ChangeLog", swtBoteditor.getTitle());
+ SWTBotEclipseEditor eclipseEditor = swtBoteditor.toTextEditor();
+ // make sure expected entry has been added.
+ assertTrue(matchHead(eclipseEditor.getText(), "\t* META-INF/MANIFEST.MF:", 3));
+ }
+
+ /**
+ * Should be able to save changes to ChangeLog file in clipboard.
+ * Tests CTRL + ALT + V functionality.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void canPrepareChangeLogAndSaveChangesInChangeLogFileToClipboard() throws Exception {
+ // Find manifest file
+ IResource manifest = project.findMember(new Path("/META-INF/MANIFEST.MF"));
+ assertNotNull(manifest);
+ // delete it
+ manifest.delete(true, null);
+ project.refreshLocal(IResource.DEPTH_INFINITE, null);
+
+ // select ChangeLog file
+ String teamProviderString = "[changelog/trunk/" + PROJECT_NAME + "]";
+ SWTBotTreeItem projectItem = ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME, teamProviderString);
+ long oldTimeout = SWTBotPreferences.TIMEOUT;
+ SWTBotPreferences.TIMEOUT = 5000;
+ bot.waitUntil(new ProjectExplorerTreeItemAppearsCondition(projectExplorerViewTree, PROJECT_NAME, teamProviderString, "ChangeLog"));
+ SWTBotPreferences.TIMEOUT = oldTimeout;
+ SWTBotTreeItem changeLogItem = ProjectExplorer.getProjectItem(projectItem, "ChangeLog");
+ changeLogItem.select();
+ // CTRL + ALT + P
+ bot.activeShell().pressShortcut(Keystrokes.CTRL, Keystrokes.ALT, KeyStroke.getInstance("P"));
+
+ oldTimeout = SWTBotPreferences.TIMEOUT;
+ SWTBotPreferences.TIMEOUT = 3 * 5000;
+ // Wait for ChangeLog editor to open
+ Matcher<IEditorReference> editorMatcher = allOf(
+ IsInstanceOf.instanceOf(IEditorReference.class),
+ withPartName("ChangeLog")
+ );
+ bot.waitUntil(Conditions.waitForEditor(editorMatcher));
+ SWTBotEditor swtBoteditor = bot.activeEditor();
+ swtBoteditor.save(); // save to avoid "save changes"-pop-up
+ assertEquals("ChangeLog", swtBoteditor.getTitle());
+ SWTBotEclipseEditor eclipseEditor = swtBoteditor.toTextEditor();
+ // make sure expected entry has been added.
+ assertTrue(matchHead(eclipseEditor.getText(), "\t* META-INF/MANIFEST.MF:", 3));
+ eclipseEditor.selectLine(0); // select first line
+ final String expectedFirstLineContent = eclipseEditor.getSelection();
+
+ // save changes to clipboard: CTRL + ALT + V
+ eclipseEditor.pressShortcut(Keystrokes.CTRL, Keystrokes.ALT, KeyStroke.getInstance("V"));
+
+ // create and open a new file for pasting
+ String pasteFile = "newFile";
+ IFile newFile = project.getFile(new Path(pasteFile));
+ newFile.create(new ByteArrayInputStream("".getBytes()) /* empty content */, false, null);
+ project.refreshLocal(IResource.DEPTH_INFINITE, null);
+
+ assertNotNull(project.findMember(new Path(pasteFile)));
+
+ ProjectExplorer.expandProject(projectExplorerViewTree, PROJECT_NAME,
+ teamProviderString).expandNode(pasteFile).select().doubleClick();
+ //bot.activeShell().pressShortcut(Keystrokes.F3); // open file
+ editorMatcher = allOf(
+ IsInstanceOf.instanceOf(IEditorReference.class),
+ withPartName(pasteFile)
+ );
+ bot.waitUntil(Conditions.waitForEditor(editorMatcher));
+ SWTBotPreferences.TIMEOUT = oldTimeout;
+ swtBoteditor = bot.activeEditor();
+ assertEquals(pasteFile, swtBoteditor.getTitle());
+ eclipseEditor = swtBoteditor.toTextEditor();
+
+ // go to beginning of editor
+ eclipseEditor.selectRange(0, 0, 0);
+ // paste
+ eclipseEditor.pressShortcut(Keystrokes.CTRL, KeyStroke.getInstance("V"));
+ swtBoteditor.save();
+ // make sure proper content was pasted
+ assertTrue(matchHead(eclipseEditor.getText(), "\t* META-INF/MANIFEST.MF:", 3));
+ eclipseEditor.selectLine(0); // select first line
+ final String actualFirstLineContent = eclipseEditor.getSelection();
+ assertEquals(expectedFirstLineContent, actualFirstLineContent);
+ }
+
+ /**
+ * Determine if first <code>i</code> lines in <code>text</code> contain
+ * the string <code>matchText</code>.
+ *
+ * @param text The text to compare to.
+ * @param matchText The match string to look for.
+ * @param i The number of lines in text to consider.
+ * @return
+ *
+ * @throws IllegalArgumentException if <code>i</code> is invalid.
+ */
+ private boolean matchHead(String text, String matchText, int i) throws IllegalArgumentException {
+ if ( i < 0 ) {
+ throw new IllegalArgumentException();
+ }
+ String[] lines = text.split("\n");
+ if ( lines.length < i ) {
+ throw new IllegalArgumentException();
+ }
+ // arguments appear to be good
+ for (int j = 0; j < i; j++) {
+ if (lines[j].contains(matchText)) {
+ return true;
+ }
+ }
+ return false; // no match
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ChangeLogTestProject.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ChangeLogTestProject.java
index 6826806edb..e6fa276f77 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ChangeLogTestProject.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ChangeLogTestProject.java
@@ -32,117 +32,117 @@ import org.eclipse.jdt.core.JavaCore;
*/
public class ChangeLogTestProject {
- private IProject testProject;
+ private IProject testProject;
- /**
- * Create a new ChangelogTestProject
- *
- * @param projectName The name of the project to be created.
- * @throws Exception
- */
- public ChangeLogTestProject(String projectName) throws Exception {
- testProject = createNewProject(projectName);
- }
+ /**
+ * Create a new ChangelogTestProject
+ *
+ * @param projectName The name of the project to be created.
+ * @throws Exception
+ */
+ public ChangeLogTestProject(String projectName) throws Exception {
+ testProject = createNewProject(projectName);
+ }
- /**
- * @return the testProject
- */
- public IProject getTestProject() {
- return testProject;
- }
+ /**
+ * @return the testProject
+ */
+ public IProject getTestProject() {
+ return testProject;
+ }
- /**
- * @param testProject the testProject to set
- */
- public void setTestProject(IProject testProject) {
- this.testProject = testProject;
- }
+ /**
+ * @param testProject the testProject to set
+ */
+ public void setTestProject(IProject testProject) {
+ this.testProject = testProject;
+ }
- /**
- * Adds a file to this project at the specified <code>path</code>
- * and the provided <code>filename</code>. If segments of <code>path</code>
- * do not exist, they will be created.
- *
- * @param destPath The path relative to the project (use '/' as path separator).
- * @param filename The name of the to be created file
- * @param fileInputStream A stream to the new files content.
- */
- public IFile addFileToProject(String destPath, String filename, InputStream fileInputStream) throws CoreException {
- String[] pathSegments = destPath.split("/");
+ /**
+ * Adds a file to this project at the specified <code>path</code>
+ * and the provided <code>filename</code>. If segments of <code>path</code>
+ * do not exist, they will be created.
+ *
+ * @param destPath The path relative to the project (use '/' as path separator).
+ * @param filename The name of the to be created file
+ * @param fileInputStream A stream to the new files content.
+ */
+ public IFile addFileToProject(String destPath, String filename, InputStream fileInputStream) throws CoreException {
+ String[] pathSegments = destPath.split("/");
- IContainer parent = this.testProject;
- for (String segment: pathSegments) {
- if (segment.isEmpty()) {
- continue; // ignore
- }
- IResource segmentResource = parent.findMember(new Path(IPath.SEPARATOR + segment));
- if (segmentResource == null) {
- // create folder
- IFolder newFolder = parent.getFolder(new Path(segment));
- newFolder.create(false, true, null);
- parent = newFolder;
- } else {
- // resource existed
- parent = (IContainer)segmentResource;
- }
- }
- // Finally add the file
- IFile newFile = parent.getFile(new Path(filename));
- if (fileInputStream == null) {
- throw new IllegalStateException("fileInputStream must not be null");
- }
- newFile.create(fileInputStream, false, null);
+ IContainer parent = this.testProject;
+ for (String segment: pathSegments) {
+ if (segment.isEmpty()) {
+ continue; // ignore
+ }
+ IResource segmentResource = parent.findMember(new Path(IPath.SEPARATOR + segment));
+ if (segmentResource == null) {
+ // create folder
+ IFolder newFolder = parent.getFolder(new Path(segment));
+ newFolder.create(false, true, null);
+ parent = newFolder;
+ } else {
+ // resource existed
+ parent = (IContainer)segmentResource;
+ }
+ }
+ // Finally add the file
+ IFile newFile = parent.getFile(new Path(filename));
+ if (fileInputStream == null) {
+ throw new IllegalStateException("fileInputStream must not be null");
+ }
+ newFile.create(fileInputStream, false, null);
- // refresh project
- this.testProject.refreshLocal(IResource.DEPTH_INFINITE, null);
+ // refresh project
+ this.testProject.refreshLocal(IResource.DEPTH_INFINITE, null);
- return newFile;
- }
+ return newFile;
+ }
- /**
- * Add the Java nature to this project. I.e. make it a Java project.
- */
- public IJavaProject addJavaNature() throws CoreException {
- IProjectDescription description = this.testProject.getDescription();
- String[] natures = description.getNatureIds();
- String[] newNatures = new String[natures.length + 1];
- System.arraycopy(natures, 0, newNatures, 0, natures.length);
- newNatures[natures.length] = JavaCore.NATURE_ID;
- description.setNatureIds(newNatures);
- this.testProject.setDescription(description, null);
- return JavaCore.create(this.testProject);
- }
+ /**
+ * Add the Java nature to this project. I.e. make it a Java project.
+ */
+ public IJavaProject addJavaNature() throws CoreException {
+ IProjectDescription description = this.testProject.getDescription();
+ String[] natures = description.getNatureIds();
+ String[] newNatures = new String[natures.length + 1];
+ System.arraycopy(natures, 0, newNatures, 0, natures.length);
+ newNatures[natures.length] = JavaCore.NATURE_ID;
+ description.setNatureIds(newNatures);
+ this.testProject.setDescription(description, null);
+ return JavaCore.create(this.testProject);
+ }
- /**
- * Add the C nature to this project. I.e. make it a C project.
- * @throws CoreException
- */
- public void addCNature() throws CoreException {
- this.testProject = CCorePlugin.getDefault().createCDTProject(
- testProject.getDescription(), testProject, null);
- }
+ /**
+ * Add the C nature to this project. I.e. make it a C project.
+ * @throws CoreException
+ */
+ public void addCNature() throws CoreException {
+ this.testProject = CCorePlugin.getDefault().createCDTProject(
+ testProject.getDescription(), testProject, null);
+ }
- /**
- * Add the C++ nature to this project. I.e. make it a C++ project.
- * @throws CoreException
- */
- public void addCCNature() throws CoreException {
- addCNature();
- CCorePlugin.getDefault().convertProjectFromCtoCC(testProject, null);
- }
+ /**
+ * Add the C++ nature to this project. I.e. make it a C++ project.
+ * @throws CoreException
+ */
+ public void addCCNature() throws CoreException {
+ addCNature();
+ CCorePlugin.getDefault().convertProjectFromCtoCC(testProject, null);
+ }
- /**
- * Create a new Eclipse project in the current workspace
- *
- * @param name
- * @throws CoreException if project creation fails for some reason.
- * @return The newly created project.
- */
- private IProject createNewProject(String name) throws CoreException {
- IProject newProject = ResourcesPlugin.getWorkspace().getRoot()
- .getProject(name);
- newProject.create(null);
- newProject.open(null); // needs to be open
- return newProject;
- }
+ /**
+ * Create a new Eclipse project in the current workspace
+ *
+ * @param name
+ * @throws CoreException if project creation fails for some reason.
+ * @return The newly created project.
+ */
+ private IProject createNewProject(String name) throws CoreException {
+ IProject newProject = ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(name);
+ newProject.create(null);
+ newProject.open(null); // needs to be open
+ return newProject;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ContextMenuHelper.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ContextMenuHelper.java
index 0d69b794b7..c1b4cdf7c7 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ContextMenuHelper.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ContextMenuHelper.java
@@ -34,150 +34,150 @@ import org.hamcrest.Matcher;
public class ContextMenuHelper {
- /**
- * Clicks the context menu matching the text.
- *
- * @param bot
- *
- * @param texts
- * the text on the context menu.
- * @throws WidgetNotFoundException
- * if the widget is not found.
- * @throws SWTException
- * if the menu item is disabled (the root cause being an
- * {@link IllegalStateException})
- */
- public static void clickContextMenu(final AbstractSWTBot<?> bot,
- final String... texts) {
-
- // show
- final MenuItem menuItem = UIThreadRunnable
- .syncExec(new WidgetResult<MenuItem>() {
- @Override
- public MenuItem run() {
- MenuItem theItem = getMenuItem(bot, texts);
- if (theItem != null && !theItem.isEnabled())
- throw new IllegalStateException(
- "Menu item is diabled");
-
- return theItem;
- }
- });
- if (menuItem == null) {
- throw new WidgetNotFoundException("Could not find menu: "
- + Arrays.asList(texts));
- }
-
- // click
- click(menuItem);
-
- // hide
- UIThreadRunnable.syncExec(new VoidResult() {
- @Override
- public void run() {
- if (menuItem.isDisposed())
- return; // menu already gone
- hide(menuItem.getParent());
- }
- });
- }
-
- private static MenuItem getMenuItem(final AbstractSWTBot<?> bot,
- final String... texts) {
- MenuItem theItem = null;
- Control control = (Control) bot.widget;
- // for dynamic menus, we need to issue this event
- control.notifyListeners(SWT.MenuDetect, new Event());
- Menu menu = control.getMenu();
- for (String text : texts) {
- Matcher<MenuItem> matcher = allOf(instanceOf(MenuItem.class),
- withMnemonic(text));
- theItem = show(menu, matcher);
- if (theItem != null) {
- menu = theItem.getMenu();
- } else {
- hide(menu);
- break;
- }
- }
- return theItem;
- }
-
- /**
- * Checks if the context menu matching the text is enabled
- *
- * @param bot
- *
- * @param texts
- * the text on the context menu.
- * @return true if the context menu is enabled
- * @throws WidgetNotFoundException
- * if the widget is not found.
- */
- public static boolean isContextMenuItemEnabled(final AbstractSWTBot<?> bot,
- final String... texts) {
-
- final AtomicBoolean enabled = new AtomicBoolean(false);
- // show
- final MenuItem menuItem = UIThreadRunnable
- .syncExec(new WidgetResult<MenuItem>() {
- @Override
- public MenuItem run() {
- MenuItem theItem = getMenuItem(bot, texts);
- if (theItem != null && theItem.isEnabled())
- enabled.set(true);
- return theItem;
- }
- });
- if (menuItem == null) {
- throw new WidgetNotFoundException("Could not find menu: "
- + Arrays.asList(texts));
- }
- // hide
- UIThreadRunnable.syncExec(new VoidResult() {
- @Override
- public void run() {
- if (menuItem.isDisposed())
- return; // menu already gone
- hide(menuItem.getParent());
- }
- });
- return enabled.get();
- }
-
- private static MenuItem show(final Menu menu, final Matcher<MenuItem> matcher) {
- if (menu != null) {
- menu.notifyListeners(SWT.Show, new Event());
- MenuItem[] items = menu.getItems();
- for (final MenuItem menuItem : items) {
- if (matcher.matches(menuItem)) {
- return menuItem;
- }
- }
- menu.notifyListeners(SWT.Hide, new Event());
- }
- return null;
- }
-
- private static void click(final MenuItem menuItem) {
- final Event event = new Event();
- event.time = (int) System.currentTimeMillis();
- event.widget = menuItem;
- event.display = menuItem.getDisplay();
- event.type = SWT.Selection;
-
- UIThreadRunnable.asyncExec(menuItem.getDisplay(), new VoidResult() {
- @Override
- public void run() {
- menuItem.notifyListeners(SWT.Selection, event);
- }
- });
- }
-
- private static void hide(final Menu menu) {
- menu.notifyListeners(SWT.Hide, new Event());
- if (menu.getParentMenu() != null) {
- hide(menu.getParentMenu());
- }
- }
+ /**
+ * Clicks the context menu matching the text.
+ *
+ * @param bot
+ *
+ * @param texts
+ * the text on the context menu.
+ * @throws WidgetNotFoundException
+ * if the widget is not found.
+ * @throws SWTException
+ * if the menu item is disabled (the root cause being an
+ * {@link IllegalStateException})
+ */
+ public static void clickContextMenu(final AbstractSWTBot<?> bot,
+ final String... texts) {
+
+ // show
+ final MenuItem menuItem = UIThreadRunnable
+ .syncExec(new WidgetResult<MenuItem>() {
+ @Override
+ public MenuItem run() {
+ MenuItem theItem = getMenuItem(bot, texts);
+ if (theItem != null && !theItem.isEnabled())
+ throw new IllegalStateException(
+ "Menu item is diabled");
+
+ return theItem;
+ }
+ });
+ if (menuItem == null) {
+ throw new WidgetNotFoundException("Could not find menu: "
+ + Arrays.asList(texts));
+ }
+
+ // click
+ click(menuItem);
+
+ // hide
+ UIThreadRunnable.syncExec(new VoidResult() {
+ @Override
+ public void run() {
+ if (menuItem.isDisposed())
+ return; // menu already gone
+ hide(menuItem.getParent());
+ }
+ });
+ }
+
+ private static MenuItem getMenuItem(final AbstractSWTBot<?> bot,
+ final String... texts) {
+ MenuItem theItem = null;
+ Control control = (Control) bot.widget;
+ // for dynamic menus, we need to issue this event
+ control.notifyListeners(SWT.MenuDetect, new Event());
+ Menu menu = control.getMenu();
+ for (String text : texts) {
+ Matcher<MenuItem> matcher = allOf(instanceOf(MenuItem.class),
+ withMnemonic(text));
+ theItem = show(menu, matcher);
+ if (theItem != null) {
+ menu = theItem.getMenu();
+ } else {
+ hide(menu);
+ break;
+ }
+ }
+ return theItem;
+ }
+
+ /**
+ * Checks if the context menu matching the text is enabled
+ *
+ * @param bot
+ *
+ * @param texts
+ * the text on the context menu.
+ * @return true if the context menu is enabled
+ * @throws WidgetNotFoundException
+ * if the widget is not found.
+ */
+ public static boolean isContextMenuItemEnabled(final AbstractSWTBot<?> bot,
+ final String... texts) {
+
+ final AtomicBoolean enabled = new AtomicBoolean(false);
+ // show
+ final MenuItem menuItem = UIThreadRunnable
+ .syncExec(new WidgetResult<MenuItem>() {
+ @Override
+ public MenuItem run() {
+ MenuItem theItem = getMenuItem(bot, texts);
+ if (theItem != null && theItem.isEnabled())
+ enabled.set(true);
+ return theItem;
+ }
+ });
+ if (menuItem == null) {
+ throw new WidgetNotFoundException("Could not find menu: "
+ + Arrays.asList(texts));
+ }
+ // hide
+ UIThreadRunnable.syncExec(new VoidResult() {
+ @Override
+ public void run() {
+ if (menuItem.isDisposed())
+ return; // menu already gone
+ hide(menuItem.getParent());
+ }
+ });
+ return enabled.get();
+ }
+
+ private static MenuItem show(final Menu menu, final Matcher<MenuItem> matcher) {
+ if (menu != null) {
+ menu.notifyListeners(SWT.Show, new Event());
+ MenuItem[] items = menu.getItems();
+ for (final MenuItem menuItem : items) {
+ if (matcher.matches(menuItem)) {
+ return menuItem;
+ }
+ }
+ menu.notifyListeners(SWT.Hide, new Event());
+ }
+ return null;
+ }
+
+ private static void click(final MenuItem menuItem) {
+ final Event event = new Event();
+ event.time = (int) System.currentTimeMillis();
+ event.widget = menuItem;
+ event.display = menuItem.getDisplay();
+ event.type = SWT.Selection;
+
+ UIThreadRunnable.asyncExec(menuItem.getDisplay(), new VoidResult() {
+ @Override
+ public void run() {
+ menuItem.notifyListeners(SWT.Selection, event);
+ }
+ });
+ }
+
+ private static void hide(final Menu menu) {
+ menu.notifyListeners(SWT.Hide, new Event());
+ if (menu.getParentMenu() != null) {
+ hide(menu.getParentMenu());
+ }
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ProjectExplorer.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ProjectExplorer.java
index 300c5e6912..eea9162702 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ProjectExplorer.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ProjectExplorer.java
@@ -23,73 +23,73 @@ import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
*/
public class ProjectExplorer {
- private static SWTWorkbenchBot bot = new SWTWorkbenchBot();
+ private static SWTWorkbenchBot bot = new SWTWorkbenchBot();
- /**
- * Opens the Project Explorer view.
- */
- public static void openView() throws Exception {
- bot.menu("Window").menu("Show View").menu("Project Explorer").click();
- }
+ /**
+ * Opens the Project Explorer view.
+ */
+ public static void openView() throws Exception {
+ bot.menu("Window").menu("Show View").menu("Project Explorer").click();
+ }
- /**
- * Assumes Project Explorer view is shown.
- *
- * @return The tree of the Project Explorer view
- */
- public static SWTBotTree getTree() {
- SWTBotView projectExplorer = bot.viewByTitle("Project Explorer");
- projectExplorer.show();
- Composite projectExplorerComposite = (Composite) projectExplorer.getWidget();
- Tree swtTree = bot.widget(WidgetMatcherFactory.widgetOfType(Tree.class), projectExplorerComposite);
- return new SWTBotTree(swtTree);
- }
+ /**
+ * Assumes Project Explorer view is shown.
+ *
+ * @return The tree of the Project Explorer view
+ */
+ public static SWTBotTree getTree() {
+ SWTBotView projectExplorer = bot.viewByTitle("Project Explorer");
+ projectExplorer.show();
+ Composite projectExplorerComposite = (Composite) projectExplorer.getWidget();
+ Tree swtTree = bot.widget(WidgetMatcherFactory.widgetOfType(Tree.class), projectExplorerComposite);
+ return new SWTBotTree(swtTree);
+ }
- /**
- * @param projectItem The tree item corresponding to the project.
- * @param name
- * name of an item
- * @return the project item pertaining to the project
- */
- public static SWTBotTreeItem getProjectItem(SWTBotTreeItem projectItem,
- String file) {
- for (SWTBotTreeItem item : projectItem.getItems()) {
- String itemText = item.getText();
- if (itemText.contains(file)) {
- if (itemText.contains(" ")) {
- StringTokenizer tok = new StringTokenizer(itemText, " ");
- String name = tok.nextToken();
- if (file.equals(name))
- return item;
- } else if (itemText.equals(file)) {
- return item;
- }
- }
- }
- return null;
- }
+ /**
+ * @param projectItem The tree item corresponding to the project.
+ * @param name
+ * name of an item
+ * @return the project item pertaining to the project
+ */
+ public static SWTBotTreeItem getProjectItem(SWTBotTreeItem projectItem,
+ String file) {
+ for (SWTBotTreeItem item : projectItem.getItems()) {
+ String itemText = item.getText();
+ if (itemText.contains(file)) {
+ if (itemText.contains(" ")) {
+ StringTokenizer tok = new StringTokenizer(itemText, " ");
+ String name = tok.nextToken();
+ if (file.equals(name))
+ return item;
+ } else if (itemText.equals(file)) {
+ return item;
+ }
+ }
+ }
+ return null;
+ }
- /**
- * Expand the given project (optionally stripping off the team provider bits)
- *
- * @param projectName
- * @param teamProviderString
- * @return
- */
- public static SWTBotTreeItem expandProject(SWTBotTree projectExplorerTree, String projectName, String teamProviderString) {
- String itemName;
- for (SWTBotTreeItem item: projectExplorerTree.getAllItems()) {
- itemName = item.getText();
- if (itemName.contains(projectName)) { // may also contain repo info
- if (itemName.contains(teamProviderString)) {
- return projectExplorerTree.expandNode(projectName + " "
- + teamProviderString);
- } else {
- return projectExplorerTree.expandNode(projectName);
- }
- }
- }
- // nothing appropriate found
- return null;
- }
+ /**
+ * Expand the given project (optionally stripping off the team provider bits)
+ *
+ * @param projectName
+ * @param teamProviderString
+ * @return
+ */
+ public static SWTBotTreeItem expandProject(SWTBotTree projectExplorerTree, String projectName, String teamProviderString) {
+ String itemName;
+ for (SWTBotTreeItem item: projectExplorerTree.getAllItems()) {
+ itemName = item.getText();
+ if (itemName.contains(projectName)) { // may also contain repo info
+ if (itemName.contains(teamProviderString)) {
+ return projectExplorerTree.expandNode(projectName + " "
+ + teamProviderString);
+ } else {
+ return projectExplorerTree.expandNode(projectName);
+ }
+ }
+ }
+ // nothing appropriate found
+ return null;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ProjectExplorerTreeItemAppearsCondition.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ProjectExplorerTreeItemAppearsCondition.java
index aa54f8ccac..09716e3649 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ProjectExplorerTreeItemAppearsCondition.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/ProjectExplorerTreeItemAppearsCondition.java
@@ -19,38 +19,38 @@ import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
*/
public class ProjectExplorerTreeItemAppearsCondition implements ICondition {
- private SWTBotTreeItem treeItem;
- private String itemName;
- private String parent;
- private String teamDirt;
- private SWTBotTree projectExplorerTree;
-
- public ProjectExplorerTreeItemAppearsCondition(SWTBotTree projectExplorerTree, String parent, String teamDirt, String treeItemName) {
- this.itemName = treeItemName;
- this.parent = parent;
- this.teamDirt = teamDirt;
- this.projectExplorerTree = projectExplorerTree;
- }
-
- @Override
- public boolean test() {
- treeItem = ProjectExplorer.expandProject(projectExplorerTree, parent, teamDirt);
- for (SWTBotTreeItem i : treeItem.getItems()) {
- if (i.getText().contains(itemName)) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public void init(SWTBot bot) {
- // no initialization
- }
-
- @Override
- public String getFailureMessage() {
- return null;
- }
+ private SWTBotTreeItem treeItem;
+ private String itemName;
+ private String parent;
+ private String teamDirt;
+ private SWTBotTree projectExplorerTree;
+
+ public ProjectExplorerTreeItemAppearsCondition(SWTBotTree projectExplorerTree, String parent, String teamDirt, String treeItemName) {
+ this.itemName = treeItemName;
+ this.parent = parent;
+ this.teamDirt = teamDirt;
+ this.projectExplorerTree = projectExplorerTree;
+ }
+
+ @Override
+ public boolean test() {
+ treeItem = ProjectExplorer.expandProject(projectExplorerTree, parent, teamDirt);
+ for (SWTBotTreeItem i : treeItem.getItems()) {
+ if (i.getText().contains(itemName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public void init(SWTBot bot) {
+ // no initialization
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return null;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNProject.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNProject.java
index df0054a05e..4652fd70c6 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNProject.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNProject.java
@@ -29,133 +29,133 @@ import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
*/
public class SVNProject {
- private SWTWorkbenchBot bot;
- private String repoURL;
- private String projectName;
- private IProject project; // available after checkout
-
- public SVNProject(SWTWorkbenchBot bot) {
- this.bot = bot;
- }
-
- /**
- * @return the repoURL
- */
- public String getRepoURL() {
- return repoURL;
- }
-
- /**
- * @param repoURL the repoURL to set
- */
- public SVNProject setRepoURL(String repoURL) {
- this.repoURL = repoURL;
- return this;
- }
-
- /**
- * @return the projectName
- */
- public String getProjectName() {
- return projectName;
- }
-
- /**
- * @param projectName the projectName to set
- */
- public SVNProject setProjectName(String projectName) {
- this.projectName = projectName;
- return this;
- }
-
- /**
- * @return the project
- */
- public IProject getProject() {
- return project;
- }
-
- /**
- * @param project the project to set
- */
- public SVNProject setProject(IProject project) {
- this.project = project;
- return this;
- }
-
- /**
- * Use File => Import => SVN to create a svn-backed project.
- */
- public IProject checkoutProject() throws IllegalStateException {
- if (repoURL == null || projectName == null) {
- // need to have url and project set
- throw new IllegalStateException();
- }
- bot.menu("File").menu("Import...").click();
-
- SWTBotShell shell = bot.shell("Import");
- shell.activate();
- bot.tree().expandNode("SVN").select("Checkout Projects from SVN");
- bot.button("Next >").click();
-
- // create new repo
- shell = bot.shell("Checkout from SVN");
- shell.activate();
- bot.button("Next >").click();
-
- shell = bot.shell("Checkout from SVN");
- shell.activate();
- // Enter url
- bot.comboBoxWithLabelInGroup("Url:", "Location").setText(repoURL);
- bot.button("Next >").click();
-
- // the next few operation can take quite a while, adjust
- // timout accordingly.
- long oldTimeout = SWTBotPreferences.TIMEOUT;
- SWTBotPreferences.TIMEOUT = 3 * 5000;
-
- bot.waitUntil(Conditions.shellIsActive("Progress Information"));
- shell = bot.shell("Progress Information");
- bot.waitUntil(Conditions.shellCloses(shell));
- bot.waitUntil(Conditions.shellIsActive("Checkout from SVN"));
- shell = bot.shell("Checkout from SVN");
- bot.waitUntil(new TreeItemAppearsCondition(repoURL, projectName));
- SWTBotTreeItem projectTree = bot.tree().expandNode(repoURL);
- projectTree.expandNode(projectName).select();
- bot.button("Finish").click();
- // Wait for import operation to finish
- bot.waitUntil(Conditions.shellCloses(shell));
- bot.waitUntil(Conditions.shellIsActive("SVN Checkout"));
- SWTBotShell svnCheckoutPopup = bot.shell("SVN Checkout");
- bot.waitUntil(Conditions.shellCloses(svnCheckoutPopup));
- // need a little delay
- bot.waitUntil(new SVNProjectCreatedCondition(projectName));
-
- // Set timout back what it was.
- SWTBotPreferences.TIMEOUT = oldTimeout;
-
- // A quick sanity check
- IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
- IProject changelogTestsProject = (IProject)wsRoot.findMember(new Path(projectName));
- assertNotNull(changelogTestsProject);
- try {
- changelogTestsProject.refreshLocal(IResource.DEPTH_INFINITE, null);
- } catch (CoreException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- IResource manifest = changelogTestsProject.findMember(new Path("/META-INF/MANIFEST.MF"));
- assertNotNull(manifest);
- return changelogTestsProject;
- }
-
- /**
- * Discard the automatically created SVN repo URL from the list.
- */
- public void discardRepositoryLocation() throws Exception {
- if (repoURL == null) { // need to have repoURL set
- throw new IllegalStateException();
- }
- new SVNReporsitoriesView(bot).open().discardRepository(repoURL);
- }
+ private SWTWorkbenchBot bot;
+ private String repoURL;
+ private String projectName;
+ private IProject project; // available after checkout
+
+ public SVNProject(SWTWorkbenchBot bot) {
+ this.bot = bot;
+ }
+
+ /**
+ * @return the repoURL
+ */
+ public String getRepoURL() {
+ return repoURL;
+ }
+
+ /**
+ * @param repoURL the repoURL to set
+ */
+ public SVNProject setRepoURL(String repoURL) {
+ this.repoURL = repoURL;
+ return this;
+ }
+
+ /**
+ * @return the projectName
+ */
+ public String getProjectName() {
+ return projectName;
+ }
+
+ /**
+ * @param projectName the projectName to set
+ */
+ public SVNProject setProjectName(String projectName) {
+ this.projectName = projectName;
+ return this;
+ }
+
+ /**
+ * @return the project
+ */
+ public IProject getProject() {
+ return project;
+ }
+
+ /**
+ * @param project the project to set
+ */
+ public SVNProject setProject(IProject project) {
+ this.project = project;
+ return this;
+ }
+
+ /**
+ * Use File => Import => SVN to create a svn-backed project.
+ */
+ public IProject checkoutProject() throws IllegalStateException {
+ if (repoURL == null || projectName == null) {
+ // need to have url and project set
+ throw new IllegalStateException();
+ }
+ bot.menu("File").menu("Import...").click();
+
+ SWTBotShell shell = bot.shell("Import");
+ shell.activate();
+ bot.tree().expandNode("SVN").select("Checkout Projects from SVN");
+ bot.button("Next >").click();
+
+ // create new repo
+ shell = bot.shell("Checkout from SVN");
+ shell.activate();
+ bot.button("Next >").click();
+
+ shell = bot.shell("Checkout from SVN");
+ shell.activate();
+ // Enter url
+ bot.comboBoxWithLabelInGroup("Url:", "Location").setText(repoURL);
+ bot.button("Next >").click();
+
+ // the next few operation can take quite a while, adjust
+ // timout accordingly.
+ long oldTimeout = SWTBotPreferences.TIMEOUT;
+ SWTBotPreferences.TIMEOUT = 3 * 5000;
+
+ bot.waitUntil(Conditions.shellIsActive("Progress Information"));
+ shell = bot.shell("Progress Information");
+ bot.waitUntil(Conditions.shellCloses(shell));
+ bot.waitUntil(Conditions.shellIsActive("Checkout from SVN"));
+ shell = bot.shell("Checkout from SVN");
+ bot.waitUntil(new TreeItemAppearsCondition(repoURL, projectName));
+ SWTBotTreeItem projectTree = bot.tree().expandNode(repoURL);
+ projectTree.expandNode(projectName).select();
+ bot.button("Finish").click();
+ // Wait for import operation to finish
+ bot.waitUntil(Conditions.shellCloses(shell));
+ bot.waitUntil(Conditions.shellIsActive("SVN Checkout"));
+ SWTBotShell svnCheckoutPopup = bot.shell("SVN Checkout");
+ bot.waitUntil(Conditions.shellCloses(svnCheckoutPopup));
+ // need a little delay
+ bot.waitUntil(new SVNProjectCreatedCondition(projectName));
+
+ // Set timout back what it was.
+ SWTBotPreferences.TIMEOUT = oldTimeout;
+
+ // A quick sanity check
+ IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
+ IProject changelogTestsProject = (IProject)wsRoot.findMember(new Path(projectName));
+ assertNotNull(changelogTestsProject);
+ try {
+ changelogTestsProject.refreshLocal(IResource.DEPTH_INFINITE, null);
+ } catch (CoreException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ IResource manifest = changelogTestsProject.findMember(new Path("/META-INF/MANIFEST.MF"));
+ assertNotNull(manifest);
+ return changelogTestsProject;
+ }
+
+ /**
+ * Discard the automatically created SVN repo URL from the list.
+ */
+ public void discardRepositoryLocation() throws Exception {
+ if (repoURL == null) { // need to have repoURL set
+ throw new IllegalStateException();
+ }
+ new SVNReporsitoriesView(bot).open().discardRepository(repoURL);
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNProjectCreatedCondition.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNProjectCreatedCondition.java
index 661599dd8c..d21fb52021 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNProjectCreatedCondition.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNProjectCreatedCondition.java
@@ -22,31 +22,31 @@ import org.eclipse.swtbot.swt.finder.waits.ICondition;
*/
public class SVNProjectCreatedCondition implements ICondition {
- private String projectName;
-
- public SVNProjectCreatedCondition(String projectName) {
- this.projectName = projectName;
- }
-
- @Override
- public boolean test() {
- IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
- IProject project = (IProject)wsRoot.findMember(new Path(projectName));
- if (project == null) {
- return false;
- } else {
- return true;
- }
- }
-
- @Override
- public void init(SWTBot bot) {
- // no initialization; don't need bot
- }
-
- @Override
- public String getFailureMessage() {
- return null;
- }
+ private String projectName;
+
+ public SVNProjectCreatedCondition(String projectName) {
+ this.projectName = projectName;
+ }
+
+ @Override
+ public boolean test() {
+ IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
+ IProject project = (IProject)wsRoot.findMember(new Path(projectName));
+ if (project == null) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ @Override
+ public void init(SWTBot bot) {
+ // no initialization; don't need bot
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return null;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNReporsitoriesView.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNReporsitoriesView.java
index 720aab0df9..1abf4509cb 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNReporsitoriesView.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/SVNReporsitoriesView.java
@@ -17,44 +17,44 @@ import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
*/
public class SVNReporsitoriesView {
- private SWTWorkbenchBot bot;
+ private SWTWorkbenchBot bot;
- public SVNReporsitoriesView(SWTWorkbenchBot bot) {
- this.bot = bot;
- }
+ public SVNReporsitoriesView(SWTWorkbenchBot bot) {
+ this.bot = bot;
+ }
- /**
- * Open the SVNRepositoriesView
- */
- public SVNReporsitoriesView open() {
- bot.menu("Window").menu("Show View").menu("Other...").click();
- SWTBotShell shell = bot.shell("Show View");
- shell.activate();
- bot.tree().expandNode("SVN").select("SVN Repositories");
- bot.button("OK").click();
- return this;
- }
+ /**
+ * Open the SVNRepositoriesView
+ */
+ public SVNReporsitoriesView open() {
+ bot.menu("Window").menu("Show View").menu("Other...").click();
+ SWTBotShell shell = bot.shell("Show View");
+ shell.activate();
+ bot.tree().expandNode("SVN").select("SVN Repositories");
+ bot.button("OK").click();
+ return this;
+ }
- /**
- * Select repository
- */
- public void discardRepository(String repo) {
- SWTBotView svnRepoView = bot.viewByTitle("SVN Repositories");
- svnRepoView.show();
- svnRepoView.setFocus();
- SWTBotTree tree = svnRepoView.bot().tree();
- tree.select(repo);
- clickOnDiscardRepo(tree); // discard
- }
+ /**
+ * Select repository
+ */
+ public void discardRepository(String repo) {
+ SWTBotView svnRepoView = bot.viewByTitle("SVN Repositories");
+ svnRepoView.show();
+ svnRepoView.setFocus();
+ SWTBotTree tree = svnRepoView.bot().tree();
+ tree.select(repo);
+ clickOnDiscardRepo(tree); // discard
+ }
- /**
- * Context menu click helper. Click on "Add to existing sources".
- *
- * @param Tree of Package Explorer view.
- * @throws Exception
- */
- private void clickOnDiscardRepo(SWTBotTree svnReposTree) {
- String menuItem = "Discard location";
- ContextMenuHelper.clickContextMenu(svnReposTree, menuItem);
- }
+ /**
+ * Context menu click helper. Click on "Add to existing sources".
+ *
+ * @param Tree of Package Explorer view.
+ * @throws Exception
+ */
+ private void clickOnDiscardRepo(SWTBotTree svnReposTree) {
+ String menuItem = "Discard location";
+ ContextMenuHelper.clickContextMenu(svnReposTree, menuItem);
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/TableAppearsCondition.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/TableAppearsCondition.java
index 4d0a62895a..8a2967b261 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/TableAppearsCondition.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/TableAppearsCondition.java
@@ -18,31 +18,31 @@ import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable;
*/
public class TableAppearsCondition implements ICondition {
- private SWTBot bot;
+ private SWTBot bot;
- @Override
- public boolean test() {
- try {
- SWTBotTable table = bot.table();
- // table available
- // make sure rowcount > 0
- if (table.rowCount() > 0) {
- return true;
- }
- } catch (WidgetNotFoundException e) {
- // ignore
- }
- return false;
- }
+ @Override
+ public boolean test() {
+ try {
+ SWTBotTable table = bot.table();
+ // table available
+ // make sure rowcount > 0
+ if (table.rowCount() > 0) {
+ return true;
+ }
+ } catch (WidgetNotFoundException e) {
+ // ignore
+ }
+ return false;
+ }
- @Override
- public void init(SWTBot bot) {
- this.bot = bot;
- }
+ @Override
+ public void init(SWTBot bot) {
+ this.bot = bot;
+ }
- @Override
- public String getFailureMessage() {
- return null;
- }
+ @Override
+ public String getFailureMessage() {
+ return null;
+ }
}
diff --git a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/TreeItemAppearsCondition.java b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/TreeItemAppearsCondition.java
index 23b4be12d8..03c10f853b 100644
--- a/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/TreeItemAppearsCondition.java
+++ b/changelog/org.eclipse.linuxtools.changelog.ui.tests/src/org/eclipse/linuxtools/changelog/ui/tests/utils/TreeItemAppearsCondition.java
@@ -19,35 +19,35 @@ import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
*/
public class TreeItemAppearsCondition implements ICondition {
- private SWTBot bot;
- private SWTBotTreeItem treeItem;
- private String itemName;
- private String parent;
-
- public TreeItemAppearsCondition(String parent, String treeItemName) {
- this.itemName = treeItemName;
- this.parent = parent;
- }
-
- @Override
- public boolean test() {
- for (SWTBotTreeItem i : treeItem.getItems()) {
- if (i.getText().contains(itemName)) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public void init(SWTBot bot) {
- this.bot = bot;
- treeItem = this.bot.tree().expandNode(parent);
- }
-
- @Override
- public String getFailureMessage() {
- return null;
- }
+ private SWTBot bot;
+ private SWTBotTreeItem treeItem;
+ private String itemName;
+ private String parent;
+
+ public TreeItemAppearsCondition(String parent, String treeItemName) {
+ this.itemName = treeItemName;
+ this.parent = parent;
+ }
+
+ @Override
+ public boolean test() {
+ for (SWTBotTreeItem i : treeItem.getItems()) {
+ if (i.getText().contains(itemName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public void init(SWTBot bot) {
+ this.bot = bot;
+ treeItem = this.bot.tree().expandNode(parent);
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return null;
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov-feature/pom.xml b/gcov/org.eclipse.linuxtools.gcov-feature/pom.xml
index a0398234df..d94ec3c524 100644
--- a/gcov/org.eclipse.linuxtools.gcov-feature/pom.xml
+++ b/gcov/org.eclipse.linuxtools.gcov-feature/pom.xml
@@ -22,7 +22,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools GCov Feature</name>
-
+
<build>
<plugins>
<plugin>
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/plugin.xml b/gcov/org.eclipse.linuxtools.gcov.core/plugin.xml
index 5e234505ab..daabd6c417 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/plugin.xml
+++ b/gcov/org.eclipse.linuxtools.gcov.core/plugin.xml
@@ -45,7 +45,7 @@
class="org.eclipse.linuxtools.internal.gcov.preferences.ColorPreferencesInitializer">
</initializer>
</extension>
-
+
<extension
point="org.eclipse.ui.editors.markerAnnotationSpecification">
<specification
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/Activator.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/Activator.java
index a2e1dc0cff..0c3744f4ff 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/Activator.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/Activator.java
@@ -19,44 +19,44 @@ import org.osgi.framework.BundleContext;
*/
public class Activator extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.gcov.core"; //$NON-NLS-1$
-
- // The shared instance
- private static Activator plugin;
-
- /**
- * The constructor
- */
- public Activator() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.gcov.core"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/action/SwitchContentProviderAction.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/action/SwitchContentProviderAction.java
index 395450aca8..9e084d2fd2 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/action/SwitchContentProviderAction.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/action/SwitchContentProviderAction.java
@@ -18,28 +18,28 @@ import org.eclipse.linuxtools.internal.gcov.Activator;
import org.eclipse.ui.plugin.AbstractUIPlugin;
- /**
- * This action changes the content provider
- */
+ /**
+ * This action changes the content provider
+ */
- public class SwitchContentProviderAction extends Action {
+ public class SwitchContentProviderAction extends Action {
- private final ColumnViewer viewer;
- private final IContentProvider provider;
+ private final ColumnViewer viewer;
+ private final IContentProvider provider;
- public SwitchContentProviderAction(String name, String iconPath, ColumnViewer viewer, IContentProvider provider) {
- super(name, AS_RADIO_BUTTON);
- this.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, iconPath));
- this.setToolTipText(name);
- this.viewer = viewer;
- this.provider = provider;
- }
+ public SwitchContentProviderAction(String name, String iconPath, ColumnViewer viewer, IContentProvider provider) {
+ super(name, AS_RADIO_BUTTON);
+ this.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, iconPath));
+ this.setToolTipText(name);
+ this.viewer = viewer;
+ this.provider = provider;
+ }
- @Override
- public void run() {
- viewer.getControl().setRedraw(false);
- viewer.setContentProvider(provider);
- ((TreeViewer)viewer).expandToLevel(2);
- viewer.getControl().setRedraw(true);
- }
- } \ No newline at end of file
+ @Override
+ public void run() {
+ viewer.getControl().setRedraw(false);
+ viewer.setContentProvider(provider);
+ ((TreeViewer)viewer).expandToLevel(2);
+ viewer.getControl().setRedraw(true);
+ }
+ } \ No newline at end of file
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/dialog/Messages.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/dialog/Messages.java
index 8b8961aebd..dd402d2f85 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/dialog/Messages.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/dialog/Messages.java
@@ -13,27 +13,27 @@ package org.eclipse.linuxtools.internal.gcov.dialog;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.gcov.dialog.messages"; //$NON-NLS-1$
- public static String OpenGCDialog_bin_browser_button_text;
- public static String OpenGCDialog_bin_browser_fs_button_text;
- public static String OpenGCDialog_bin_browser_handler_text;
- public static String OpenGCDialog_no_bin_error_label;
- public static String OpenGCDialog_bin_dne_error_label;
- public static String OpenGCDialog_bin_group_header;
- public static String OpenGCDialog_bin_group_label;
- public static String OpenGCDialog_bin_group_tooltip;
- public static String OpenGCDialog_coverage_mode_header;
- public static String OpenGCDialog_coverage_mode_tooltip;
- public static String OpenGCDialog_invalid_bin_error_title;
- public static String OpenGCDialog_invalid_bin_error_message;
- public static String OpenGCDialog_open_results;
- public static String OpenGCDialog_summ_button_text;
- public static String OpenGCDialog_open_file_button_text;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.gcov.dialog.messages"; //$NON-NLS-1$
+ public static String OpenGCDialog_bin_browser_button_text;
+ public static String OpenGCDialog_bin_browser_fs_button_text;
+ public static String OpenGCDialog_bin_browser_handler_text;
+ public static String OpenGCDialog_no_bin_error_label;
+ public static String OpenGCDialog_bin_dne_error_label;
+ public static String OpenGCDialog_bin_group_header;
+ public static String OpenGCDialog_bin_group_label;
+ public static String OpenGCDialog_bin_group_tooltip;
+ public static String OpenGCDialog_coverage_mode_header;
+ public static String OpenGCDialog_coverage_mode_tooltip;
+ public static String OpenGCDialog_invalid_bin_error_title;
+ public static String OpenGCDialog_invalid_bin_error_message;
+ public static String OpenGCDialog_open_results;
+ public static String OpenGCDialog_summ_button_text;
+ public static String OpenGCDialog_open_file_button_text;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/AbstractTreeElement.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/AbstractTreeElement.java
index de4eb6a664..d1b4784acd 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/AbstractTreeElement.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/AbstractTreeElement.java
@@ -14,78 +14,78 @@ import java.util.LinkedList;
public abstract class AbstractTreeElement implements TreeElement{
- /**
- *
- */
- private static final long serialVersionUID = -4911602250295116203L;
- private final TreeElement parent;
- private final LinkedList<TreeElement> children = new LinkedList<>();
- private final String name;
- private final int totalLines;
- private final int executedLines;
- private final int instrumentedLines;
-
- public AbstractTreeElement(TreeElement parent, String name, int totalLines,
- int executedLines, int instrumentedLines) {
- this.parent = parent;
- this.name = name;
- this.totalLines = totalLines;
- this.executedLines = executedLines;
- this.instrumentedLines = instrumentedLines;
- }
-
- @Override
- public TreeElement getParent() {
- return parent;
- }
-
- @Override
- public boolean hasChildren() {
- return (children.size()>0);
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -4911602250295116203L;
+ private final TreeElement parent;
+ private final LinkedList<TreeElement> children = new LinkedList<>();
+ private final String name;
+ private final int totalLines;
+ private final int executedLines;
+ private final int instrumentedLines;
- @Override
- public LinkedList<? extends TreeElement> getChildren() {
- return children;
- }
+ public AbstractTreeElement(TreeElement parent, String name, int totalLines,
+ int executedLines, int instrumentedLines) {
+ this.parent = parent;
+ this.name = name;
+ this.totalLines = totalLines;
+ this.executedLines = executedLines;
+ this.instrumentedLines = instrumentedLines;
+ }
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public TreeElement getRoot() {
- if (parent == null) {
- return this;
- }
- return parent.getRoot();
- }
+ @Override
+ public TreeElement getParent() {
+ return parent;
+ }
- @Override
- public int getExecutedLines() {
- return executedLines;
- }
-
- @Override
- public int getInstrumentedLines() {
- return instrumentedLines;
- }
+ @Override
+ public boolean hasChildren() {
+ return (children.size()>0);
+ }
- @Override
- public float getCoveragePercentage() {
- if (instrumentedLines !=0 ) {
- return (100.f*executedLines)/(instrumentedLines);
- }
- else return 0;
- }
+ @Override
+ public LinkedList<? extends TreeElement> getChildren() {
+ return children;
+ }
- public void addChild(TreeElement child){
- children.add(child);
- }
-
- @Override
- public int getTotalLines() {
- return totalLines;
- }
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public TreeElement getRoot() {
+ if (parent == null) {
+ return this;
+ }
+ return parent.getRoot();
+ }
+
+ @Override
+ public int getExecutedLines() {
+ return executedLines;
+ }
+
+ @Override
+ public int getInstrumentedLines() {
+ return instrumentedLines;
+ }
+
+ @Override
+ public float getCoveragePercentage() {
+ if (instrumentedLines !=0 ) {
+ return (100.f*executedLines)/(instrumentedLines);
+ }
+ else return 0;
+ }
+
+ public void addChild(TreeElement child){
+ children.add(child);
+ }
+
+ @Override
+ public int getTotalLines() {
+ return totalLines;
+ }
} \ No newline at end of file
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFileTreeElement.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFileTreeElement.java
index 82a1d4e38b..69c24c2156 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFileTreeElement.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFileTreeElement.java
@@ -13,13 +13,13 @@ package org.eclipse.linuxtools.internal.gcov.model;
public class CovFileTreeElement extends AbstractTreeElement {
- /**
- *
- */
- private static final long serialVersionUID = -5017234616535899796L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -5017234616535899796L;
- public CovFileTreeElement(TreeElement parent,
- String name, int totalLines, int executedLines, int instrumentedLines) {
- super(parent, name, totalLines, executedLines, instrumentedLines);
- }
+ public CovFileTreeElement(TreeElement parent,
+ String name, int totalLines, int executedLines, int instrumentedLines) {
+ super(parent, name, totalLines, executedLines, instrumentedLines);
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFolderTreeElement.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFolderTreeElement.java
index 9e9b6c9549..1bd11f4333 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFolderTreeElement.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFolderTreeElement.java
@@ -12,13 +12,13 @@ package org.eclipse.linuxtools.internal.gcov.model;
public class CovFolderTreeElement extends AbstractTreeElement {
- /**
- *
- */
- private static final long serialVersionUID = 583359546284716138L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 583359546284716138L;
- public CovFolderTreeElement(TreeElement parent,
- String name, int totalLines, int executedLines, int instrumentedLines) {
- super(parent, name, totalLines, executedLines, instrumentedLines);
- }
+ public CovFolderTreeElement(TreeElement parent,
+ String name, int totalLines, int executedLines, int instrumentedLines) {
+ super(parent, name, totalLines, executedLines, instrumentedLines);
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFunctionTreeElement.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFunctionTreeElement.java
index 239ac02bcd..31e06af866 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFunctionTreeElement.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovFunctionTreeElement.java
@@ -14,47 +14,47 @@ import java.util.LinkedList;
public class CovFunctionTreeElement extends AbstractTreeElement {
-
- /**
- *
- */
- private static final long serialVersionUID = -2025221943523670378L;
- private final String sourceFilePath;
- private final long firstLnNmbr;
-
- public CovFunctionTreeElement(TreeElement parent, String name, String sourceFilePath,
- long firstLnNmbr, int executedLines, int instrumentedLines) {
- super(parent, name, -1, executedLines, instrumentedLines);
- this.sourceFilePath = sourceFilePath;
- this.firstLnNmbr = firstLnNmbr;
- }
-
-
- /* no children for functions*/
-
- @Override
- public boolean hasChildren() {
- return false;
- }
-
- @Override
- public LinkedList<? extends TreeElement> getChildren() {
- return null;
- }
-
- @Override
- public void addChild(TreeElement child){
- }
-
-
- /* specific methods for functions*/
-
- public String getSourceFilePath() {
- return sourceFilePath;
- }
-
- public long getFirstLnNmbr() {
- return firstLnNmbr;
- }
-
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -2025221943523670378L;
+ private final String sourceFilePath;
+ private final long firstLnNmbr;
+
+ public CovFunctionTreeElement(TreeElement parent, String name, String sourceFilePath,
+ long firstLnNmbr, int executedLines, int instrumentedLines) {
+ super(parent, name, -1, executedLines, instrumentedLines);
+ this.sourceFilePath = sourceFilePath;
+ this.firstLnNmbr = firstLnNmbr;
+ }
+
+
+ /* no children for functions*/
+
+ @Override
+ public boolean hasChildren() {
+ return false;
+ }
+
+ @Override
+ public LinkedList<? extends TreeElement> getChildren() {
+ return null;
+ }
+
+ @Override
+ public void addChild(TreeElement child){
+ }
+
+
+ /* specific methods for functions*/
+
+ public String getSourceFilePath() {
+ return sourceFilePath;
+ }
+
+ public long getFirstLnNmbr() {
+ return firstLnNmbr;
+ }
+
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovRootTreeElement.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovRootTreeElement.java
index 51646602a2..d86e561d1c 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovRootTreeElement.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/CovRootTreeElement.java
@@ -13,13 +13,13 @@ package org.eclipse.linuxtools.internal.gcov.model;
public class CovRootTreeElement extends AbstractTreeElement {
- /**
- *
- */
- private static final long serialVersionUID = 877070271548608926L;
+ /**
+ *
+ */
+ private static final long serialVersionUID = 877070271548608926L;
- public CovRootTreeElement(String name, int totalLines, int executedLines,
- int instrumentedLines) {
- super(null, name, totalLines, executedLines, instrumentedLines);
- }
+ public CovRootTreeElement(String name, int totalLines, int executedLines,
+ int instrumentedLines) {
+ super(null, name, totalLines, executedLines, instrumentedLines);
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/TreeElement.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/TreeElement.java
index ee6d708e6a..7e99c4d848 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/TreeElement.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/model/TreeElement.java
@@ -14,14 +14,14 @@ import java.io.Serializable;
import java.util.LinkedList;
public interface TreeElement extends Serializable{
- TreeElement getParent();
- LinkedList<? extends TreeElement> getChildren();
- boolean hasChildren();
- TreeElement getRoot();
+ TreeElement getParent();
+ LinkedList<? extends TreeElement> getChildren();
+ boolean hasChildren();
+ TreeElement getRoot();
- String getName();
- int getExecutedLines();
- int getInstrumentedLines();
- int getTotalLines();
- float getCoveragePercentage();
+ String getName();
+ int getExecutedLines();
+ int getInstrumentedLines();
+ int getTotalLines();
+ float getCoveragePercentage();
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Arc.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Arc.java
index 6323c8cbea..7db610d4ac 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Arc.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Arc.java
@@ -15,117 +15,117 @@ import java.util.List;
public class Arc implements Serializable{
- /**
- *
- */
- private static final long serialVersionUID = 4104429137191407662L;
-
- private static final int VCOV_ARC_ON_TREE = (1 << 0);
- private static final int VCOV_ARC_FAKE = (1 << 1);
- private static final int VCOV_ARC_FALLTHROUGH = (1 << 2);
-
- private final Block srcBlock;
- private final Block dstnatnBlock;
- private final long flag;
- private final boolean fake;
- private final boolean onTree;
- private final boolean fallthrough;
-
- private long count = 0;
- private boolean countValid = false;
- private boolean isCallNonReturn = false; // Arc is for a function that abnormally returns
- private boolean isNonLoclaReturn = false; // Arc is for catch/setjump
- private boolean isUnconditionnal = false; // Is an unconditional branch.
-
- /**
- * Constructor
- */
- public Arc(int srcBlockIndice, int dstnatnBlockIndice, long flag, List<Block> otherArcParams) {
- this.flag = flag;
- this.dstnatnBlock = otherArcParams.get(dstnatnBlockIndice);
- this.srcBlock = otherArcParams.get(srcBlockIndice);
- this.count = 0;
- this.countValid = false;
- if ((flag & VCOV_ARC_ON_TREE) != 0) {
- onTree = true;
- fake = false;
- fallthrough = false;
- } else if ((flag & VCOV_ARC_FAKE) != 0) {
- onTree = false;
- fake = true;
- fallthrough = true;
- } else if ((flag & VCOV_ARC_FALLTHROUGH) != 0) {
- onTree = false;
- fake = false;
- fallthrough = true;
- } else {
- onTree = false;
- fake = false;
- fallthrough = false;
- }
- }
-
- public Block getDstnatnBlock() {
- return dstnatnBlock;
- }
-
- public long getFlag() {
- return flag;
- }
-
- public boolean isFake() {
- return fake;
- }
-
- public boolean isOnTree() {
- return onTree;
- }
-
- public boolean isFallthrough() {
- return fallthrough;
- }
-
- public boolean isUnconditionnal() {
- return isUnconditionnal;
- }
-
- public boolean isNonLoclaReturn() {
- return isNonLoclaReturn;
- }
-
- public boolean isCallNonReturn() {
- return isCallNonReturn;
- }
-
- public void setCallNonReturn(boolean isCallNonReturn) {
- this.isCallNonReturn = isCallNonReturn;
- }
-
- public void setNonLoclaReturn(boolean isNonLoclaReturn) {
- this.isNonLoclaReturn = isNonLoclaReturn;
- }
-
- public void setUnconditionnal(boolean isUnconditionnal) {
- this.isUnconditionnal = isUnconditionnal;
- }
-
- public Block getSrcBlock() {
- return srcBlock;
- }
-
- public void setCount(long count) {
- this.count = count;
- }
-
- public void setCountValid(boolean countValid) {
- this.countValid = countValid;
- }
-
- public long getCount() {
- return count;
- }
-
- public boolean isCountValid() {
- return countValid;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 4104429137191407662L;
+
+ private static final int VCOV_ARC_ON_TREE = (1 << 0);
+ private static final int VCOV_ARC_FAKE = (1 << 1);
+ private static final int VCOV_ARC_FALLTHROUGH = (1 << 2);
+
+ private final Block srcBlock;
+ private final Block dstnatnBlock;
+ private final long flag;
+ private final boolean fake;
+ private final boolean onTree;
+ private final boolean fallthrough;
+
+ private long count = 0;
+ private boolean countValid = false;
+ private boolean isCallNonReturn = false; // Arc is for a function that abnormally returns
+ private boolean isNonLoclaReturn = false; // Arc is for catch/setjump
+ private boolean isUnconditionnal = false; // Is an unconditional branch.
+
+ /**
+ * Constructor
+ */
+ public Arc(int srcBlockIndice, int dstnatnBlockIndice, long flag, List<Block> otherArcParams) {
+ this.flag = flag;
+ this.dstnatnBlock = otherArcParams.get(dstnatnBlockIndice);
+ this.srcBlock = otherArcParams.get(srcBlockIndice);
+ this.count = 0;
+ this.countValid = false;
+ if ((flag & VCOV_ARC_ON_TREE) != 0) {
+ onTree = true;
+ fake = false;
+ fallthrough = false;
+ } else if ((flag & VCOV_ARC_FAKE) != 0) {
+ onTree = false;
+ fake = true;
+ fallthrough = true;
+ } else if ((flag & VCOV_ARC_FALLTHROUGH) != 0) {
+ onTree = false;
+ fake = false;
+ fallthrough = true;
+ } else {
+ onTree = false;
+ fake = false;
+ fallthrough = false;
+ }
+ }
+
+ public Block getDstnatnBlock() {
+ return dstnatnBlock;
+ }
+
+ public long getFlag() {
+ return flag;
+ }
+
+ public boolean isFake() {
+ return fake;
+ }
+
+ public boolean isOnTree() {
+ return onTree;
+ }
+
+ public boolean isFallthrough() {
+ return fallthrough;
+ }
+
+ public boolean isUnconditionnal() {
+ return isUnconditionnal;
+ }
+
+ public boolean isNonLoclaReturn() {
+ return isNonLoclaReturn;
+ }
+
+ public boolean isCallNonReturn() {
+ return isCallNonReturn;
+ }
+
+ public void setCallNonReturn(boolean isCallNonReturn) {
+ this.isCallNonReturn = isCallNonReturn;
+ }
+
+ public void setNonLoclaReturn(boolean isNonLoclaReturn) {
+ this.isNonLoclaReturn = isNonLoclaReturn;
+ }
+
+ public void setUnconditionnal(boolean isUnconditionnal) {
+ this.isUnconditionnal = isUnconditionnal;
+ }
+
+ public Block getSrcBlock() {
+ return srcBlock;
+ }
+
+ public void setCount(long count) {
+ this.count = count;
+ }
+
+ public void setCountValid(boolean countValid) {
+ this.countValid = countValid;
+ }
+
+ public long getCount() {
+ return count;
+ }
+
+ public boolean isCountValid() {
+ return countValid;
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Block.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Block.java
index 4afe47f229..b5c68b46d6 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Block.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Block.java
@@ -15,163 +15,163 @@ import java.util.ArrayList;
public class Block implements Serializable{
- /**
- *
- */
- private static final long serialVersionUID = -7665287885679756014L;
- private final ArrayList<Arc> entryArcs = new ArrayList<>();
- private final ArrayList<Arc> exitArcs = new ArrayList<>();
- private final long flag;
- private long numSuccs = 0;
- private long numPreds = 0;
- private long count = 0;
- private boolean isCallSite = false;// Does the call
- private boolean isCallReturn = false; // Is the return
- private boolean isNonLocalReturn = false;
- private boolean validChain = false;
- private boolean invalidChain = false;
- private boolean countValid = false;
- private final BlkLine blkline = new BlkLine();
-
- /**
- * Constructor
- */
- public Block(long flag) {
- this.flag = flag;
- }
-
-
- /* getters & setters */
- public long getFlag() {
- return flag;
- }
-
- public ArrayList<Arc> getEntryArcs() {
- return entryArcs;
- }
-
- public ArrayList<Arc> getExitArcs() {
- return exitArcs;
- }
-
- public boolean isCallSite() {
- return isCallSite;
- }
-
- public boolean isCallReturn() {
- return isCallReturn;
- }
-
- public boolean isNonLocalReturn() {
- return isNonLocalReturn;
- }
-
- public void addEntryArcs(Arc arcEntry) {
- this.entryArcs.add(arcEntry);
- }
-
- public void addExitArcs(Arc arcExit) {
- this.exitArcs.add(arcExit);
- }
-
- public void setCallSite(boolean isCallSite) {
- this.isCallSite = isCallSite;
- }
-
- public void setCallReturn(boolean isCallReturn) {
- this.isCallReturn = isCallReturn;
- }
-
- public void setNonLocalReturn(boolean isNonLocalReturn) {
- this.isNonLocalReturn = isNonLocalReturn;
- }
-
- public void decNumSuccs() {
- this.numSuccs--;
- }
-
- public void decNumPreds() {
- this.numPreds--;
- }
-
- public void incNumPreds() {
- this.numPreds++;
- }
-
- public void incNumSuccs() {
- this.numSuccs++;
- }
-
- public boolean isValidChain() {
- return validChain;
- }
-
- public void setValidChain(boolean validChain) {
- this.validChain = validChain;
- }
-
- public boolean isInvalidChain() {
- return invalidChain;
- }
-
- public void setInvalidChain(boolean invalidChain) {
- this.invalidChain = invalidChain;
- }
-
- public long getCount() {
- return count;
- }
-
- public void setCount(long count) {
- this.count = count;
- }
-
- public void setCountValid(boolean countValid) {
- this.countValid = countValid;
- }
-
- public boolean isCountValid() {
- return countValid;
- }
-
- public long getNumSuccs() {
- return numSuccs;
- }
-
- public long getNumPreds() {
- return numPreds;
- }
-
- public void setNumSuccs(long numSuccs) {
- this.numSuccs = numSuccs;
- }
-
- public void setNumPreds(long numPreds) {
- this.numPreds = numPreds;
- }
-
- public long[] getEncoding() {
- return blkline.encoding;
- }
-
- public void setEncoding(long[] lineNos) {
- this.blkline.encoding = lineNos;
- }
-
- public int getLineNum() {
- return blkline.num;
- }
-
- public void setNumLine(int numline) {
- this.blkline.num = numline;
- }
-
- static class BlkLine implements Serializable{
- /**
- *
- */
- private static final long serialVersionUID = 2757557929188979686L;
- public long[] encoding;
- public int num;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = -7665287885679756014L;
+ private final ArrayList<Arc> entryArcs = new ArrayList<>();
+ private final ArrayList<Arc> exitArcs = new ArrayList<>();
+ private final long flag;
+ private long numSuccs = 0;
+ private long numPreds = 0;
+ private long count = 0;
+ private boolean isCallSite = false;// Does the call
+ private boolean isCallReturn = false; // Is the return
+ private boolean isNonLocalReturn = false;
+ private boolean validChain = false;
+ private boolean invalidChain = false;
+ private boolean countValid = false;
+ private final BlkLine blkline = new BlkLine();
+
+ /**
+ * Constructor
+ */
+ public Block(long flag) {
+ this.flag = flag;
+ }
+
+
+ /* getters & setters */
+ public long getFlag() {
+ return flag;
+ }
+
+ public ArrayList<Arc> getEntryArcs() {
+ return entryArcs;
+ }
+
+ public ArrayList<Arc> getExitArcs() {
+ return exitArcs;
+ }
+
+ public boolean isCallSite() {
+ return isCallSite;
+ }
+
+ public boolean isCallReturn() {
+ return isCallReturn;
+ }
+
+ public boolean isNonLocalReturn() {
+ return isNonLocalReturn;
+ }
+
+ public void addEntryArcs(Arc arcEntry) {
+ this.entryArcs.add(arcEntry);
+ }
+
+ public void addExitArcs(Arc arcExit) {
+ this.exitArcs.add(arcExit);
+ }
+
+ public void setCallSite(boolean isCallSite) {
+ this.isCallSite = isCallSite;
+ }
+
+ public void setCallReturn(boolean isCallReturn) {
+ this.isCallReturn = isCallReturn;
+ }
+
+ public void setNonLocalReturn(boolean isNonLocalReturn) {
+ this.isNonLocalReturn = isNonLocalReturn;
+ }
+
+ public void decNumSuccs() {
+ this.numSuccs--;
+ }
+
+ public void decNumPreds() {
+ this.numPreds--;
+ }
+
+ public void incNumPreds() {
+ this.numPreds++;
+ }
+
+ public void incNumSuccs() {
+ this.numSuccs++;
+ }
+
+ public boolean isValidChain() {
+ return validChain;
+ }
+
+ public void setValidChain(boolean validChain) {
+ this.validChain = validChain;
+ }
+
+ public boolean isInvalidChain() {
+ return invalidChain;
+ }
+
+ public void setInvalidChain(boolean invalidChain) {
+ this.invalidChain = invalidChain;
+ }
+
+ public long getCount() {
+ return count;
+ }
+
+ public void setCount(long count) {
+ this.count = count;
+ }
+
+ public void setCountValid(boolean countValid) {
+ this.countValid = countValid;
+ }
+
+ public boolean isCountValid() {
+ return countValid;
+ }
+
+ public long getNumSuccs() {
+ return numSuccs;
+ }
+
+ public long getNumPreds() {
+ return numPreds;
+ }
+
+ public void setNumSuccs(long numSuccs) {
+ this.numSuccs = numSuccs;
+ }
+
+ public void setNumPreds(long numPreds) {
+ this.numPreds = numPreds;
+ }
+
+ public long[] getEncoding() {
+ return blkline.encoding;
+ }
+
+ public void setEncoding(long[] lineNos) {
+ this.blkline.encoding = lineNos;
+ }
+
+ public int getLineNum() {
+ return blkline.num;
+ }
+
+ public void setNumLine(int numline) {
+ this.blkline.num = numline;
+ }
+
+ static class BlkLine implements Serializable{
+ /**
+ *
+ */
+ private static final long serialVersionUID = 2757557929188979686L;
+ public long[] encoding;
+ public int num;
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/CovManager.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/CovManager.java
index 1c469dad7c..4a59f8cc2c 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/CovManager.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/CovManager.java
@@ -52,8 +52,8 @@ import org.eclipse.ui.PlatformUI;
public class CovManager implements Serializable {
/**
- *
- */
+ *
+ */
private static final long serialVersionUID = 5582066617970911413L;
// input
private final String binaryPath;
@@ -263,9 +263,9 @@ public class CovManager implements Serializable {
File dir = null;
do {
if (postfix.isEmpty()) {
- postfix = f.getName();
+ postfix = f.getName();
} else {
- postfix = f.getName() + File.separator + postfix;
+ postfix = f.getName() + File.separator + postfix;
}
f = f.getParentFile();
if (f != null) {
@@ -289,7 +289,7 @@ public class CovManager implements Serializable {
fg.setText(NLS.bind(Messages.CovManager_No_FilePath_Error, new Object[] { filePath, filename }));
String s = fg.open();
if (s == null) {
- return null;
+ return null;
} else {
f = new File(s).getAbsoluteFile();
addSourceLookup(sourcePath, f, new File(filePath).getAbsoluteFile());
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/CoverageInfo.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/CoverageInfo.java
index 761289ee43..d7b30c27fc 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/CoverageInfo.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/CoverageInfo.java
@@ -14,39 +14,39 @@ import java.io.Serializable;
public class CoverageInfo implements Serializable{
- /**
- *
- */
- private static final long serialVersionUID = -6067335353999481231L;
-
- private int linesInstrumented = 0;
- private int linesExecuted = 0;
-
- /**
- * Constructor
- */
- public CoverageInfo() {
-
- }
-
-
- /*getters & setters */
-
- public int getLinesInstrumented() {
- return linesInstrumented;
- }
-
- public int getLinesExecuted() {
- return linesExecuted;
- }
-
- public void incLinesInstrumented(){
- this.linesInstrumented++;
- }
-
- public void incLinesExecuted(){
- this.linesExecuted++;
- }
-
-
+ /**
+ *
+ */
+ private static final long serialVersionUID = -6067335353999481231L;
+
+ private int linesInstrumented = 0;
+ private int linesExecuted = 0;
+
+ /**
+ * Constructor
+ */
+ public CoverageInfo() {
+
+ }
+
+
+ /*getters & setters */
+
+ public int getLinesInstrumented() {
+ return linesInstrumented;
+ }
+
+ public int getLinesExecuted() {
+ return linesExecuted;
+ }
+
+ public void incLinesInstrumented(){
+ this.linesInstrumented++;
+ }
+
+ public void incLinesExecuted(){
+ this.linesExecuted++;
+ }
+
+
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Folder.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Folder.java
index 65f3d244ae..00f46b6b86 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Folder.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Folder.java
@@ -15,51 +15,51 @@ import java.util.ArrayList;
public class Folder implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 5155033391199109661L;
- private final String path;
- private final ArrayList<SourceFile> srcFiles = new ArrayList<>();
- private int numLines = 0;
- private int linesInstrumented = 0;
- private int linesExecuted = 0;
-
- /**
- * Constructor
- */
- public Folder(String path) {
- this.path = path;
- }
-
-
- public void accumulateSourcesCounts(){
- for (SourceFile srcFile: srcFiles) {
- numLines += srcFile.getNumLines();
- linesInstrumented += srcFile.getLinesInstrumented();
- linesExecuted += srcFile.getLinesExecuted();
- }
- }
-
- public String getPath() {
- return path;
- }
-
- public ArrayList<SourceFile> getSrcFiles() {
- return srcFiles;
- }
-
- public void addSrcFiles(SourceFile srcFile) {
- this.srcFiles.add(srcFile);
- }
-
- public int getNumLines() {
- return numLines;
- }
- public int getLinesExecuted() {
- return linesExecuted;
- }
- public int getLinesInstrumented() {
- return linesInstrumented;
- }
+ /**
+ *
+ */
+ private static final long serialVersionUID = 5155033391199109661L;
+ private final String path;
+ private final ArrayList<SourceFile> srcFiles = new ArrayList<>();
+ private int numLines = 0;
+ private int linesInstrumented = 0;
+ private int linesExecuted = 0;
+
+ /**
+ * Constructor
+ */
+ public Folder(String path) {
+ this.path = path;
+ }
+
+
+ public void accumulateSourcesCounts(){
+ for (SourceFile srcFile: srcFiles) {
+ numLines += srcFile.getNumLines();
+ linesInstrumented += srcFile.getLinesInstrumented();
+ linesExecuted += srcFile.getLinesExecuted();
+ }
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public ArrayList<SourceFile> getSrcFiles() {
+ return srcFiles;
+ }
+
+ public void addSrcFiles(SourceFile srcFile) {
+ this.srcFiles.add(srcFile);
+ }
+
+ public int getNumLines() {
+ return numLines;
+ }
+ public int getLinesExecuted() {
+ return linesExecuted;
+ }
+ public int getLinesInstrumented() {
+ return linesInstrumented;
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/GcnoFunction.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/GcnoFunction.java
index 54c139c5a7..51c01be56d 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/GcnoFunction.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/GcnoFunction.java
@@ -16,8 +16,8 @@ import java.util.ArrayList;
public class GcnoFunction implements Serializable, Comparable<GcnoFunction> {
/**
- *
- */
+ *
+ */
private static final long serialVersionUID = -4159055012321132651L;
private final long ident;
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Line.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Line.java
index a3fbc5ae34..2629a5f424 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Line.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Line.java
@@ -15,27 +15,27 @@ import java.io.Serializable;
public class Line implements Serializable{
- /** */
- private static final long serialVersionUID = 8804878976767948267L;
- private boolean exists = false;
- private long count = 0;
+ /** */
+ private static final long serialVersionUID = 8804878976767948267L;
+ private boolean exists = false;
+ private long count = 0;
- /*Getters & setters*/
+ /*Getters & setters*/
- public boolean exists() {
- return exists;
- }
+ public boolean exists() {
+ return exists;
+ }
- public void setExists(boolean exists) {
- this.exists = exists;
- }
+ public void setExists(boolean exists) {
+ this.exists = exists;
+ }
- public void setCount(long count) {
- this.count = count;
- }
+ public void setCount(long count) {
+ this.count = count;
+ }
- public long getCount() {
- return count;
- }
+ public long getCount() {
+ return count;
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Messages.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Messages.java
index b89ebec9af..dd18295eaa 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Messages.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/Messages.java
@@ -13,28 +13,28 @@ package org.eclipse.linuxtools.internal.gcov.parser;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.gcov.parser.messages"; //$NON-NLS-1$
- public static String CovManager_Parsing_Done;
- public static String CovManager_Retrieval_Error;
- public static String CovManager_Strings;
- public static String CovManager_Summary;
- public static String CovManager_No_Funcs_Error;
- public static String CovManager_No_FilePath_Error;
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.gcov.parser.messages"; //$NON-NLS-1$
+ public static String CovManager_Parsing_Done;
+ public static String CovManager_Retrieval_Error;
+ public static String CovManager_Strings;
+ public static String CovManager_Summary;
+ public static String CovManager_No_Funcs_Error;
+ public static String CovManager_No_FilePath_Error;
- public static String GcdaRecordsParser_content_inconsistent;
- public static String GcdaRecordsParser_func_block_empty;
- public static String GcdaRecordsParser_func_counter_error;
- public static String GcdaRecordsParser_magic_num_error;
- public static String GcdaRecordsParser_checksum_error;
- public static String GcdaRecordsParser_func_not_found;
- public static String GcnoRecordsParser_null_string;
- public static String GcnoRecordsParser_magic_num_error;
+ public static String GcdaRecordsParser_content_inconsistent;
+ public static String GcdaRecordsParser_func_block_empty;
+ public static String GcdaRecordsParser_func_counter_error;
+ public static String GcdaRecordsParser_magic_num_error;
+ public static String GcdaRecordsParser_checksum_error;
+ public static String GcdaRecordsParser_func_not_found;
+ public static String GcnoRecordsParser_null_string;
+ public static String GcnoRecordsParser_magic_num_error;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/SourceFile.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/SourceFile.java
index 8544a5ca12..b2ac834160 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/SourceFile.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/parser/SourceFile.java
@@ -17,96 +17,96 @@ import java.util.TreeSet;
public class SourceFile implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -9182882194956475711L;
- private final String name;
- private final int index;
- private final ArrayList<Line> lines = new ArrayList<>();
- private final TreeSet<GcnoFunction> fnctns = new TreeSet<>();
- private int numLines = 1;
- private final CoverageInfo cvrge = new CoverageInfo();
- private long maxCount = -1;
-
- /**
- * Constructor
- */
- public SourceFile(String name, int index) {
- this.name = name;
- this.index = index;
- }
-
-
- public void accumulateLineCounts() {
- for (Line line : lines) {
- if (line.exists()) {
- cvrge.incLinesInstrumented();
- if (line.getCount() != 0) {
- cvrge.incLinesExecuted();
- }
- }
- }
- }
-
- public long getmaxLineCount() {
- if (maxCount < 0) {
- for (Line line : lines) {
- if (line.getCount() > maxCount) {
- maxCount = line.getCount();
- }
- }
- }
- return maxCount;
- }
-
- /* getters & setters */
-
-
-
- public int getLinesExecuted() {
- return cvrge.getLinesExecuted();
- }
-
- public int getLinesInstrumented() {
- return cvrge.getLinesInstrumented();
- }
-
- public String getName() {
- return name;
- }
-
- public ArrayList<Line> getLines() {
- return lines;
- }
-
- public SortedSet<GcnoFunction> getFnctns() {
- return fnctns;
- }
-
- public void addFnctn(GcnoFunction fnctn) {
- this.fnctns.add(fnctn);
- }
-
- public int getNumLines() {
- return numLines;
- }
-
- public void setNumLines(int numLines) {
- this.numLines = numLines;
- }
-
- public int getIndex() {
- return index;
- }
-
- public void createLines() {
- int n = getNumLines();
- lines.ensureCapacity(n);
- for (int j = 0; j < n; j++) {
- lines.add(new Line());
- }
- }
-
-
+ /**
+ *
+ */
+ private static final long serialVersionUID = -9182882194956475711L;
+ private final String name;
+ private final int index;
+ private final ArrayList<Line> lines = new ArrayList<>();
+ private final TreeSet<GcnoFunction> fnctns = new TreeSet<>();
+ private int numLines = 1;
+ private final CoverageInfo cvrge = new CoverageInfo();
+ private long maxCount = -1;
+
+ /**
+ * Constructor
+ */
+ public SourceFile(String name, int index) {
+ this.name = name;
+ this.index = index;
+ }
+
+
+ public void accumulateLineCounts() {
+ for (Line line : lines) {
+ if (line.exists()) {
+ cvrge.incLinesInstrumented();
+ if (line.getCount() != 0) {
+ cvrge.incLinesExecuted();
+ }
+ }
+ }
+ }
+
+ public long getmaxLineCount() {
+ if (maxCount < 0) {
+ for (Line line : lines) {
+ if (line.getCount() > maxCount) {
+ maxCount = line.getCount();
+ }
+ }
+ }
+ return maxCount;
+ }
+
+ /* getters & setters */
+
+
+
+ public int getLinesExecuted() {
+ return cvrge.getLinesExecuted();
+ }
+
+ public int getLinesInstrumented() {
+ return cvrge.getLinesInstrumented();
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public ArrayList<Line> getLines() {
+ return lines;
+ }
+
+ public SortedSet<GcnoFunction> getFnctns() {
+ return fnctns;
+ }
+
+ public void addFnctn(GcnoFunction fnctn) {
+ this.fnctns.add(fnctn);
+ }
+
+ public int getNumLines() {
+ return numLines;
+ }
+
+ public void setNumLines(int numLines) {
+ this.numLines = numLines;
+ }
+
+ public int getIndex() {
+ return index;
+ }
+
+ public void createLines() {
+ int n = getNumLines();
+ lines.ensureCapacity(n);
+ for (int j = 0; j < n; j++) {
+ lines.add(new Line());
+ }
+ }
+
+
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/preferences/Messages.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/preferences/Messages.java
index 10c5ff65e0..79a6dc3ea6 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/preferences/Messages.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/preferences/Messages.java
@@ -13,19 +13,19 @@ package org.eclipse.linuxtools.internal.gcov.preferences;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.gcov.preferences.messages"; //$NON-NLS-1$
- public static String ColorPreferencePage_BackColorHighest;
- public static String ColorPreferencePage_BackColorLowest;
- public static String ColorPreferencePage_BackColorNotCovered;
- public static String ColorPreferencePage_ColorizeCode;
- public static String ColorPreferencePage_Description;
- public static String ColorPreferencePage_Title;
- public static String ColorPreferencePage_UseGradient;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.gcov.preferences.messages"; //$NON-NLS-1$
+ public static String ColorPreferencePage_BackColorHighest;
+ public static String ColorPreferencePage_BackColorLowest;
+ public static String ColorPreferencePage_BackColorNotCovered;
+ public static String ColorPreferencePage_ColorizeCode;
+ public static String ColorPreferencePage_Description;
+ public static String ColorPreferencePage_Title;
+ public static String ColorPreferencePage_UseGradient;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/utils/BEDataInputStream.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/utils/BEDataInputStream.java
index e4baf5ab2e..2654767960 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/utils/BEDataInputStream.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/utils/BEDataInputStream.java
@@ -18,67 +18,67 @@ import java.io.IOException;
*/
public class BEDataInputStream implements DataInput {
- private final DataInputStream in;
- private final byte[] buffer = new byte[8];
-
- /**
- * Constructor
- * @param in
- */
- public BEDataInputStream(DataInputStream in) {
- this.in = in;
- }
-
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readShort()
- */
- @Override
- public final short readShort() throws IOException
- {
- return in.readShort();
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readUnsignedShort()
- */
- @Override
- public final int readUnsignedShort() throws IOException
- {
- return in.readUnsignedShort();
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readChar()
- */
- @Override
- public final char readChar() throws IOException
- {
- return in.readChar();
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readInt()
- */
- @Override
- public final int readInt() throws IOException
- {
- return in.readInt();
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readLong()
- */
- @Override
- public final long readLong() throws IOException
- {
- in.readFully(buffer, 0, 8);
- return (((long)buffer[7] << 32) +
+ private final DataInputStream in;
+ private final byte[] buffer = new byte[8];
+
+ /**
+ * Constructor
+ * @param in
+ */
+ public BEDataInputStream(DataInputStream in) {
+ this.in = in;
+ }
+
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readShort()
+ */
+ @Override
+ public final short readShort() throws IOException
+ {
+ return in.readShort();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readUnsignedShort()
+ */
+ @Override
+ public final int readUnsignedShort() throws IOException
+ {
+ return in.readUnsignedShort();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readChar()
+ */
+ @Override
+ public final char readChar() throws IOException
+ {
+ return in.readChar();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readInt()
+ */
+ @Override
+ public final int readInt() throws IOException
+ {
+ return in.readInt();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readLong()
+ */
+ @Override
+ public final long readLong() throws IOException
+ {
+ in.readFully(buffer, 0, 8);
+ return (((long)buffer[7] << 32) +
((long)(buffer[6] & 255) << 40) +
((long)(buffer[5] & 255) << 48) +
((long)(buffer[4] & 255) << 56) +
@@ -86,120 +86,120 @@ public class BEDataInputStream implements DataInput {
((buffer[2] & 255) << 8) +
((buffer[1] & 255) << 16) +
((buffer[0] & 255) << 24));
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readFloat()
- */
- @Override
- public final float readFloat() throws IOException
- {
- return Float.intBitsToFloat(readInt());
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readDouble()
- */
- @Override
- public final double readDouble() throws IOException
- {
- return Double.longBitsToDouble(readLong());
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readBoolean()
- */
- @Override
- public boolean readBoolean() throws IOException {
- return in.readBoolean();
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readByte()
- */
- @Override
- public byte readByte() throws IOException {
- return in.readByte();
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readFully(byte[])
- */
- @Override
- public void readFully(byte[] b) throws IOException {
- in.readFully(b);
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readFully(byte[], int, int)
- */
- @Override
- public void readFully(byte[] b, int off, int len) throws IOException {
- in.readFully(b,off,len);
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readLine()
- */
- @Override
- @Deprecated
- public String readLine() throws IOException {
- return in.readLine();
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readUTF()
- */
- @Override
- public String readUTF() throws IOException {
- return in.readUTF();
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#readUnsignedByte()
- */
- @Override
- public int readUnsignedByte() throws IOException {
- return in.readUnsignedByte();
- }
-
- /*
- * (non-Javadoc)
- * @see java.io.DataInput#skipBytes(int)
- */
- @Override
- public int skipBytes(int n) throws IOException {
- return in.skipBytes(n);
- }
-
- /**
- * Close this stream.
- */
- public void close() throws IOException {
- in.close();
- }
-
- public final long readUnsignedInt() throws IOException
- {
- in.readFully(buffer, 0, 4);
- return
- ((
- (buffer[0]) << 24 |
- (buffer[1]&0xff) << 16 |
- (buffer[2]&0xff) << 8 |
- (buffer[3]&0xff)
- )
- & MasksGenerator.UNSIGNED_INT_MASK );
- }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readFloat()
+ */
+ @Override
+ public final float readFloat() throws IOException
+ {
+ return Float.intBitsToFloat(readInt());
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readDouble()
+ */
+ @Override
+ public final double readDouble() throws IOException
+ {
+ return Double.longBitsToDouble(readLong());
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readBoolean()
+ */
+ @Override
+ public boolean readBoolean() throws IOException {
+ return in.readBoolean();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readByte()
+ */
+ @Override
+ public byte readByte() throws IOException {
+ return in.readByte();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readFully(byte[])
+ */
+ @Override
+ public void readFully(byte[] b) throws IOException {
+ in.readFully(b);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readFully(byte[], int, int)
+ */
+ @Override
+ public void readFully(byte[] b, int off, int len) throws IOException {
+ in.readFully(b,off,len);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readLine()
+ */
+ @Override
+ @Deprecated
+ public String readLine() throws IOException {
+ return in.readLine();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readUTF()
+ */
+ @Override
+ public String readUTF() throws IOException {
+ return in.readUTF();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#readUnsignedByte()
+ */
+ @Override
+ public int readUnsignedByte() throws IOException {
+ return in.readUnsignedByte();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.io.DataInput#skipBytes(int)
+ */
+ @Override
+ public int skipBytes(int n) throws IOException {
+ return in.skipBytes(n);
+ }
+
+ /**
+ * Close this stream.
+ */
+ public void close() throws IOException {
+ in.close();
+ }
+
+ public final long readUnsignedInt() throws IOException
+ {
+ in.readFully(buffer, 0, 4);
+ return
+ ((
+ (buffer[0]) << 24 |
+ (buffer[1]&0xff) << 16 |
+ (buffer[2]&0xff) << 8 |
+ (buffer[3]&0xff)
+ )
+ & MasksGenerator.UNSIGNED_INT_MASK );
+ }
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/utils/MasksGenerator.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/utils/MasksGenerator.java
index eb8a61ba9d..63330ae1e9 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/utils/MasksGenerator.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/utils/MasksGenerator.java
@@ -11,5 +11,5 @@
package org.eclipse.linuxtools.internal.gcov.utils;
public class MasksGenerator {
- public static final long UNSIGNED_INT_MASK = 0xffffffffL;
+ public static final long UNSIGNED_INT_MASK = 0xffffffffL;
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFileContentProvider.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFileContentProvider.java
index 2bdf41efae..bcb8d1f02c 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFileContentProvider.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFileContentProvider.java
@@ -20,41 +20,41 @@ import org.eclipse.linuxtools.internal.gcov.model.TreeElement;
public class CovFileContentProvider extends CovFolderContentProvider {
- public static final CovFileContentProvider sharedInstance = new CovFileContentProvider();
-
- /**
- * Constructor
- */
- protected CovFileContentProvider() {
- }
-
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof CovRootTreeElement) {
- CovRootTreeElement root = (CovRootTreeElement) parentElement;
- LinkedList<? extends TreeElement> ret = getElementChildrenList(root);
- return ret.toArray();
- }
- return super.getChildren(parentElement);
- }
-
- protected LinkedList<? extends TreeElement> getElementChildrenList(CovRootTreeElement root) {
- LinkedList<TreeElement> ret = new LinkedList<>();
- LinkedList<? extends TreeElement> list = root.getChildren();
- for (TreeElement folderlist : list) {
- LinkedList<? extends TreeElement> partialList = folderlist.getChildren();
- ret.addAll(partialList);
- }
- return ret;
- }
-
- @Override
- public Object getParent(Object element) {
- Object o = super.getParent(element);
- if (o instanceof CovFolderTreeElement) {
- o = super.getParent(o);
- }
- return o;
- }
+ public static final CovFileContentProvider sharedInstance = new CovFileContentProvider();
+
+ /**
+ * Constructor
+ */
+ protected CovFileContentProvider() {
+ }
+
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ if (parentElement instanceof CovRootTreeElement) {
+ CovRootTreeElement root = (CovRootTreeElement) parentElement;
+ LinkedList<? extends TreeElement> ret = getElementChildrenList(root);
+ return ret.toArray();
+ }
+ return super.getChildren(parentElement);
+ }
+
+ protected LinkedList<? extends TreeElement> getElementChildrenList(CovRootTreeElement root) {
+ LinkedList<TreeElement> ret = new LinkedList<>();
+ LinkedList<? extends TreeElement> list = root.getChildren();
+ for (TreeElement folderlist : list) {
+ LinkedList<? extends TreeElement> partialList = folderlist.getChildren();
+ ret.addAll(partialList);
+ }
+ return ret;
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ Object o = super.getParent(element);
+ if (o instanceof CovFolderTreeElement) {
+ o = super.getParent(o);
+ }
+ return o;
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFolderContentProvider.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFolderContentProvider.java
index 16e872f67e..1915efbb29 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFolderContentProvider.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFolderContentProvider.java
@@ -20,57 +20,57 @@ import org.eclipse.linuxtools.internal.gcov.parser.CovManager;
public class CovFolderContentProvider implements ITreeContentProvider {
- /** Shared instance: this class is implemented as a Singleton */
- public static final CovFolderContentProvider sharedInstance = new CovFolderContentProvider();
+ /** Shared instance: this class is implemented as a Singleton */
+ public static final CovFolderContentProvider sharedInstance = new CovFolderContentProvider();
- protected CovFolderContentProvider(){
- }
+ protected CovFolderContentProvider(){
+ }
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof TreeElement) {
- TreeElement elem = (TreeElement) parentElement;
- LinkedList<? extends TreeElement> list = elem.getChildren();
- if (list != null)
- return list.toArray();
- }
- return null;
- }
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ if (parentElement instanceof TreeElement) {
+ TreeElement elem = (TreeElement) parentElement;
+ LinkedList<? extends TreeElement> list = elem.getChildren();
+ if (list != null)
+ return list.toArray();
+ }
+ return null;
+ }
- @Override
- public Object getParent(Object element) {
- if (element instanceof TreeElement) {
- TreeElement elem = (TreeElement) element;
- return elem.getParent();
- }
- return null;
- }
+ @Override
+ public Object getParent(Object element) {
+ if (element instanceof TreeElement) {
+ TreeElement elem = (TreeElement) element;
+ return elem.getParent();
+ }
+ return null;
+ }
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof TreeElement) {
- TreeElement elem = (TreeElement) element;
- return elem.hasChildren();
- }
- return false;
- }
+ @Override
+ public boolean hasChildren(Object element) {
+ if (element instanceof TreeElement) {
+ TreeElement elem = (TreeElement) element;
+ return elem.hasChildren();
+ }
+ return false;
+ }
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof CovManager) {
- CovManager cvrgMnger = (CovManager)inputElement;
- return new Object[] {
- cvrgMnger.getRootNode()
- };
- }
- return new Object[0];
- }
+ @Override
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof CovManager) {
+ CovManager cvrgMnger = (CovManager)inputElement;
+ return new Object[] {
+ cvrgMnger.getRootNode()
+ };
+ }
+ return new Object[0];
+ }
- @Override
- public void dispose() {
- }
+ @Override
+ public void dispose() {
+ }
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFunctionContentProvider.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFunctionContentProvider.java
index 9b4dabf81d..56b71b8e35 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFunctionContentProvider.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovFunctionContentProvider.java
@@ -21,33 +21,33 @@ import org.eclipse.linuxtools.internal.gcov.model.TreeElement;
public class CovFunctionContentProvider extends CovFileContentProvider {
- public static final CovFunctionContentProvider sharedInstance = new CovFunctionContentProvider();
-
- /**
- * Constructor
- */
- protected CovFunctionContentProvider() {
- }
-
- @Override
- protected LinkedList<? extends TreeElement> getElementChildrenList(CovRootTreeElement root) {
- LinkedList<? extends TreeElement> list = super.getElementChildrenList(root);
- LinkedList<TreeElement> ret = new LinkedList<>();
- for (TreeElement histTreeElem : list) {
- LinkedList<? extends TreeElement> partialList = histTreeElem.getChildren();
- ret.addAll(partialList);
- }
- return ret;
- }
-
-
- @Override
- public Object getParent(Object element) {
- Object o = super.getParent(element);
- if (o instanceof CovFileTreeElement) {
- o = super.getParent(o);
- }
- return o;
- }
+ public static final CovFunctionContentProvider sharedInstance = new CovFunctionContentProvider();
+
+ /**
+ * Constructor
+ */
+ protected CovFunctionContentProvider() {
+ }
+
+ @Override
+ protected LinkedList<? extends TreeElement> getElementChildrenList(CovRootTreeElement root) {
+ LinkedList<? extends TreeElement> list = super.getElementChildrenList(root);
+ LinkedList<TreeElement> ret = new LinkedList<>();
+ for (TreeElement histTreeElem : list) {
+ LinkedList<? extends TreeElement> partialList = histTreeElem.getChildren();
+ ret.addAll(partialList);
+ }
+ return ret;
+ }
+
+
+ @Override
+ public Object getParent(Object element) {
+ Object o = super.getParent(element);
+ if (o instanceof CovFileTreeElement) {
+ o = super.getParent(o);
+ }
+ return o;
+ }
} \ No newline at end of file
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovViewer.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovViewer.java
index b311a70462..b474157764 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovViewer.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/CovViewer.java
@@ -35,75 +35,75 @@ import org.eclipse.swt.widgets.Composite;
public class CovViewer extends AbstractSTTreeViewer {
- private ISTDataViewersField[] fields;
+ private ISTDataViewersField[] fields;
- /**
- * Constructor
- * @param parent
- */
- public CovViewer(Composite parent) {
- super(parent, SWT.BORDER | SWT.H_SCROLL| SWT.V_SCROLL | SWT.MULTI |
- SWT.FULL_SELECTION);
- }
+ /**
+ * Constructor
+ * @param parent
+ */
+ public CovViewer(Composite parent) {
+ super(parent, SWT.BORDER | SWT.H_SCROLL| SWT.V_SCROLL | SWT.MULTI |
+ SWT.FULL_SELECTION);
+ }
- @Override
- protected IContentProvider createContentProvider() {
- return CovFileContentProvider.sharedInstance;
+ @Override
+ protected IContentProvider createContentProvider() {
+ return CovFileContentProvider.sharedInstance;
- }
+ }
- @Override
- public ISTDataViewersField[] getAllFields() {
- if (fields == null) {
- fields = new ISTDataViewersField[] {
- new FieldName(),
- new FieldTotalLines(),
- new FieldInstrumentedLines(),
- new FieldExecutedLines(),
- new FieldCoveragePercentage() };
- }
- return fields;
- }
+ @Override
+ public ISTDataViewersField[] getAllFields() {
+ if (fields == null) {
+ fields = new ISTDataViewersField[] {
+ new FieldName(),
+ new FieldTotalLines(),
+ new FieldInstrumentedLines(),
+ new FieldExecutedLines(),
+ new FieldCoveragePercentage() };
+ }
+ return fields;
+ }
- @Override
- public IDialogSettings getDialogSettings() {
- return org.eclipse.linuxtools.internal.gcov.Activator.getDefault().getDialogSettings();
- }
+ @Override
+ public IDialogSettings getDialogSettings() {
+ return org.eclipse.linuxtools.internal.gcov.Activator.getDefault().getDialogSettings();
+ }
- @Override
- protected void handleOpenEvent(OpenEvent event) {
+ @Override
+ protected void handleOpenEvent(OpenEvent event) {
- IStructuredSelection selection = (IStructuredSelection) event
- .getSelection();
- TreeElement element = (TreeElement) selection.getFirstElement();
+ IStructuredSelection selection = (IStructuredSelection) event
+ .getSelection();
+ TreeElement element = (TreeElement) selection.getFirstElement();
- if (element != null) {
- if (element.getParent() != null) {
- String sourceLoc = ""; //$NON-NLS-1$
- long lineNumber = 0;
+ if (element != null) {
+ if (element.getParent() != null) {
+ String sourceLoc = ""; //$NON-NLS-1$
+ long lineNumber = 0;
- if (element.getClass() == CovFileTreeElement.class) {
- sourceLoc = element.getName();
- } else if (element.getClass() == CovFunctionTreeElement.class) {
- sourceLoc = ((CovFunctionTreeElement) element).getSourceFilePath();
- lineNumber =((CovFunctionTreeElement)element).getFirstLnNmbr();
- }
- CovManager cvm = (CovManager) this.getInput();
- SourceFile sourceFile = cvm.getSourceFile(sourceLoc);
- if (sourceFile != null) {
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- String binaryLoc = cvm.getBinaryPath();
- IPath binaryPath = new Path(binaryLoc);
- IFile binary = root.getFileForLocation(binaryPath);
- IProject project = null;
- if (binary != null) {
- project = binary.getProject();
- }
+ if (element.getClass() == CovFileTreeElement.class) {
+ sourceLoc = element.getName();
+ } else if (element.getClass() == CovFunctionTreeElement.class) {
+ sourceLoc = ((CovFunctionTreeElement) element).getSourceFilePath();
+ lineNumber =((CovFunctionTreeElement)element).getFirstLnNmbr();
+ }
+ CovManager cvm = (CovManager) this.getInput();
+ SourceFile sourceFile = cvm.getSourceFile(sourceLoc);
+ if (sourceFile != null) {
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ String binaryLoc = cvm.getBinaryPath();
+ IPath binaryPath = new Path(binaryLoc);
+ IFile binary = root.getFileForLocation(binaryPath);
+ IProject project = null;
+ if (binary != null) {
+ project = binary.getProject();
+ }
- OpenSourceFileAction.openAnnotatedSourceFile(project,
- binary, sourceFile, (int)lineNumber);
- }
- }
- }
- }
+ OpenSourceFileAction.openAnnotatedSourceFile(project,
+ binary, sourceFile, (int)lineNumber);
+ }
+ }
+ }
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/annotatedsource/GcovAnnotationModel.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/annotatedsource/GcovAnnotationModel.java
index cfd5fe7334..03e8e8430d 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/annotatedsource/GcovAnnotationModel.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/annotatedsource/GcovAnnotationModel.java
@@ -49,9 +49,9 @@ import org.eclipse.ui.texteditor.ITextEditor;
*/
public final class GcovAnnotationModel implements IAnnotationModel {
- private static final String THOROUGH_COVERAGE = "org.eclipse.linuxtools.gcov.ThoroughCoverageAnnotation"; //$NON-NLS-1$
- private static final String COVERAGE = "org.eclipse.linuxtools.gcov.CoverageAnnotation"; //$NON-NLS-1$
- private static final String NO_COVERAGE = "org.eclipse.linuxtools.gcov.NoCoverageAnnotation"; //$NON-NLS-1$
+ private static final String THOROUGH_COVERAGE = "org.eclipse.linuxtools.gcov.ThoroughCoverageAnnotation"; //$NON-NLS-1$
+ private static final String COVERAGE = "org.eclipse.linuxtools.gcov.CoverageAnnotation"; //$NON-NLS-1$
+ private static final String NO_COVERAGE = "org.eclipse.linuxtools.gcov.NoCoverageAnnotation"; //$NON-NLS-1$
/** Key for identifying our model from other Editor models. */
private static final Object KEY = new Object();
diff --git a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/annotatedsource/STAnnotatedSourceNotFoundEditorInput.java b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/annotatedsource/STAnnotatedSourceNotFoundEditorInput.java
index b3f89e5322..191116aeae 100644
--- a/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/annotatedsource/STAnnotatedSourceNotFoundEditorInput.java
+++ b/gcov/org.eclipse.linuxtools.gcov.core/src/org/eclipse/linuxtools/internal/gcov/view/annotatedsource/STAnnotatedSourceNotFoundEditorInput.java
@@ -18,53 +18,53 @@ import org.eclipse.linuxtools.internal.gcov.parser.SourceFile;
public class STAnnotatedSourceNotFoundEditorInput extends STCSourceNotFoundEditorInput {
- private final SourceFile sourceFile;
-
- public STAnnotatedSourceNotFoundEditorInput(IProject project,
- SourceFile sourceFile,
- IPath sourcePath, int lineNumber) {
- super(project, sourcePath, lineNumber);
- this.sourceFile = sourceFile;
- }
+ private final SourceFile sourceFile;
- /**
- * @return the sourceFile
- */
- public SourceFile getSourceFile() {
- return sourceFile;
- }
+ public STAnnotatedSourceNotFoundEditorInput(IProject project,
+ SourceFile sourceFile,
+ IPath sourcePath, int lineNumber) {
+ super(project, sourcePath, lineNumber);
+ this.sourceFile = sourceFile;
+ }
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result
- + ((sourceFile == null) ? 0 : sourceFile.hashCode());
- return result;
- }
+ /**
+ * @return the sourceFile
+ */
+ public SourceFile getSourceFile() {
+ return sourceFile;
+ }
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!super.equals(obj))
- return false;
- if (getClass() != obj.getClass())
- return false;
- final STAnnotatedSourceNotFoundEditorInput other = (STAnnotatedSourceNotFoundEditorInput) obj;
- if (sourceFile == null) {
- if (other.sourceFile != null) {
- return false;
- }
- } else if (!sourceFile.equals(other.sourceFile))
- return false;
- return true;
- }
+ /* (non-Javadoc)
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = super.hashCode();
+ result = prime * result
+ + ((sourceFile == null) ? 0 : sourceFile.hashCode());
+ return result;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (!super.equals(obj))
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ final STAnnotatedSourceNotFoundEditorInput other = (STAnnotatedSourceNotFoundEditorInput) obj;
+ if (sourceFile == null) {
+ if (other.sourceFile != null) {
+ return false;
+ }
+ } else if (!sourceFile.equals(other.sourceFile))
+ return false;
+ return true;
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.docs/build-helper.xml b/gcov/org.eclipse.linuxtools.gcov.docs/build-helper.xml
index 8b2a68cdf4..73561c4eaf 100644
--- a/gcov/org.eclipse.linuxtools.gcov.docs/build-helper.xml
+++ b/gcov/org.eclipse.linuxtools.gcov.docs/build-helper.xml
@@ -5,7 +5,7 @@
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-
+
Contributors:
Red Hat - initial API and implementation
-->
@@ -14,58 +14,58 @@
Generate Eclipse help content for the Linux Tools gcov user guide
</description>
- <property name="gcov.help.doc.url.base" value="http://wiki.eclipse.org"/>
- <property name="gcov.wiki.url.base" value="${gcov.help.doc.url.base}/Linux_Tools_Project/GCov"/>
- <property name="imageFolder" value="images"/>
+ <property name="gcov.help.doc.url.base" value="http://wiki.eclipse.org"/>
+ <property name="gcov.wiki.url.base" value="${gcov.help.doc.url.base}/Linux_Tools_Project/GCov"/>
+ <property name="imageFolder" value="images"/>
- <path id="wikitext.tasks.classpath">
- <!-- Replace dir with the dir you have wikitext installed into.-->
- <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
- <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
- </fileset>
- </path>
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
+ <path id="wikitext.tasks.classpath">
+ <!-- Replace dir with the dir you have wikitext installed into.-->
+ <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
+ <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
+ </fileset>
+ </path>
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
- <target name="all" description="Generate Eclipse help content for the Linux Tools gcov user guide">
- <mediawiki-to-eclipse-help wikiBaseUrl="${gcov.help.doc.url.base}" title="GCov User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
+ <target name="all" description="Generate Eclipse help content for the Linux Tools gcov user guide">
+ <mediawiki-to-eclipse-help wikiBaseUrl="${gcov.help.doc.url.base}" title="GCov User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
- <path name="Linux_Tools_Project/GCov/User_Guide" title="GCov Plug-in User Guide" generateToc="false"/>
- <stylesheet url="book.css" />
- <pageAppendum>
+ <path name="Linux_Tools_Project/GCov/User_Guide" title="GCov Plug-in User Guide" generateToc="false"/>
+ <stylesheet url="book.css" />
+ <pageAppendum>
= Updating This Document =
-
-This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
+
+This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
http://wiki.eclipse.org/Linux_Tools_Project/GCov/User_Guide
</pageAppendum>
- </mediawiki-to-eclipse-help>
- <antcall target="test" />
- </target>
+ </mediawiki-to-eclipse-help>
+ <antcall target="test" />
+ </target>
- <target name="test" description="verify that all of the HTML files are well-formed XML">
- <echo level="info">
+ <target name="test" description="verify that all of the HTML files are well-formed XML">
+ <echo level="info">
Validating help content XML and HTML files: The Eclipse help system expects well-formed XML
-
+
If validation fails it is because either:
-
+
* the userguide source code is poorly formed, or
* the WikiText MediaWiki parser has a bug
-
+
Problems with userguide source are usually caused by improper use of HTML markup in the MediaWiki source,
or inadvertently starting a line with a space character (in MediaWiki this starts a preformatted block)
- </echo>
+ </echo>
- <!--
- Don't bother with DTD validation: we only care if the files are well-formed.
- We therefore provide an empty DTD
- -->
- <echo file="tmp/__empty.dtd" message="" />
- <xmlvalidate lenient="true">
- <fileset dir="Linux_Tools_Project">
- <include name="**/*.html" />
- </fileset>
- <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
- </xmlvalidate>
- <delete dir="tmp"/>
- </target>
+ <!--
+ Don't bother with DTD validation: we only care if the files are well-formed.
+ We therefore provide an empty DTD
+ -->
+ <echo file="tmp/__empty.dtd" message="" />
+ <xmlvalidate lenient="true">
+ <fileset dir="Linux_Tools_Project">
+ <include name="**/*.html" />
+ </fileset>
+ <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
+ </xmlvalidate>
+ <delete dir="tmp"/>
+ </target>
</project>
diff --git a/gcov/org.eclipse.linuxtools.gcov.docs/toc.xml b/gcov/org.eclipse.linuxtools.gcov.docs/toc.xml
index 603e401e10..aad7a23e6d 100644
--- a/gcov/org.eclipse.linuxtools.gcov.docs/toc.xml
+++ b/gcov/org.eclipse.linuxtools.gcov.docs/toc.xml
@@ -1,12 +1,12 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/GCov/User_Guide/User-Guide.html" label="GCov User Guide">
- <topic href="Linux_Tools_Project/GCov/User_Guide/User-Guide.html" label="GCov Plug-in User Guide">
- <topic href="Linux_Tools_Project/GCov/User_Guide/User-Guide.html" label="Overview"></topic>
- <topic href="Linux_Tools_Project/GCov/User_Guide/Installation-and-Set-Up.html" label="Installation and Set-Up"></topic>
- <topic href="Linux_Tools_Project/GCov/User_Guide/Opening-gcov-result.html" label="Opening gcov result"></topic>
- <topic href="Linux_Tools_Project/GCov/User_Guide/Profiling-Code-Coverage.html" label="Profiling Code Coverage"></topic>
- <topic href="Linux_Tools_Project/GCov/User_Guide/Gcov-main-view.html" label="Gcov main view"></topic>
- <topic href="Linux_Tools_Project/GCov/User_Guide/Troubleshooting.html" label="Troubleshooting"></topic>
- <topic href="Linux_Tools_Project/GCov/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
- </topic>
+ <topic href="Linux_Tools_Project/GCov/User_Guide/User-Guide.html" label="GCov Plug-in User Guide">
+ <topic href="Linux_Tools_Project/GCov/User_Guide/User-Guide.html" label="Overview"></topic>
+ <topic href="Linux_Tools_Project/GCov/User_Guide/Installation-and-Set-Up.html" label="Installation and Set-Up"></topic>
+ <topic href="Linux_Tools_Project/GCov/User_Guide/Opening-gcov-result.html" label="Opening gcov result"></topic>
+ <topic href="Linux_Tools_Project/GCov/User_Guide/Profiling-Code-Coverage.html" label="Profiling Code Coverage"></topic>
+ <topic href="Linux_Tools_Project/GCov/User_Guide/Gcov-main-view.html" label="Gcov main view"></topic>
+ <topic href="Linux_Tools_Project/GCov/User_Guide/Troubleshooting.html" label="Troubleshooting"></topic>
+ <topic href="Linux_Tools_Project/GCov/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
+ </topic>
</toc> \ No newline at end of file
diff --git a/gcov/org.eclipse.linuxtools.gcov.launch/plugin.xml b/gcov/org.eclipse.linuxtools.gcov.launch/plugin.xml
index 32b82373cf..5039066a27 100644
--- a/gcov/org.eclipse.linuxtools.gcov.launch/plugin.xml
+++ b/gcov/org.eclipse.linuxtools.gcov.launch/plugin.xml
@@ -12,5 +12,5 @@
tabgroup="org.eclipse.linuxtools.internal.gcov.launch.GcovLaunchConfigurationTabGroup"
type="coverage">
</provider>
- </extension>
+ </extension>
</plugin>
diff --git a/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchConfigurationDelegate.java b/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchConfigurationDelegate.java
index 123083e7b2..d562a61396 100644
--- a/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchConfigurationDelegate.java
+++ b/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchConfigurationDelegate.java
@@ -41,118 +41,118 @@ import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
public class GcovLaunchConfigurationDelegate extends AbstractCLaunchDelegate {
- protected ILaunchConfiguration config;
-
- @Override
- public void launch(ILaunchConfiguration config, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException {
- this.config = config;
- IPath exePath = getExePath(config);
-
- /*
- * this code written by QNX Software Systems and others and was
- * originally in the CDT under LocalCDILaunchDelegate::RunLocalApplication
- */
- //set up and launch the local c/c++ program
- IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(getProject());
-
- File workDir = getWorkingDirectory(config);
- if (workDir == null) {
- workDir = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
- }
- String arguments[] = getProgramArgumentsArray( config );
-
- //add a listener for termination of the launch
- ILaunchManager lmgr = DebugPlugin.getDefault().getLaunchManager();
- lmgr.addLaunchListener(new LaunchTerminationWatcher(launch, exePath));
-
- Process process = launcher.execute(exePath, arguments, getEnvironment(config), new Path(workDir.getAbsolutePath()), monitor);
-
- DebugPlugin.newProcess( launch, process, renderProcessLabel( exePath.toOSString() ) );
-
- }
-
- //A class used to listen for the termination of the current launch, and
- // run some functions when it is finished.
- class LaunchTerminationWatcher implements ILaunchesListener2 {
- private ILaunch launch;
- private IPath exePath;
- public LaunchTerminationWatcher(ILaunch il, IPath exePath) {
- launch = il;
- this.exePath = exePath;
- }
- @Override
- public void launchesTerminated(ILaunch[] launches) {
-
- for (ILaunch l : launches) {
- /**
- * Dump samples from the daemon,
- * shut down the daemon,
- * activate the OProfile view (open it if it isn't already),
- * refresh the view (which parses the data/ui model and displays it).
- */
- if (l.equals(launch)) {
- //need to run this in the ui thread otherwise get SWT Exceptions
- // based on concurrency issues
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- String s = exePath.toOSString();
- CovManager cvrgeMnger = new CovManager(s, getProject());
-
- try {
- List<String> gcdaPaths = cvrgeMnger.getGCDALocations();
- if (gcdaPaths.isEmpty()) {
- String title = GcovLaunchMessages.GcovCompilerOptions_msg;
- String message = GcovLaunchMessages.GcovCompileAgain_msg;
- Shell parent = PlatformUI.getWorkbench().getDisplay().getActiveShell();
- MessageDialog.openWarning(parent, title, message);
- }
- CovView.displayCovResults(s, null);
- GcovAnnotationModelTracker.getInstance().addProject(getProject(), exePath);
- GcovAnnotationModelTracker.getInstance().annotateAllCEditors();
- } catch (InterruptedException e) {
- // Do nothing
- }
- }
- });
- }
- }
-
- }
- @Override
- public void launchesAdded(ILaunch[] launches) { /* dont care */}
- @Override
- public void launchesChanged(ILaunch[] launches) { /* dont care */ }
- @Override
- public void launchesRemoved(ILaunch[] launches) { /* dont care */ }
-
- }
-
- @Override
- protected String getPluginID() {
- return GcovLaunchPlugin.PLUGIN_ID;
- }
-
- /* all these functions exist to be overridden by the test class in order to allow launch testing */
-
- private IProject getProject(){
- try{
- return CDebugUtils.verifyCProject(config).getProject();
- } catch (CoreException e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- *
- * Return the exe path of the binary to be profiled.
- * @param config
- * @return the exe path of the binary stored in the configuration
- * @throws CoreException
- * @since 1.1
- */
- private static IPath getExePath(ILaunchConfiguration config) throws CoreException{
- return CDebugUtils.verifyProgramPath( config );
- }
+ protected ILaunchConfiguration config;
+
+ @Override
+ public void launch(ILaunchConfiguration config, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException {
+ this.config = config;
+ IPath exePath = getExePath(config);
+
+ /*
+ * this code written by QNX Software Systems and others and was
+ * originally in the CDT under LocalCDILaunchDelegate::RunLocalApplication
+ */
+ //set up and launch the local c/c++ program
+ IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(getProject());
+
+ File workDir = getWorkingDirectory(config);
+ if (workDir == null) {
+ workDir = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ String arguments[] = getProgramArgumentsArray( config );
+
+ //add a listener for termination of the launch
+ ILaunchManager lmgr = DebugPlugin.getDefault().getLaunchManager();
+ lmgr.addLaunchListener(new LaunchTerminationWatcher(launch, exePath));
+
+ Process process = launcher.execute(exePath, arguments, getEnvironment(config), new Path(workDir.getAbsolutePath()), monitor);
+
+ DebugPlugin.newProcess( launch, process, renderProcessLabel( exePath.toOSString() ) );
+
+ }
+
+ //A class used to listen for the termination of the current launch, and
+ // run some functions when it is finished.
+ class LaunchTerminationWatcher implements ILaunchesListener2 {
+ private ILaunch launch;
+ private IPath exePath;
+ public LaunchTerminationWatcher(ILaunch il, IPath exePath) {
+ launch = il;
+ this.exePath = exePath;
+ }
+ @Override
+ public void launchesTerminated(ILaunch[] launches) {
+
+ for (ILaunch l : launches) {
+ /**
+ * Dump samples from the daemon,
+ * shut down the daemon,
+ * activate the OProfile view (open it if it isn't already),
+ * refresh the view (which parses the data/ui model and displays it).
+ */
+ if (l.equals(launch)) {
+ //need to run this in the ui thread otherwise get SWT Exceptions
+ // based on concurrency issues
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ String s = exePath.toOSString();
+ CovManager cvrgeMnger = new CovManager(s, getProject());
+
+ try {
+ List<String> gcdaPaths = cvrgeMnger.getGCDALocations();
+ if (gcdaPaths.isEmpty()) {
+ String title = GcovLaunchMessages.GcovCompilerOptions_msg;
+ String message = GcovLaunchMessages.GcovCompileAgain_msg;
+ Shell parent = PlatformUI.getWorkbench().getDisplay().getActiveShell();
+ MessageDialog.openWarning(parent, title, message);
+ }
+ CovView.displayCovResults(s, null);
+ GcovAnnotationModelTracker.getInstance().addProject(getProject(), exePath);
+ GcovAnnotationModelTracker.getInstance().annotateAllCEditors();
+ } catch (InterruptedException e) {
+ // Do nothing
+ }
+ }
+ });
+ }
+ }
+
+ }
+ @Override
+ public void launchesAdded(ILaunch[] launches) { /* dont care */}
+ @Override
+ public void launchesChanged(ILaunch[] launches) { /* dont care */ }
+ @Override
+ public void launchesRemoved(ILaunch[] launches) { /* dont care */ }
+
+ }
+
+ @Override
+ protected String getPluginID() {
+ return GcovLaunchPlugin.PLUGIN_ID;
+ }
+
+ /* all these functions exist to be overridden by the test class in order to allow launch testing */
+
+ private IProject getProject(){
+ try{
+ return CDebugUtils.verifyCProject(config).getProject();
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+ /**
+ *
+ * Return the exe path of the binary to be profiled.
+ * @param config
+ * @return the exe path of the binary stored in the configuration
+ * @throws CoreException
+ * @since 1.1
+ */
+ private static IPath getExePath(ILaunchConfiguration config) throws CoreException{
+ return CDebugUtils.verifyProgramPath( config );
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchConfigurationTabGroup.java b/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchConfigurationTabGroup.java
index 845fb5ad02..3a115cf790 100644
--- a/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchConfigurationTabGroup.java
+++ b/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchConfigurationTabGroup.java
@@ -7,18 +7,18 @@
*
* Contributors:
* Red Hat Inc. - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.gcov.launch;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTabGroup;
public class GcovLaunchConfigurationTabGroup extends
- ProfileLaunchConfigurationTabGroup {
+ ProfileLaunchConfigurationTabGroup {
+
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ return new AbstractLaunchConfigurationTab[0];
+ }
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- return new AbstractLaunchConfigurationTab[0];
- }
-
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchMessages.java b/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchMessages.java
index 16537adcf9..a9b0d25c4f 100644
--- a/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchMessages.java
+++ b/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchMessages.java
@@ -14,11 +14,11 @@ import org.eclipse.osgi.util.NLS;
public class GcovLaunchMessages extends NLS {
- public static String GcovCompilerOptions_msg;
- public static String GcovCompileAgain_msg;
+ public static String GcovCompilerOptions_msg;
+ public static String GcovCompileAgain_msg;
- static {
- NLS.initializeMessages(GcovLaunchMessages.class.getName(), GcovLaunchMessages.class);
- }
+ static {
+ NLS.initializeMessages(GcovLaunchMessages.class.getName(), GcovLaunchMessages.class);
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchPlugin.java b/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchPlugin.java
index 6ddafaddec..800e3d6564 100644
--- a/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchPlugin.java
+++ b/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchPlugin.java
@@ -16,10 +16,10 @@ package org.eclipse.linuxtools.internal.gcov.launch;
* The main plugin class to be used in the desktop.
*/
public class GcovLaunchPlugin {
- //shared cache instance for configuration
+ //shared cache instance for configuration
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.gcov.launch"; //$NON-NLS-1$
- public static final String ID_GCOV_VIEW = "org.eclipse.linuxtools.gcov.view"; //$NON-NLS-1$
- public static final String LAUNCH_ID = PLUGIN_ID + ".gcovLaunch"; //$NON-NLS-1$
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.gcov.launch"; //$NON-NLS-1$
+ public static final String ID_GCOV_VIEW = "org.eclipse.linuxtools.gcov.view"; //$NON-NLS-1$
+ public static final String LAUNCH_ID = PLUGIN_ID + ".gcovLaunch"; //$NON-NLS-1$
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchShortcut.java b/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchShortcut.java
index e738f532f5..c5536ab836 100644
--- a/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchShortcut.java
+++ b/gcov/org.eclipse.linuxtools.gcov.launch/src/org/eclipse/linuxtools/internal/gcov/launch/GcovLaunchShortcut.java
@@ -8,7 +8,7 @@
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
* Red Hat Inc. - modification to use code in this plug-in
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.gcov.launch;
import org.eclipse.debug.core.ILaunchConfigurationType;
@@ -18,18 +18,18 @@ import org.eclipse.linuxtools.profiling.launch.ProfileLaunchShortcut;
public class GcovLaunchShortcut extends ProfileLaunchShortcut {
- @Override
- protected void setDefaultProfileAttributes(
- ILaunchConfigurationWorkingCopy wc) {
- }
+ @Override
+ protected void setDefaultProfileAttributes(
+ ILaunchConfigurationWorkingCopy wc) {
+ }
- /**
- * Method getValgrindLaunchConfigType.
- * @return ILaunchConfigurationType
- */
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(GcovLaunchPlugin.LAUNCH_ID);
- }
+ /**
+ * Method getValgrindLaunchConfigType.
+ * @return ILaunchConfigurationType
+ */
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(GcovLaunchPlugin.LAUNCH_ID);
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.test/pom.xml b/gcov/org.eclipse.linuxtools.gcov.test/pom.xml
index 720424295a..6f3b4e3349 100644
--- a/gcov/org.eclipse.linuxtools.gcov.test/pom.xml
+++ b/gcov/org.eclipse.linuxtools.gcov.test/pom.xml
@@ -36,7 +36,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.gcov.test</testSuite>
<testClass>org.eclipse.linuxtools.internal.gcov.test.AllGcovTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>false</useUIThread>
<product>org.eclipse.platform.ide</product>
<dependencies>
@@ -50,7 +50,7 @@
<artifactId>org.eclipse.platform.feature.group</artifactId>
<version>${sdk-version}</version>
</dependency>
- </dependencies>
+ </dependencies>
</configuration>
</plugin>
</plugins>
diff --git a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/AllGcovTests.java b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/AllGcovTests.java
index 83c006133e..c2a8fabc05 100644
--- a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/AllGcovTests.java
+++ b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/AllGcovTests.java
@@ -5,9 +5,9 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
- GcovTestC.class,
- GcovTestCPP.class,
- GcovTestCLibrary.class
+ GcovTestC.class,
+ GcovTestCPP.class,
+ GcovTestCLibrary.class
})
public class AllGcovTests {
diff --git a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTest.java b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTest.java
index b423f3278d..0e4893b964 100644
--- a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTest.java
+++ b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTest.java
@@ -53,453 +53,453 @@ import org.junit.After;
import org.osgi.framework.FrameworkUtil;
public abstract class GcovTest {
- private static final String PROJECT_EXPLORER = "Project Explorer";
- private static SWTBotView projectExplorer;
- private static SWTBotShell mainShell;
-
- private static final class UnCheckTest implements ICondition {
- SWTBotCheckBox checkBox;
-
- public UnCheckTest(SWTBotCheckBox bot) {
- checkBox = bot;
- }
-
- @Override
- public boolean test() {
- return !checkBox.isChecked();
- }
-
- @Override
- public void init(SWTBot bot) {
- }
-
- @Override
- public String getFailureMessage() {
- return null;
- }
- }
-
- private static class NodeAvailableAndSelect extends DefaultCondition {
-
- private SWTBotTree tree;
- private String parent;
- private String node;
-
- /**
- * Wait for a tree node (with a known parent) to become visible, and select it
- * when it does. Note that this wait condition should only be used after having
- * made an attempt to reveal the node.
- * @param tree The SWTBotTree that contains the node to select.
- * @param parent The text of the parent node that contains the node to select.
- * @param node The text of the node to select.
- */
- NodeAvailableAndSelect(SWTBotTree tree, String parent, String node){
- this.tree = tree;
- this.node = node;
- this.parent = parent;
- }
-
- @Override
- public boolean test() {
- try {
- SWTBotTreeItem parentNode = tree.getTreeItem(parent);
- parentNode.getNode(node).select();
- return true;
- } catch (WidgetNotFoundException e) {
- return false;
- }
- }
-
- @Override
- public String getFailureMessage() {
- return "Timed out waiting for " + node; //$NON-NLS-1$
- }
- }
-
- public static SWTWorkbenchBot init(String PROJECT_NAME, String PROJECT_TYPE)
- throws Exception {
- SWTWorkbenchBot bot = new SWTWorkbenchBot();
- bot.captureScreenshot(PROJECT_NAME + ".beforeClass.1.jpg");
- try {
- bot.viewByTitle("Welcome").close();
- // hide Subclipse Usage stats popup if present/installed
- bot.shell("Subclipse Usage").activate();
- bot.button("Cancel").click();
- } catch (WidgetNotFoundException e) {
- // ignore
- }
-
- bot.perspectiveByLabel("C/C++").activate();
- for (SWTBotShell sh : bot.shells()) {
- if (sh.getText().startsWith("C/C++")) {
- sh.activate();
- bot.waitUntil(Conditions.shellIsActive(sh.getText()));
- mainShell = sh;
- break;
- }
- }
-
- bot.captureScreenshot(PROJECT_NAME + ".beforeClass.2.jpg");
- // Turn off automatic building by default
- SWTBotMenu windowsMenu = bot.menu("Window");
- windowsMenu.menu("Preferences").click();
- SWTBotShell shell = bot.shell("Preferences");
- shell.activate();
- bot.text().setText("Workspace");
- bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "General", "Workspace"));
- SWTBotCheckBox buildAuto = bot.checkBox("Build automatically");
- if (buildAuto != null && buildAuto.isChecked()) {
- buildAuto.click();
- }
- bot.waitUntil(new UnCheckTest(buildAuto));
- bot.button("Apply").click();
- bot.button("OK").click();
- bot.waitUntil(Conditions.shellCloses(shell));
-
-
- // define & repopulate project explorer
- projectExplorer = bot.viewByTitle(PROJECT_EXPLORER);
- GcovTest.createProject(bot, PROJECT_NAME, PROJECT_TYPE);
- GcovTest.populateProject(bot, PROJECT_NAME);
- GcovTest.compileProject(bot, PROJECT_NAME);
- return bot;
- }
-
- @After
- public void cleanUp() {
- SWTWorkbenchBot bot = new SWTWorkbenchBot();
- SWTBotShell[] shells = bot.shells();
- for (final SWTBotShell shell : shells) {
- String shellTitle = shell.getText();
- if (shellTitle.length() > 0
- && !shellTitle.startsWith("SystemTap IDE")
- && !shellTitle.startsWith("Quick Access")) {
- UIThreadRunnable.syncExec(new VoidResult() {
- @Override
- public void run() {
- if (shell.widget.getParent() != null) {
- shell.close();
- }
- }
- });
- }
- }
- bot.closeAllEditors();
- }
-
- public static void cleanup(SWTWorkbenchBot bot) {
- // clear project explorer
- exitProjectFolder(bot);
- projectExplorer.setFocus();
- SWTBotTree treeBot = projectExplorer.bot().tree();
- for (SWTBotTreeItem treeItem : treeBot.getAllItems()) {
- removeTreeItem(bot, treeItem);
- }
- }
-
- /**
- * Enter the project folder so as to avoid expanding trees later
- */
- private static SWTBotView enterProjectFolder(SWTWorkbenchBot bot, String projectName) {
- projectExplorer.bot().tree().select(projectName).
- contextMenu("Go Into").click();
- bot.waitUntil(waitForWidget(WidgetMatcherFactory.withText(
- projectName), projectExplorer.getWidget()));
- return projectExplorer;
- }
-
- /**
- * Exit from the project tree.
- */
- private static void exitProjectFolder(SWTWorkbenchBot bot) {
- try {
- SWTBotToolbarButton forwardButton = projectExplorer.toolbarPushButton("Forward");
- projectExplorer.toolbarPushButton("Back to Workspace").click();
- bot.waitUntil(widgetIsEnabled(forwardButton));
- } catch (WidgetNotFoundException e) {
- // Already exited from project folder
- }
- }
-
- public static void createProject(SWTWorkbenchBot bot, String projectName, String projectType) {
- mainShell.activate();
- SWTBotMenu fileMenu = bot.menu("File");
- SWTBotMenu newMenu = fileMenu.menu("New");
- SWTBotMenu projectMenu = newMenu.menu(projectType);
- projectMenu.click();
-
- SWTBotShell shell = bot.shell(projectType);
- shell.activate();
-
- bot.tree().expandNode("Makefile project").select("Empty Project");
- bot.textWithLabel("Project name:").setText(projectName);
- bot.table().select("Linux GCC");
-
- bot.button("Next >").click();
- bot.button("Finish").click();
- bot.waitUntil(Conditions.shellCloses(shell));
- }
-
- public static void populateProject(SWTWorkbenchBot bot, String projectName) throws Exception {
- IProject project = ResourcesPlugin.getWorkspace().getRoot()
- .getProject(projectName);
- try (InputStream is = FileLocator.openStream(
- FrameworkUtil.getBundle(GcovTest.class), new Path("resource/"
- + projectName + "/content"), false);
- LineNumberReader lnr = new LineNumberReader(
- new InputStreamReader(is))) {
- String filename;
- while (null != (filename = lnr.readLine())) {
- final ProgressMonitor pm = new ProgressMonitor();
- final IFile ifile = project.getFile(filename);
- InputStream fis = FileLocator.openStream(FrameworkUtil
- .getBundle(GcovTest.class), new Path("resource/"
- + projectName + "/" + filename), false);
- ifile.create(fis, true, pm);
- bot.waitUntil(new DefaultCondition() {
-
- @Override
- public boolean test() {
- return pm.isDone();
- }
-
- @Override
- public String getFailureMessage() {
- return ifile + " not yet created after 6000ms";
- }
- }, 6000);
- }
- }
- }
-
- public static void compileProject(SWTWorkbenchBot bot, String projectName) {
- SWTBotTree treeBot = projectExplorer.bot().tree();
- treeBot.setFocus();
- treeBot = treeBot.select(projectName);
- bot.waitUntil(Conditions.treeHasRows(treeBot, 1));
- mainShell.activate();
- SWTBotMenu menu = bot.menu("Build Project");
- menu.click();
- bot.waitUntil(new JobsRunning(ResourcesPlugin.FAMILY_MANUAL_BUILD), 30000);
- }
-
- private static void removeTreeItem(SWTWorkbenchBot bot,
- SWTBotTreeItem treeItem) {
- String shellTitle = "Delete Resources";
- treeItem.contextMenu("Delete").click();
- Matcher<Shell> withText = withText(shellTitle);
- bot.waitUntil(Conditions.waitForShell(withText));
- SWTBotShell deleteShell = bot.shell(shellTitle);
- deleteShell.activate();
- bot.button("OK").click();
- // Another shell (with the same name!) may appear if resources aren't synced.
- // If it does appear, it will be a child of the first shell.
- try {
- bot.waitUntil(Conditions.shellCloses(deleteShell));
- } catch (TimeoutException e) {
- SWTBotShell deleteShell2;
- try {
- deleteShell2 = bot.shell(shellTitle, deleteShell.widget);
- } catch (WidgetNotFoundException e2) {
- // If the other shell isn't found, that means the first one just didn't close.
- System.out.println("ERROR: \"Delete Resources\" shell did not close, and no extra shell appeared");
- throw e;
- }
- System.out.println("Deleting out-of-sync resources - new \"Delete Resources\" shell found");
- deleteShell2.activate();
- bot.button("Continue").click();
- bot.waitUntil(Conditions.shellCloses(deleteShell2));
- bot.waitUntil(Conditions.shellCloses(deleteShell));
- }
- }
-
- private static TreeSet<String> getGcovFiles(SWTWorkbenchBot bot, String projectName) throws Exception {
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
- TreeSet<String> ret = new TreeSet<>();
- for (IResource r : project.members()) {
- if (r.getType() == IResource.FILE && r.exists()) {
- if (r.getName().endsWith(".gcda") || r.getName().endsWith(".gcno")) {
- ret.add(r.getFullPath().toOSString());
- }
- }
- }
- return ret;
- }
-
- private static void testGcovSummary(SWTWorkbenchBot bot, String projectName, String filename, String binName,
- boolean testProducedReference) throws Exception {
- IPath filePath = new Path(filename);
- IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
- String binPath = file.getProject().getFile(binName).getLocation().toOSString();
-
- openResource(bot, file.getName());
- Matcher<Shell> withText = withText("Gcov - Open coverage results...");
- bot.waitUntil(Conditions.waitForShell(withText));
-
- SWTBotShell shell = bot.shell("Gcov - Open coverage results...");
- shell.activate();
- bot.textInGroup("Binary File", 0).setText(binPath);
- bot.button("OK").click();
- bot.waitUntil(Conditions.shellCloses(shell));
-
- SWTBotView botView = bot.viewByTitle("gcov");
- // The following cannot be tested on 4.2 because the SWTBot implementation of toolbarButton()
- // is broken there because it relies PartPane having a method getPane() which is no longer true.
- botView.toolbarButton("Sort coverage per function").click();
- dumpCSV(bot, botView, projectName, "function", testProducedReference);
- botView.toolbarButton("Sort coverage per file").click();
- dumpCSV(bot, botView, projectName, "file", testProducedReference);
- botView.toolbarButton("Sort coverage per folder").click();
- dumpCSV(bot, botView, projectName, "folder", testProducedReference);
- botView.close();
- }
-
- private static void openResource(SWTWorkbenchBot bot, String fileName) {
- mainShell.activate();
- bot.menu("Navigate").menu("Open Resource...").click();
- bot.waitUntil(Conditions.shellIsActive("Open Resource"));
- SWTBotShell shell = bot.shell("Open Resource");
- shell.activate();
- bot.text().setText(fileName);
- bot.button("Open").click();
- bot.waitUntil(Conditions.shellCloses(shell));
- }
-
- private static void testGcovFileDetails(SWTWorkbenchBot bot, String projectName, String filename, String binName) throws Exception {
- IPath filePath = new Path(filename);
- IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
- String binPath = file.getProject().getFile(binName).getLocation().toOSString();
-
- openResource(bot, file.getName());
- Matcher<Shell> withText = withText("Gcov - Open coverage results...");
- bot.waitUntil(Conditions.waitForShell(withText));
-
- SWTBotShell shell = bot.shell("Gcov - Open coverage results...");
- shell.activate();
- bot.textInGroup("Binary File", 0).setText(binPath);
- SWTBotRadio button = bot.radioInGroup("Coverage result", 0);
- button.click();
- bot.button("OK").click();
- bot.waitUntil(Conditions.shellCloses(shell));
-
- SWTBotEditor editor = bot.activeEditor();
- SWTBotEclipseEditor edt = editor.toTextEditor(); /* just to verify that the correct file was found */
- edt.close();
- }
-
- private static void testGcovLaunchSummary(SWTWorkbenchBot bot, String projectName, String binName) {
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
- String binLocation = project.getFile(binName).getLocation().toOSString();
- IPath binPath = new Path(binLocation);
- IFile binFile = ResourcesPlugin.getWorkspace().getRoot().getFile(binPath);
-
- SWTBot viewBot = projectExplorer.bot();
-
- SWTBotTree treeBot = viewBot.tree();
- treeBot.setFocus();
- // We need to select the binary, but in the tree, it may have additional info appended to the
- // name such as [x86_64/le]. So, we look at all nodes of the project and look for the one that
- // starts with our binary file name. We can then select the node.
- enterProjectFolder(bot, projectName);
- bot.waitUntil(Conditions.waitForWidget(withText(projectName), projectExplorer.getWidget()));
-
- SWTBotTreeItem[] nodes = treeBot.getAllItems();
- String binNodeName = binFile.getName();
- for (SWTBotTreeItem node : nodes) {
- if (node.getText().startsWith(binNodeName)) {
- node.select();
- break;
- }
- }
- assertNotEquals(treeBot.selectionCount(), 0);
- String menuItem = "Profiling Tools";
- String subMenuItem = "1 Profile Code Coverage";
- click(contextMenu(treeBot, menuItem, subMenuItem));
-
- final boolean result[] = new boolean[1];
- Display.getDefault().syncExec(new Runnable() {
-
- @Override
- public void run() {
- try {
- PlatformUI.getWorkbench().getActiveWorkbenchWindow()
- .getActivePage()
- .showView("org.eclipse.linuxtools.gcov.view");
- result[0] = true;
- } catch (PartInitException e) {
- result[0] = false;
- }
- }
- });
- assertTrue(result[0]);
- SWTBotView botView = bot.viewByTitle("gcov");
-
- botView.close();
- }
-
- private static void dumpCSV(SWTWorkbenchBot bot, SWTBotView botView, String projectName, String type,
- boolean testProducedReference) {
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
- botView.toolbarButton("Export to CSV").click();
- SWTBotShell shell = bot.shell("Export to CSV");
- shell.activate();
- String s = project.getLocation() + "/" + type + "-dump.csv";
- new File(s).delete();
- bot.text().setText(s);
- bot.button("OK").click();
- bot.waitUntil(new JobsRunning(STExportToCSVAction.EXPORT_TO_CSV_JOB_FAMILY), 3000);
- if (testProducedReference) {
- String ref = STJunitUtils.getAbsolutePath(FrameworkUtil.getBundle(GcovTest.class).getSymbolicName(), "resource/" + projectName + "/" + type + ".csv");
- STJunitUtils.compareIgnoreEOL(project.getLocation() + "/" + type + "-dump.csv", ref, false);
- }
- }
-
- public static void openGcovFileDetails(SWTWorkbenchBot bot, String projectName) throws Exception {
- openGcovFileDetails(bot, projectName, "a.out");
- }
-
- public static void openGcovSummary(SWTWorkbenchBot bot, String projectName, boolean testProducedReference)
- throws Exception {
- openGcovSummary(bot, projectName, "a.out", testProducedReference);
- }
-
- public static void openGcovSummary(SWTWorkbenchBot bot, String projectName, String binName,
- boolean testProducedReference) throws Exception {
- TreeSet<String> ts = getGcovFiles(bot, projectName);
- for (String string : ts) {
- testGcovSummary(bot, projectName, string, binName, testProducedReference);
- }
- }
-
- public static void openGcovFileDetails(SWTWorkbenchBot bot,
- String projectName, String binName) throws Exception {
- TreeSet<String> ts = getGcovFiles(bot, projectName);
- for (String string : ts) {
- testGcovFileDetails(bot, projectName, string, binName);
- }
- }
-
- public static void openGcovSummaryByLaunch(SWTWorkbenchBot bot,
- String projectName) {
- testGcovLaunchSummary(bot, projectName, "a.out");
- }
-
- /**
- * Click on the specified MenuItem.
- * @param menuItem MenuItem item to click
- */
- private static void click(final MenuItem menuItem) {
- final Event event = new Event();
- event.time = (int) System.currentTimeMillis();
- event.widget = menuItem;
- event.display = menuItem.getDisplay();
- event.type = SWT.Selection;
-
- UIThreadRunnable.asyncExec(menuItem.getDisplay(), new VoidResult() {
- @Override
- public void run() {
- menuItem.notifyListeners(SWT.Selection, event);
- }
- });
- }
+ private static final String PROJECT_EXPLORER = "Project Explorer";
+ private static SWTBotView projectExplorer;
+ private static SWTBotShell mainShell;
+
+ private static final class UnCheckTest implements ICondition {
+ SWTBotCheckBox checkBox;
+
+ public UnCheckTest(SWTBotCheckBox bot) {
+ checkBox = bot;
+ }
+
+ @Override
+ public boolean test() {
+ return !checkBox.isChecked();
+ }
+
+ @Override
+ public void init(SWTBot bot) {
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return null;
+ }
+ }
+
+ private static class NodeAvailableAndSelect extends DefaultCondition {
+
+ private SWTBotTree tree;
+ private String parent;
+ private String node;
+
+ /**
+ * Wait for a tree node (with a known parent) to become visible, and select it
+ * when it does. Note that this wait condition should only be used after having
+ * made an attempt to reveal the node.
+ * @param tree The SWTBotTree that contains the node to select.
+ * @param parent The text of the parent node that contains the node to select.
+ * @param node The text of the node to select.
+ */
+ NodeAvailableAndSelect(SWTBotTree tree, String parent, String node){
+ this.tree = tree;
+ this.node = node;
+ this.parent = parent;
+ }
+
+ @Override
+ public boolean test() {
+ try {
+ SWTBotTreeItem parentNode = tree.getTreeItem(parent);
+ parentNode.getNode(node).select();
+ return true;
+ } catch (WidgetNotFoundException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return "Timed out waiting for " + node; //$NON-NLS-1$
+ }
+ }
+
+ public static SWTWorkbenchBot init(String PROJECT_NAME, String PROJECT_TYPE)
+ throws Exception {
+ SWTWorkbenchBot bot = new SWTWorkbenchBot();
+ bot.captureScreenshot(PROJECT_NAME + ".beforeClass.1.jpg");
+ try {
+ bot.viewByTitle("Welcome").close();
+ // hide Subclipse Usage stats popup if present/installed
+ bot.shell("Subclipse Usage").activate();
+ bot.button("Cancel").click();
+ } catch (WidgetNotFoundException e) {
+ // ignore
+ }
+
+ bot.perspectiveByLabel("C/C++").activate();
+ for (SWTBotShell sh : bot.shells()) {
+ if (sh.getText().startsWith("C/C++")) {
+ sh.activate();
+ bot.waitUntil(Conditions.shellIsActive(sh.getText()));
+ mainShell = sh;
+ break;
+ }
+ }
+
+ bot.captureScreenshot(PROJECT_NAME + ".beforeClass.2.jpg");
+ // Turn off automatic building by default
+ SWTBotMenu windowsMenu = bot.menu("Window");
+ windowsMenu.menu("Preferences").click();
+ SWTBotShell shell = bot.shell("Preferences");
+ shell.activate();
+ bot.text().setText("Workspace");
+ bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "General", "Workspace"));
+ SWTBotCheckBox buildAuto = bot.checkBox("Build automatically");
+ if (buildAuto != null && buildAuto.isChecked()) {
+ buildAuto.click();
+ }
+ bot.waitUntil(new UnCheckTest(buildAuto));
+ bot.button("Apply").click();
+ bot.button("OK").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+
+
+ // define & repopulate project explorer
+ projectExplorer = bot.viewByTitle(PROJECT_EXPLORER);
+ GcovTest.createProject(bot, PROJECT_NAME, PROJECT_TYPE);
+ GcovTest.populateProject(bot, PROJECT_NAME);
+ GcovTest.compileProject(bot, PROJECT_NAME);
+ return bot;
+ }
+
+ @After
+ public void cleanUp() {
+ SWTWorkbenchBot bot = new SWTWorkbenchBot();
+ SWTBotShell[] shells = bot.shells();
+ for (final SWTBotShell shell : shells) {
+ String shellTitle = shell.getText();
+ if (shellTitle.length() > 0
+ && !shellTitle.startsWith("SystemTap IDE")
+ && !shellTitle.startsWith("Quick Access")) {
+ UIThreadRunnable.syncExec(new VoidResult() {
+ @Override
+ public void run() {
+ if (shell.widget.getParent() != null) {
+ shell.close();
+ }
+ }
+ });
+ }
+ }
+ bot.closeAllEditors();
+ }
+
+ public static void cleanup(SWTWorkbenchBot bot) {
+ // clear project explorer
+ exitProjectFolder(bot);
+ projectExplorer.setFocus();
+ SWTBotTree treeBot = projectExplorer.bot().tree();
+ for (SWTBotTreeItem treeItem : treeBot.getAllItems()) {
+ removeTreeItem(bot, treeItem);
+ }
+ }
+
+ /**
+ * Enter the project folder so as to avoid expanding trees later
+ */
+ private static SWTBotView enterProjectFolder(SWTWorkbenchBot bot, String projectName) {
+ projectExplorer.bot().tree().select(projectName).
+ contextMenu("Go Into").click();
+ bot.waitUntil(waitForWidget(WidgetMatcherFactory.withText(
+ projectName), projectExplorer.getWidget()));
+ return projectExplorer;
+ }
+
+ /**
+ * Exit from the project tree.
+ */
+ private static void exitProjectFolder(SWTWorkbenchBot bot) {
+ try {
+ SWTBotToolbarButton forwardButton = projectExplorer.toolbarPushButton("Forward");
+ projectExplorer.toolbarPushButton("Back to Workspace").click();
+ bot.waitUntil(widgetIsEnabled(forwardButton));
+ } catch (WidgetNotFoundException e) {
+ // Already exited from project folder
+ }
+ }
+
+ public static void createProject(SWTWorkbenchBot bot, String projectName, String projectType) {
+ mainShell.activate();
+ SWTBotMenu fileMenu = bot.menu("File");
+ SWTBotMenu newMenu = fileMenu.menu("New");
+ SWTBotMenu projectMenu = newMenu.menu(projectType);
+ projectMenu.click();
+
+ SWTBotShell shell = bot.shell(projectType);
+ shell.activate();
+
+ bot.tree().expandNode("Makefile project").select("Empty Project");
+ bot.textWithLabel("Project name:").setText(projectName);
+ bot.table().select("Linux GCC");
+
+ bot.button("Next >").click();
+ bot.button("Finish").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+ }
+
+ public static void populateProject(SWTWorkbenchBot bot, String projectName) throws Exception {
+ IProject project = ResourcesPlugin.getWorkspace().getRoot()
+ .getProject(projectName);
+ try (InputStream is = FileLocator.openStream(
+ FrameworkUtil.getBundle(GcovTest.class), new Path("resource/"
+ + projectName + "/content"), false);
+ LineNumberReader lnr = new LineNumberReader(
+ new InputStreamReader(is))) {
+ String filename;
+ while (null != (filename = lnr.readLine())) {
+ final ProgressMonitor pm = new ProgressMonitor();
+ final IFile ifile = project.getFile(filename);
+ InputStream fis = FileLocator.openStream(FrameworkUtil
+ .getBundle(GcovTest.class), new Path("resource/"
+ + projectName + "/" + filename), false);
+ ifile.create(fis, true, pm);
+ bot.waitUntil(new DefaultCondition() {
+
+ @Override
+ public boolean test() {
+ return pm.isDone();
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return ifile + " not yet created after 6000ms";
+ }
+ }, 6000);
+ }
+ }
+ }
+
+ public static void compileProject(SWTWorkbenchBot bot, String projectName) {
+ SWTBotTree treeBot = projectExplorer.bot().tree();
+ treeBot.setFocus();
+ treeBot = treeBot.select(projectName);
+ bot.waitUntil(Conditions.treeHasRows(treeBot, 1));
+ mainShell.activate();
+ SWTBotMenu menu = bot.menu("Build Project");
+ menu.click();
+ bot.waitUntil(new JobsRunning(ResourcesPlugin.FAMILY_MANUAL_BUILD), 30000);
+ }
+
+ private static void removeTreeItem(SWTWorkbenchBot bot,
+ SWTBotTreeItem treeItem) {
+ String shellTitle = "Delete Resources";
+ treeItem.contextMenu("Delete").click();
+ Matcher<Shell> withText = withText(shellTitle);
+ bot.waitUntil(Conditions.waitForShell(withText));
+ SWTBotShell deleteShell = bot.shell(shellTitle);
+ deleteShell.activate();
+ bot.button("OK").click();
+ // Another shell (with the same name!) may appear if resources aren't synced.
+ // If it does appear, it will be a child of the first shell.
+ try {
+ bot.waitUntil(Conditions.shellCloses(deleteShell));
+ } catch (TimeoutException e) {
+ SWTBotShell deleteShell2;
+ try {
+ deleteShell2 = bot.shell(shellTitle, deleteShell.widget);
+ } catch (WidgetNotFoundException e2) {
+ // If the other shell isn't found, that means the first one just didn't close.
+ System.out.println("ERROR: \"Delete Resources\" shell did not close, and no extra shell appeared");
+ throw e;
+ }
+ System.out.println("Deleting out-of-sync resources - new \"Delete Resources\" shell found");
+ deleteShell2.activate();
+ bot.button("Continue").click();
+ bot.waitUntil(Conditions.shellCloses(deleteShell2));
+ bot.waitUntil(Conditions.shellCloses(deleteShell));
+ }
+ }
+
+ private static TreeSet<String> getGcovFiles(SWTWorkbenchBot bot, String projectName) throws Exception {
+ IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
+ TreeSet<String> ret = new TreeSet<>();
+ for (IResource r : project.members()) {
+ if (r.getType() == IResource.FILE && r.exists()) {
+ if (r.getName().endsWith(".gcda") || r.getName().endsWith(".gcno")) {
+ ret.add(r.getFullPath().toOSString());
+ }
+ }
+ }
+ return ret;
+ }
+
+ private static void testGcovSummary(SWTWorkbenchBot bot, String projectName, String filename, String binName,
+ boolean testProducedReference) throws Exception {
+ IPath filePath = new Path(filename);
+ IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
+ String binPath = file.getProject().getFile(binName).getLocation().toOSString();
+
+ openResource(bot, file.getName());
+ Matcher<Shell> withText = withText("Gcov - Open coverage results...");
+ bot.waitUntil(Conditions.waitForShell(withText));
+
+ SWTBotShell shell = bot.shell("Gcov - Open coverage results...");
+ shell.activate();
+ bot.textInGroup("Binary File", 0).setText(binPath);
+ bot.button("OK").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+
+ SWTBotView botView = bot.viewByTitle("gcov");
+ // The following cannot be tested on 4.2 because the SWTBot implementation of toolbarButton()
+ // is broken there because it relies PartPane having a method getPane() which is no longer true.
+ botView.toolbarButton("Sort coverage per function").click();
+ dumpCSV(bot, botView, projectName, "function", testProducedReference);
+ botView.toolbarButton("Sort coverage per file").click();
+ dumpCSV(bot, botView, projectName, "file", testProducedReference);
+ botView.toolbarButton("Sort coverage per folder").click();
+ dumpCSV(bot, botView, projectName, "folder", testProducedReference);
+ botView.close();
+ }
+
+ private static void openResource(SWTWorkbenchBot bot, String fileName) {
+ mainShell.activate();
+ bot.menu("Navigate").menu("Open Resource...").click();
+ bot.waitUntil(Conditions.shellIsActive("Open Resource"));
+ SWTBotShell shell = bot.shell("Open Resource");
+ shell.activate();
+ bot.text().setText(fileName);
+ bot.button("Open").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+ }
+
+ private static void testGcovFileDetails(SWTWorkbenchBot bot, String projectName, String filename, String binName) throws Exception {
+ IPath filePath = new Path(filename);
+ IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
+ String binPath = file.getProject().getFile(binName).getLocation().toOSString();
+
+ openResource(bot, file.getName());
+ Matcher<Shell> withText = withText("Gcov - Open coverage results...");
+ bot.waitUntil(Conditions.waitForShell(withText));
+
+ SWTBotShell shell = bot.shell("Gcov - Open coverage results...");
+ shell.activate();
+ bot.textInGroup("Binary File", 0).setText(binPath);
+ SWTBotRadio button = bot.radioInGroup("Coverage result", 0);
+ button.click();
+ bot.button("OK").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+
+ SWTBotEditor editor = bot.activeEditor();
+ SWTBotEclipseEditor edt = editor.toTextEditor(); /* just to verify that the correct file was found */
+ edt.close();
+ }
+
+ private static void testGcovLaunchSummary(SWTWorkbenchBot bot, String projectName, String binName) {
+ IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
+ String binLocation = project.getFile(binName).getLocation().toOSString();
+ IPath binPath = new Path(binLocation);
+ IFile binFile = ResourcesPlugin.getWorkspace().getRoot().getFile(binPath);
+
+ SWTBot viewBot = projectExplorer.bot();
+
+ SWTBotTree treeBot = viewBot.tree();
+ treeBot.setFocus();
+ // We need to select the binary, but in the tree, it may have additional info appended to the
+ // name such as [x86_64/le]. So, we look at all nodes of the project and look for the one that
+ // starts with our binary file name. We can then select the node.
+ enterProjectFolder(bot, projectName);
+ bot.waitUntil(Conditions.waitForWidget(withText(projectName), projectExplorer.getWidget()));
+
+ SWTBotTreeItem[] nodes = treeBot.getAllItems();
+ String binNodeName = binFile.getName();
+ for (SWTBotTreeItem node : nodes) {
+ if (node.getText().startsWith(binNodeName)) {
+ node.select();
+ break;
+ }
+ }
+ assertNotEquals(treeBot.selectionCount(), 0);
+ String menuItem = "Profiling Tools";
+ String subMenuItem = "1 Profile Code Coverage";
+ click(contextMenu(treeBot, menuItem, subMenuItem));
+
+ final boolean result[] = new boolean[1];
+ Display.getDefault().syncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage()
+ .showView("org.eclipse.linuxtools.gcov.view");
+ result[0] = true;
+ } catch (PartInitException e) {
+ result[0] = false;
+ }
+ }
+ });
+ assertTrue(result[0]);
+ SWTBotView botView = bot.viewByTitle("gcov");
+
+ botView.close();
+ }
+
+ private static void dumpCSV(SWTWorkbenchBot bot, SWTBotView botView, String projectName, String type,
+ boolean testProducedReference) {
+ IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
+ botView.toolbarButton("Export to CSV").click();
+ SWTBotShell shell = bot.shell("Export to CSV");
+ shell.activate();
+ String s = project.getLocation() + "/" + type + "-dump.csv";
+ new File(s).delete();
+ bot.text().setText(s);
+ bot.button("OK").click();
+ bot.waitUntil(new JobsRunning(STExportToCSVAction.EXPORT_TO_CSV_JOB_FAMILY), 3000);
+ if (testProducedReference) {
+ String ref = STJunitUtils.getAbsolutePath(FrameworkUtil.getBundle(GcovTest.class).getSymbolicName(), "resource/" + projectName + "/" + type + ".csv");
+ STJunitUtils.compareIgnoreEOL(project.getLocation() + "/" + type + "-dump.csv", ref, false);
+ }
+ }
+
+ public static void openGcovFileDetails(SWTWorkbenchBot bot, String projectName) throws Exception {
+ openGcovFileDetails(bot, projectName, "a.out");
+ }
+
+ public static void openGcovSummary(SWTWorkbenchBot bot, String projectName, boolean testProducedReference)
+ throws Exception {
+ openGcovSummary(bot, projectName, "a.out", testProducedReference);
+ }
+
+ public static void openGcovSummary(SWTWorkbenchBot bot, String projectName, String binName,
+ boolean testProducedReference) throws Exception {
+ TreeSet<String> ts = getGcovFiles(bot, projectName);
+ for (String string : ts) {
+ testGcovSummary(bot, projectName, string, binName, testProducedReference);
+ }
+ }
+
+ public static void openGcovFileDetails(SWTWorkbenchBot bot,
+ String projectName, String binName) throws Exception {
+ TreeSet<String> ts = getGcovFiles(bot, projectName);
+ for (String string : ts) {
+ testGcovFileDetails(bot, projectName, string, binName);
+ }
+ }
+
+ public static void openGcovSummaryByLaunch(SWTWorkbenchBot bot,
+ String projectName) {
+ testGcovLaunchSummary(bot, projectName, "a.out");
+ }
+
+ /**
+ * Click on the specified MenuItem.
+ * @param menuItem MenuItem item to click
+ */
+ private static void click(final MenuItem menuItem) {
+ final Event event = new Event();
+ event.time = (int) System.currentTimeMillis();
+ event.widget = menuItem;
+ event.display = menuItem.getDisplay();
+ event.type = SWT.Selection;
+
+ UIThreadRunnable.asyncExec(menuItem.getDisplay(), new VoidResult() {
+ @Override
+ public void run() {
+ menuItem.notifyListeners(SWT.Selection, event);
+ }
+ });
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestC.java b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestC.java
index 6b37fe3ba1..50f7e4fdf5 100644
--- a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestC.java
+++ b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestC.java
@@ -10,33 +10,33 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class GcovTestC {
- private static SWTWorkbenchBot bot;
-
- private static final String PROJECT_NAME = "Gcov_C_test";
- private static final String PROJECT_TYPE = "C Project";
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- bot = GcovTest.init(PROJECT_NAME, PROJECT_TYPE);
- }
-
- @AfterClass
- public static void afterClass() {
- GcovTest.cleanup(bot);
- }
-
- @Test
- public void openGcovFileDetails() throws Exception {
- GcovTest.openGcovFileDetails(bot, PROJECT_NAME);
- }
-
- @Test
- public void openGcovSummary() throws Exception {
- GcovTest.openGcovSummary(bot, PROJECT_NAME, true);
- }
-
- @Test
- public void testGcovSummaryByLaunch() {
- GcovTest.openGcovSummaryByLaunch(bot, PROJECT_NAME);
- }
+ private static SWTWorkbenchBot bot;
+
+ private static final String PROJECT_NAME = "Gcov_C_test";
+ private static final String PROJECT_TYPE = "C Project";
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ bot = GcovTest.init(PROJECT_NAME, PROJECT_TYPE);
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ GcovTest.cleanup(bot);
+ }
+
+ @Test
+ public void openGcovFileDetails() throws Exception {
+ GcovTest.openGcovFileDetails(bot, PROJECT_NAME);
+ }
+
+ @Test
+ public void openGcovSummary() throws Exception {
+ GcovTest.openGcovSummary(bot, PROJECT_NAME, true);
+ }
+
+ @Test
+ public void testGcovSummaryByLaunch() {
+ GcovTest.openGcovSummaryByLaunch(bot, PROJECT_NAME);
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestCLibrary.java b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestCLibrary.java
index e1c08534a8..0eea908c9c 100644
--- a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestCLibrary.java
+++ b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestCLibrary.java
@@ -10,30 +10,30 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class GcovTestCLibrary {
- private static SWTWorkbenchBot bot;
-
- private static final String PROJECT_NAME = "Gcov_C_library_test";
- private static final String PROJECT_TYPE = "C Project";
- private static final String BIN_NAME = "libtestgcovlib.so";
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- bot = GcovTest.init(PROJECT_NAME, PROJECT_TYPE);
- }
-
- @AfterClass
- public static void afterClass() {
- GcovTest.cleanup(bot);
- }
-
- @Test
- public void openGcovFileDetails() throws Exception {
- GcovTest.openGcovFileDetails(bot, PROJECT_NAME, BIN_NAME);
- }
-
- @Test
- public void openGcovSummary() throws Exception {
- GcovTest.openGcovSummary(bot, PROJECT_NAME, BIN_NAME, true);
- }
+ private static SWTWorkbenchBot bot;
+
+ private static final String PROJECT_NAME = "Gcov_C_library_test";
+ private static final String PROJECT_TYPE = "C Project";
+ private static final String BIN_NAME = "libtestgcovlib.so";
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ bot = GcovTest.init(PROJECT_NAME, PROJECT_TYPE);
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ GcovTest.cleanup(bot);
+ }
+
+ @Test
+ public void openGcovFileDetails() throws Exception {
+ GcovTest.openGcovFileDetails(bot, PROJECT_NAME, BIN_NAME);
+ }
+
+ @Test
+ public void openGcovSummary() throws Exception {
+ GcovTest.openGcovSummary(bot, PROJECT_NAME, BIN_NAME, true);
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestCPP.java b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestCPP.java
index 3bfebd99ad..18b57aa50d 100644
--- a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestCPP.java
+++ b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/GcovTestCPP.java
@@ -10,33 +10,33 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class GcovTestCPP {
- private static SWTWorkbenchBot bot;
-
- private static final String PROJECT_NAME = "Gcov_CPP_test";
- private static final String PROJECT_TYPE = "C++ Project";
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- bot = GcovTest.init(PROJECT_NAME, PROJECT_TYPE);
- }
-
- @AfterClass
- public static void afterClass() {
- GcovTest.cleanup(bot);
- }
-
- @Test
- public void openGcovFileDetails() throws Exception {
- GcovTest.openGcovFileDetails(bot, PROJECT_NAME);
- }
-
- @Test
- public void openGcovSummary() throws Exception {
- GcovTest.openGcovSummary(bot, PROJECT_NAME, false);
- }
-
- @Test
- public void testGcovSummaryByLaunch() {
- GcovTest.openGcovSummaryByLaunch(bot, PROJECT_NAME);
- }
+ private static SWTWorkbenchBot bot;
+
+ private static final String PROJECT_NAME = "Gcov_CPP_test";
+ private static final String PROJECT_TYPE = "C++ Project";
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ bot = GcovTest.init(PROJECT_NAME, PROJECT_TYPE);
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ GcovTest.cleanup(bot);
+ }
+
+ @Test
+ public void openGcovFileDetails() throws Exception {
+ GcovTest.openGcovFileDetails(bot, PROJECT_NAME);
+ }
+
+ @Test
+ public void openGcovSummary() throws Exception {
+ GcovTest.openGcovSummary(bot, PROJECT_NAME, false);
+ }
+
+ @Test
+ public void testGcovSummaryByLaunch() {
+ GcovTest.openGcovSummaryByLaunch(bot, PROJECT_NAME);
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/JobsRunning.java b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/JobsRunning.java
index e49a10907f..dbd3c3df74 100644
--- a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/JobsRunning.java
+++ b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/JobsRunning.java
@@ -6,25 +6,25 @@ import org.eclipse.swtbot.swt.finder.waits.ICondition;
public class JobsRunning implements ICondition {
- private final Object family;
-
- public JobsRunning(Object family) {
- this.family = family;
- }
-
- @Override
- public boolean test() {
- Job[] allJobs = Job.getJobManager().find(family);
- return allJobs.length == 0;
- }
-
- @Override
- public void init(SWTBot bot) {
-
- }
-
- @Override
- public String getFailureMessage() {
- return "Jobs still running...";
- }
+ private final Object family;
+
+ public JobsRunning(Object family) {
+ this.family = family;
+ }
+
+ @Override
+ public boolean test() {
+ Job[] allJobs = Job.getJobManager().find(family);
+ return allJobs.length == 0;
+ }
+
+ @Override
+ public void init(SWTBot bot) {
+
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return "Jobs still running...";
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/ProgressMonitor.java b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/ProgressMonitor.java
index 424d96abe0..ea39f69b9e 100644
--- a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/ProgressMonitor.java
+++ b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/ProgressMonitor.java
@@ -4,16 +4,16 @@ import org.eclipse.core.runtime.NullProgressMonitor;
public class ProgressMonitor extends NullProgressMonitor {
- private boolean done = false;
-
- public boolean isDone() {
- return done;
- }
+ private boolean done = false;
- @Override
- public void done() {
- super.done();
- done = true;
- }
+ public boolean isDone() {
+ return done;
+ }
+
+ @Override
+ public void done() {
+ super.done();
+ done = true;
+ }
}
diff --git a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/STJunitUtils.java b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/STJunitUtils.java
index e27e56f6c5..070431c0bf 100755
--- a/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/STJunitUtils.java
+++ b/gcov/org.eclipse.linuxtools.gcov.test/src/org/eclipse/linuxtools/internal/gcov/test/STJunitUtils.java
@@ -34,66 +34,66 @@ import org.osgi.framework.Bundle;
*/
public class STJunitUtils {
- /**
- * Utility method to compare files
- * @param dumpFile
- * @param refFile
- * @return
- */
- public static boolean compareIgnoreEOL(String dumpFile, String refFile, boolean deleteDumpFileIfOk) {
- String message = "Comparing ref file (" + refFile + ")and dump file ("
- + dumpFile + ")";
- boolean equals = false;
- try (LineNumberReader is1 = new LineNumberReader(new FileReader(
- dumpFile));
- LineNumberReader is2 = new LineNumberReader(new FileReader(
- refFile))) {
- do {
- String line1 = is1.readLine();
- String line2 = is2.readLine();
- if (line1 == null) {
- if (line2 == null) {
- equals = true;
- }
- break;
- } else if (line2 == null || !line1.equals(line2)) {
- break;
- }
- } while (true);
+ /**
+ * Utility method to compare files
+ * @param dumpFile
+ * @param refFile
+ * @return
+ */
+ public static boolean compareIgnoreEOL(String dumpFile, String refFile, boolean deleteDumpFileIfOk) {
+ String message = "Comparing ref file (" + refFile + ")and dump file ("
+ + dumpFile + ")";
+ boolean equals = false;
+ try (LineNumberReader is1 = new LineNumberReader(new FileReader(
+ dumpFile));
+ LineNumberReader is2 = new LineNumberReader(new FileReader(
+ refFile))) {
+ do {
+ String line1 = is1.readLine();
+ String line2 = is2.readLine();
+ if (line1 == null) {
+ if (line2 == null) {
+ equals = true;
+ }
+ break;
+ } else if (line2 == null || !line1.equals(line2)) {
+ break;
+ }
+ } while (true);
- if (!equals) {
- assertEquals(message + ": not correspond ", true, false);
- }
+ if (!equals) {
+ assertEquals(message + ": not correspond ", true, false);
+ }
- // delete dump only for successful tests
- if (equals && deleteDumpFileIfOk) {
- new File(dumpFile).delete();
- }
- } catch (FileNotFoundException _) {
- message += "... FAILED: One of these files may not exist";
- assertNull(message, _);
- } catch (Exception e) {
- message += ": exception raised ... FAILED";
- assertNull(message, e);
- }
- return equals;
- }
+ // delete dump only for successful tests
+ if (equals && deleteDumpFileIfOk) {
+ new File(dumpFile).delete();
+ }
+ } catch (FileNotFoundException _) {
+ message += "... FAILED: One of these files may not exist";
+ assertNull(message, _);
+ } catch (Exception e) {
+ message += ": exception raised ... FAILED";
+ assertNull(message, e);
+ }
+ return equals;
+ }
- /**
- * Gets the absolute path of a resource in the given plugin
- * @param pluginId
- * @param relativeName
- * @return an absolute path to a file
- */
- public static String getAbsolutePath(String pluginId, String relativeName) {
- Bundle b = Platform.getBundle(pluginId);
- URL url = FileLocator.find(b, new Path(relativeName), null);
- try {
- url = FileLocator.toFileURL(url);
- } catch (IOException e) {
- assertNotNull("Problem locating " + relativeName + " in" + pluginId,e);
- }
- String filename = url.getFile();
- return filename;
- }
+ /**
+ * Gets the absolute path of a resource in the given plugin
+ * @param pluginId
+ * @param relativeName
+ * @return an absolute path to a file
+ */
+ public static String getAbsolutePath(String pluginId, String relativeName) {
+ Bundle b = Platform.getBundle(pluginId);
+ URL url = FileLocator.find(b, new Path(relativeName), null);
+ try {
+ url = FileLocator.toFileURL(url);
+ } catch (IOException e) {
+ assertNotNull("Problem locating " + relativeName + " in" + pluginId,e);
+ }
+ String filename = url.getFile();
+ return filename;
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof-feature/pom.xml b/gprof/org.eclipse.linuxtools.gprof-feature/pom.xml
index e6eeeaa207..6bfe0666b0 100644
--- a/gprof/org.eclipse.linuxtools.gprof-feature/pom.xml
+++ b/gprof/org.eclipse.linuxtools.gprof-feature/pom.xml
@@ -22,7 +22,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools GProf Integration Feature</name>
-
+
<build>
<plugins>
<plugin>
diff --git a/gprof/org.eclipse.linuxtools.gprof.docs/build-doc.xml b/gprof/org.eclipse.linuxtools.gprof.docs/build-doc.xml
index 85cfad0f73..90901296eb 100644
--- a/gprof/org.eclipse.linuxtools.gprof.docs/build-doc.xml
+++ b/gprof/org.eclipse.linuxtools.gprof.docs/build-doc.xml
@@ -11,63 +11,63 @@
-->
<project name="org.eclipse.linuxtools.gprof.docs" default="all">
- <description>
+ <description>
Generate Eclipse help content from the Eclipsepedia wiki
</description>
- <property name="gprof.help.doc.url.base" value="http://wiki.eclipse.org"/>
- <property name="gprof.wiki.url.base" value="${gprof.help.doc.url.base}/Linux_Tools_Project/GProf"/>
- <property name="imageFolder" value="images"/>
+ <property name="gprof.help.doc.url.base" value="http://wiki.eclipse.org"/>
+ <property name="gprof.wiki.url.base" value="${gprof.help.doc.url.base}/Linux_Tools_Project/GProf"/>
+ <property name="imageFolder" value="images"/>
- <path id="wikitext.tasks.classpath">
- <!-- Replace dir with the dir you have wikitext installed into.-->
- <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
- <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
- </fileset>
- </path>
+ <path id="wikitext.tasks.classpath">
+ <!-- Replace dir with the dir you have wikitext installed into.-->
+ <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
+ <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
+ </fileset>
+ </path>
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
- <target name="all" description="Generate Eclipse help content for the Linux Tools Gprof user guide">
- <mediawiki-to-eclipse-help wikiBaseUrl="${gprof.help.doc.url.base}" title="GProf User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
+ <target name="all" description="Generate Eclipse help content for the Linux Tools Gprof user guide">
+ <mediawiki-to-eclipse-help wikiBaseUrl="${gprof.help.doc.url.base}" title="GProf User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
- <path name="Linux_Tools_Project/GProf/User_Guide" title="GProf User Guide" generateToc="false" />
- <stylesheet url="book.css" />
- <pageAppendum>
- = Updating This Document =
+ <path name="Linux_Tools_Project/GProf/User_Guide" title="GProf User Guide" generateToc="false" />
+ <stylesheet url="book.css" />
+ <pageAppendum>
+ = Updating This Document =
- This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
- http://wiki.eclipse.org/Linux_Tools_Project/GProf/User_Guide .
- </pageAppendum>
- </mediawiki-to-eclipse-help>
- <antcall target="test" />
- </target>
+ This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
+ http://wiki.eclipse.org/Linux_Tools_Project/GProf/User_Guide .
+ </pageAppendum>
+ </mediawiki-to-eclipse-help>
+ <antcall target="test" />
+ </target>
- <target name="test" description="verify that all of the HTML files are well-formed XML">
- <echo level="info">
+ <target name="test" description="verify that all of the HTML files are well-formed XML">
+ <echo level="info">
Validating help content XML and HTML files: The Eclipse help system expects well-formed XML
-
+
If validation fails it is because either:
-
+
* the userguide source code is poorly formed, or
* the WikiText MediaWiki parser has a bug
-
+
Problems with userguide source are usually caused by improper use of HTML markup in the MediaWiki source,
or inadvertently starting a line with a space character (in MediaWiki this starts a preformatted block)
- </echo>
+ </echo>
- <!--
- Don't bother with DTD validation: we only care if the files are well-formed.
- We therefore provide an empty DTD
- -->
- <echo file="tmp/__empty.dtd" message="" />
- <xmlvalidate lenient="true">
- <fileset dir="Linux_Tools_Project">
- <include name="**/*.html" />
- </fileset>
- <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
- </xmlvalidate>
- <delete dir="tmp"/>
- </target>
+ <!--
+ Don't bother with DTD validation: we only care if the files are well-formed.
+ We therefore provide an empty DTD
+ -->
+ <echo file="tmp/__empty.dtd" message="" />
+ <xmlvalidate lenient="true">
+ <fileset dir="Linux_Tools_Project">
+ <include name="**/*.html" />
+ </fileset>
+ <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
+ </xmlvalidate>
+ <delete dir="tmp"/>
+ </target>
</project>
diff --git a/gprof/org.eclipse.linuxtools.gprof.docs/toc.xml b/gprof/org.eclipse.linuxtools.gprof.docs/toc.xml
index b3eb7ef645..73c8d441bc 100644
--- a/gprof/org.eclipse.linuxtools.gprof.docs/toc.xml
+++ b/gprof/org.eclipse.linuxtools.gprof.docs/toc.xml
@@ -1,13 +1,13 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/GProf/User_Guide/User-Guide.html" label="GProf User Guide">
- <topic href="Linux_Tools_Project/GProf/User_Guide/User-Guide.html" label="GProf User Guide">
- <topic href="Linux_Tools_Project/GProf/User_Guide/User-Guide.html" label="Overview"></topic>
- <topic href="Linux_Tools_Project/GProf/User_Guide/Installation-and-Set-Up.html" label="Installation and Set-Up"></topic>
- <topic href="Linux_Tools_Project/GProf/User_Guide/Supported-format.html" label="Supported format"></topic>
- <topic href="Linux_Tools_Project/GProf/User_Guide/Opening-gmon-out.html" label="Opening gmon.out"></topic>
- <topic href="Linux_Tools_Project/GProf/User_Guide/Profiling-Using-GProf.html" label="Profiling Using GProf"></topic>
- <topic href="Linux_Tools_Project/GProf/User_Guide/GProf-View.html" label="GProf View"></topic>
- <topic href="Linux_Tools_Project/GProf/User_Guide/Troubleshooting.html" label="Troubleshooting"></topic>
- <topic href="Linux_Tools_Project/GProf/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
- </topic>
+ <topic href="Linux_Tools_Project/GProf/User_Guide/User-Guide.html" label="GProf User Guide">
+ <topic href="Linux_Tools_Project/GProf/User_Guide/User-Guide.html" label="Overview"></topic>
+ <topic href="Linux_Tools_Project/GProf/User_Guide/Installation-and-Set-Up.html" label="Installation and Set-Up"></topic>
+ <topic href="Linux_Tools_Project/GProf/User_Guide/Supported-format.html" label="Supported format"></topic>
+ <topic href="Linux_Tools_Project/GProf/User_Guide/Opening-gmon-out.html" label="Opening gmon.out"></topic>
+ <topic href="Linux_Tools_Project/GProf/User_Guide/Profiling-Using-GProf.html" label="Profiling Using GProf"></topic>
+ <topic href="Linux_Tools_Project/GProf/User_Guide/GProf-View.html" label="GProf View"></topic>
+ <topic href="Linux_Tools_Project/GProf/User_Guide/Troubleshooting.html" label="Troubleshooting"></topic>
+ <topic href="Linux_Tools_Project/GProf/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
+ </topic>
</toc> \ No newline at end of file
diff --git a/gprof/org.eclipse.linuxtools.gprof.launch/plugin.xml b/gprof/org.eclipse.linuxtools.gprof.launch/plugin.xml
index 04ba5f9957..71edbfccc8 100644
--- a/gprof/org.eclipse.linuxtools.gprof.launch/plugin.xml
+++ b/gprof/org.eclipse.linuxtools.gprof.launch/plugin.xml
@@ -12,5 +12,5 @@
tabgroup="org.eclipse.linuxtools.internal.gprof.launch.GprofLaunchConfigurationTabGroup"
type="timing">
</provider>
- </extension>
+ </extension>
</plugin>
diff --git a/gprof/org.eclipse.linuxtools.gprof.test/pom.xml b/gprof/org.eclipse.linuxtools.gprof.test/pom.xml
index 2e5f7cf272..036b72d110 100644
--- a/gprof/org.eclipse.linuxtools.gprof.test/pom.xml
+++ b/gprof/org.eclipse.linuxtools.gprof.test/pom.xml
@@ -36,7 +36,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.gprof.test</testSuite>
<testClass>org.eclipse.linuxtools.internal.gprof.test.AllGprofTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.platform.ide</product>
</configuration>
diff --git a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/AllGprofTests.java b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/AllGprofTests.java
index ac130df2fa..f22ea7e1b1 100644
--- a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/AllGprofTests.java
+++ b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/AllGprofTests.java
@@ -15,7 +15,7 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ GprofAggregatorTest.class, GprofBinaryTest.class,
- GprofParserTest.class, GprofLaunchTest.class, GprofShortcutTest.class,
- GprofTest.class })
+ GprofParserTest.class, GprofLaunchTest.class, GprofShortcutTest.class,
+ GprofTest.class })
public class AllGprofTests {
}
diff --git a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofAggregatorTest.java b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofAggregatorTest.java
index 37839a5d88..24916006c2 100644
--- a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofAggregatorTest.java
+++ b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofAggregatorTest.java
@@ -32,51 +32,51 @@ import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class GprofAggregatorTest {
- @Parameters
- public static Collection<Object[]> data() {
- List<Object[]> params = new ArrayList<>();
- for (File testDir : STJunitUtils.getTestDirs()) {
- final String dirName = testDir.getName();
- params.add(new Object[] { dirName });
- }
- return params;
- }
+ @Parameters
+ public static Collection<Object[]> data() {
+ List<Object[]> params = new ArrayList<>();
+ for (File testDir : STJunitUtils.getTestDirs()) {
+ final String dirName = testDir.getName();
+ params.add(new Object[] { dirName });
+ }
+ return params;
+ }
- private String dir;
+ private String dir;
- public GprofAggregatorTest(String dir) {
- this.dir = dir;
- }
+ public GprofAggregatorTest(String dir) {
+ this.dir = dir;
+ }
- @Test
- public void testAggregation() throws IOException, InterruptedException {
- File directory = new File(STJunitUtils.getAbsolutePath(
- "org.eclipse.linuxtools.gprof.test", dir));
- File gmonPath = new File(STJunitUtils.getAbsolutePath(
- "org.eclipse.linuxtools.gprof.test", dir + File.separator
- + OUTPUT_FILE));
- File binaryPath = new File(STJunitUtils.getAbsolutePath(
- "org.eclipse.linuxtools.gprof.test", dir + File.separator
- + BINARY_FILE));
+ @Test
+ public void testAggregation() throws IOException, InterruptedException {
+ File directory = new File(STJunitUtils.getAbsolutePath(
+ "org.eclipse.linuxtools.gprof.test", dir));
+ File gmonPath = new File(STJunitUtils.getAbsolutePath(
+ "org.eclipse.linuxtools.gprof.test", dir + File.separator
+ + OUTPUT_FILE));
+ File binaryPath = new File(STJunitUtils.getAbsolutePath(
+ "org.eclipse.linuxtools.gprof.test", dir + File.separator
+ + BINARY_FILE));
- String gmon = gmonPath.toString();
- String binary = binaryPath.toString();
+ String gmon = gmonPath.toString();
+ String binary = binaryPath.toString();
- LinkedList<String> s = new LinkedList<>();
- s.add(gmon.toString());
- s.add(gmon.toString());
+ LinkedList<String> s = new LinkedList<>();
+ s.add(gmon.toString());
+ s.add(gmon.toString());
- String gprof2use = "gprof";
- File f = Aggregator.aggregate(gprof2use, binary, s, directory);
+ String gprof2use = "gprof";
+ File f = Aggregator.aggregate(gprof2use, binary, s, directory);
- Process p = Runtime.getRuntime().exec(
- new String[] { gprof2use, binary, f.getAbsolutePath() });
- Process p2 = Runtime.getRuntime().exec(
- new String[] { gprof2use, binary,
- directory + File.separator + "gmon.sum.ref" });
+ Process p = Runtime.getRuntime().exec(
+ new String[] { gprof2use, binary, f.getAbsolutePath() });
+ Process p2 = Runtime.getRuntime().exec(
+ new String[] { gprof2use, binary,
+ directory + File.separator + "gmon.sum.ref" });
- STJunitUtils.compare(p.getInputStream(), p2.getInputStream());
- p.waitFor();
- p2.waitFor();
- }
+ STJunitUtils.compare(p.getInputStream(), p2.getInputStream());
+ p.waitFor();
+ p2.waitFor();
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofBinaryTest.java b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofBinaryTest.java
index 94b537f983..104b6f4e28 100644
--- a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofBinaryTest.java
+++ b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofBinaryTest.java
@@ -26,24 +26,24 @@ import org.osgi.framework.FrameworkUtil;
@RunWith(Parameterized.class)
public class GprofBinaryTest {
- @Parameters
+ @Parameters
public static Collection<Object[]> data() {
- List<Object[]> params = new ArrayList<>();
- for (File testDir : STJunitUtils.getTestDirs()) {
- params.add(new Object[]{testDir.getName()+File.separator+BINARY_FILE});
- }
- return params;
- }
+ List<Object[]> params = new ArrayList<>();
+ for (File testDir : STJunitUtils.getTestDirs()) {
+ params.add(new Object[]{testDir.getName()+File.separator+BINARY_FILE});
+ }
+ return params;
+ }
private String path;
public GprofBinaryTest(String path){
- this.path = path;
+ this.path = path;
}
@Test
- public void testValidBinary() {
- STJunitUtils.getAbsolutePath(FrameworkUtil.getBundle(GprofBinaryTest.class).getSymbolicName(), path);
- }
+ public void testValidBinary() {
+ STJunitUtils.getAbsolutePath(FrameworkUtil.getBundle(GprofBinaryTest.class).getSymbolicName(), path);
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofLaunchTest.java b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofLaunchTest.java
index 58bf3deb02..6ef0f34fa8 100644
--- a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofLaunchTest.java
+++ b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofLaunchTest.java
@@ -38,65 +38,65 @@ import org.osgi.framework.FrameworkUtil;
public class GprofLaunchTest extends AbstractTest {
- protected ILaunchConfiguration config;
- protected AbstractCLaunchDelegate delegate;
- protected ILaunch launch;
- protected ILaunchConfigurationWorkingCopy wc;
- private static final String ID = "org.eclipse.linuxtools.profiling.provider.TimingLaunchShortcut"; //$NON-NLS-1$
- private static final String LAUNCH_SHORT_EXTPT = "org.eclipse.debug.ui.launchShortcuts"; //$NON-NLS-1$
- private static final String GPROF_PROVIDER_ID = "org.eclipse.linuxtools.profiling.provider.timing.gprof"; //$NON-NLS-1$
- private static final String GPROF_CATEGORY = "timing"; //$NON-NLS-1$
+ protected ILaunchConfiguration config;
+ protected AbstractCLaunchDelegate delegate;
+ protected ILaunch launch;
+ protected ILaunchConfigurationWorkingCopy wc;
+ private static final String ID = "org.eclipse.linuxtools.profiling.provider.TimingLaunchShortcut"; //$NON-NLS-1$
+ private static final String LAUNCH_SHORT_EXTPT = "org.eclipse.debug.ui.launchShortcuts"; //$NON-NLS-1$
+ private static final String GPROF_PROVIDER_ID = "org.eclipse.linuxtools.profiling.provider.timing.gprof"; //$NON-NLS-1$
+ private static final String GPROF_CATEGORY = "timing"; //$NON-NLS-1$
- ProviderLaunchShortcut shortcut;
- String launchConfigTypeId;
+ ProviderLaunchShortcut shortcut;
+ String launchConfigTypeId;
- @Before
- public void setUp() throws Exception {
- proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), "fibTest"); //$NON-NLS-1$
- ProjectScope ps = new ProjectScope(proj.getProject());
- ScopedPreferenceStore scoped = new ScopedPreferenceStore(ps, ProviderProfileConstants.PLUGIN_ID);
- scoped.setSearchContexts(new IScopeContext[] { ps, InstanceScope.INSTANCE });
- scoped.setValue(ProviderProfileConstants.PREFS_KEY + GPROF_CATEGORY, GPROF_PROVIDER_ID);
- scoped.setValue(ProviderProfileConstants.USE_PROJECT_SETTINGS + GPROF_CATEGORY, true);
- scoped.save();
+ @Before
+ public void setUp() throws Exception {
+ proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), "fibTest"); //$NON-NLS-1$
+ ProjectScope ps = new ProjectScope(proj.getProject());
+ ScopedPreferenceStore scoped = new ScopedPreferenceStore(ps, ProviderProfileConstants.PLUGIN_ID);
+ scoped.setSearchContexts(new IScopeContext[] { ps, InstanceScope.INSTANCE });
+ scoped.setValue(ProviderProfileConstants.PREFS_KEY + GPROF_CATEGORY, GPROF_PROVIDER_ID);
+ scoped.setValue(ProviderProfileConstants.USE_PROJECT_SETTINGS + GPROF_CATEGORY, true);
+ scoped.save();
- IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(LAUNCH_SHORT_EXTPT);
- IConfigurationElement[] configs = extPoint.getConfigurationElements();
- for (IConfigurationElement cfg : configs) {
- if (cfg.getAttribute("id").equals(ID)){ //$NON-NLS-1$
- try {
- shortcut = (ProviderLaunchShortcut) cfg.createExecutableExtension("class"); //$NON-NLS-1$
- launchConfigTypeId = cfg.getChildren("class")[0].getChildren("parameter")[1].getAttribute("value"); //$NON-NLS-1$
- } catch (Exception e){
- fail (e.getMessage());
- }
- }
- }
- config = createConfiguration(proj.getProject());
- launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
- wc = config.getWorkingCopy();
- }
+ IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(LAUNCH_SHORT_EXTPT);
+ IConfigurationElement[] configs = extPoint.getConfigurationElements();
+ for (IConfigurationElement cfg : configs) {
+ if (cfg.getAttribute("id").equals(ID)){ //$NON-NLS-1$
+ try {
+ shortcut = (ProviderLaunchShortcut) cfg.createExecutableExtension("class"); //$NON-NLS-1$
+ launchConfigTypeId = cfg.getChildren("class")[0].getChildren("parameter")[1].getAttribute("value"); //$NON-NLS-1$
+ } catch (Exception e){
+ fail (e.getMessage());
+ }
+ }
+ }
+ config = createConfiguration(proj.getProject());
+ launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
+ wc = config.getWorkingCopy();
+ }
- @After
- public void tearDown() throws Exception {
- deleteProject(proj);
- wc.delete();
- config.delete();
- }
+ @After
+ public void tearDown() throws Exception {
+ deleteProject(proj);
+ wc.delete();
+ config.delete();
+ }
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(launchConfigTypeId);
- }
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(launchConfigTypeId);
+ }
- @Override
- protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- }
+ @Override
+ protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ }
- @Test
- public void testDelegateLaunch() throws CoreException {
- delegate = new GprofLaunchConfigurationDelegate();
- delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
- }
+ @Test
+ public void testDelegateLaunch() throws CoreException {
+ delegate = new GprofLaunchConfigurationDelegate();
+ delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofParserTest.java b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofParserTest.java
index fe1bd40733..aa589a2589 100644
--- a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofParserTest.java
+++ b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofParserTest.java
@@ -30,40 +30,40 @@ import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class GprofParserTest {
- @Parameters
- public static Collection<Object[]> data() {
- List<Object[]> params = new ArrayList<>();
- for (File testDir : STJunitUtils.getTestDirs()) {
- params.add(new Object[] { new File(testDir, OUTPUT_FILE),
- new File(testDir, BINARY_FILE),
- new File(testDir, "testParse.ref"),
- new File(testDir, "testParse.dump") });
- }
- return params;
- }
+ @Parameters
+ public static Collection<Object[]> data() {
+ List<Object[]> params = new ArrayList<>();
+ for (File testDir : STJunitUtils.getTestDirs()) {
+ params.add(new Object[] { new File(testDir, OUTPUT_FILE),
+ new File(testDir, BINARY_FILE),
+ new File(testDir, "testParse.ref"),
+ new File(testDir, "testParse.dump") });
+ }
+ return params;
+ }
- private File gmonFile;
- private File binaryFile;
- private File parserRefFile;
- private File parserDumpFile;
+ private File gmonFile;
+ private File binaryFile;
+ private File parserRefFile;
+ private File parserDumpFile;
- public GprofParserTest(File gmonFile, File binaryFile, File parserRefFile,
- File parserDumpFile) {
- this.gmonFile = gmonFile;
- this.binaryFile = binaryFile;
- this.parserRefFile = parserRefFile;
- this.parserDumpFile = parserDumpFile;
- }
+ public GprofParserTest(File gmonFile, File binaryFile, File parserRefFile,
+ File parserDumpFile) {
+ this.gmonFile = gmonFile;
+ this.binaryFile = binaryFile;
+ this.parserRefFile = parserRefFile;
+ this.parserDumpFile = parserDumpFile;
+ }
- @Test
- public void testProcessGmonFile() throws IOException {
- IBinaryObject binary = STSymbolManager.sharedInstance
- .getBinaryObject(binaryFile.getAbsolutePath());
- final GmonDecoder gmondecoder = new GmonDecoder(binary,
- new PrintStream(parserDumpFile), null);
- gmondecoder.setShouldDump(true);
- gmondecoder.read(gmonFile.getAbsolutePath());
- STJunitUtils.compareIgnoreEOL(parserDumpFile.getAbsolutePath(),
- parserRefFile.getAbsolutePath(), true);
- }
+ @Test
+ public void testProcessGmonFile() throws IOException {
+ IBinaryObject binary = STSymbolManager.sharedInstance
+ .getBinaryObject(binaryFile.getAbsolutePath());
+ final GmonDecoder gmondecoder = new GmonDecoder(binary,
+ new PrintStream(parserDumpFile), null);
+ gmondecoder.setShouldDump(true);
+ gmondecoder.read(gmonFile.getAbsolutePath());
+ STJunitUtils.compareIgnoreEOL(parserDumpFile.getAbsolutePath(),
+ parserRefFile.getAbsolutePath(), true);
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofShortcutTest.java b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofShortcutTest.java
index 67640f9099..9dc9f9a3c7 100644
--- a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofShortcutTest.java
+++ b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofShortcutTest.java
@@ -38,67 +38,67 @@ import org.osgi.framework.FrameworkUtil;
public class GprofShortcutTest extends AbstractTest {
- protected ILaunchConfiguration config;
- protected GprofLaunchConfigurationDelegate delegate;
- protected ILaunch launch;
- protected ILaunchConfigurationWorkingCopy wc;
- private static final String ID = "org.eclipse.linuxtools.profiling.provider.TimingLaunchShortcut"; //$NON-NLS-1$
- private static final String LAUNCH_SHORT_EXTPT = "org.eclipse.debug.ui.launchShortcuts"; //$NON-NLS-1$
- private static final String GPROF_PROVIDER_ID = "org.eclipse.linuxtools.profiling.provider.timing.gprof"; //$NON-NLS-1$
- private static final String GPROF_CATEGORY = "timing"; //$NON-NLS-1$
+ protected ILaunchConfiguration config;
+ protected GprofLaunchConfigurationDelegate delegate;
+ protected ILaunch launch;
+ protected ILaunchConfigurationWorkingCopy wc;
+ private static final String ID = "org.eclipse.linuxtools.profiling.provider.TimingLaunchShortcut"; //$NON-NLS-1$
+ private static final String LAUNCH_SHORT_EXTPT = "org.eclipse.debug.ui.launchShortcuts"; //$NON-NLS-1$
+ private static final String GPROF_PROVIDER_ID = "org.eclipse.linuxtools.profiling.provider.timing.gprof"; //$NON-NLS-1$
+ private static final String GPROF_CATEGORY = "timing"; //$NON-NLS-1$
- ProviderLaunchShortcut shortcut;
- String launchConfigTypeId;
+ ProviderLaunchShortcut shortcut;
+ String launchConfigTypeId;
- @Before
- public void setUp() throws Exception {
- proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), "fibTest2"); //$NON-NLS-1$
- ProjectScope ps = new ProjectScope(proj.getProject());
- ScopedPreferenceStore scoped = new ScopedPreferenceStore(ps, ProviderProfileConstants.PLUGIN_ID);
- scoped.setSearchContexts(new IScopeContext[] { ps, InstanceScope.INSTANCE });
- scoped.setValue(ProviderProfileConstants.PREFS_KEY + GPROF_CATEGORY, GPROF_PROVIDER_ID);
- scoped.setValue(ProviderProfileConstants.USE_PROJECT_SETTINGS + GPROF_CATEGORY, true);
- scoped.save();
+ @Before
+ public void setUp() throws Exception {
+ proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), "fibTest2"); //$NON-NLS-1$
+ ProjectScope ps = new ProjectScope(proj.getProject());
+ ScopedPreferenceStore scoped = new ScopedPreferenceStore(ps, ProviderProfileConstants.PLUGIN_ID);
+ scoped.setSearchContexts(new IScopeContext[] { ps, InstanceScope.INSTANCE });
+ scoped.setValue(ProviderProfileConstants.PREFS_KEY + GPROF_CATEGORY, GPROF_PROVIDER_ID);
+ scoped.setValue(ProviderProfileConstants.USE_PROJECT_SETTINGS + GPROF_CATEGORY, true);
+ scoped.save();
- IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(LAUNCH_SHORT_EXTPT);
- IConfigurationElement[] configs = extPoint.getConfigurationElements();
- for (IConfigurationElement cfg : configs) {
- if (cfg.getAttribute("id").equals(ID)){ //$NON-NLS-1$
- try {
- shortcut = (ProviderLaunchShortcut) cfg.createExecutableExtension("class"); //$NON-NLS-1$
- launchConfigTypeId = cfg.getChildren("class")[0].getChildren("parameter")[1].getAttribute("value"); //$NON-NLS-1$
- } catch (Exception e){
- fail (e.getMessage());
- }
- }
- }
- config = createConfiguration(proj.getProject());
- launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
- wc = config.getWorkingCopy();
- }
+ IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(LAUNCH_SHORT_EXTPT);
+ IConfigurationElement[] configs = extPoint.getConfigurationElements();
+ for (IConfigurationElement cfg : configs) {
+ if (cfg.getAttribute("id").equals(ID)){ //$NON-NLS-1$
+ try {
+ shortcut = (ProviderLaunchShortcut) cfg.createExecutableExtension("class"); //$NON-NLS-1$
+ launchConfigTypeId = cfg.getChildren("class")[0].getChildren("parameter")[1].getAttribute("value"); //$NON-NLS-1$
+ } catch (Exception e){
+ fail (e.getMessage());
+ }
+ }
+ }
+ config = createConfiguration(proj.getProject());
+ launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
+ wc = config.getWorkingCopy();
+ }
- @After
- public void tearDown() throws Exception {
- deleteProject(proj);
- wc.delete();
- config.delete();
- }
+ @After
+ public void tearDown() throws Exception {
+ deleteProject(proj);
+ wc.delete();
+ config.delete();
+ }
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(launchConfigTypeId);
- }
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(launchConfigTypeId);
+ }
- @Override
- protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- }
+ @Override
+ protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ }
- @Test
- public void testShortCut() throws CModelException {
- String id = ProviderFramework.getProviderIdToRun(wc, GPROF_CATEGORY);
- assertTrue(id.equals(GPROF_PROVIDER_ID));
- shortcut.launch(proj.getBinaryContainer().getBinaries()[0],
- ILaunchManager.PROFILE_MODE);
- }
+ @Test
+ public void testShortCut() throws CModelException {
+ String id = ProviderFramework.getProviderIdToRun(wc, GPROF_CATEGORY);
+ assertTrue(id.equals(GPROF_PROVIDER_ID));
+ shortcut.launch(proj.getBinaryContainer().getBinaries()[0],
+ ILaunchManager.PROFILE_MODE);
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofTest.java b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofTest.java
index 41667aab39..a276539938 100644
--- a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofTest.java
+++ b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/GprofTest.java
@@ -48,164 +48,164 @@ import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class GprofTest {
- @Parameters
- public static Collection<Object[]> data() {
- List<Object[]> params = new ArrayList<>();
- boolean addr2line2_16 = false;
- try {
- Process p = Runtime.getRuntime().exec("addr2line --version");
- InputStream is = p.getInputStream();
- LineNumberReader reader = new LineNumberReader(
- new InputStreamReader(is));
- String line;
- while ((line = reader.readLine()) != null) {
- if (line.contains("addr2line 2.16.")) {
- addr2line2_16 = true;
- break;
- }
- }
- } catch (IOException _) {
- }
-
- for (File testDir : STJunitUtils.getTestDirs()) {
- final File gmonFile = new File(testDir, OUTPUT_FILE);
- final File binaryFile = new File(testDir, BINARY_FILE);
-
- File view_cg_RefFile_default = new File(testDir,
- "testCallgraphView.ref");
- File view_cg_RefFile_alternate = new File(testDir,
- "testCallgraphView.ref.binutils-2.16");
- File view_cg2_RefFile_default = new File(testDir,
- "testCallgraphTimeView.ref");
- File view_cg2_RefFile_alternate = new File(testDir,
- "testCallgraphTimeView.ref.binutils-2.16");
- final File view_cg_RefFile;
- final File view_cg2_RefFile;
- if (addr2line2_16 && view_cg_RefFile_alternate.exists()) {
- view_cg_RefFile = view_cg_RefFile_alternate;
- } else {
- view_cg_RefFile = view_cg_RefFile_default;
- }
- if (addr2line2_16 && view_cg2_RefFile_alternate.exists()) {
- view_cg2_RefFile = view_cg2_RefFile_alternate;
- } else {
- view_cg2_RefFile = view_cg2_RefFile_default;
- }
- final File view_cg2_DumpFile = new File(testDir,
- "testCallgraphTimeView.dump");
- final File view_cg_DumpFile = new File(testDir,
- "testCallgraphView.dump");
-
- final File view_samplesFile_RefFile = new File(testDir,
- "testSampleView.ref");
- final File view_samplesFile_DumpFile = new File(testDir,
- "testSampleView.dump");
- final File view_samplesFileT_RefFile = new File(testDir,
- "testTimeView.ref");
- final File view_samplesFileT_DumpFile = new File(testDir,
- "testTimeView.dump");
-
- final File view_samplesFunction_RefFile = new File(testDir,
- "testFunctionSampleView.ref");
- final File view_samplesFunction_DumpFile = new File(testDir,
- "testFunctionSampleView.dump");
- final File view_samplesFunctionT_RefFile = new File(testDir,
- "testFunctionTimeView.ref");
- final File view_samplesFunctionT_DumpFile = new File(testDir,
- "testFunctionTimeView.dump");
- final File view_samplesFlat_RefFile = new File(testDir,
- "testFlatSampleView.ref");
- final File view_samplesFlat_DumpFile = new File(testDir,
- "testFlatSampleView.dump");
- final File view_samplesFlatT_RefFile = new File(testDir,
- "testFlatTimeView.ref");
- final File view_samplesFlatT_DumpFile = new File(testDir,
- "testFlatTimeView.dump");
-
- IBinaryObject binary = STSymbolManager.sharedInstance
- .getBinaryObject(new Path(binaryFile.getAbsolutePath()));
- final GmonDecoder gd = new GmonDecoder(binary, null);
- try {
- gd.read(gmonFile.getAbsolutePath());
- } catch (IOException e) {
- e.printStackTrace();
- }
- params.add(new Object[] { gmonFile, gd, view_cg_RefFile,
- view_cg_DumpFile, CallGraphContentProvider.sharedInstance,
- false });
- params.add(new Object[] { gmonFile, gd, view_cg2_RefFile,
- view_cg2_DumpFile, CallGraphContentProvider.sharedInstance,
- true });
- params.add(new Object[] { gmonFile, gd, view_samplesFile_RefFile,
- view_samplesFile_DumpFile,
- FileHistogramContentProvider.sharedInstance, false });
- params.add(new Object[] { gmonFile, gd, view_samplesFileT_RefFile,
- view_samplesFileT_DumpFile,
- FileHistogramContentProvider.sharedInstance, true });
- params.add(new Object[] { gmonFile, gd,
- view_samplesFunction_RefFile,
- view_samplesFunction_DumpFile,
- FunctionHistogramContentProvider.sharedInstance, false });
- params.add(new Object[] { gmonFile, gd,
- view_samplesFunctionT_RefFile,
- view_samplesFunctionT_DumpFile,
- FunctionHistogramContentProvider.sharedInstance, true });
- params.add(new Object[] { gmonFile, gd, view_samplesFlat_RefFile,
- view_samplesFlat_DumpFile,
- FlatHistogramContentProvider.sharedInstance, false });
- params.add(new Object[] { gmonFile, gd, view_samplesFlatT_RefFile,
- view_samplesFlatT_DumpFile,
- FlatHistogramContentProvider.sharedInstance, true });
- }
- return params;
- }
-
- private File gmonFile;
- private GmonDecoder gd;
- private File refFile;
- private File dumpFile;
- private ITreeContentProvider contentProvider;
- private boolean timeMode;
-
- public GprofTest(File gmonFile, GmonDecoder gd, File refFile,
- File dumpFile, ITreeContentProvider contentProvider,
- boolean timeMode) {
- this.gmonFile = gmonFile;
- this.gd = gd;
- this.refFile = refFile;
- this.dumpFile = dumpFile;
- this.contentProvider = contentProvider;
- this.timeMode = timeMode;
-
- }
-
- private void changeMode(GmonView view, boolean timeModeRequested) {
- AbstractSTTreeViewer gmonViewer = (AbstractSTTreeViewer) view
- .getSTViewer();
- GmonDecoder decoder = (GmonDecoder) gmonViewer.getInput();
- int prof_rate = decoder.getHistogramDecoder().getProfRate();
- if (prof_rate == 0) {
- return;
- }
-
- TreeColumn tc = gmonViewer.getViewer().getTree().getColumn(1);
- SampleProfField spf = (SampleProfField) tc.getData();
-
- if (spf.getColumnHeaderText().endsWith("Samples") ^ !timeModeRequested) {
- new SwitchSampleTimeAction(view).run();
- }
- }
-
- @Test
- public void testView() {
- GmonView view = GmonView.displayGprofView(gd,
- gmonFile.getAbsolutePath());
- SwitchContentProviderAction action = new SwitchContentProviderAction(
- "testAction", "icons/ch_callees.png" /* to avoid error */, view
- .getSTViewer().getViewer(), contentProvider);
- action.run();
- changeMode(view, timeMode);
- STJunitUtils.testCSVExport(view, dumpFile.getAbsolutePath(),
- refFile.getAbsolutePath());
- }
+ @Parameters
+ public static Collection<Object[]> data() {
+ List<Object[]> params = new ArrayList<>();
+ boolean addr2line2_16 = false;
+ try {
+ Process p = Runtime.getRuntime().exec("addr2line --version");
+ InputStream is = p.getInputStream();
+ LineNumberReader reader = new LineNumberReader(
+ new InputStreamReader(is));
+ String line;
+ while ((line = reader.readLine()) != null) {
+ if (line.contains("addr2line 2.16.")) {
+ addr2line2_16 = true;
+ break;
+ }
+ }
+ } catch (IOException _) {
+ }
+
+ for (File testDir : STJunitUtils.getTestDirs()) {
+ final File gmonFile = new File(testDir, OUTPUT_FILE);
+ final File binaryFile = new File(testDir, BINARY_FILE);
+
+ File view_cg_RefFile_default = new File(testDir,
+ "testCallgraphView.ref");
+ File view_cg_RefFile_alternate = new File(testDir,
+ "testCallgraphView.ref.binutils-2.16");
+ File view_cg2_RefFile_default = new File(testDir,
+ "testCallgraphTimeView.ref");
+ File view_cg2_RefFile_alternate = new File(testDir,
+ "testCallgraphTimeView.ref.binutils-2.16");
+ final File view_cg_RefFile;
+ final File view_cg2_RefFile;
+ if (addr2line2_16 && view_cg_RefFile_alternate.exists()) {
+ view_cg_RefFile = view_cg_RefFile_alternate;
+ } else {
+ view_cg_RefFile = view_cg_RefFile_default;
+ }
+ if (addr2line2_16 && view_cg2_RefFile_alternate.exists()) {
+ view_cg2_RefFile = view_cg2_RefFile_alternate;
+ } else {
+ view_cg2_RefFile = view_cg2_RefFile_default;
+ }
+ final File view_cg2_DumpFile = new File(testDir,
+ "testCallgraphTimeView.dump");
+ final File view_cg_DumpFile = new File(testDir,
+ "testCallgraphView.dump");
+
+ final File view_samplesFile_RefFile = new File(testDir,
+ "testSampleView.ref");
+ final File view_samplesFile_DumpFile = new File(testDir,
+ "testSampleView.dump");
+ final File view_samplesFileT_RefFile = new File(testDir,
+ "testTimeView.ref");
+ final File view_samplesFileT_DumpFile = new File(testDir,
+ "testTimeView.dump");
+
+ final File view_samplesFunction_RefFile = new File(testDir,
+ "testFunctionSampleView.ref");
+ final File view_samplesFunction_DumpFile = new File(testDir,
+ "testFunctionSampleView.dump");
+ final File view_samplesFunctionT_RefFile = new File(testDir,
+ "testFunctionTimeView.ref");
+ final File view_samplesFunctionT_DumpFile = new File(testDir,
+ "testFunctionTimeView.dump");
+ final File view_samplesFlat_RefFile = new File(testDir,
+ "testFlatSampleView.ref");
+ final File view_samplesFlat_DumpFile = new File(testDir,
+ "testFlatSampleView.dump");
+ final File view_samplesFlatT_RefFile = new File(testDir,
+ "testFlatTimeView.ref");
+ final File view_samplesFlatT_DumpFile = new File(testDir,
+ "testFlatTimeView.dump");
+
+ IBinaryObject binary = STSymbolManager.sharedInstance
+ .getBinaryObject(new Path(binaryFile.getAbsolutePath()));
+ final GmonDecoder gd = new GmonDecoder(binary, null);
+ try {
+ gd.read(gmonFile.getAbsolutePath());
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ params.add(new Object[] { gmonFile, gd, view_cg_RefFile,
+ view_cg_DumpFile, CallGraphContentProvider.sharedInstance,
+ false });
+ params.add(new Object[] { gmonFile, gd, view_cg2_RefFile,
+ view_cg2_DumpFile, CallGraphContentProvider.sharedInstance,
+ true });
+ params.add(new Object[] { gmonFile, gd, view_samplesFile_RefFile,
+ view_samplesFile_DumpFile,
+ FileHistogramContentProvider.sharedInstance, false });
+ params.add(new Object[] { gmonFile, gd, view_samplesFileT_RefFile,
+ view_samplesFileT_DumpFile,
+ FileHistogramContentProvider.sharedInstance, true });
+ params.add(new Object[] { gmonFile, gd,
+ view_samplesFunction_RefFile,
+ view_samplesFunction_DumpFile,
+ FunctionHistogramContentProvider.sharedInstance, false });
+ params.add(new Object[] { gmonFile, gd,
+ view_samplesFunctionT_RefFile,
+ view_samplesFunctionT_DumpFile,
+ FunctionHistogramContentProvider.sharedInstance, true });
+ params.add(new Object[] { gmonFile, gd, view_samplesFlat_RefFile,
+ view_samplesFlat_DumpFile,
+ FlatHistogramContentProvider.sharedInstance, false });
+ params.add(new Object[] { gmonFile, gd, view_samplesFlatT_RefFile,
+ view_samplesFlatT_DumpFile,
+ FlatHistogramContentProvider.sharedInstance, true });
+ }
+ return params;
+ }
+
+ private File gmonFile;
+ private GmonDecoder gd;
+ private File refFile;
+ private File dumpFile;
+ private ITreeContentProvider contentProvider;
+ private boolean timeMode;
+
+ public GprofTest(File gmonFile, GmonDecoder gd, File refFile,
+ File dumpFile, ITreeContentProvider contentProvider,
+ boolean timeMode) {
+ this.gmonFile = gmonFile;
+ this.gd = gd;
+ this.refFile = refFile;
+ this.dumpFile = dumpFile;
+ this.contentProvider = contentProvider;
+ this.timeMode = timeMode;
+
+ }
+
+ private void changeMode(GmonView view, boolean timeModeRequested) {
+ AbstractSTTreeViewer gmonViewer = (AbstractSTTreeViewer) view
+ .getSTViewer();
+ GmonDecoder decoder = (GmonDecoder) gmonViewer.getInput();
+ int prof_rate = decoder.getHistogramDecoder().getProfRate();
+ if (prof_rate == 0) {
+ return;
+ }
+
+ TreeColumn tc = gmonViewer.getViewer().getTree().getColumn(1);
+ SampleProfField spf = (SampleProfField) tc.getData();
+
+ if (spf.getColumnHeaderText().endsWith("Samples") ^ !timeModeRequested) {
+ new SwitchSampleTimeAction(view).run();
+ }
+ }
+
+ @Test
+ public void testView() {
+ GmonView view = GmonView.displayGprofView(gd,
+ gmonFile.getAbsolutePath());
+ SwitchContentProviderAction action = new SwitchContentProviderAction(
+ "testAction", "icons/ch_callees.png" /* to avoid error */, view
+ .getSTViewer().getViewer(), contentProvider);
+ action.run();
+ changeMode(view, timeMode);
+ STJunitUtils.testCSVExport(view, dumpFile.getAbsolutePath(),
+ refFile.getAbsolutePath());
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/STJunitUtils.java b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/STJunitUtils.java
index d295cd8a64..ba490afe2b 100644
--- a/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/STJunitUtils.java
+++ b/gprof/org.eclipse.linuxtools.gprof.test/src/org/eclipse/linuxtools/internal/gprof/test/STJunitUtils.java
@@ -39,203 +39,203 @@ import org.osgi.framework.Bundle;
*/
public class STJunitUtils {
- public static final String BINARY_FILE = "a.out";
- public static final String OUTPUT_FILE = "gmon.out";
- public static final String DIRECTORY_SUFFIX = "_gprof_input";
-
-
- /**
- * Test CSV export of the given view
- * @param view
- * @param dumpFullFileName
- * @param refFullFileName
- */
- public static boolean testCSVExport(AbstractSTDataView view, String dumpFullFileName, String refFullFileName) {
- STDataViewersCSVExporter exporter = new STDataViewersCSVExporter(view.getSTViewer());
- exporter.exportTo(dumpFullFileName, new NullProgressMonitor());
- // compare with ref
- return compareCSVIgnoreEOL(dumpFullFileName, refFullFileName, true);
- }
-
- /**
- * Utility method to compare files
- * @param dumpFile
- * @param refFile
- * @return
- */
- public static boolean compareIgnoreEOL(String dumpFile, String refFile, boolean deleteDumpFileIfOk) {
- String message = "Comparing ref file ("+refFile+ ")and dump file (" +
- dumpFile+")";
- boolean equals = false;
- try (LineNumberReader is1 = new LineNumberReader(new FileReader(dumpFile));
- LineNumberReader is2 = new LineNumberReader(new FileReader(refFile))){
- do {
- String line1 = is1.readLine();
- String line2 = is2.readLine();
- if (line1 == null) {
- if (line2 == null) {
- equals = true;
- }
- break;
- } else if (line2 == null || !line1.equals(line2)) {
- break;
- }
- } while (true);
-
- if (!equals) {
- assertEquals(message + ": not correspond ", true, false);
- }
-
- is1.close();
- is2.close();
- // delete dump only for successful tests
- if (equals && deleteDumpFileIfOk) {
- new File(dumpFile).delete();
- }
- }catch (FileNotFoundException fnfe) {
- message += "... FAILED: One of these files may not exist";
- assertNull(message, fnfe);
- }
- catch (Exception e) {
- message += ": exception raised ... FAILED";
- assertNull(message, e);
- }
- return equals;
- }
-
- /**
- * Utility method to compare exported CSV files
- * @param dumpFile
- * @param refFile
- * @return
- */
- public static boolean compareCSVIgnoreEOL(String dumpFile, String refFile, boolean deleteDumpFileIfOk) {
- String message = "Comparing ref file ("+refFile+ ")and dump file (" +
- dumpFile+")";
- boolean equals = false;
- String str = "[in-charge]"; // this string can be dumped according to binutils version installed on local machine
-
- try (LineNumberReader is1 = new LineNumberReader(new FileReader(dumpFile));
- LineNumberReader is2 = new LineNumberReader(new FileReader(refFile))){
- do {
- String line1 = is1.readLine();
- String line2 = is2.readLine();
- int length = str.length();
- if (line1 == null) {
- if (line2 == null) {
- equals = true;
- }
- break;
- } else if (line1.contains(str)){
- int idx = line1.indexOf("[in-charge]");
- char c = line1.charAt(idx -1);
- if (c == ' ' ){
- idx--;
- length++;
- }
- line1 = line1.substring(0, idx) + line1.substring(idx+length, line1.length());
- if (!line1.equals(line2))
- break;
- } else if (line2 == null || !line1.equals(line2)) {
- break;
- }
- } while (true);
-
- is1.close();
- is2.close();
- if (!equals) {
- StringBuffer msg = new StringBuffer(message + ": not correspond ");
- msg.append("\n========= begin dump file =========\n");
- try (FileReader fr = new FileReader(dumpFile)) {
- int c;
- while ((c = fr.read()) != -1) {
- msg.append((char) c);
- }
- }
- msg.append("\n========= end dump file =========\n");
- assertEquals(msg.toString(), true, false);
- }
-
- // delete dump only for successful tests
- if (equals && deleteDumpFileIfOk) {
- new File(dumpFile).delete();
- }
- }catch (FileNotFoundException _) {
- message += "... FAILED: One of these files may not exist";
- assertNull(message, _);
- }
- catch (Exception _) {
- message += ": exception raised ... FAILED";
- assertNull(message, _);
- }
- return equals;
- }
-
- /**
- * Utility method to compare Input streams
- * @param ISdump
- * @param ISref
- * @return
- * @throws IOException
- */
- public static boolean compare(InputStream ISdump, InputStream ISref) throws IOException {
- try {
- boolean equals = false;
- do {
- int char1 = ISdump.read();
- int char2 = ISref.read();
- if (char1 != char2)
- break;
- if (char1 == -1) {
- equals = true;
- break;
- }
- } while (true);
- return equals;
- } finally {
- ISdump.close();
- ISref.close();
- }
- }
-
- /**
- * Gets the absolute path of a resource in the given plugin
- * @param pluginId
- * @param relativeName
- * @return an absolute path to a file
- */
- public static String getAbsolutePath(String pluginId, String relativeName) {
- Bundle b = Platform.getBundle(pluginId);
- URL url = FileLocator.find(b, new Path(relativeName), null);
- try {
- url = FileLocator.toFileURL(url);
- } catch (IOException e) {
- assertNotNull("Problem locating " + relativeName + " in" + pluginId,e);
- }
- String filename = url.getFile();
- return filename;
- }
-
- /**
- * Utility method
- * @return the list of directories that belong to the pluginDirectory and
- * ends with the given extensionSuffix
- */
- public static File[] getTestDirs() {
- // load directories containing tests
- String filename = getAbsolutePath("org.eclipse.linuxtools.gprof.test", ".");
- File dir = new File(filename);
- File[] testDirs = dir.listFiles(
- new FileFilter() {
- @Override
- public boolean accept(File arg0) {
- return (arg0.isDirectory() && arg0.getName().matches(".*" + DIRECTORY_SUFFIX));
- }
- }
- );
-
- // test if there is any directory samples
- assertNotNull("No project files to test",testDirs);
- return testDirs;
- }
+ public static final String BINARY_FILE = "a.out";
+ public static final String OUTPUT_FILE = "gmon.out";
+ public static final String DIRECTORY_SUFFIX = "_gprof_input";
+
+
+ /**
+ * Test CSV export of the given view
+ * @param view
+ * @param dumpFullFileName
+ * @param refFullFileName
+ */
+ public static boolean testCSVExport(AbstractSTDataView view, String dumpFullFileName, String refFullFileName) {
+ STDataViewersCSVExporter exporter = new STDataViewersCSVExporter(view.getSTViewer());
+ exporter.exportTo(dumpFullFileName, new NullProgressMonitor());
+ // compare with ref
+ return compareCSVIgnoreEOL(dumpFullFileName, refFullFileName, true);
+ }
+
+ /**
+ * Utility method to compare files
+ * @param dumpFile
+ * @param refFile
+ * @return
+ */
+ public static boolean compareIgnoreEOL(String dumpFile, String refFile, boolean deleteDumpFileIfOk) {
+ String message = "Comparing ref file ("+refFile+ ")and dump file (" +
+ dumpFile+")";
+ boolean equals = false;
+ try (LineNumberReader is1 = new LineNumberReader(new FileReader(dumpFile));
+ LineNumberReader is2 = new LineNumberReader(new FileReader(refFile))){
+ do {
+ String line1 = is1.readLine();
+ String line2 = is2.readLine();
+ if (line1 == null) {
+ if (line2 == null) {
+ equals = true;
+ }
+ break;
+ } else if (line2 == null || !line1.equals(line2)) {
+ break;
+ }
+ } while (true);
+
+ if (!equals) {
+ assertEquals(message + ": not correspond ", true, false);
+ }
+
+ is1.close();
+ is2.close();
+ // delete dump only for successful tests
+ if (equals && deleteDumpFileIfOk) {
+ new File(dumpFile).delete();
+ }
+ }catch (FileNotFoundException fnfe) {
+ message += "... FAILED: One of these files may not exist";
+ assertNull(message, fnfe);
+ }
+ catch (Exception e) {
+ message += ": exception raised ... FAILED";
+ assertNull(message, e);
+ }
+ return equals;
+ }
+
+ /**
+ * Utility method to compare exported CSV files
+ * @param dumpFile
+ * @param refFile
+ * @return
+ */
+ public static boolean compareCSVIgnoreEOL(String dumpFile, String refFile, boolean deleteDumpFileIfOk) {
+ String message = "Comparing ref file ("+refFile+ ")and dump file (" +
+ dumpFile+")";
+ boolean equals = false;
+ String str = "[in-charge]"; // this string can be dumped according to binutils version installed on local machine
+
+ try (LineNumberReader is1 = new LineNumberReader(new FileReader(dumpFile));
+ LineNumberReader is2 = new LineNumberReader(new FileReader(refFile))){
+ do {
+ String line1 = is1.readLine();
+ String line2 = is2.readLine();
+ int length = str.length();
+ if (line1 == null) {
+ if (line2 == null) {
+ equals = true;
+ }
+ break;
+ } else if (line1.contains(str)){
+ int idx = line1.indexOf("[in-charge]");
+ char c = line1.charAt(idx -1);
+ if (c == ' ' ){
+ idx--;
+ length++;
+ }
+ line1 = line1.substring(0, idx) + line1.substring(idx+length, line1.length());
+ if (!line1.equals(line2))
+ break;
+ } else if (line2 == null || !line1.equals(line2)) {
+ break;
+ }
+ } while (true);
+
+ is1.close();
+ is2.close();
+ if (!equals) {
+ StringBuffer msg = new StringBuffer(message + ": not correspond ");
+ msg.append("\n========= begin dump file =========\n");
+ try (FileReader fr = new FileReader(dumpFile)) {
+ int c;
+ while ((c = fr.read()) != -1) {
+ msg.append((char) c);
+ }
+ }
+ msg.append("\n========= end dump file =========\n");
+ assertEquals(msg.toString(), true, false);
+ }
+
+ // delete dump only for successful tests
+ if (equals && deleteDumpFileIfOk) {
+ new File(dumpFile).delete();
+ }
+ }catch (FileNotFoundException _) {
+ message += "... FAILED: One of these files may not exist";
+ assertNull(message, _);
+ }
+ catch (Exception _) {
+ message += ": exception raised ... FAILED";
+ assertNull(message, _);
+ }
+ return equals;
+ }
+
+ /**
+ * Utility method to compare Input streams
+ * @param ISdump
+ * @param ISref
+ * @return
+ * @throws IOException
+ */
+ public static boolean compare(InputStream ISdump, InputStream ISref) throws IOException {
+ try {
+ boolean equals = false;
+ do {
+ int char1 = ISdump.read();
+ int char2 = ISref.read();
+ if (char1 != char2)
+ break;
+ if (char1 == -1) {
+ equals = true;
+ break;
+ }
+ } while (true);
+ return equals;
+ } finally {
+ ISdump.close();
+ ISref.close();
+ }
+ }
+
+ /**
+ * Gets the absolute path of a resource in the given plugin
+ * @param pluginId
+ * @param relativeName
+ * @return an absolute path to a file
+ */
+ public static String getAbsolutePath(String pluginId, String relativeName) {
+ Bundle b = Platform.getBundle(pluginId);
+ URL url = FileLocator.find(b, new Path(relativeName), null);
+ try {
+ url = FileLocator.toFileURL(url);
+ } catch (IOException e) {
+ assertNotNull("Problem locating " + relativeName + " in" + pluginId,e);
+ }
+ String filename = url.getFile();
+ return filename;
+ }
+
+ /**
+ * Utility method
+ * @return the list of directories that belong to the pluginDirectory and
+ * ends with the given extensionSuffix
+ */
+ public static File[] getTestDirs() {
+ // load directories containing tests
+ String filename = getAbsolutePath("org.eclipse.linuxtools.gprof.test", ".");
+ File dir = new File(filename);
+ File[] testDirs = dir.listFiles(
+ new FileFilter() {
+ @Override
+ public boolean accept(File arg0) {
+ return (arg0.isDirectory() && arg0.getName().matches(".*" + DIRECTORY_SUFFIX));
+ }
+ }
+ );
+
+ // test if there is any directory samples
+ assertNotNull("No project files to test",testDirs);
+ return testDirs;
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/Activator.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/Activator.java
index 40f7da000e..16c42691d4 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/Activator.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/Activator.java
@@ -19,42 +19,42 @@ import org.osgi.framework.BundleContext;
*/
public class Activator extends AbstractUIPlugin {
- /** The plug-in ID */
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.gprof"; //$NON-NLS-1$
-
- // The shared instance
- private static Activator plugin;
-
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
-
- /**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
+ /** The plug-in ID */
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.gprof"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns an image descriptor for the image file at the given
+ * plug-in relative path
+ *
+ * @param path the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/OpenGmonAction.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/OpenGmonAction.java
index 5b6d7af363..16780cb168 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/OpenGmonAction.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/OpenGmonAction.java
@@ -33,43 +33,43 @@ import org.eclipse.ui.PlatformUI;
*/
public class OpenGmonAction implements IEditorLauncher {
- @Override
- public void open(IPath file) {
- String s = getDefaultBinary(file);
- Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
- OpenGmonDialog d = new OpenGmonDialog(shell, s, file);
- if (d.open() != Window.OK) {
- return;
- }
- String binaryPath = d.getBinaryFile();
- IProject project = null;
- IFile f = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(file);
- if (f != null) {
- project = f.getProject();
- }
- GmonView.displayGprofView(binaryPath, file.toOSString(), project);
- }
+ @Override
+ public void open(IPath file) {
+ String s = getDefaultBinary(file);
+ Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
+ OpenGmonDialog d = new OpenGmonDialog(shell, s, file);
+ if (d.open() != Window.OK) {
+ return;
+ }
+ String binaryPath = d.getBinaryFile();
+ IProject project = null;
+ IFile f = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(file);
+ if (f != null) {
+ project = f.getProject();
+ }
+ GmonView.displayGprofView(binaryPath, file.toOSString(), project);
+ }
- private String getDefaultBinary(IPath file) {
- IProject project = null;
- IFile c = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(file);
- if (c != null) {
- project = c.getProject();
- if (project != null && project.exists()) {
- ICProject cproject = CoreModel.getDefault().create(project);
- if (cproject != null) {
- try {
- IBinary[] b = cproject.getBinaryContainer()
- .getBinaries();
- if (b != null && b.length > 0 && b[0] != null) {
- IResource r = b[0].getResource();
- return r.getLocation().toOSString();
- }
- } catch (CModelException _) {
- }
- }
- }
- }
- return ""; //$NON-NLS-1$
- }
+ private String getDefaultBinary(IPath file) {
+ IProject project = null;
+ IFile c = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(file);
+ if (c != null) {
+ project = c.getProject();
+ if (project != null && project.exists()) {
+ ICProject cproject = CoreModel.getDefault().create(project);
+ if (cproject != null) {
+ try {
+ IBinary[] b = cproject.getBinaryContainer()
+ .getBinaries();
+ if (b != null && b.length > 0 && b[0] != null) {
+ IResource r = b[0].getResource();
+ return r.getLocation().toOSString();
+ }
+ } catch (CModelException _) {
+ }
+ }
+ }
+ }
+ return ""; //$NON-NLS-1$
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/SwitchContentProviderAction.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/SwitchContentProviderAction.java
index 0fb697c1ee..82ff6d7946 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/SwitchContentProviderAction.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/SwitchContentProviderAction.java
@@ -24,30 +24,30 @@ import org.eclipse.linuxtools.internal.gprof.Activator;
*/
public class SwitchContentProviderAction extends Action {
- private final ColumnViewer viewer;
- private final ITreeContentProvider provider;
+ private final ColumnViewer viewer;
+ private final ITreeContentProvider provider;
- /**
- * Constructor
- * @param name of the action
- * @param iconPath the icon path
- * @param viewer TreeViewer
- * @param provider the new content provider for the given TreeViewer
- */
- public SwitchContentProviderAction(String name, String iconPath, ColumnViewer viewer, ITreeContentProvider provider) {
- super(name, AS_RADIO_BUTTON);
- this.setImageDescriptor(Activator.getImageDescriptor(iconPath));
- this.setToolTipText(name);
- this.viewer = viewer;
- this.provider = provider;
- }
+ /**
+ * Constructor
+ * @param name of the action
+ * @param iconPath the icon path
+ * @param viewer TreeViewer
+ * @param provider the new content provider for the given TreeViewer
+ */
+ public SwitchContentProviderAction(String name, String iconPath, ColumnViewer viewer, ITreeContentProvider provider) {
+ super(name, AS_RADIO_BUTTON);
+ this.setImageDescriptor(Activator.getImageDescriptor(iconPath));
+ this.setToolTipText(name);
+ this.viewer = viewer;
+ this.provider = provider;
+ }
- @Override
- public void run() {
- viewer.getControl().setRedraw(false);
- viewer.setContentProvider(provider);
- ((TreeViewer)viewer).expandToLevel(2);
- viewer.getControl().setRedraw(true);
- }
+ @Override
+ public void run() {
+ viewer.getControl().setRedraw(false);
+ viewer.setContentProvider(provider);
+ ((TreeViewer)viewer).expandToLevel(2);
+ viewer.getControl().setRedraw(true);
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/SwitchSampleTimeAction.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/SwitchSampleTimeAction.java
index 6daef53f8f..3d9bb7be0d 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/SwitchSampleTimeAction.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/action/SwitchSampleTimeAction.java
@@ -30,41 +30,41 @@ import org.eclipse.swt.widgets.TreeColumn;
*/
public class SwitchSampleTimeAction extends Action {
- private final AbstractSTDataView view;
+ private final AbstractSTDataView view;
- /**
- * Constructor
- * @param name name of the action
- * @param view the Gmon viewer
- */
- public SwitchSampleTimeAction(AbstractSTDataView view) {
- super(Messages.SwitchSampleTimeAction_SWITCH_SAMPLE_TIME, SWT.TOGGLE);
- this.setImageDescriptor(Activator.getImageDescriptor("icons/datetime_obj.gif")); //$NON-NLS-1$
- this.setToolTipText(Messages.SwitchSampleTimeAction_SWITCH_SAMPLE_TIME);
- this.view = view;
- }
+ /**
+ * Constructor
+ * @param name name of the action
+ * @param view the Gmon viewer
+ */
+ public SwitchSampleTimeAction(AbstractSTDataView view) {
+ super(Messages.SwitchSampleTimeAction_SWITCH_SAMPLE_TIME, SWT.TOGGLE);
+ this.setImageDescriptor(Activator.getImageDescriptor("icons/datetime_obj.gif")); //$NON-NLS-1$
+ this.setToolTipText(Messages.SwitchSampleTimeAction_SWITCH_SAMPLE_TIME);
+ this.view = view;
+ }
- @Override
- public void run() {
- AbstractSTTreeViewer gmonViewer = (AbstractSTTreeViewer)view.getSTViewer();
- GmonDecoder decoder = (GmonDecoder) gmonViewer.getInput();
- if(decoder != null){
- int prof_rate = decoder.getHistogramDecoder().getProfRate();
+ @Override
+ public void run() {
+ AbstractSTTreeViewer gmonViewer = (AbstractSTTreeViewer)view.getSTViewer();
+ GmonDecoder decoder = (GmonDecoder) gmonViewer.getInput();
+ if(decoder != null){
+ int prof_rate = decoder.getHistogramDecoder().getProfRate();
- if (prof_rate == 0) {
- MessageDialog.openError(view.getSite().getShell(),
- Messages.SwitchSampleTimeAction_GMON_PROF_RATE_IS_NULL,
- Messages.SwitchSampleTimeAction_GMON_PROF_RATE_IS_NULL_LONG_MSG);
- return;
- }
+ if (prof_rate == 0) {
+ MessageDialog.openError(view.getSite().getShell(),
+ Messages.SwitchSampleTimeAction_GMON_PROF_RATE_IS_NULL,
+ Messages.SwitchSampleTimeAction_GMON_PROF_RATE_IS_NULL_LONG_MSG);
+ return;
+ }
- TreeColumn tc = gmonViewer.getViewer().getTree().getColumn(1);
- SampleProfField spf = (SampleProfField) tc.getData();
- spf.toggle();
- tc.setText(spf.getColumnHeaderText());
- gmonViewer.getViewer().refresh();
- }
- }
+ TreeColumn tc = gmonViewer.getViewer().getTree().getColumn(1);
+ SampleProfField spf = (SampleProfField) tc.getData();
+ spf.toggle();
+ tc.setText(spf.getColumnHeaderText());
+ gmonViewer.getViewer().refresh();
+ }
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/CallGraphDecoder.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/CallGraphDecoder.java
index 01b2605178..b32a8051dc 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/CallGraphDecoder.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/CallGraphDecoder.java
@@ -31,73 +31,73 @@ import org.eclipse.linuxtools.internal.gprof.view.histogram.HistRoot;
*/
public class CallGraphDecoder {
- protected final GmonDecoder decoder;
-
-
- private final Map<ISymbol, CallGraphNode> nodes = new HashMap<>();
-
- /**
- * Constructor
- * @param decoder the Gmon decoder
- */
- public CallGraphDecoder(GmonDecoder decoder) {
- this.decoder = decoder;
- }
-
- /**
- * Decode call-graph record from gmon file.
- * @param stream
- * @throws IOException
- */
- public void decodeCallGraphRecord(DataInput stream, boolean BSDFormat) throws IOException {
- long from_pc = readAddress(stream);
- long self_pc = readAddress(stream);
- int count = BSDFormat?(int)readAddress(stream):stream.readInt();
- IBinaryObject program = decoder.getProgram();
- IAddressFactory addressFactory = program.getAddressFactory();
- IAddress parentAddress = addressFactory.createAddress(Long.toString(from_pc));
- ISymbol parentSymbol = program.getSymbol(parentAddress);
- IAddress childAddress = addressFactory.createAddress(Long.toString(self_pc));
- ISymbol childSymbol = program.getSymbol(childAddress);
- if (childSymbol == null || parentSymbol == null) {
- return;
- }
- addCallArc(parentSymbol, parentAddress, childSymbol, count);
- }
-
-
- protected long readAddress(DataInput stream) throws IOException {
- long ret = stream.readInt() & 0xFFFFFFFFL;
- return ret;
- }
-
-
- private void addCallArc(ISymbol parent, IAddress parentAddress, ISymbol child, int count) {
- CallGraphNode parentNode = nodes.get(parent);
- CallGraphNode childNode = nodes.get(child);
- if (parentNode == null) {
- parentNode = new CallGraphNode(parent);
- nodes.put(parent, parentNode);
- }
- if (childNode == null) {
- childNode = new CallGraphNode(child);
- nodes.put(child, childNode);
- }
- CallGraphArc arc = parentNode.getOutputArc(childNode);
- if (arc == null) {
- arc = new CallGraphArc(parentNode, parentAddress, childNode, count, decoder.getProgram(), decoder.getProject());
- parentNode.getChildren().add(arc);
- childNode.getParents().add(arc);
- } else {
- arc.setCount(arc.getCount() + count);
- }
- }
-
- void populate(HistRoot rootNode) {
- for (CallGraphNode callGraphNode : nodes.values()) {
- rootNode.addCallGraphNode(callGraphNode);
- }
- }
+ protected final GmonDecoder decoder;
+
+
+ private final Map<ISymbol, CallGraphNode> nodes = new HashMap<>();
+
+ /**
+ * Constructor
+ * @param decoder the Gmon decoder
+ */
+ public CallGraphDecoder(GmonDecoder decoder) {
+ this.decoder = decoder;
+ }
+
+ /**
+ * Decode call-graph record from gmon file.
+ * @param stream
+ * @throws IOException
+ */
+ public void decodeCallGraphRecord(DataInput stream, boolean BSDFormat) throws IOException {
+ long from_pc = readAddress(stream);
+ long self_pc = readAddress(stream);
+ int count = BSDFormat?(int)readAddress(stream):stream.readInt();
+ IBinaryObject program = decoder.getProgram();
+ IAddressFactory addressFactory = program.getAddressFactory();
+ IAddress parentAddress = addressFactory.createAddress(Long.toString(from_pc));
+ ISymbol parentSymbol = program.getSymbol(parentAddress);
+ IAddress childAddress = addressFactory.createAddress(Long.toString(self_pc));
+ ISymbol childSymbol = program.getSymbol(childAddress);
+ if (childSymbol == null || parentSymbol == null) {
+ return;
+ }
+ addCallArc(parentSymbol, parentAddress, childSymbol, count);
+ }
+
+
+ protected long readAddress(DataInput stream) throws IOException {
+ long ret = stream.readInt() & 0xFFFFFFFFL;
+ return ret;
+ }
+
+
+ private void addCallArc(ISymbol parent, IAddress parentAddress, ISymbol child, int count) {
+ CallGraphNode parentNode = nodes.get(parent);
+ CallGraphNode childNode = nodes.get(child);
+ if (parentNode == null) {
+ parentNode = new CallGraphNode(parent);
+ nodes.put(parent, parentNode);
+ }
+ if (childNode == null) {
+ childNode = new CallGraphNode(child);
+ nodes.put(child, childNode);
+ }
+ CallGraphArc arc = parentNode.getOutputArc(childNode);
+ if (arc == null) {
+ arc = new CallGraphArc(parentNode, parentAddress, childNode, count, decoder.getProgram(), decoder.getProject());
+ parentNode.getChildren().add(arc);
+ childNode.getParents().add(arc);
+ } else {
+ arc.setCount(arc.getCount() + count);
+ }
+ }
+
+ void populate(HistRoot rootNode) {
+ for (CallGraphNode callGraphNode : nodes.values()) {
+ rootNode.addCallGraphNode(callGraphNode);
+ }
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/GmonDecoder.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/GmonDecoder.java
index 4cdfbfcf35..2e9036aa0f 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/GmonDecoder.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/GmonDecoder.java
@@ -105,53 +105,53 @@ public class GmonDecoder {
* @throws IOException
*/
public void read(String file) throws IOException {
- this.file = file;
- DataInputStream beStream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
- if (program.isLittleEndian()) {
- try (LEDataInputStream leStream = new LEDataInputStream(beStream)) {
- leStream.mark(1000);
- boolean gmonType = readHeader(leStream);
- if (gmonType)
- readGmonContent(leStream);
- else {
- leStream.reset();
- histo.decodeOldHeader(leStream);
- histo.decodeHistRecord(leStream);
- try {
- do {
- this.callGraph.decodeCallGraphRecord(leStream, true);
- } while (true);
- } catch (EOFException e) {
- // normal. End of file reached.
- }
- this.callGraph.populate(rootNode);
- this.histo.assignSamplesSymbol();
- }
- }
- } else {
- try {
- beStream.mark(1000);
- boolean gmonType = readHeader(beStream);
- if (gmonType) {
- readGmonContent(beStream);
- } else {
- beStream.reset();
- histo.decodeOldHeader(beStream);
- histo.decodeHistRecord(beStream);
- try {
- do {
- this.callGraph.decodeCallGraphRecord(beStream, true);
- } while (true);
- } catch (EOFException e) {
- // normal. End of file reached.
- }
- this.callGraph.populate(rootNode);
- this.histo.assignSamplesSymbol();
- }
- } finally {
- beStream.close();
- }
- }
+ this.file = file;
+ DataInputStream beStream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
+ if (program.isLittleEndian()) {
+ try (LEDataInputStream leStream = new LEDataInputStream(beStream)) {
+ leStream.mark(1000);
+ boolean gmonType = readHeader(leStream);
+ if (gmonType)
+ readGmonContent(leStream);
+ else {
+ leStream.reset();
+ histo.decodeOldHeader(leStream);
+ histo.decodeHistRecord(leStream);
+ try {
+ do {
+ this.callGraph.decodeCallGraphRecord(leStream, true);
+ } while (true);
+ } catch (EOFException e) {
+ // normal. End of file reached.
+ }
+ this.callGraph.populate(rootNode);
+ this.histo.assignSamplesSymbol();
+ }
+ }
+ } else {
+ try {
+ beStream.mark(1000);
+ boolean gmonType = readHeader(beStream);
+ if (gmonType) {
+ readGmonContent(beStream);
+ } else {
+ beStream.reset();
+ histo.decodeOldHeader(beStream);
+ histo.decodeHistRecord(beStream);
+ try {
+ do {
+ this.callGraph.decodeCallGraphRecord(beStream, true);
+ } while (true);
+ } catch (EOFException e) {
+ // normal. End of file reached.
+ }
+ this.callGraph.populate(rootNode);
+ this.histo.assignSamplesSymbol();
+ }
+ } finally {
+ beStream.close();
+ }
+ }
}
/**
@@ -260,9 +260,9 @@ public class GmonDecoder {
/**
* @return the modification timestamp of (last) parsed gmon file
*/
- public String getGmonFileTimeStamp() {
- return DateFormat.getInstance().format(new Date(new File(file).lastModified()));
- }
+ public String getGmonFileTimeStamp() {
+ return DateFormat.getInstance().format(new Date(new File(file).lastModified()));
+ }
public String getFileName(ISymbol s) {
String ret = filenames.get(s);
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/HistogramDecoder.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/HistogramDecoder.java
index 11b9dab4d8..fdb4be810d 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/HistogramDecoder.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/parser/HistogramDecoder.java
@@ -26,279 +26,279 @@ import org.eclipse.linuxtools.internal.gprof.view.histogram.HistRoot;
*/
public class HistogramDecoder {
- private static final int GMON_HDRSIZE_BSD44 = (3 * 4);
-
- private static final int GMON_HDRSIZE_BSD44_32 = (4 + 4 + 4 + 4 + 4 + GMON_HDRSIZE_BSD44);
- private static final int GMON_HDRSIZE_BSD44_64 = (8 + 8 + 4 + 4 + 4 + GMON_HDRSIZE_BSD44);
- private static final int GMON_HDRSIZE_OLDBSD_32 = (4 + 4 + 4) ;
- private static final int GMON_HDRSIZE_OLDBSD_64 = (8 + 8 + 4);
-
-
- /** the decoder */
- protected final GmonDecoder decoder;
-
- // histogram header
- /** Base pc address of sampled buffer */
- protected long lowpc;
- /** Max pc address of sampled buffer */
- protected long highpc;
- /** Profiling clock rate */
- protected int profRate;
- /** usually 's' for seconds, 'm' for milliseconds... */
- protected char dimenAbbrev;
- /** used when aggregate several gmon files */
- private boolean initialized = false;
-
-
- /** Histogram samples (shorts in the file!). */
- protected int[] hist_sample;
- /** Total time for all routines. */
- protected double total_time;
-
- protected long bucketSize;
-
-
- /**
- * Constructor
- * @param decoder the Gmon decoder
- */
- public HistogramDecoder(GmonDecoder decoder) {
- this.decoder = decoder;
- }
-
- protected long readAddress(DataInput stream) throws IOException {
- long ret = stream.readInt() & 0xFFFFFFFFL;
- return ret;
- }
-
- public boolean hasValues() {
- return (this.hist_sample != null && this.hist_sample.length > 0);
- }
-
- /**
- * Decode the given stream
- * @param stream a DataInputStream, pointing on a histogram header in a gmon file.
- * @throws IOException if an IO error occurs
- */
- public void decodeHeader(DataInput stream) throws IOException {
- long lowpc = readAddress(stream);
- long highpc = readAddress(stream);
- int hist_num_bins = stream.readInt();
- int prof_rate = stream.readInt();
- byte[] bytes = new byte[15];
- stream.readFully(bytes);
- byte b = stream.readByte();
-
- if (!isCompatible(lowpc, highpc, prof_rate, hist_num_bins)) {
- // TODO exception to normalize
- throw new RuntimeException(Messages.HistogramDecoder_INCOMPATIBLE_HIST_HEADER_ERROR_MSG);
- }
- this.lowpc = lowpc;
- this.highpc = highpc;
- this.profRate = prof_rate;
- hist_sample = new int[hist_num_bins]; // Impl note: JVM sets all integers to 0
- dimenAbbrev = (char) b;
- long temp = highpc - lowpc;
- bucketSize = Math.round(temp/(double)hist_num_bins);
- }
-
- /**
- * Decode the given stream
- * @param stream a DataInputStream, pointing on a histogram header in a gmon file.
- * @throws IOException if an IO error occurs
- */
- public void decodeOldHeader(DataInput stream) throws IOException {
- long low_pc = readAddress(stream);
- long high_pc = readAddress(stream);
- int ncnt = stream.readInt();
- int version = stream.readInt();
- int header_size;
- int profrate = 0;
- if (version == GmonDecoder.GMONVERSION)
- {
- profrate = stream.readInt();
- stream.skipBytes(GMON_HDRSIZE_BSD44);
- if (decoder._32_bit_platform) {
- header_size = GMON_HDRSIZE_BSD44_32;
- } else {
- header_size = GMON_HDRSIZE_BSD44_64;
- }
- } else {
- /* Old style BSD format. */
- if (decoder._32_bit_platform) {
- header_size = GMON_HDRSIZE_OLDBSD_32;
- } else {
- header_size = GMON_HDRSIZE_OLDBSD_64;
- }
- }
-
- int samp_bytes = ncnt - header_size;
- int hist_num_bins = samp_bytes / 2;
-
- if (!isCompatible(low_pc, high_pc, profrate, hist_num_bins))
- {
- // TODO exception to normalize
- throw new RuntimeException(Messages.HistogramDecoder_INCOMPATIBLE_HIST_HEADER_ERROR_MSG);
- }
-
-
- this.lowpc = low_pc;
- this.highpc = high_pc;
- this.profRate = profrate;
- hist_sample = new int[hist_num_bins]; // Impl note: JVM sets all integers to 0
- dimenAbbrev = 's';
- long temp = highpc - lowpc;
- bucketSize = Math.round(temp/(double)hist_num_bins);
- }
-
-
- /**
- * Checks whether the gmon file currently parsed is compatible with the previous one (if any).
- * @param lowpc
- * @param highpc
- * @param profrate
- * @param sample_count
- * @return whether the gmon file currently parsed is compatible with the previous one (if any).
- */
- private boolean isCompatible(long lowpc, long highpc, int profrate, int sample_count) {
- if (!initialized) return true;
- return (
- (this.lowpc == lowpc) &&
- (this.highpc == highpc) &&
- (this.profRate == profrate) &&
- (this.hist_sample.length == sample_count)
- );
- }
-
-
-
- /**
- * Reads hitogram record
- * @param stream a DataInputStream, pointing just after histogram header in a gmon file.
- * @throws IOException if an IO error occurs
- */
- public void decodeHistRecord(DataInput stream) throws IOException {
- for (int i = 0; i<hist_sample.length; i++) {
- short rv = stream.readShort();
- if (rv != 0) {
- int hist_size = (rv & 0xFFFF);
- hist_sample[i] += hist_size;
- }
- }
- }
-
-
- /**
- * Print the histogram header, for debug usage.
- * @param ps a printstream (typically System.out)
- */
- public void printHistHeader(PrintStream ps) {
- ps.println(" \nHistogram Header : \n"); //$NON-NLS-1$
- ps.print(" Base pc address of sample buffer = 0x"); //$NON-NLS-1$
- ps.println(Long.toHexString(lowpc));
- ps.print(" Max pc address of sampled buffer = 0x"); //$NON-NLS-1$
- ps.println(Long.toHexString(highpc));
- ps.print(" Number of histogram samples = "); //$NON-NLS-1$
- ps.println(hist_sample.length);
- ps.print(" Profiling clock rate = "); //$NON-NLS-1$
- ps.println(profRate);
-// ps.print(" Physical dimension usually \"seconds\" = ");
-// ps.println(dimen);
- ps.print(" Physical dimension abreviation : 's' for \"seconds\" 'm' for \"milliseconds\" = "); //$NON-NLS-1$
- ps.println(dimenAbbrev);
- }
-
- /**
- * Print the histogram, for debug usage.
- * @param ps a printstream (typically System.out)
- */
- public void printHistRecords(PrintStream ps) {
- ps.println();
- ps.println(" == HISTOGRAM RECORDS == "); //$NON-NLS-1$
- ps.println(" ========================= "); //$NON-NLS-1$
-
- printHistHeader(ps);
-
- /*ps.println(" \nHistogram Samples : ");
+ private static final int GMON_HDRSIZE_BSD44 = (3 * 4);
+
+ private static final int GMON_HDRSIZE_BSD44_32 = (4 + 4 + 4 + 4 + 4 + GMON_HDRSIZE_BSD44);
+ private static final int GMON_HDRSIZE_BSD44_64 = (8 + 8 + 4 + 4 + 4 + GMON_HDRSIZE_BSD44);
+ private static final int GMON_HDRSIZE_OLDBSD_32 = (4 + 4 + 4) ;
+ private static final int GMON_HDRSIZE_OLDBSD_64 = (8 + 8 + 4);
+
+
+ /** the decoder */
+ protected final GmonDecoder decoder;
+
+ // histogram header
+ /** Base pc address of sampled buffer */
+ protected long lowpc;
+ /** Max pc address of sampled buffer */
+ protected long highpc;
+ /** Profiling clock rate */
+ protected int profRate;
+ /** usually 's' for seconds, 'm' for milliseconds... */
+ protected char dimenAbbrev;
+ /** used when aggregate several gmon files */
+ private boolean initialized = false;
+
+
+ /** Histogram samples (shorts in the file!). */
+ protected int[] hist_sample;
+ /** Total time for all routines. */
+ protected double total_time;
+
+ protected long bucketSize;
+
+
+ /**
+ * Constructor
+ * @param decoder the Gmon decoder
+ */
+ public HistogramDecoder(GmonDecoder decoder) {
+ this.decoder = decoder;
+ }
+
+ protected long readAddress(DataInput stream) throws IOException {
+ long ret = stream.readInt() & 0xFFFFFFFFL;
+ return ret;
+ }
+
+ public boolean hasValues() {
+ return (this.hist_sample != null && this.hist_sample.length > 0);
+ }
+
+ /**
+ * Decode the given stream
+ * @param stream a DataInputStream, pointing on a histogram header in a gmon file.
+ * @throws IOException if an IO error occurs
+ */
+ public void decodeHeader(DataInput stream) throws IOException {
+ long lowpc = readAddress(stream);
+ long highpc = readAddress(stream);
+ int hist_num_bins = stream.readInt();
+ int prof_rate = stream.readInt();
+ byte[] bytes = new byte[15];
+ stream.readFully(bytes);
+ byte b = stream.readByte();
+
+ if (!isCompatible(lowpc, highpc, prof_rate, hist_num_bins)) {
+ // TODO exception to normalize
+ throw new RuntimeException(Messages.HistogramDecoder_INCOMPATIBLE_HIST_HEADER_ERROR_MSG);
+ }
+ this.lowpc = lowpc;
+ this.highpc = highpc;
+ this.profRate = prof_rate;
+ hist_sample = new int[hist_num_bins]; // Impl note: JVM sets all integers to 0
+ dimenAbbrev = (char) b;
+ long temp = highpc - lowpc;
+ bucketSize = Math.round(temp/(double)hist_num_bins);
+ }
+
+ /**
+ * Decode the given stream
+ * @param stream a DataInputStream, pointing on a histogram header in a gmon file.
+ * @throws IOException if an IO error occurs
+ */
+ public void decodeOldHeader(DataInput stream) throws IOException {
+ long low_pc = readAddress(stream);
+ long high_pc = readAddress(stream);
+ int ncnt = stream.readInt();
+ int version = stream.readInt();
+ int header_size;
+ int profrate = 0;
+ if (version == GmonDecoder.GMONVERSION)
+ {
+ profrate = stream.readInt();
+ stream.skipBytes(GMON_HDRSIZE_BSD44);
+ if (decoder._32_bit_platform) {
+ header_size = GMON_HDRSIZE_BSD44_32;
+ } else {
+ header_size = GMON_HDRSIZE_BSD44_64;
+ }
+ } else {
+ /* Old style BSD format. */
+ if (decoder._32_bit_platform) {
+ header_size = GMON_HDRSIZE_OLDBSD_32;
+ } else {
+ header_size = GMON_HDRSIZE_OLDBSD_64;
+ }
+ }
+
+ int samp_bytes = ncnt - header_size;
+ int hist_num_bins = samp_bytes / 2;
+
+ if (!isCompatible(low_pc, high_pc, profrate, hist_num_bins))
+ {
+ // TODO exception to normalize
+ throw new RuntimeException(Messages.HistogramDecoder_INCOMPATIBLE_HIST_HEADER_ERROR_MSG);
+ }
+
+
+ this.lowpc = low_pc;
+ this.highpc = high_pc;
+ this.profRate = profrate;
+ hist_sample = new int[hist_num_bins]; // Impl note: JVM sets all integers to 0
+ dimenAbbrev = 's';
+ long temp = highpc - lowpc;
+ bucketSize = Math.round(temp/(double)hist_num_bins);
+ }
+
+
+ /**
+ * Checks whether the gmon file currently parsed is compatible with the previous one (if any).
+ * @param lowpc
+ * @param highpc
+ * @param profrate
+ * @param sample_count
+ * @return whether the gmon file currently parsed is compatible with the previous one (if any).
+ */
+ private boolean isCompatible(long lowpc, long highpc, int profrate, int sample_count) {
+ if (!initialized) return true;
+ return (
+ (this.lowpc == lowpc) &&
+ (this.highpc == highpc) &&
+ (this.profRate == profrate) &&
+ (this.hist_sample.length == sample_count)
+ );
+ }
+
+
+
+ /**
+ * Reads hitogram record
+ * @param stream a DataInputStream, pointing just after histogram header in a gmon file.
+ * @throws IOException if an IO error occurs
+ */
+ public void decodeHistRecord(DataInput stream) throws IOException {
+ for (int i = 0; i<hist_sample.length; i++) {
+ short rv = stream.readShort();
+ if (rv != 0) {
+ int hist_size = (rv & 0xFFFF);
+ hist_sample[i] += hist_size;
+ }
+ }
+ }
+
+
+ /**
+ * Print the histogram header, for debug usage.
+ * @param ps a printstream (typically System.out)
+ */
+ public void printHistHeader(PrintStream ps) {
+ ps.println(" \nHistogram Header : \n"); //$NON-NLS-1$
+ ps.print(" Base pc address of sample buffer = 0x"); //$NON-NLS-1$
+ ps.println(Long.toHexString(lowpc));
+ ps.print(" Max pc address of sampled buffer = 0x"); //$NON-NLS-1$
+ ps.println(Long.toHexString(highpc));
+ ps.print(" Number of histogram samples = "); //$NON-NLS-1$
+ ps.println(hist_sample.length);
+ ps.print(" Profiling clock rate = "); //$NON-NLS-1$
+ ps.println(profRate);
+// ps.print(" Physical dimension usually \"seconds\" = ");
+// ps.println(dimen);
+ ps.print(" Physical dimension abreviation : 's' for \"seconds\" 'm' for \"milliseconds\" = "); //$NON-NLS-1$
+ ps.println(dimenAbbrev);
+ }
+
+ /**
+ * Print the histogram, for debug usage.
+ * @param ps a printstream (typically System.out)
+ */
+ public void printHistRecords(PrintStream ps) {
+ ps.println();
+ ps.println(" == HISTOGRAM RECORDS == "); //$NON-NLS-1$
+ ps.println(" ========================= "); //$NON-NLS-1$
+
+ printHistHeader(ps);
+
+ /*ps.println(" \nHistogram Samples : ");
ISymbol[] symbols = this.decoder.getProgram().getSymbols();
for (ISymbol iSymbol : symbols) {
- ps.println(iSymbol.getName() + "\t" + iSymbol.getAddress());
- }
+ ps.println(iSymbol.getName() + "\t" + iSymbol.getAddress());
+ }
for (int i = 0; i<hist_sample.length; i++) {
- ps.println("histSample[" + i + "]\t" + hist_sample[i]);
+ ps.println("histSample[" + i + "]\t" + hist_sample[i]);
}*/
- }
-
- /**
- * Assign the hits to the given symbols
- * @param symblist
- */
- public void assignSamplesSymbol() {
- if (hist_sample == null || hist_sample.length == 0) return;
- ISymbol[] symblist = this.decoder.getProgram().getSymbols();
- /* read samples and assign to namelist symbols */
- int j = 1;
- for (int i = 0; i < hist_sample.length; i++)
- {
- int ccnt = hist_sample[i];
- if (ccnt != 0)
- {
- long pcl = lowpc + (bucketSize*i);
- long pch = pcl+bucketSize;
- total_time += ccnt;
- long svalue0;
- long svalue1 = symblist[j-1].getAddress().getValue().longValue();
- for (j = j-1; j < symblist.length - 1; j++)
- {
- svalue0 = svalue1;
- svalue1 = symblist[j+1].getAddress().getValue().longValue();
- /* if high end of tick is below entry address,
- * go for next tick. */
- if(pch < svalue0) {
- break;
- }
- /* if low end of tick into next routine,
- * go for next routine. */
- if(pcl < svalue1) {
- long start_addr = pcl>svalue0?pcl:svalue0;
- long end_addr = pch<svalue1?pch:svalue1;
- long overlap = end_addr - start_addr;
- if(overlap > 0) {
- ISymbol symbol = symblist[j];
- int time = (int) ((overlap * ccnt) / bucketSize);
- Bucket bck = new Bucket(start_addr, end_addr, time);
- addBucket(bck,symbol);
- }
- }
- }
- }
- }
- }
-
- private void addBucket(Bucket b, ISymbol s) {
- HistRoot root = this.decoder.getRootNode();
- root.addBucket(b, s, decoder.getProgram());
- }
-
- /**
- * @return the profRate
- */
- public int getProfRate() {
- return profRate;
- }
-
- /**
- *
- * @return 's' for seconds, 'm' for ms, 'u' for �s....
- */
- public char getTimeDimension() {
- return dimenAbbrev;
- }
-
- /**
- * get the bucket size
- */
- public long getBucketSize(){
- return bucketSize;
- }
+ }
+
+ /**
+ * Assign the hits to the given symbols
+ * @param symblist
+ */
+ public void assignSamplesSymbol() {
+ if (hist_sample == null || hist_sample.length == 0) return;
+ ISymbol[] symblist = this.decoder.getProgram().getSymbols();
+ /* read samples and assign to namelist symbols */
+ int j = 1;
+ for (int i = 0; i < hist_sample.length; i++)
+ {
+ int ccnt = hist_sample[i];
+ if (ccnt != 0)
+ {
+ long pcl = lowpc + (bucketSize*i);
+ long pch = pcl+bucketSize;
+ total_time += ccnt;
+ long svalue0;
+ long svalue1 = symblist[j-1].getAddress().getValue().longValue();
+ for (j = j-1; j < symblist.length - 1; j++)
+ {
+ svalue0 = svalue1;
+ svalue1 = symblist[j+1].getAddress().getValue().longValue();
+ /* if high end of tick is below entry address,
+ * go for next tick. */
+ if(pch < svalue0) {
+ break;
+ }
+ /* if low end of tick into next routine,
+ * go for next routine. */
+ if(pcl < svalue1) {
+ long start_addr = pcl>svalue0?pcl:svalue0;
+ long end_addr = pch<svalue1?pch:svalue1;
+ long overlap = end_addr - start_addr;
+ if(overlap > 0) {
+ ISymbol symbol = symblist[j];
+ int time = (int) ((overlap * ccnt) / bucketSize);
+ Bucket bck = new Bucket(start_addr, end_addr, time);
+ addBucket(bck,symbol);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private void addBucket(Bucket b, ISymbol s) {
+ HistRoot root = this.decoder.getRootNode();
+ root.addBucket(b, s, decoder.getProgram());
+ }
+
+ /**
+ * @return the profRate
+ */
+ public int getProfRate() {
+ return profRate;
+ }
+
+ /**
+ *
+ * @return 's' for seconds, 'm' for ms, 'u' for �s....
+ */
+ public char getTimeDimension() {
+ return dimenAbbrev;
+ }
+
+ /**
+ * get the bucket size
+ */
+ public long getBucketSize(){
+ return bucketSize;
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/symbolManager/Bucket.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/symbolManager/Bucket.java
index c64b59517c..f982a7b603 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/symbolManager/Bucket.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/symbolManager/Bucket.java
@@ -17,24 +17,24 @@ package org.eclipse.linuxtools.internal.gprof.symbolManager;
* @author Xavier Raynaud <xavier.raynaud@st.com>
*/
public class Bucket {
-
- /** Start address of this bucket */
- public final long startAddr;
- /** End address of this bucket */
- public final long endAddr;
- /** time spent in this bucket */
- public final int time;
-
- /**
- * Constructor
- * @param startAddr
- * @param endAddr
- * @param time
- */
- public Bucket(long startAddr, long endAddr, int time) {
- this.startAddr = startAddr;
- this.endAddr = endAddr;
- this.time = time;
- }
+
+ /** Start address of this bucket */
+ public final long startAddr;
+ /** End address of this bucket */
+ public final long endAddr;
+ /** time spent in this bucket */
+ public final int time;
+
+ /**
+ * Constructor
+ * @param startAddr
+ * @param endAddr
+ * @param time
+ */
+ public Bucket(long startAddr, long endAddr, int time) {
+ this.startAddr = startAddr;
+ this.endAddr = endAddr;
+ this.time = time;
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/utils/LEDataInputStream.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/utils/LEDataInputStream.java
index 1eddc1fcc2..94fec8b26f 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/utils/LEDataInputStream.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/utils/LEDataInputStream.java
@@ -21,122 +21,122 @@ import java.io.IOException;
*/
public class LEDataInputStream extends FilterInputStream implements DataInput {
- private final DataInputStream in;
- private final byte[] buffer = new byte[8];
-
- /**
- * Constructor
- * @param in
- */
- public LEDataInputStream(DataInputStream in) {
- super(in);
- this.in = in;
- }
-
- @Override
- public final short readShort() throws IOException {
- in.readFully(buffer, 0, 2);
- return (short)(
- (buffer[1]&0xff) << 8 |
- (buffer[0]&0xff));
- }
-
- @Override
- public final int readUnsignedShort() throws IOException {
- in.readFully(buffer, 0, 2);
- return (
- (buffer[1]&0xff) << 8 |
- (buffer[0]&0xff));
- }
-
- @Override
- public final char readChar() throws IOException {
- in.readFully(buffer, 0, 2);
- return (char) (
- (buffer[1]&0xff) << 8 |
- (buffer[0]&0xff));
- }
-
- @Override
- public final int readInt() throws IOException {
- in.readFully(buffer, 0, 4);
- return
- (buffer[3]) << 24 |
- (buffer[2]&0xff) << 16 |
- (buffer[1]&0xff) << 8 |
- (buffer[0]&0xff);
- }
-
- @Override
- public final long readLong() throws IOException {
- in.readFully(buffer, 0, 8);
- return
- (long)(buffer[7]) << 56 | /* long cast needed or shift done modulo 32 */
- (long)(buffer[6]&0xff) << 48 |
- (long)(buffer[5]&0xff) << 40 |
- (long)(buffer[4]&0xff) << 32 |
- (long)(buffer[3]&0xff) << 24 |
- (long)(buffer[2]&0xff) << 16 |
- (long)(buffer[1]&0xff) << 8 |
- (long)(buffer[0]&0xff);
- }
-
- @Override
- public final float readFloat() throws IOException {
- return Float.intBitsToFloat(readInt());
- }
-
- @Override
- public final double readDouble() throws IOException {
- return Double.longBitsToDouble(readLong());
- }
-
- @Override
- public boolean readBoolean() throws IOException {
- return in.readBoolean();
- }
-
- @Override
- public byte readByte() throws IOException {
- return in.readByte();
- }
-
- @Override
- public void readFully(byte[] b) throws IOException {
- in.readFully(b);
- }
-
- @Override
- public void readFully(byte[] b, int off, int len) throws IOException {
- in.readFully(b,off,len);
- }
-
- @Override
- @Deprecated
- public String readLine() throws IOException {
- return in.readLine();
- }
-
- @Override
- public String readUTF() throws IOException {
- return in.readUTF();
- }
-
- @Override
- public int readUnsignedByte() throws IOException {
- return in.readUnsignedByte();
- }
-
- @Override
- public int skipBytes(int n) throws IOException {
- return in.skipBytes(n);
- }
-
- /**
- * Close this stream.
- */
- @Override
- public void close() throws IOException {
- in.close();
- }
+ private final DataInputStream in;
+ private final byte[] buffer = new byte[8];
+
+ /**
+ * Constructor
+ * @param in
+ */
+ public LEDataInputStream(DataInputStream in) {
+ super(in);
+ this.in = in;
+ }
+
+ @Override
+ public final short readShort() throws IOException {
+ in.readFully(buffer, 0, 2);
+ return (short)(
+ (buffer[1]&0xff) << 8 |
+ (buffer[0]&0xff));
+ }
+
+ @Override
+ public final int readUnsignedShort() throws IOException {
+ in.readFully(buffer, 0, 2);
+ return (
+ (buffer[1]&0xff) << 8 |
+ (buffer[0]&0xff));
+ }
+
+ @Override
+ public final char readChar() throws IOException {
+ in.readFully(buffer, 0, 2);
+ return (char) (
+ (buffer[1]&0xff) << 8 |
+ (buffer[0]&0xff));
+ }
+
+ @Override
+ public final int readInt() throws IOException {
+ in.readFully(buffer, 0, 4);
+ return
+ (buffer[3]) << 24 |
+ (buffer[2]&0xff) << 16 |
+ (buffer[1]&0xff) << 8 |
+ (buffer[0]&0xff);
+ }
+
+ @Override
+ public final long readLong() throws IOException {
+ in.readFully(buffer, 0, 8);
+ return
+ (long)(buffer[7]) << 56 | /* long cast needed or shift done modulo 32 */
+ (long)(buffer[6]&0xff) << 48 |
+ (long)(buffer[5]&0xff) << 40 |
+ (long)(buffer[4]&0xff) << 32 |
+ (long)(buffer[3]&0xff) << 24 |
+ (long)(buffer[2]&0xff) << 16 |
+ (long)(buffer[1]&0xff) << 8 |
+ (long)(buffer[0]&0xff);
+ }
+
+ @Override
+ public final float readFloat() throws IOException {
+ return Float.intBitsToFloat(readInt());
+ }
+
+ @Override
+ public final double readDouble() throws IOException {
+ return Double.longBitsToDouble(readLong());
+ }
+
+ @Override
+ public boolean readBoolean() throws IOException {
+ return in.readBoolean();
+ }
+
+ @Override
+ public byte readByte() throws IOException {
+ return in.readByte();
+ }
+
+ @Override
+ public void readFully(byte[] b) throws IOException {
+ in.readFully(b);
+ }
+
+ @Override
+ public void readFully(byte[] b, int off, int len) throws IOException {
+ in.readFully(b,off,len);
+ }
+
+ @Override
+ @Deprecated
+ public String readLine() throws IOException {
+ return in.readLine();
+ }
+
+ @Override
+ public String readUTF() throws IOException {
+ return in.readUTF();
+ }
+
+ @Override
+ public int readUnsignedByte() throws IOException {
+ return in.readUnsignedByte();
+ }
+
+ @Override
+ public int skipBytes(int n) throws IOException {
+ return in.skipBytes(n);
+ }
+
+ /**
+ * Close this stream.
+ */
+ @Override
+ public void close() throws IOException {
+ in.close();
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/utils/PPC64ElfBinaryObjectWrapper.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/utils/PPC64ElfBinaryObjectWrapper.java
index 010155b0f7..69f727123c 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/utils/PPC64ElfBinaryObjectWrapper.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/utils/PPC64ElfBinaryObjectWrapper.java
@@ -27,65 +27,65 @@ import org.eclipse.cdt.utils.elf.parser.ElfBinaryObject;
import org.eclipse.core.runtime.IPath;
public class PPC64ElfBinaryObjectWrapper extends ElfBinaryObject {
- private Elf.Section dataSection = null;
- private ISymbol[] symbols = null;
+ private Elf.Section dataSection = null;
+ private ISymbol[] symbols = null;
- public PPC64ElfBinaryObjectWrapper(IBinaryParser parser, IPath path, int type) {
- super(parser, path, type);
- }
+ public PPC64ElfBinaryObjectWrapper(IBinaryParser parser, IPath path, int type) {
+ super(parser, path, type);
+ }
- private IAddress fixAddr(IAddress addr) {
- try {
- //PPC64 is big endian, so we don't need to worry with byte order
- InputStream input = getContents();
- byte bytes[]=new byte[8];
- long index = addr.getValue().longValue() - dataSection.sh_addr.getValue().longValue() +
- dataSection.sh_offset;
+ private IAddress fixAddr(IAddress addr) {
+ try {
+ //PPC64 is big endian, so we don't need to worry with byte order
+ InputStream input = getContents();
+ byte bytes[]=new byte[8];
+ long index = addr.getValue().longValue() - dataSection.sh_addr.getValue().longValue() +
+ dataSection.sh_offset;
- input.skip(index);
- input.read(bytes);
- return new Addr64(new BigInteger(bytes));
- } catch(IOException e) {
- return null;
- }
- }
+ input.skip(index);
+ input.read(bytes);
+ return new Addr64(new BigInteger(bytes));
+ } catch(IOException e) {
+ return null;
+ }
+ }
- @Override
- public ISymbol[] getSymbols() {
- if (symbols != null) {
- return symbols;
- }
+ @Override
+ public ISymbol[] getSymbols() {
+ if (symbols != null) {
+ return symbols;
+ }
- symbols = super.getSymbols();
- try {
- if (dataSection == null) {
- Elf elf = new Elf(getPath().toOSString());
- dataSection = elf.getSectionByName(".data"); //$NON-NLS-1$
- }
- } catch (IOException e) {
- }
+ symbols = super.getSymbols();
+ try {
+ if (dataSection == null) {
+ Elf elf = new Elf(getPath().toOSString());
+ dataSection = elf.getSectionByName(".data"); //$NON-NLS-1$
+ }
+ } catch (IOException e) {
+ }
- //Failed to load data Section
- if (dataSection == null) {
- return symbols;
- }
+ //Failed to load data Section
+ if (dataSection == null) {
+ return symbols;
+ }
- LinkedList<ISymbol> list = new LinkedList<>();
- for (ISymbol s : symbols) {
- if (s.getType() == ISymbol.FUNCTION && s instanceof Symbol){
- IAddress addr = fixAddr(s.getAddress());
- if (addr == null) {
- addr = s.getAddress();
- }
- list.add(new Symbol((BinaryObjectAdapter)s.getBinaryObject(), s.getName(), s.getType(), addr, s.getSize()));
- } else {
- list.add(s);
- }
- }
+ LinkedList<ISymbol> list = new LinkedList<>();
+ for (ISymbol s : symbols) {
+ if (s.getType() == ISymbol.FUNCTION && s instanceof Symbol){
+ IAddress addr = fixAddr(s.getAddress());
+ if (addr == null) {
+ addr = s.getAddress();
+ }
+ list.add(new Symbol((BinaryObjectAdapter)s.getBinaryObject(), s.getName(), s.getType(), addr, s.getSize()));
+ } else {
+ list.add(s);
+ }
+ }
- symbols = list.toArray(new Symbol[0]);
- Arrays.sort(symbols);
+ symbols = list.toArray(new Symbol[0]);
+ Arrays.sort(symbols);
- return symbols;
- }
+ return symbols;
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/CallGraphContentProvider.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/CallGraphContentProvider.java
index 9bb1098422..733e66dbfc 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/CallGraphContentProvider.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/CallGraphContentProvider.java
@@ -28,126 +28,126 @@ import org.eclipse.linuxtools.internal.gprof.view.histogram.TreeElement;
*/
public class CallGraphContentProvider implements ITreeContentProvider {
- public static final CallGraphContentProvider sharedInstance = new CallGraphContentProvider();
+ public static final CallGraphContentProvider sharedInstance = new CallGraphContentProvider();
- /**
- * Constructor
- */
- private CallGraphContentProvider() {
- }
+ /**
+ * Constructor
+ */
+ private CallGraphContentProvider() {
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
- */
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof HistRoot) {
- HistRoot root = (HistRoot) parentElement;
- LinkedList<? extends TreeElement> ret = getFunctionChildrenList(root);
- return ret.toArray();
- }
- if (parentElement instanceof HistFunction) {
- HistFunction function = (HistFunction) parentElement;
- CGCategory parents = function.getParentsFunctions();
- CGCategory children = function.getChildrenFunctions();
- if (parents == null) {
- if (children == null) return new Object[0];
- return new Object[] {children};
- } else if (children == null) {
- return new Object[] {parents};
- } else {
- return new Object[] {
- parents,
- children
- };
- }
- }
- if (parentElement instanceof CGCategory) {
- CGCategory cat = (CGCategory) parentElement;
- return cat.getChildren().toArray();
- }
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
+ */
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ if (parentElement instanceof HistRoot) {
+ HistRoot root = (HistRoot) parentElement;
+ LinkedList<? extends TreeElement> ret = getFunctionChildrenList(root);
+ return ret.toArray();
+ }
+ if (parentElement instanceof HistFunction) {
+ HistFunction function = (HistFunction) parentElement;
+ CGCategory parents = function.getParentsFunctions();
+ CGCategory children = function.getChildrenFunctions();
+ if (parents == null) {
+ if (children == null) return new Object[0];
+ return new Object[] {children};
+ } else if (children == null) {
+ return new Object[] {parents};
+ } else {
+ return new Object[] {
+ parents,
+ children
+ };
+ }
+ }
+ if (parentElement instanceof CGCategory) {
+ CGCategory cat = (CGCategory) parentElement;
+ return cat.getChildren().toArray();
+ }
+ return null;
+ }
- protected LinkedList<? extends TreeElement> getFunctionChildrenList(HistRoot root) {
- LinkedList<TreeElement> ret = new LinkedList<>();
- LinkedList<? extends TreeElement> list = root.getChildren();
- for (TreeElement histTreeElem : list) {
- LinkedList<? extends TreeElement> partialList = histTreeElem.getChildren();
- ret.addAll(partialList);
- }
- return ret;
- }
+ protected LinkedList<? extends TreeElement> getFunctionChildrenList(HistRoot root) {
+ LinkedList<TreeElement> ret = new LinkedList<>();
+ LinkedList<? extends TreeElement> list = root.getChildren();
+ for (TreeElement histTreeElem : list) {
+ LinkedList<? extends TreeElement> partialList = histTreeElem.getChildren();
+ ret.addAll(partialList);
+ }
+ return ret;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
- */
- @Override
- public TreeElement getParent(Object element) {
- if (element instanceof TreeElement) {
- TreeElement cge = (TreeElement) element;
- if (cge instanceof HistFunction) {
- return cge.getParent().getParent();
- }
- return cge.getParent();
- }
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
+ */
+ @Override
+ public TreeElement getParent(Object element) {
+ if (element instanceof TreeElement) {
+ TreeElement cge = (TreeElement) element;
+ if (cge instanceof HistFunction) {
+ return cge.getParent().getParent();
+ }
+ return cge.getParent();
+ }
+ return null;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
- */
- @Override
- public boolean hasChildren(Object parentElement) {
- if (parentElement instanceof HistRoot) {
- HistRoot root = (HistRoot) parentElement;
- LinkedList<? extends TreeElement> ret = getFunctionChildrenList(root);
- return !ret.isEmpty();
- }
- if (parentElement instanceof HistFunction) {
- HistFunction function = (HistFunction) parentElement;
- CGCategory parents = function.getParentsFunctions();
- CGCategory children = function.getChildrenFunctions();
- return (parents != null || children != null);
- }
- if (parentElement instanceof CGCategory) {
- CGCategory cat = (CGCategory) parentElement;
- return !cat.getChildren().isEmpty();
- }
- return false;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
+ */
+ @Override
+ public boolean hasChildren(Object parentElement) {
+ if (parentElement instanceof HistRoot) {
+ HistRoot root = (HistRoot) parentElement;
+ LinkedList<? extends TreeElement> ret = getFunctionChildrenList(root);
+ return !ret.isEmpty();
+ }
+ if (parentElement instanceof HistFunction) {
+ HistFunction function = (HistFunction) parentElement;
+ CGCategory parents = function.getParentsFunctions();
+ CGCategory children = function.getChildrenFunctions();
+ return (parents != null || children != null);
+ }
+ if (parentElement instanceof CGCategory) {
+ CGCategory cat = (CGCategory) parentElement;
+ return !cat.getChildren().isEmpty();
+ }
+ return false;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
- */
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof GmonDecoder) {
- GmonDecoder obj = (GmonDecoder) inputElement;
- HistRoot root = obj.getRootNode();
- return new Object[] { root };
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
+ */
+ @Override
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof GmonDecoder) {
+ GmonDecoder obj = (GmonDecoder) inputElement;
+ HistRoot root = obj.getRootNode();
+ return new Object[] { root };
+ }
return new Object[0];
- }
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.IContentProvider#dispose()
- */
- @Override
- public void dispose() {
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.IContentProvider#dispose()
+ */
+ @Override
+ public void dispose() {
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FileHistogramContentProvider.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FileHistogramContentProvider.java
index b4dce4fde6..120641302c 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FileHistogramContentProvider.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FileHistogramContentProvider.java
@@ -26,61 +26,61 @@ import org.eclipse.linuxtools.internal.gprof.view.histogram.TreeElement;
*/
public class FileHistogramContentProvider implements ITreeContentProvider {
- public static final FileHistogramContentProvider sharedInstance = new FileHistogramContentProvider();
+ public static final FileHistogramContentProvider sharedInstance = new FileHistogramContentProvider();
- /**
- * Constructor
- */
- FileHistogramContentProvider() {
- }
+ /**
+ * Constructor
+ */
+ FileHistogramContentProvider() {
+ }
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof AbstractTreeElement) {
- AbstractTreeElement elem = (AbstractTreeElement) parentElement;
- LinkedList<? extends TreeElement> list = elem.getChildren();
- return list.toArray();
- }
- return null;
- }
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ if (parentElement instanceof AbstractTreeElement) {
+ AbstractTreeElement elem = (AbstractTreeElement) parentElement;
+ LinkedList<? extends TreeElement> list = elem.getChildren();
+ return list.toArray();
+ }
+ return null;
+ }
- @Override
- public Object getParent(Object element) {
- if (element instanceof AbstractTreeElement) {
- AbstractTreeElement elem = (AbstractTreeElement) element;
- return elem.getParent();
- }
- return null;
- }
+ @Override
+ public Object getParent(Object element) {
+ if (element instanceof AbstractTreeElement) {
+ AbstractTreeElement elem = (AbstractTreeElement) element;
+ return elem.getParent();
+ }
+ return null;
+ }
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof AbstractTreeElement) {
- AbstractTreeElement elem = (AbstractTreeElement) element;
- return elem.hasChildren() && !elem.getChildren().isEmpty();
- }
- return false;
- }
+ @Override
+ public boolean hasChildren(Object element) {
+ if (element instanceof AbstractTreeElement) {
+ AbstractTreeElement elem = (AbstractTreeElement) element;
+ return elem.hasChildren() && !elem.getChildren().isEmpty();
+ }
+ return false;
+ }
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof GmonDecoder) {
- GmonDecoder obj = (GmonDecoder) inputElement;
- HistRoot root = obj.getRootNode();
- return new Object[] {
- root
- };
- }
+ @Override
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof GmonDecoder) {
+ GmonDecoder obj = (GmonDecoder) inputElement;
+ HistRoot root = obj.getRootNode();
+ return new Object[] {
+ root
+ };
+ }
return new Object[0];
- }
+ }
- @Override
- public void dispose() {
- }
+ @Override
+ public void dispose() {
+ }
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FlatHistogramContentProvider.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FlatHistogramContentProvider.java
index 67c6102564..cf7c726fb5 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FlatHistogramContentProvider.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FlatHistogramContentProvider.java
@@ -24,32 +24,32 @@ import org.eclipse.linuxtools.internal.gprof.view.histogram.TreeElement;
*/
public final class FlatHistogramContentProvider extends FunctionHistogramContentProvider {
- public static final FlatHistogramContentProvider sharedInstance = new FlatHistogramContentProvider();
-
- /**
- * Constructor
- */
- private FlatHistogramContentProvider() {
- }
-
- @Override
- protected LinkedList<? extends TreeElement> getFunctionChildrenList(HistRoot root) {
- LinkedList<? extends TreeElement> list = super.getFunctionChildrenList(root);
- LinkedList<TreeElement> ret = new LinkedList<>();
- for (TreeElement histTreeElem : list) {
- LinkedList<? extends TreeElement> partialList = histTreeElem.getChildren();
- ret.addAll(partialList);
- }
- return ret;
- }
-
- @Override
- public Object getParent(Object element) {
- Object o = super.getParent(element);
- if (o instanceof HistFunction) {
- o = super.getParent(o);
- }
- return o;
- }
+ public static final FlatHistogramContentProvider sharedInstance = new FlatHistogramContentProvider();
+
+ /**
+ * Constructor
+ */
+ private FlatHistogramContentProvider() {
+ }
+
+ @Override
+ protected LinkedList<? extends TreeElement> getFunctionChildrenList(HistRoot root) {
+ LinkedList<? extends TreeElement> list = super.getFunctionChildrenList(root);
+ LinkedList<TreeElement> ret = new LinkedList<>();
+ for (TreeElement histTreeElem : list) {
+ LinkedList<? extends TreeElement> partialList = histTreeElem.getChildren();
+ ret.addAll(partialList);
+ }
+ return ret;
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ Object o = super.getParent(element);
+ if (o instanceof HistFunction) {
+ o = super.getParent(o);
+ }
+ return o;
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FunctionHistogramContentProvider.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FunctionHistogramContentProvider.java
index 69d99d3c92..a3e6eb2bb6 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FunctionHistogramContentProvider.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/FunctionHistogramContentProvider.java
@@ -24,51 +24,51 @@ import org.eclipse.linuxtools.internal.gprof.view.histogram.TreeElement;
*/
public class FunctionHistogramContentProvider extends FileHistogramContentProvider {
- public static final FunctionHistogramContentProvider sharedInstance = new FunctionHistogramContentProvider();
+ public static final FunctionHistogramContentProvider sharedInstance = new FunctionHistogramContentProvider();
- /**
- * Constructor
- */
- FunctionHistogramContentProvider() {
- }
+ /**
+ * Constructor
+ */
+ FunctionHistogramContentProvider() {
+ }
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof HistRoot) {
- HistRoot root = (HistRoot) parentElement;
- LinkedList<? extends TreeElement> ret = getFunctionChildrenList(root);
- return ret.toArray();
- }
- return super.getChildren(parentElement);
- }
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ if (parentElement instanceof HistRoot) {
+ HistRoot root = (HistRoot) parentElement;
+ LinkedList<? extends TreeElement> ret = getFunctionChildrenList(root);
+ return ret.toArray();
+ }
+ return super.getChildren(parentElement);
+ }
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof HistRoot) {
- HistRoot root = (HistRoot) element;
- LinkedList<? extends TreeElement> ret = getFunctionChildrenList(root);
- return !ret.isEmpty();
- }
- return super.hasChildren(element);
- }
+ @Override
+ public boolean hasChildren(Object element) {
+ if (element instanceof HistRoot) {
+ HistRoot root = (HistRoot) element;
+ LinkedList<? extends TreeElement> ret = getFunctionChildrenList(root);
+ return !ret.isEmpty();
+ }
+ return super.hasChildren(element);
+ }
- protected LinkedList<? extends TreeElement> getFunctionChildrenList(HistRoot root) {
- LinkedList<TreeElement> ret = new LinkedList<>();
- LinkedList<? extends TreeElement> list = root.getChildren();
- for (TreeElement histTreeElem : list) {
- LinkedList<? extends TreeElement> partialList = histTreeElem.getChildren();
- ret.addAll(partialList);
- }
- return ret;
- }
+ protected LinkedList<? extends TreeElement> getFunctionChildrenList(HistRoot root) {
+ LinkedList<TreeElement> ret = new LinkedList<>();
+ LinkedList<? extends TreeElement> list = root.getChildren();
+ for (TreeElement histTreeElem : list) {
+ LinkedList<? extends TreeElement> partialList = histTreeElem.getChildren();
+ ret.addAll(partialList);
+ }
+ return ret;
+ }
- @Override
- public Object getParent(Object element) {
- Object o = super.getParent(element);
- if (o instanceof HistFile) {
- o = super.getParent(o);
- }
- return o;
- }
+ @Override
+ public Object getParent(Object element) {
+ Object o = super.getParent(element);
+ if (o instanceof HistFile) {
+ o = super.getParent(o);
+ }
+ return o;
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/GmonView.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/GmonView.java
index 04ff277b3f..b7144684c1 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/GmonView.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/GmonView.java
@@ -63,21 +63,21 @@ import org.eclipse.ui.PlatformUI;
*/
public class GmonView extends AbstractSTDataView {
- public static final String ID = "org.eclipse.linuxtools.gprof.view"; //$NON-NLS-1$
+ public static final String ID = "org.eclipse.linuxtools.gprof.view"; //$NON-NLS-1$
- /** WHITE color */
- public static final Color DEFAULT_BG = PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
- /** GREEN1 color : for children category */
- public static final Color GREEN1 = new Color(PlatformUI.getWorkbench().getDisplay(), 207, 255, 207);
- /** GREEN2 color : for children */
- public static final Color GREEN2 = new Color(PlatformUI.getWorkbench().getDisplay(), 175, 255, 175);
- /** BLUE1 color : for parent category */
- public static final Color BLUE1 = new Color(PlatformUI.getWorkbench().getDisplay(), 207, 207, 255);
- /** BLUE2 color : for parents */
- public static final Color BLUE2 = new Color(PlatformUI.getWorkbench().getDisplay(), 175, 175, 255);
+ /** WHITE color */
+ public static final Color DEFAULT_BG = PlatformUI.getWorkbench().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
+ /** GREEN1 color : for children category */
+ public static final Color GREEN1 = new Color(PlatformUI.getWorkbench().getDisplay(), 207, 255, 207);
+ /** GREEN2 color : for children */
+ public static final Color GREEN2 = new Color(PlatformUI.getWorkbench().getDisplay(), 175, 255, 175);
+ /** BLUE1 color : for parent category */
+ public static final Color BLUE1 = new Color(PlatformUI.getWorkbench().getDisplay(), 207, 207, 255);
+ /** BLUE2 color : for parents */
+ public static final Color BLUE2 = new Color(PlatformUI.getWorkbench().getDisplay(), 175, 175, 255);
- public static final int CALL_GRAPH_MODE = 0;
- public static final int SAMPLE_MODE = 1;
+ public static final int CALL_GRAPH_MODE = 0;
+ public static final int SAMPLE_MODE = 1;
private Label label;
private Text fFilterText;
@@ -103,24 +103,24 @@ public class GmonView extends AbstractSTDataView {
@Override
protected void createTitle(Composite parent) {
- ColorRegistry colorRegistry = JFaceResources.getColorRegistry();
- Color background = colorRegistry.get("org.eclipse.ui.workbench.INACTIVE_TAB_BG_START"); //$NON-NLS-1$
- label = new Label(parent, SWT.WRAP);
- if (background != null)
- label.setBackground(background);
- GridData data = new GridData(SWT.FILL, SWT.BEGINNING, true, false, 1, 1);
- label.setLayoutData(data);
- fFilterText = new Text(parent, SWT.BORDER | SWT.SINGLE | SWT.SEARCH | SWT.ICON_SEARCH | SWT.ICON_CANCEL);
- fFilterText.setMessage(Messages.GmonView_type_filter_text);
- fFilterText.setToolTipText(Messages.GmonView_filter_by_name);
- fFilterText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- fFilterText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- String text = fFilterText.getText();
- fViewerFilter.setMatchingText(text);
- }
- });
+ ColorRegistry colorRegistry = JFaceResources.getColorRegistry();
+ Color background = colorRegistry.get("org.eclipse.ui.workbench.INACTIVE_TAB_BG_START"); //$NON-NLS-1$
+ label = new Label(parent, SWT.WRAP);
+ if (background != null)
+ label.setBackground(background);
+ GridData data = new GridData(SWT.FILL, SWT.BEGINNING, true, false, 1, 1);
+ label.setLayoutData(data);
+ fFilterText = new Text(parent, SWT.BORDER | SWT.SINGLE | SWT.SEARCH | SWT.ICON_SEARCH | SWT.ICON_CANCEL);
+ fFilterText.setMessage(Messages.GmonView_type_filter_text);
+ fFilterText.setToolTipText(Messages.GmonView_filter_by_name);
+ fFilterText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
+ fFilterText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ String text = fFilterText.getText();
+ fViewerFilter.setMatchingText(text);
+ }
+ });
}
@Override
@@ -155,37 +155,37 @@ public class GmonView extends AbstractSTDataView {
* I do not know where to put this static method. It is used by all ProfFields
*/
public static Color getBackground(Object element) {
- ColorRegistry colorRegistry = JFaceResources.getColorRegistry();
+ ColorRegistry colorRegistry = JFaceResources.getColorRegistry();
- // FIXME: Not sure if color1-color4 are ever used...picked colors found in JFacesResources ColorRegistry
- // not tied to any particular language (e.g. didn't choose CDT or Java colors)
- // Color5 seems to work ok as bg in the one dark theme I tried (Nissl-Adwaita-dark-4) and as well
- // in default light adwaita, but it is much simpler to just return null and let the table color default
- // appropriately.
- Color color1 = colorRegistry.get("org.eclipse.ui.editors.currentLineColor"); //$NON-NLS-1$
- Color color2 = colorRegistry.get("org.eclipse.ui.workbench.INACTIVE_TAB_BG_START"); //$NON-NLS-1$
- Color color3 = colorRegistry.get("org.eclipse.ui.workbench.ACTIVE_NOFOCUS_TAB_BG_END"); //$NON-NLS-1$
- Color color4 = colorRegistry.get("org.eclipse.ui.workbench.ACTIVE_TAB_BG_END"); //$NON-NLS-1$
- // Color color5 = colorRegistry.get("org.eclipse.ui.workbench.INACTIVE_TAB_BG_START"); //$NON-NLS-1$
+ // FIXME: Not sure if color1-color4 are ever used...picked colors found in JFacesResources ColorRegistry
+ // not tied to any particular language (e.g. didn't choose CDT or Java colors)
+ // Color5 seems to work ok as bg in the one dark theme I tried (Nissl-Adwaita-dark-4) and as well
+ // in default light adwaita, but it is much simpler to just return null and let the table color default
+ // appropriately.
+ Color color1 = colorRegistry.get("org.eclipse.ui.editors.currentLineColor"); //$NON-NLS-1$
+ Color color2 = colorRegistry.get("org.eclipse.ui.workbench.INACTIVE_TAB_BG_START"); //$NON-NLS-1$
+ Color color3 = colorRegistry.get("org.eclipse.ui.workbench.ACTIVE_NOFOCUS_TAB_BG_END"); //$NON-NLS-1$
+ Color color4 = colorRegistry.get("org.eclipse.ui.workbench.ACTIVE_TAB_BG_END"); //$NON-NLS-1$
+ // Color color5 = colorRegistry.get("org.eclipse.ui.workbench.INACTIVE_TAB_BG_START"); //$NON-NLS-1$
- if (element instanceof CGCategory) {
- CGCategory cat = (CGCategory) element;
- if (CGCategory.CHILDREN.equals(cat.category)) {
- return color1 == null ? BLUE1 : color1;
- } else {
- return color2 == null ? GREEN1 : color2;
- }
- } else if (element instanceof CGArc) {
- CGArc arc = (CGArc) element;
- CGCategory cat = (CGCategory) arc.getParent();
- if (CGCategory.CHILDREN.equals(cat.category)) {
- return color3 == null ? BLUE2 : color3;
- } else {
- return color4 == null ? GREEN2 : color4;
- }
- }
- return null; // default background
- // return color5 == null ? DEFAULT_BG : color5;
+ if (element instanceof CGCategory) {
+ CGCategory cat = (CGCategory) element;
+ if (CGCategory.CHILDREN.equals(cat.category)) {
+ return color1 == null ? BLUE1 : color1;
+ } else {
+ return color2 == null ? GREEN1 : color2;
+ }
+ } else if (element instanceof CGArc) {
+ CGArc arc = (CGArc) element;
+ CGCategory cat = (CGCategory) arc.getParent();
+ if (CGCategory.CHILDREN.equals(cat.category)) {
+ return color3 == null ? BLUE2 : color3;
+ } else {
+ return color4 == null ? GREEN2 : color4;
+ }
+ }
+ return null; // default background
+ // return color5 == null ? DEFAULT_BG : color5;
}
@Override
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/GmonViewer.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/GmonViewer.java
index 293fba913d..e9c2334680 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/GmonViewer.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/GmonViewer.java
@@ -36,61 +36,61 @@ import org.eclipse.swt.widgets.Composite;
*/
public class GmonViewer extends AbstractSTTreeViewer {
- private ISTDataViewersField[] fields;
+ private ISTDataViewersField[] fields;
- /**
- * Constructor
- * @param parent
- */
- public GmonViewer(Composite parent) {
- super(parent);
- }
+ /**
+ * Constructor
+ * @param parent
+ */
+ public GmonViewer(Composite parent) {
+ super(parent);
+ }
- @Override
- protected TreeViewer createViewer(Composite parent, int style) {
- TreeViewer tv = super.createViewer(parent, style);
- tv.setAutoExpandLevel(2);
- return tv;
- }
+ @Override
+ protected TreeViewer createViewer(Composite parent, int style) {
+ TreeViewer tv = super.createViewer(parent, style);
+ tv.setAutoExpandLevel(2);
+ return tv;
+ }
- @Override
- protected ITreeContentProvider createContentProvider() {
- return FileHistogramContentProvider.sharedInstance;
- }
+ @Override
+ protected ITreeContentProvider createContentProvider() {
+ return FileHistogramContentProvider.sharedInstance;
+ }
- @Override
- public ISTDataViewersField[] getAllFields() {
- if (fields == null) {
- fields = new ISTDataViewersField[] {
- new NameProfField(),
- new SampleProfField(this),
- new CallsProfField(),
- new SamplePerCallField(this),
- new RatioProfField()
- };
- }
- return fields;
- }
+ @Override
+ public ISTDataViewersField[] getAllFields() {
+ if (fields == null) {
+ fields = new ISTDataViewersField[] {
+ new NameProfField(),
+ new SampleProfField(this),
+ new CallsProfField(),
+ new SamplePerCallField(this),
+ new RatioProfField()
+ };
+ }
+ return fields;
+ }
- @Override
- public IDialogSettings getDialogSettings() {
- return Activator.getDefault().getDialogSettings();
- }
+ @Override
+ public IDialogSettings getDialogSettings() {
+ return Activator.getDefault().getDialogSettings();
+ }
- @Override
- protected void handleOpenEvent(OpenEvent event) {
- IStructuredSelection selection = (IStructuredSelection) event.getSelection();
- TreeElement element = (TreeElement) selection.getFirstElement();
- if (element != null){
- String s = element.getSourcePath();
- if (s == null || "??".equals(s)) { //$NON-NLS-1$
- return; // nothing to do here.
- } else {
- int lineNumber = element.getSourceLine();
- IBinaryObject exec = ((HistRoot)element.getRoot()).decoder.getProgram();
- STLink2SourceSupport.openSourceFileAtLocation(exec, s, lineNumber);
- }
- }
- }
+ @Override
+ protected void handleOpenEvent(OpenEvent event) {
+ IStructuredSelection selection = (IStructuredSelection) event.getSelection();
+ TreeElement element = (TreeElement) selection.getFirstElement();
+ if (element != null){
+ String s = element.getSourcePath();
+ if (s == null || "??".equals(s)) { //$NON-NLS-1$
+ return; // nothing to do here.
+ } else {
+ int lineNumber = element.getSourceLine();
+ IBinaryObject exec = ((HistRoot)element.getRoot()).decoder.getProgram();
+ STLink2SourceSupport.openSourceFileAtLocation(exec, s, lineNumber);
+ }
+ }
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/fields/SampleProfField.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/fields/SampleProfField.java
index a55472ed5f..0005d897a6 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/fields/SampleProfField.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/fields/SampleProfField.java
@@ -32,169 +32,169 @@ import org.eclipse.swt.graphics.Color;
*/
public class SampleProfField extends AbstractSTDataViewersField implements IChartField{
- private boolean samples = true;
- protected final AbstractSTTreeViewer viewer;
- protected final static double UNINITIALIZED = 0;
-
- /**
- * Constructor
- * @param viewer the gmon viewer
- */
- public SampleProfField(AbstractSTTreeViewer viewer) {
- this.viewer = viewer;
- }
-
- @Override
- public int compare(Object obj1, Object obj2) {
- TreeElement e1 = (TreeElement) obj1;
- TreeElement e2 = (TreeElement) obj2;
- int s1 = e1.getSamples();
- int s2 = e2.getSamples();
- return s1 - s2;
- }
-
- @Override
- public String getColumnHeaderText() {
- if (samples) {
- return Messages.SampleProfField_SAMPLE_HDR;
- }
- return Messages.SampleProfField_TIME_HDR;
- }
-
- @Override
- public String getColumnHeaderTooltip() {
- return null;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.linuxtools.dataviewers.abstractviewers.ISTDataViewersField#getValue(java.lang.Object)
- */
- @Override
- public String getValue(Object obj) {
- TreeElement e = (TreeElement) obj;
- int i = e.getSamples();
- if (i == -1) {
- return ""; //$NON-NLS-1$
- }
- if (samples) {
- return String.valueOf(i);
- } else {
- double prof_rate = getProfRate();
- if (prof_rate == UNINITIALIZED) {
- return "?"; //$NON-NLS-1$
- }
- return getValue(i, prof_rate);
- }
- }
-
- /**
- * Get the time value with the best unit display
- * @param i nbr of samples
- * @param profRate profiling frequency
- * @return time value with the best adapted time unit
- */
- public static String getValue(double i, double prof_rate)
- {
- long timeInNs = (long) (i/prof_rate);
- long ns = timeInNs%1000;
-
- long timeInUs = timeInNs/1000;
- if (timeInUs == 0) {
- return ns + "ns"; //$NON-NLS-1$
- }
- long us = timeInUs%1000;
-
- long timeInMs = timeInUs/1000;
- if (timeInMs == 0) {
- String ns_s = "" + ns; //$NON-NLS-1$
- while (ns_s.length() < 3) {
- ns_s = "0" + ns_s; //$NON-NLS-1$
- }
- return us + "." + ns_s + "us"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- long ms = timeInMs%1000;
-
- long timeInS = timeInMs/1000;
- if (timeInS == 0) {
- String us_s = "" + us; //$NON-NLS-1$
- while (us_s.length() < 3) {
- us_s = "0" + us_s; //$NON-NLS-1$
- }
- return ms + "." + us_s + "ms"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- long s = timeInS%60;
-
- long timeInMin = timeInS/60;
- if (timeInMin == 0) {
- String ms_s = "" + ms; //$NON-NLS-1$
- while (ms_s.length() < 3) {
- ms_s = "0" + ms_s; //$NON-NLS-1$
- }
- return s + "." + ms_s + "s"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- long min = timeInMin%60;
-
- long timeInHour = timeInMin/60;
- if (timeInHour == 0) {
- return min + "min " + s + "s"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return timeInHour + "h " + min + "min"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
-
- protected double getProfRate() {
- double prof_rate = UNINITIALIZED;
- Object o = viewer.getViewer().getInput();
- if (o instanceof GmonDecoder) {
- GmonDecoder decoder = (GmonDecoder) o;
- HistogramDecoder histo = decoder.getHistogramDecoder();
- prof_rate = histo.getProfRate();
- char tUnit = histo.getTimeDimension();
- switch (tUnit) {
- case 's': prof_rate /= 1000000000; break;
- case 'm': prof_rate /= 1000000; break;
- case 'u': prof_rate /= 1000; break;
- }
- }
- return prof_rate;
- }
-
- @Override
- public Color getBackground(Object element) {
- return GmonView.getBackground(element);
- }
-
- @Override
- public String getToolTipText(Object element) {
- if (element instanceof HistRoot) {
- return Messages.SampleProfField_TOTAL_TIME_SPENT;
- } else if (element instanceof HistFunction) {
- return Messages.SampleProfField_TIME_SPENT_IN_FUNCTION;
- } else if (element instanceof HistFile) {
- return Messages.SampleProfField_TIME_SPENT_IN_FILE;
- } else if (element instanceof HistLine) {
- return Messages.SampleProfField_TIME_SPENT_AT_LOCATION;
- }
- return null;
- }
-
- /**
- * Switch from samples to time ans vice-versa
- */
- public void toggle() {
- this.samples = !this.samples;
- }
-
- @Override
- public Number getNumber(Object obj) {
- TreeElement e = (TreeElement) obj;
- int i = e.getSamples();
- if (i == -1) {
- return 0L;
- }
- return i;
- }
+ private boolean samples = true;
+ protected final AbstractSTTreeViewer viewer;
+ protected final static double UNINITIALIZED = 0;
+
+ /**
+ * Constructor
+ * @param viewer the gmon viewer
+ */
+ public SampleProfField(AbstractSTTreeViewer viewer) {
+ this.viewer = viewer;
+ }
+
+ @Override
+ public int compare(Object obj1, Object obj2) {
+ TreeElement e1 = (TreeElement) obj1;
+ TreeElement e2 = (TreeElement) obj2;
+ int s1 = e1.getSamples();
+ int s2 = e2.getSamples();
+ return s1 - s2;
+ }
+
+ @Override
+ public String getColumnHeaderText() {
+ if (samples) {
+ return Messages.SampleProfField_SAMPLE_HDR;
+ }
+ return Messages.SampleProfField_TIME_HDR;
+ }
+
+ @Override
+ public String getColumnHeaderTooltip() {
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.linuxtools.dataviewers.abstractviewers.ISTDataViewersField#getValue(java.lang.Object)
+ */
+ @Override
+ public String getValue(Object obj) {
+ TreeElement e = (TreeElement) obj;
+ int i = e.getSamples();
+ if (i == -1) {
+ return ""; //$NON-NLS-1$
+ }
+ if (samples) {
+ return String.valueOf(i);
+ } else {
+ double prof_rate = getProfRate();
+ if (prof_rate == UNINITIALIZED) {
+ return "?"; //$NON-NLS-1$
+ }
+ return getValue(i, prof_rate);
+ }
+ }
+
+ /**
+ * Get the time value with the best unit display
+ * @param i nbr of samples
+ * @param profRate profiling frequency
+ * @return time value with the best adapted time unit
+ */
+ public static String getValue(double i, double prof_rate)
+ {
+ long timeInNs = (long) (i/prof_rate);
+ long ns = timeInNs%1000;
+
+ long timeInUs = timeInNs/1000;
+ if (timeInUs == 0) {
+ return ns + "ns"; //$NON-NLS-1$
+ }
+ long us = timeInUs%1000;
+
+ long timeInMs = timeInUs/1000;
+ if (timeInMs == 0) {
+ String ns_s = "" + ns; //$NON-NLS-1$
+ while (ns_s.length() < 3) {
+ ns_s = "0" + ns_s; //$NON-NLS-1$
+ }
+ return us + "." + ns_s + "us"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ long ms = timeInMs%1000;
+
+ long timeInS = timeInMs/1000;
+ if (timeInS == 0) {
+ String us_s = "" + us; //$NON-NLS-1$
+ while (us_s.length() < 3) {
+ us_s = "0" + us_s; //$NON-NLS-1$
+ }
+ return ms + "." + us_s + "ms"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ long s = timeInS%60;
+
+ long timeInMin = timeInS/60;
+ if (timeInMin == 0) {
+ String ms_s = "" + ms; //$NON-NLS-1$
+ while (ms_s.length() < 3) {
+ ms_s = "0" + ms_s; //$NON-NLS-1$
+ }
+ return s + "." + ms_s + "s"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ long min = timeInMin%60;
+
+ long timeInHour = timeInMin/60;
+ if (timeInHour == 0) {
+ return min + "min " + s + "s"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ return timeInHour + "h " + min + "min"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+
+ protected double getProfRate() {
+ double prof_rate = UNINITIALIZED;
+ Object o = viewer.getViewer().getInput();
+ if (o instanceof GmonDecoder) {
+ GmonDecoder decoder = (GmonDecoder) o;
+ HistogramDecoder histo = decoder.getHistogramDecoder();
+ prof_rate = histo.getProfRate();
+ char tUnit = histo.getTimeDimension();
+ switch (tUnit) {
+ case 's': prof_rate /= 1000000000; break;
+ case 'm': prof_rate /= 1000000; break;
+ case 'u': prof_rate /= 1000; break;
+ }
+ }
+ return prof_rate;
+ }
+
+ @Override
+ public Color getBackground(Object element) {
+ return GmonView.getBackground(element);
+ }
+
+ @Override
+ public String getToolTipText(Object element) {
+ if (element instanceof HistRoot) {
+ return Messages.SampleProfField_TOTAL_TIME_SPENT;
+ } else if (element instanceof HistFunction) {
+ return Messages.SampleProfField_TIME_SPENT_IN_FUNCTION;
+ } else if (element instanceof HistFile) {
+ return Messages.SampleProfField_TIME_SPENT_IN_FILE;
+ } else if (element instanceof HistLine) {
+ return Messages.SampleProfField_TIME_SPENT_AT_LOCATION;
+ }
+ return null;
+ }
+
+ /**
+ * Switch from samples to time ans vice-versa
+ */
+ public void toggle() {
+ this.samples = !this.samples;
+ }
+
+ @Override
+ public Number getNumber(Object obj) {
+ TreeElement e = (TreeElement) obj;
+ int i = e.getSamples();
+ if (i == -1) {
+ return 0L;
+ }
+ return i;
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/AbstractTreeElement.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/AbstractTreeElement.java
index 88148bfaba..fd2cefd59d 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/AbstractTreeElement.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/AbstractTreeElement.java
@@ -18,81 +18,81 @@ package org.eclipse.linuxtools.internal.gprof.view.histogram;
*/
public abstract class AbstractTreeElement implements TreeElement {
- private final TreeElement parent;
- protected int samples = -1;
- protected int calls = -1;
+ private final TreeElement parent;
+ protected int samples = -1;
+ protected int calls = -1;
- /**
- * Constructor
- * @param parent
- */
- public AbstractTreeElement(TreeElement parent) {
- this.parent = parent;
- }
+ /**
+ * Constructor
+ * @param parent
+ */
+ public AbstractTreeElement(TreeElement parent) {
+ this.parent = parent;
+ }
- /**
- * Gets the parent of this tree node;
- * @return a tree node
- */
- @Override
- public TreeElement getParent() {
- return parent;
- }
+ /**
+ * Gets the parent of this tree node;
+ * @return a tree node
+ */
+ @Override
+ public TreeElement getParent() {
+ return parent;
+ }
- /**
- * Checks whether this tree node has children
- * @return <code>true</code> if this tree node has children,
- * <code>false</code> otherwise.
- */
- @Override
- public boolean hasChildren() {
- return true;
- }
+ /**
+ * Checks whether this tree node has children
+ * @return <code>true</code> if this tree node has children,
+ * <code>false</code> otherwise.
+ */
+ @Override
+ public boolean hasChildren() {
+ return true;
+ }
- @Override
- public int getCalls() {
- if (calls == -1) {
- calls = 0;
- for (TreeElement elem : getChildren()) {
- int i = elem.getCalls();
- if (i != -1) {
- calls += elem.getCalls();
- }
- }
- }
- return calls;
- }
+ @Override
+ public int getCalls() {
+ if (calls == -1) {
+ calls = 0;
+ for (TreeElement elem : getChildren()) {
+ int i = elem.getCalls();
+ if (i != -1) {
+ calls += elem.getCalls();
+ }
+ }
+ }
+ return calls;
+ }
- @Override
- public int getSamples() {
- if (samples == -1) {
- samples = 0;
- for (TreeElement elem : getChildren()) {
- samples += elem.getSamples();
- }
- }
- return samples;
- }
+ @Override
+ public int getSamples() {
+ if (samples == -1) {
+ samples = 0;
+ for (TreeElement elem : getChildren()) {
+ samples += elem.getSamples();
+ }
+ }
+ return samples;
+ }
- @Override
- public int getSourceLine() {
- return 0;
- }
+ @Override
+ public int getSourceLine() {
+ return 0;
+ }
- @Override
- public String getSourcePath() {
- return null;
- }
+ @Override
+ public String getSourcePath() {
+ return null;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.linuxtools.internal.gprof.view.histogram.TreeElement#getRoot()
- */
- @Override
- public TreeElement getRoot() {
- if (parent == null) {
- return this;
- }
- return parent.getRoot();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.linuxtools.internal.gprof.view.histogram.TreeElement#getRoot()
+ */
+ @Override
+ public TreeElement getRoot() {
+ if (parent == null) {
+ return this;
+ }
+ return parent.getRoot();
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistBucket.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistBucket.java
index 8094bd1d35..b7a91cc5a7 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistBucket.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistBucket.java
@@ -22,41 +22,41 @@ import org.eclipse.linuxtools.internal.gprof.symbolManager.Bucket;
*/
public class HistBucket extends AbstractTreeElement {
- public final Bucket bucket;
-
- /**
- * Constructor
- * @param parent the parent of this tree node
- * @param b the object to display in the tree
- */
- public HistBucket(HistLine parent, Bucket b) {
- super(parent);
- this.bucket = b;
- }
-
- @Override
- public boolean hasChildren() {
- return false;
- }
-
- @Override
- public LinkedList<? extends TreeElement> getChildren() {
- return null;
- }
-
- @Override
- public int getCalls() {
- return -1;
- }
-
- @Override
- public String getName() {
- return "0x" + Long.toHexString(bucket.startAddr); //$NON-NLS-1$
- }
-
- @Override
- public int getSamples() {
- return bucket.time;
- }
+ public final Bucket bucket;
+
+ /**
+ * Constructor
+ * @param parent the parent of this tree node
+ * @param b the object to display in the tree
+ */
+ public HistBucket(HistLine parent, Bucket b) {
+ super(parent);
+ this.bucket = b;
+ }
+
+ @Override
+ public boolean hasChildren() {
+ return false;
+ }
+
+ @Override
+ public LinkedList<? extends TreeElement> getChildren() {
+ return null;
+ }
+
+ @Override
+ public int getCalls() {
+ return -1;
+ }
+
+ @Override
+ public String getName() {
+ return "0x" + Long.toHexString(bucket.startAddr); //$NON-NLS-1$
+ }
+
+ @Override
+ public int getSamples() {
+ return bucket.time;
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistLine.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistLine.java
index 6dd2b142cd..ec318ba795 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistLine.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistLine.java
@@ -22,56 +22,56 @@ import org.eclipse.linuxtools.internal.gprof.symbolManager.Bucket;
*/
public class HistLine extends AbstractTreeElement {
- public final int line;
- private final LinkedList<HistBucket> children = new LinkedList<>();
+ public final int line;
+ private final LinkedList<HistBucket> children = new LinkedList<>();
- /**
- * Constructor
- * @param parent
- * @param lineNumber
- */
- public HistLine(HistFunction parent, int lineNumber) {
- super(parent);
- this.line = lineNumber;
- }
+ /**
+ * Constructor
+ * @param parent
+ * @param lineNumber
+ */
+ public HistLine(HistFunction parent, int lineNumber) {
+ super(parent);
+ this.line = lineNumber;
+ }
- void addBucket(Bucket b) {
- this.children.add(new HistBucket(this,b));
- }
+ void addBucket(Bucket b) {
+ this.children.add(new HistBucket(this,b));
+ }
- @Override
- public LinkedList<? extends TreeElement> getChildren() {
- return this.children;
- }
+ @Override
+ public LinkedList<? extends TreeElement> getChildren() {
+ return this.children;
+ }
- @Override
- public int getCalls() {
- return -1;
- }
+ @Override
+ public int getCalls() {
+ return -1;
+ }
- @Override
- public String getName() {
- String functionName = getParent().getName();
- return functionName + " (" + getParent().getParent().getName() + ":" + this.line + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
+ @Override
+ public String getName() {
+ String functionName = getParent().getName();
+ return functionName + " (" + getParent().getParent().getName() + ":" + this.line + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
- @Override
- public int getSamples() {
- int ret = 0;
- for (HistBucket b : children) {
- ret += b.getSamples();
- }
- return ret;
- }
+ @Override
+ public int getSamples() {
+ int ret = 0;
+ for (HistBucket b : children) {
+ ret += b.getSamples();
+ }
+ return ret;
+ }
- @Override
- public int getSourceLine() {
- return this.line;
- }
+ @Override
+ public int getSourceLine() {
+ return this.line;
+ }
- @Override
- public String getSourcePath() {
- return getParent().getParent().getSourcePath();
- }
+ @Override
+ public String getSourcePath() {
+ return getParent().getParent().getSourcePath();
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistRoot.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistRoot.java
index ae1e68071a..f61e1c2319 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistRoot.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/HistRoot.java
@@ -27,75 +27,75 @@ import org.eclipse.linuxtools.internal.gprof.symbolManager.CallGraphNode;
*/
public class HistRoot extends AbstractTreeElement {
- private final LinkedList<HistFile> children = new LinkedList<>();
+ private final LinkedList<HistFile> children = new LinkedList<>();
- /** The decoded gmon to display */
- public final GmonDecoder decoder;
+ /** The decoded gmon to display */
+ public final GmonDecoder decoder;
- /**
- * Constructor
- * @param decoder
- */
- public HistRoot(GmonDecoder decoder) {
- super(null);
- this.decoder = decoder;
- }
+ /**
+ * Constructor
+ * @param decoder
+ */
+ public HistRoot(GmonDecoder decoder) {
+ super(null);
+ this.decoder = decoder;
+ }
- private HistFile getChild(String p) {
- for (HistFile f : this.children) {
- if (p != null) {
- if (p.equals(f.sourcePath)) {
- return f;
- }
- } else if (f.sourcePath == null) {
- return f;
- }
- }
- HistFile f = new HistFile(this, p);
- this.children.add(f);
- return f;
- }
+ private HistFile getChild(String p) {
+ for (HistFile f : this.children) {
+ if (p != null) {
+ if (p.equals(f.sourcePath)) {
+ return f;
+ }
+ } else if (f.sourcePath == null) {
+ return f;
+ }
+ }
+ HistFile f = new HistFile(this, p);
+ this.children.add(f);
+ return f;
+ }
- /**
- * Add a bucket to the tree representation of the gmon file
- * @param b a bucket
- * @param s a symbol (the bucket belong to this symbol)
- * @param program the program
- */
- public void addBucket(Bucket b, ISymbol s, IBinaryObject program) {
- String path = decoder.getFileName(s);
- HistFile hf = getChild(path);
- hf.addBucket(b, s, program);
- }
+ /**
+ * Add a bucket to the tree representation of the gmon file
+ * @param b a bucket
+ * @param s a symbol (the bucket belong to this symbol)
+ * @param program the program
+ */
+ public void addBucket(Bucket b, ISymbol s, IBinaryObject program) {
+ String path = decoder.getFileName(s);
+ HistFile hf = getChild(path);
+ hf.addBucket(b, s, program);
+ }
- /**
- * Add a callgraph node to the tree representation of the gmon file
- * @param node
- */
- public void addCallGraphNode(CallGraphNode node) {
- ISymbol s = node.getSymbol();
- String path = decoder.getFileName(s);
- HistFile hf = getChild(path);
- hf.addCallGraphNode(node);
- }
+ /**
+ * Add a callgraph node to the tree representation of the gmon file
+ * @param node
+ */
+ public void addCallGraphNode(CallGraphNode node) {
+ ISymbol s = node.getSymbol();
+ String path = decoder.getFileName(s);
+ HistFile hf = getChild(path);
+ hf.addCallGraphNode(node);
+ }
- @Override
- public LinkedList<? extends TreeElement> getChildren() {
- return this.children;
- }
+ @Override
+ public LinkedList<? extends TreeElement> getChildren() {
+ return this.children;
+ }
- @Override
- public String getName() {
- return Messages.HistRoot_Summary;
- }
+ @Override
+ public String getName() {
+ return Messages.HistRoot_Summary;
+ }
- @Override
- public int getCalls() {
- return -1;
- }
+ @Override
+ public int getCalls() {
+ return -1;
+ }
- public IProject getProject() {
- return decoder.getProject();
- }
+ public IProject getProject() {
+ return decoder.getProject();
+ }
}
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/TreeElement.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/TreeElement.java
index 66818a6baa..c1184e8b3d 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/TreeElement.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/internal/gprof/view/histogram/TreeElement.java
@@ -20,37 +20,37 @@ import java.util.LinkedList;
*/
public interface TreeElement {
- /**
- * Gets the parent of this tree node;
- * @return a tree node
- */
- TreeElement getParent();
+ /**
+ * Gets the parent of this tree node;
+ * @return a tree node
+ */
+ TreeElement getParent();
- /**
- * Gets the children of this tree node
- * @return an array of tree nodes
- */
- LinkedList<? extends TreeElement> getChildren();
+ /**
+ * Gets the children of this tree node
+ * @return an array of tree nodes
+ */
+ LinkedList<? extends TreeElement> getChildren();
- /**
- * Checks whether this tree node has children
- * @return <code>true</code> if this tree node has children,
- * <code>false</code> otherwise.
- */
- boolean hasChildren();
+ /**
+ * Checks whether this tree node has children
+ * @return <code>true</code> if this tree node has children,
+ * <code>false</code> otherwise.
+ */
+ boolean hasChildren();
- String getName();
+ String getName();
- int getSamples();
+ int getSamples();
- int getCalls();
+ int getCalls();
- String getSourcePath();
+ String getSourcePath();
- int getSourceLine();
+ int getSourceLine();
- TreeElement getRoot();
+ TreeElement getRoot();
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover-feature/pom.xml b/libhover/org.eclipse.linuxtools.cdt.libhover-feature/pom.xml
index 6589e17304..0565640d40 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover-feature/pom.xml
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover-feature/pom.xml
@@ -22,7 +22,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools Libhover Feature</name>
-
+
<build>
<plugins>
<plugin>
@@ -38,7 +38,7 @@
<configuration>
<excludes>
<plugin id="org.eclipse.linuxtools.cdt.libhover.library.docs"/>
- <plugin id="org.eclipse.linuxtools.cdt.libhover.glibc"/>
+ <plugin id="org.eclipse.linuxtools.cdt.libhover.glibc"/>
</excludes>
</configuration>
</execution>
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp-feature/pom.xml b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp-feature/pom.xml
index 0e7052f75f..7637abfc96 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp-feature/pom.xml
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp-feature/pom.xml
@@ -22,7 +22,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools Devhelp Libhover Feature</name>
-
+
<build>
<plugins>
<plugin>
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/pom.xml b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/pom.xml
index fab6b8ea0f..35e4baa83a 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/pom.xml
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/pom.xml
@@ -36,7 +36,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.cdt.libhover.devhelp.tests</testSuite>
<testClass>org.eclipse.linuxtools.cdt.libhover.devhelp.test.AllTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.platform.ide</product>
</configuration>
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/src/org/eclipse/linuxtools/cdt/libhover/devhelp/test/AllTests.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/src/org/eclipse/linuxtools/cdt/libhover/devhelp/test/AllTests.java
index 483f838776..06a9fc210c 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/src/org/eclipse/linuxtools/cdt/libhover/devhelp/test/AllTests.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/src/org/eclipse/linuxtools/cdt/libhover/devhelp/test/AllTests.java
@@ -17,10 +17,10 @@ import org.junit.runners.Suite.SuiteClasses;
*/
@RunWith(Suite.class)
@SuiteClasses({
- CheckDevhelp.class,
- }
+ CheckDevhelp.class,
+ }
)
public class AllTests {
- // empty
+ // empty
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/src/org/eclipse/linuxtools/cdt/libhover/devhelp/test/CheckDevhelp.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/src/org/eclipse/linuxtools/cdt/libhover/devhelp/test/CheckDevhelp.java
index f8879a0793..6d36981347 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/src/org/eclipse/linuxtools/cdt/libhover/devhelp/test/CheckDevhelp.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp.tests/src/org/eclipse/linuxtools/cdt/libhover/devhelp/test/CheckDevhelp.java
@@ -50,117 +50,117 @@ import org.osgi.framework.BundleReference;
public class CheckDevhelp {
- public final static String CACHE_EXT_LIBHOVER = "org.eclipse.linuxtools.cdt.libhover.testCacheExtLibhover"; //$NON-NLS-1$
+ public final static String CACHE_EXT_LIBHOVER = "org.eclipse.linuxtools.cdt.libhover.testCacheExtLibhover"; //$NON-NLS-1$
- @Before
- public void setUp() {
- IPath p = LibhoverPlugin.getDefault().getStateLocation().append("C"); //$NON-NLS-1$
- File f = new File(p.toOSString());
- f.delete();
- }
+ @Before
+ public void setUp() {
+ IPath p = LibhoverPlugin.getDefault().getStateLocation().append("C"); //$NON-NLS-1$
+ File f = new File(p.toOSString());
+ f.delete();
+ }
- @Test
- public void testParse() throws IOException {
- ParseDevHelp.DevHelpParser p = new ParseDevHelp.DevHelpParser(
- "/usr/share/gtk-doc/html"); //$NON-NLS-1$
- LibHoverInfo hover = p.parse(new NullProgressMonitor());
- assertNotNull(hover);
- Map<String, FunctionInfo> functions = hover.functions;
- assertNotNull(functions);
- assertFalse(functions.isEmpty());
- // Now, output the LibHoverInfo for caching later
- IPath location = LibhoverPlugin.getDefault().getStateLocation()
- .append("C"); //$NON-NLS-1$
- File ldir = new File(location.toOSString());
- ldir.mkdir();
- location = location.append("devhelp.libhover"); //$NON-NLS-1$
- try (FileOutputStream f = new FileOutputStream(location.toOSString());
- ObjectOutputStream out = new ObjectOutputStream(f)) {
- out.writeObject(hover);
- }
- IPreferenceStore ps = LibhoverPlugin.getDefault().getPreferenceStore();
- ps.setValue(CACHE_EXT_LIBHOVER, true);
- LibHover.getLibHoverDocs();
- Collection<LibHoverLibrary> c = LibHover.getLibraries();
- assertFalse(c.isEmpty());
- boolean found = false;
- for (LibHoverLibrary l : c) {
- if (l.getName().equals("devhelp")) { //$NON-NLS-1$
- found = true;
- }
- }
- assertTrue(found);
- }
+ @Test
+ public void testParse() throws IOException {
+ ParseDevHelp.DevHelpParser p = new ParseDevHelp.DevHelpParser(
+ "/usr/share/gtk-doc/html"); //$NON-NLS-1$
+ LibHoverInfo hover = p.parse(new NullProgressMonitor());
+ assertNotNull(hover);
+ Map<String, FunctionInfo> functions = hover.functions;
+ assertNotNull(functions);
+ assertFalse(functions.isEmpty());
+ // Now, output the LibHoverInfo for caching later
+ IPath location = LibhoverPlugin.getDefault().getStateLocation()
+ .append("C"); //$NON-NLS-1$
+ File ldir = new File(location.toOSString());
+ ldir.mkdir();
+ location = location.append("devhelp.libhover"); //$NON-NLS-1$
+ try (FileOutputStream f = new FileOutputStream(location.toOSString());
+ ObjectOutputStream out = new ObjectOutputStream(f)) {
+ out.writeObject(hover);
+ }
+ IPreferenceStore ps = LibhoverPlugin.getDefault().getPreferenceStore();
+ ps.setValue(CACHE_EXT_LIBHOVER, true);
+ LibHover.getLibHoverDocs();
+ Collection<LibHoverLibrary> c = LibHover.getLibraries();
+ assertFalse(c.isEmpty());
+ boolean found = false;
+ for (LibHoverLibrary l : c) {
+ if (l.getName().equals("devhelp")) { //$NON-NLS-1$
+ found = true;
+ }
+ }
+ assertTrue(found);
+ }
- @Test
- public void testTocProvider() {
- DevHelpTocProvider provider = new DevHelpTocProvider();
- ITocContribution[] contributions = provider
- .getTocContributions("en_US"); //$NON-NLS-1$
- assertTrue(contributions.length > 0);
- ITocContribution c = contributions[0];
- assertEquals(c.getId(),
- "org.eclipse.linuxtools.cdt.libhover.devhelp.toc"); //$NON-NLS-1$
- assertTrue(c.isPrimary());
- assertEquals(c.getCategoryId(), null);
- assertEquals(c.getLocale(), "en_US"); //$NON-NLS-1$
- String[] docs = c.getExtraDocuments();
- assertEquals(docs.length, 0);
- assertTrue(c.getLinkTo().isEmpty());
- assertEquals(c.getContributorId(),
- "org.eclipse.linuxtools.cdt.libhover.devhelp"); //$NON-NLS-1$
- }
+ @Test
+ public void testTocProvider() {
+ DevHelpTocProvider provider = new DevHelpTocProvider();
+ ITocContribution[] contributions = provider
+ .getTocContributions("en_US"); //$NON-NLS-1$
+ assertTrue(contributions.length > 0);
+ ITocContribution c = contributions[0];
+ assertEquals(c.getId(),
+ "org.eclipse.linuxtools.cdt.libhover.devhelp.toc"); //$NON-NLS-1$
+ assertTrue(c.isPrimary());
+ assertEquals(c.getCategoryId(), null);
+ assertEquals(c.getLocale(), "en_US"); //$NON-NLS-1$
+ String[] docs = c.getExtraDocuments();
+ assertEquals(docs.length, 0);
+ assertTrue(c.getLinkTo().isEmpty());
+ assertEquals(c.getContributorId(),
+ "org.eclipse.linuxtools.cdt.libhover.devhelp"); //$NON-NLS-1$
+ }
- @Test
- public void testHelpTopic() throws IOException {
- // We need to have a devhelp directory with contents to test.
- // Copy over the needed devhelp/html contents in this test plug-in,
- // test1.devhelp2 and index.html, to the workspace.
- ClassLoader cl = getClass().getClassLoader();
- Bundle bundle = null;
- if (cl instanceof BundleReference) {
- bundle = ((BundleReference) cl).getBundle();
- }
- IWorkspace ws = ResourcesPlugin.getWorkspace();
- IPath wslocpath = ws.getRoot().getLocation();
+ @Test
+ public void testHelpTopic() throws IOException {
+ // We need to have a devhelp directory with contents to test.
+ // Copy over the needed devhelp/html contents in this test plug-in,
+ // test1.devhelp2 and index.html, to the workspace.
+ ClassLoader cl = getClass().getClassLoader();
+ Bundle bundle = null;
+ if (cl instanceof BundleReference) {
+ bundle = ((BundleReference) cl).getBundle();
+ }
+ IWorkspace ws = ResourcesPlugin.getWorkspace();
+ IPath wslocpath = ws.getRoot().getLocation();
- IPath outfilepath = wslocpath.append("devhelp/html/test1"); //$NON-NLS-1$
- File outfiledir = outfilepath.toFile();
- assertTrue(outfiledir.mkdirs());
- outfilepath = outfilepath.append("test1.devhelp2"); //$NON-NLS-1$
- File outfile = outfilepath.toFile();
- IPath outfilepath2 = wslocpath.append("devhelp/html/test1/index.html"); //$NON-NLS-1$
- File outfile2 = outfilepath2.toFile();
- outfile.createNewFile();
- outfile2.createNewFile();
- try (InputStream in = FileLocator.openStream(bundle, new Path(
- "devhelp/html/test1/test1.devhelp2"), false)) { //$NON-NLS-1$
- Files.copy(in, Paths.get(outfile.toURI()), StandardCopyOption.REPLACE_EXISTING);
- }
- try (InputStream in2 = FileLocator.openStream(bundle, new Path(
- "devhelp/html/test1/index.html"), false)) { //$NON-NLS-1$
- Files.copy(in2, Paths.get(outfile2.toURI()), StandardCopyOption.REPLACE_EXISTING);
- }
+ IPath outfilepath = wslocpath.append("devhelp/html/test1"); //$NON-NLS-1$
+ File outfiledir = outfilepath.toFile();
+ assertTrue(outfiledir.mkdirs());
+ outfilepath = outfilepath.append("test1.devhelp2"); //$NON-NLS-1$
+ File outfile = outfilepath.toFile();
+ IPath outfilepath2 = wslocpath.append("devhelp/html/test1/index.html"); //$NON-NLS-1$
+ File outfile2 = outfilepath2.toFile();
+ outfile.createNewFile();
+ outfile2.createNewFile();
+ try (InputStream in = FileLocator.openStream(bundle, new Path(
+ "devhelp/html/test1/test1.devhelp2"), false)) { //$NON-NLS-1$
+ Files.copy(in, Paths.get(outfile.toURI()), StandardCopyOption.REPLACE_EXISTING);
+ }
+ try (InputStream in2 = FileLocator.openStream(bundle, new Path(
+ "devhelp/html/test1/index.html"), false)) { //$NON-NLS-1$
+ Files.copy(in2, Paths.get(outfile2.toURI()), StandardCopyOption.REPLACE_EXISTING);
+ }
- IPath x = wslocpath.append("devhelp/html"); //$NON-NLS-1$
- IPreferenceStore ps = DevHelpPlugin.getDefault().getPreferenceStore();
- ps.setValue(PreferenceConstants.DEVHELP_DIRECTORY, x.toOSString());
- DevHelpToc toc = new DevHelpToc();
- ITopic[] topics = toc.getTopics();
- // Verify we have the test1 topic
- assertTrue(topics.length > 0);
- ITopic topic = topics[0];
- assertTrue(topic.getLabel().startsWith("test1")); //$NON-NLS-1$
- ITopic[] subtopics = topic.getSubtopics();
- // Verify it has 4 or more sub-topics
- assertTrue(subtopics.length > 3);
- IUAElement[] elements = topic.getChildren();
- assertTrue(elements.length > 3);
- String href = topic.getHref();
- // Verify the topic href is the index.html file and that the topic is
- // enabled
- assertEquals(href,
- "/org.eclipse.linuxtools.cdt.libhover.devhelp/test1/index.html"); //$NON-NLS-1$
- assertTrue(topic.isEnabled(null));
- }
+ IPath x = wslocpath.append("devhelp/html"); //$NON-NLS-1$
+ IPreferenceStore ps = DevHelpPlugin.getDefault().getPreferenceStore();
+ ps.setValue(PreferenceConstants.DEVHELP_DIRECTORY, x.toOSString());
+ DevHelpToc toc = new DevHelpToc();
+ ITopic[] topics = toc.getTopics();
+ // Verify we have the test1 topic
+ assertTrue(topics.length > 0);
+ ITopic topic = topics[0];
+ assertTrue(topic.getLabel().startsWith("test1")); //$NON-NLS-1$
+ ITopic[] subtopics = topic.getSubtopics();
+ // Verify it has 4 or more sub-topics
+ assertTrue(subtopics.length > 3);
+ IUAElement[] elements = topic.getChildren();
+ assertTrue(elements.length > 3);
+ String href = topic.getHref();
+ // Verify the topic href is the index.html file and that the topic is
+ // enabled
+ assertEquals(href,
+ "/org.eclipse.linuxtools.cdt.libhover.devhelp/test1/index.html"); //$NON-NLS-1$
+ assertTrue(topic.isEnabled(null));
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpContentProducer.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpContentProducer.java
index bd7dda894b..c28b5be705 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpContentProducer.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpContentProducer.java
@@ -26,24 +26,24 @@ import org.eclipse.linuxtools.internal.cdt.libhover.devhelp.preferences.Preferen
public class DevHelpContentProducer implements IHelpContentProducer {
- @Override
- public InputStream getInputStream(String pluginID, String href,
- Locale locale) {
- // Eclipse help system adds parameters to the href but this breaks our path creation so we just strip them.
- if (href.contains("?")) { //$NON-NLS-1$
- href = href.substring(0, href.indexOf('?'));
- }
- IPreferenceStore ps = DevHelpPlugin.getDefault().getPreferenceStore();
- IPath devhelpLocation = new Path(ps.getString(PreferenceConstants.DEVHELP_DIRECTORY)).append(href);
- IFileSystem fs = EFS.getLocalFileSystem();
- IFileStore localLocation = fs.getStore(devhelpLocation);
- InputStream stream = null;
- try {
- stream = localLocation.openInputStream(EFS.NONE, new NullProgressMonitor());
- } catch (CoreException e) {
- e.printStackTrace();
- }
- return stream;
- }
+ @Override
+ public InputStream getInputStream(String pluginID, String href,
+ Locale locale) {
+ // Eclipse help system adds parameters to the href but this breaks our path creation so we just strip them.
+ if (href.contains("?")) { //$NON-NLS-1$
+ href = href.substring(0, href.indexOf('?'));
+ }
+ IPreferenceStore ps = DevHelpPlugin.getDefault().getPreferenceStore();
+ IPath devhelpLocation = new Path(ps.getString(PreferenceConstants.DEVHELP_DIRECTORY)).append(href);
+ IFileSystem fs = EFS.getLocalFileSystem();
+ IFileStore localLocation = fs.getStore(devhelpLocation);
+ InputStream stream = null;
+ try {
+ stream = localLocation.openInputStream(EFS.NONE, new NullProgressMonitor());
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ return stream;
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpPlugin.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpPlugin.java
index b9483e4d7a..bd7aeddfa6 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpPlugin.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpPlugin.java
@@ -37,103 +37,103 @@ import org.osgi.framework.BundleContext;
*/
public class DevHelpPlugin extends AbstractUIPlugin implements IStartup {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.cdt.libhover.devhelp"; //$NON-NLS-1$
- private static final String REGENERATE_MSG = "Libhover.Devhelp.Regenerate.msg"; //$NON-NLS-1$
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.cdt.libhover.devhelp"; //$NON-NLS-1$
+ private static final String REGENERATE_MSG = "Libhover.Devhelp.Regenerate.msg"; //$NON-NLS-1$
- // The shared instance
- private static DevHelpPlugin plugin;
+ // The shared instance
+ private static DevHelpPlugin plugin;
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
- * )
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- Job k = new DevhelpStartupJob(LibHoverMessages.getString(REGENERATE_MSG)) ;
- k.schedule();
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
+ * )
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ Job k = new DevhelpStartupJob(LibHoverMessages.getString(REGENERATE_MSG)) ;
+ k.schedule();
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
- * )
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static DevHelpPlugin getDefault() {
- return plugin;
- }
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static DevHelpPlugin getDefault() {
+ return plugin;
+ }
- @Override
- public void earlyStartup() {
- // do nothing...we just want start to get called and reparse the devhelp
- // directory
- }
+ @Override
+ public void earlyStartup() {
+ // do nothing...we just want start to get called and reparse the devhelp
+ // directory
+ }
- /**
- * Job used to load devhelp data on startup.
- *
- */
- private static class DevhelpStartupJob extends Job {
+ /**
+ * Job used to load devhelp data on startup.
+ *
+ */
+ private static class DevhelpStartupJob extends Job {
- public DevhelpStartupJob(String name) {
- super(name);
- }
+ public DevhelpStartupJob(String name) {
+ super(name);
+ }
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- IPreferenceStore ps = DevHelpPlugin.getDefault()
- .getPreferenceStore();
- ParseDevHelp.DevHelpParser p = new ParseDevHelp.DevHelpParser(
- ps.getString(PreferenceConstants.DEVHELP_DIRECTORY));
- LibHoverInfo hover = p.parse(monitor);
- // Update the devhelp library info if it is on library list
- Collection<LibHoverLibrary> libs = LibHover.getLibraries();
- for (LibHoverLibrary l : libs) {
- if (l.getName().equals("devhelp")) { //$NON-NLS-1$
- l.setHoverinfo(hover);
- break;
- }
- }
- try {
- // Now, output the LibHoverInfo for caching later
- IPath location = LibhoverPlugin.getDefault()
- .getStateLocation().append("C"); //$NON-NLS-1$
- File ldir = new File(location.toOSString());
- ldir.mkdir();
- location = location.append("devhelp.libhover"); //$NON-NLS-1$
- try (FileOutputStream f = new FileOutputStream(
- location.toOSString());
- ObjectOutputStream out = new ObjectOutputStream(f)) {
- out.writeObject(hover);
- }
- monitor.done();
- } catch (IOException e) {
- monitor.done();
- return new Status(IStatus.ERROR, DevHelpPlugin.PLUGIN_ID,
- e.getLocalizedMessage(), e);
- }
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ IPreferenceStore ps = DevHelpPlugin.getDefault()
+ .getPreferenceStore();
+ ParseDevHelp.DevHelpParser p = new ParseDevHelp.DevHelpParser(
+ ps.getString(PreferenceConstants.DEVHELP_DIRECTORY));
+ LibHoverInfo hover = p.parse(monitor);
+ // Update the devhelp library info if it is on library list
+ Collection<LibHoverLibrary> libs = LibHover.getLibraries();
+ for (LibHoverLibrary l : libs) {
+ if (l.getName().equals("devhelp")) { //$NON-NLS-1$
+ l.setHoverinfo(hover);
+ break;
+ }
+ }
+ try {
+ // Now, output the LibHoverInfo for caching later
+ IPath location = LibhoverPlugin.getDefault()
+ .getStateLocation().append("C"); //$NON-NLS-1$
+ File ldir = new File(location.toOSString());
+ ldir.mkdir();
+ location = location.append("devhelp.libhover"); //$NON-NLS-1$
+ try (FileOutputStream f = new FileOutputStream(
+ location.toOSString());
+ ObjectOutputStream out = new ObjectOutputStream(f)) {
+ out.writeObject(hover);
+ }
+ monitor.done();
+ } catch (IOException e) {
+ monitor.done();
+ return new Status(IStatus.ERROR, DevHelpPlugin.PLUGIN_ID,
+ e.getLocalizedMessage(), e);
+ }
- return Status.OK_STATUS;
- }
+ return Status.OK_STATUS;
+ }
- };
+ };
} \ No newline at end of file
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpToc.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpToc.java
index 1e698d1b02..6c94273f24 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpToc.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpToc.java
@@ -29,65 +29,65 @@ import org.eclipse.linuxtools.internal.cdt.libhover.devhelp.preferences.Preferen
public class DevHelpToc implements IToc {
- @Override
- public String getLabel() {
- return "Devhelp Documents"; //$NON-NLS-1$
- }
+ @Override
+ public String getLabel() {
+ return "Devhelp Documents"; //$NON-NLS-1$
+ }
- @Override
- public String getHref() {
- return null;
- }
+ @Override
+ public String getHref() {
+ return null;
+ }
- @Override
- public boolean isEnabled(IEvaluationContext context) {
- return true;
- }
+ @Override
+ public boolean isEnabled(IEvaluationContext context) {
+ return true;
+ }
- @Override
- public IUAElement[] getChildren() {
- return getTopics();
- }
+ @Override
+ public IUAElement[] getChildren() {
+ return getTopics();
+ }
- @Override
- public ITopic[] getTopics() {
- try {
- ArrayList<ITopic> topics = new ArrayList<>();
- IPreferenceStore ps = DevHelpPlugin.getDefault()
- .getPreferenceStore();
- IPath devhelpLocation = new Path(
- ps.getString(PreferenceConstants.DEVHELP_DIRECTORY));
- IFileSystem fs = EFS.getLocalFileSystem();
- IFileStore htmlDir = fs.getStore(devhelpLocation);
- IFileStore[] files = htmlDir.childStores(EFS.NONE, null);
- Arrays.sort(files, new Comparator<IFileStore>() {
+ @Override
+ public ITopic[] getTopics() {
+ try {
+ ArrayList<ITopic> topics = new ArrayList<>();
+ IPreferenceStore ps = DevHelpPlugin.getDefault()
+ .getPreferenceStore();
+ IPath devhelpLocation = new Path(
+ ps.getString(PreferenceConstants.DEVHELP_DIRECTORY));
+ IFileSystem fs = EFS.getLocalFileSystem();
+ IFileStore htmlDir = fs.getStore(devhelpLocation);
+ IFileStore[] files = htmlDir.childStores(EFS.NONE, null);
+ Arrays.sort(files, new Comparator<IFileStore>() {
- @Override
- public int compare(IFileStore arg0, IFileStore arg1) {
- return (arg0.getName().compareToIgnoreCase(arg1.getName()));
- }
+ @Override
+ public int compare(IFileStore arg0, IFileStore arg1) {
+ return (arg0.getName().compareToIgnoreCase(arg1.getName()));
+ }
- });
- for (IFileStore file: files) {
- String name = file.fetchInfo().getName();
- if (fs.getStore(
- devhelpLocation.append(name).append(name + ".devhelp2")) //$NON-NLS-1$
- .fetchInfo().exists()) {
- ITopic topic = new DevHelpTopic(name);
- topics.add(topic);
- }
- }
- ITopic[] retval = new ITopic[topics.size()];
- return topics.toArray(retval);
- } catch (CoreException e) {
- }
- return null;
- }
+ });
+ for (IFileStore file: files) {
+ String name = file.fetchInfo().getName();
+ if (fs.getStore(
+ devhelpLocation.append(name).append(name + ".devhelp2")) //$NON-NLS-1$
+ .fetchInfo().exists()) {
+ ITopic topic = new DevHelpTopic(name);
+ topics.add(topic);
+ }
+ }
+ ITopic[] retval = new ITopic[topics.size()];
+ return topics.toArray(retval);
+ } catch (CoreException e) {
+ }
+ return null;
+ }
- @Override
- public ITopic getTopic(String href) {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public ITopic getTopic(String href) {
+ // TODO Auto-generated method stub
+ return null;
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpTocProvider.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpTocProvider.java
index 245da83895..dead6d1542 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpTocProvider.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpTocProvider.java
@@ -16,48 +16,48 @@ import org.eclipse.help.ITocContribution;
public class DevHelpTocProvider extends AbstractTocProvider {
- @Override
- public ITocContribution[] getTocContributions(String locale) {
+ @Override
+ public ITocContribution[] getTocContributions(String locale) {
ITocContribution contribution = new ITocContribution() {
@Override
- public String getId() {
+ public String getId() {
// a way to identify our book
return "org.eclipse.linuxtools.cdt.libhover.devhelp.toc"; //$NON-NLS-1$
}
@Override
- public String getCategoryId() {
+ public String getCategoryId() {
// our book does not belong to any category of books
return null;
}
@Override
- public boolean isPrimary() {
+ public boolean isPrimary() {
// this is a primary, top-level contribution (a book)
return true;
}
@Override
- public IToc getToc() {
- return new DevHelpToc();
+ public IToc getToc() {
+ return new DevHelpToc();
}
@Override
- public String getLocale() {
- // this provider only provides content for the en_US locale
- return "en_US"; //$NON-NLS-1$
+ public String getLocale() {
+ // this provider only provides content for the en_US locale
+ return "en_US"; //$NON-NLS-1$
}
@Override
- public String[] getExtraDocuments() {
- // there are no extra documents associated with this book
- return new String[0];
+ public String[] getExtraDocuments() {
+ // there are no extra documents associated with this book
+ return new String[0];
}
@Override
- public String getLinkTo() {
- return ""; //$NON-NLS-1$
+ public String getLinkTo() {
+ return ""; //$NON-NLS-1$
}
@Override
public String getContributorId() {
- return "org.eclipse.linuxtools.cdt.libhover.devhelp"; //$NON-NLS-1$
+ return "org.eclipse.linuxtools.cdt.libhover.devhelp"; //$NON-NLS-1$
}
};
return new ITocContribution[] { contribution };
- }
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpTopic.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpTopic.java
index 3842579b5b..fdc61c74d6 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpTopic.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/DevHelpTopic.java
@@ -37,114 +37,114 @@ import org.xml.sax.SAXException;
public class DevHelpTopic implements ITopic {
- private String name;
- private XPath xpath;
- private String label;
- private String link;
- private List<ITopic> subTopics;
-
- DevHelpTopic(String name) {
- this.name = name;
- xpath = XPathFactory.newInstance().newXPath();
- subTopics = new ArrayList<>();
- label = name;
- init();
- }
-
- private void init() {
- IPreferenceStore ps = DevHelpPlugin.getDefault().getPreferenceStore();
- IPath devhelpLocation = new Path(
- ps.getString(PreferenceConstants.DEVHELP_DIRECTORY)).append(
- name).append(name + ".devhelp2"); //$NON-NLS-1$
- File devhelpFile = devhelpLocation.toFile();
- if (devhelpFile.exists()) {
- DocumentBuilderFactory docfactory = DocumentBuilderFactory
- .newInstance();
- docfactory.setValidating(false);
- try {
- docfactory.setFeature("http://xml.org/sax/features/namespaces", //$NON-NLS-1$
- false);
- docfactory.setFeature("http://xml.org/sax/features/validation", //$NON-NLS-1$
- false);
- docfactory
- .setFeature(
- "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", //$NON-NLS-1$
- false);
- docfactory
- .setFeature(
- "http://apache.org/xml/features/nonvalidating/load-external-dtd", //$NON-NLS-1$
- false);
-
- DocumentBuilder docbuilder = docfactory.newDocumentBuilder();
- Document docroot = docbuilder.parse(devhelpLocation.toFile());
-
- // set label
- label = xpathEval("/book/@title", docroot); //$NON-NLS-1$
- if (label.isEmpty()) {
- label = name;
- }
- link = xpathEval("/book/@link", docroot); //$NON-NLS-1$
-
- // set subtopics
- NodeList nodes = xpathEvalNodes("/book/chapters/sub", docroot); //$NON-NLS-1$
- for (int i = 0; i < nodes.getLength(); i++) {
- Node node = nodes.item(i);
- subTopics.add(new SimpleTopic(name, node));
- }
- } catch (ParserConfigurationException e) {
- e.printStackTrace();
- } catch (SAXException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- private String xpathEval(String path, Document docroot) {
- String result = ""; //$NON-NLS-1$
- try {
- result = xpath.evaluate(path, docroot);
- } catch (XPathExpressionException e) {
- e.printStackTrace();
- }
- return result;
- }
-
- private NodeList xpathEvalNodes(String path, Document docroot) {
- NodeList result = null;
- try {
- result = (NodeList) xpath.evaluate(path, docroot,
- XPathConstants.NODESET);
- } catch (XPathExpressionException e) {
- e.printStackTrace();
- }
- return result;
- }
-
- @Override
- public boolean isEnabled(IEvaluationContext context) {
- return true;
- }
-
- @Override
- public IUAElement[] getChildren() {
- return getSubtopics();
- }
-
- @Override
- public String getHref() {
- return "/" + DevHelpPlugin.PLUGIN_ID + "/" + name + "/"+link; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- }
-
- @Override
- public String getLabel() {
- return label;
- }
-
- @Override
- public ITopic[] getSubtopics() {
- return subTopics.toArray(new ITopic[subTopics.size()]);
- }
+ private String name;
+ private XPath xpath;
+ private String label;
+ private String link;
+ private List<ITopic> subTopics;
+
+ DevHelpTopic(String name) {
+ this.name = name;
+ xpath = XPathFactory.newInstance().newXPath();
+ subTopics = new ArrayList<>();
+ label = name;
+ init();
+ }
+
+ private void init() {
+ IPreferenceStore ps = DevHelpPlugin.getDefault().getPreferenceStore();
+ IPath devhelpLocation = new Path(
+ ps.getString(PreferenceConstants.DEVHELP_DIRECTORY)).append(
+ name).append(name + ".devhelp2"); //$NON-NLS-1$
+ File devhelpFile = devhelpLocation.toFile();
+ if (devhelpFile.exists()) {
+ DocumentBuilderFactory docfactory = DocumentBuilderFactory
+ .newInstance();
+ docfactory.setValidating(false);
+ try {
+ docfactory.setFeature("http://xml.org/sax/features/namespaces", //$NON-NLS-1$
+ false);
+ docfactory.setFeature("http://xml.org/sax/features/validation", //$NON-NLS-1$
+ false);
+ docfactory
+ .setFeature(
+ "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", //$NON-NLS-1$
+ false);
+ docfactory
+ .setFeature(
+ "http://apache.org/xml/features/nonvalidating/load-external-dtd", //$NON-NLS-1$
+ false);
+
+ DocumentBuilder docbuilder = docfactory.newDocumentBuilder();
+ Document docroot = docbuilder.parse(devhelpLocation.toFile());
+
+ // set label
+ label = xpathEval("/book/@title", docroot); //$NON-NLS-1$
+ if (label.isEmpty()) {
+ label = name;
+ }
+ link = xpathEval("/book/@link", docroot); //$NON-NLS-1$
+
+ // set subtopics
+ NodeList nodes = xpathEvalNodes("/book/chapters/sub", docroot); //$NON-NLS-1$
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Node node = nodes.item(i);
+ subTopics.add(new SimpleTopic(name, node));
+ }
+ } catch (ParserConfigurationException e) {
+ e.printStackTrace();
+ } catch (SAXException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private String xpathEval(String path, Document docroot) {
+ String result = ""; //$NON-NLS-1$
+ try {
+ result = xpath.evaluate(path, docroot);
+ } catch (XPathExpressionException e) {
+ e.printStackTrace();
+ }
+ return result;
+ }
+
+ private NodeList xpathEvalNodes(String path, Document docroot) {
+ NodeList result = null;
+ try {
+ result = (NodeList) xpath.evaluate(path, docroot,
+ XPathConstants.NODESET);
+ } catch (XPathExpressionException e) {
+ e.printStackTrace();
+ }
+ return result;
+ }
+
+ @Override
+ public boolean isEnabled(IEvaluationContext context) {
+ return true;
+ }
+
+ @Override
+ public IUAElement[] getChildren() {
+ return getSubtopics();
+ }
+
+ @Override
+ public String getHref() {
+ return "/" + DevHelpPlugin.PLUGIN_ID + "/" + name + "/"+link; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ }
+
+ @Override
+ public String getLabel() {
+ return label;
+ }
+
+ @Override
+ public ITopic[] getSubtopics() {
+ return subTopics.toArray(new ITopic[subTopics.size()]);
+ }
} \ No newline at end of file
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/ParseDevHelp.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/ParseDevHelp.java
index 6c7dcb0002..6c5605aa53 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/ParseDevHelp.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/ParseDevHelp.java
@@ -113,7 +113,7 @@ public class ParseDevHelp {
descStart = true;;
description.append("<p>"); //$NON-NLS-1$
}
- } else if (descStart) {
+ } else if (descStart) {
if ("P".equals(name.rawname)) { //$NON-NLS-1$
description.append("<p>"); //$NON-NLS-1$
} else if ("TABLE".equals(name.rawname)) { //$NON-NLS-1$
@@ -143,7 +143,7 @@ public class ParseDevHelp {
if (begin) {
if ("DIV".equals(name.rawname)) { //$NON-NLS-1$
--divCounter;
-// System.out.println("divCounter is " + divCounter);
+// System.out.println("divCounter is " + divCounter);
if (divCounter <= 0) {
begin = false;
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/SimpleTopic.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/SimpleTopic.java
index 41a95150c3..b49eaab11c 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/SimpleTopic.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/SimpleTopic.java
@@ -26,75 +26,75 @@ import org.w3c.dom.NodeList;
public class SimpleTopic implements ITopic {
- private String bookName;
- private Node node;
- private XPath xpath;
- private List<ITopic> subTopics;
+ private String bookName;
+ private Node node;
+ private XPath xpath;
+ private List<ITopic> subTopics;
- public SimpleTopic(String bookName, Node node) {
- this.bookName = bookName;
- this.node = node;
- xpath = XPathFactory.newInstance().newXPath();
- subTopics = new ArrayList<>();
- initSubtopics();
- }
+ public SimpleTopic(String bookName, Node node) {
+ this.bookName = bookName;
+ this.node = node;
+ xpath = XPathFactory.newInstance().newXPath();
+ subTopics = new ArrayList<>();
+ initSubtopics();
+ }
- private void initSubtopics() {
- NodeList nodes = xpathEvalNodes("sub", node); //$NON-NLS-1$
- if (nodes != null) {
- for (int i = 0; i < nodes.getLength(); i++) {
- Node innerNode = nodes.item(i);
- subTopics.add(new SimpleTopic(bookName, innerNode));
- }
- }
+ private void initSubtopics() {
+ NodeList nodes = xpathEvalNodes("sub", node); //$NON-NLS-1$
+ if (nodes != null) {
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Node innerNode = nodes.item(i);
+ subTopics.add(new SimpleTopic(bookName, innerNode));
+ }
+ }
- }
+ }
- private NodeList xpathEvalNodes(String path, Node docroot) {
- NodeList result = null;
- try {
- result = (NodeList) xpath.evaluate(path, docroot,
- XPathConstants.NODESET);
- } catch (XPathExpressionException e) {
- e.printStackTrace();
- }
- return result;
- }
+ private NodeList xpathEvalNodes(String path, Node docroot) {
+ NodeList result = null;
+ try {
+ result = (NodeList) xpath.evaluate(path, docroot,
+ XPathConstants.NODESET);
+ } catch (XPathExpressionException e) {
+ e.printStackTrace();
+ }
+ return result;
+ }
- @Override
- public boolean isEnabled(IEvaluationContext context) {
- return true;
- }
+ @Override
+ public boolean isEnabled(IEvaluationContext context) {
+ return true;
+ }
- @Override
- public IUAElement[] getChildren() {
- return getSubtopics();
- }
+ @Override
+ public IUAElement[] getChildren() {
+ return getSubtopics();
+ }
- @Override
- public String getHref() {
- String link = ""; //$NON-NLS-1$
- try {
- link = xpath.evaluate("@link", node); //$NON-NLS-1$
- } catch (XPathExpressionException e) {
- e.printStackTrace();
- }
- return "/" + DevHelpPlugin.PLUGIN_ID + "/" + bookName + "/" + link; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
+ @Override
+ public String getHref() {
+ String link = ""; //$NON-NLS-1$
+ try {
+ link = xpath.evaluate("@link", node); //$NON-NLS-1$
+ } catch (XPathExpressionException e) {
+ e.printStackTrace();
+ }
+ return "/" + DevHelpPlugin.PLUGIN_ID + "/" + bookName + "/" + link; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
- @Override
- public String getLabel() {
- try {
- return xpath.evaluate("@name", node); //$NON-NLS-1$
- } catch (XPathExpressionException e) {
- e.printStackTrace();
- }
- return ""; //$NON-NLS-1$
- }
+ @Override
+ public String getLabel() {
+ try {
+ return xpath.evaluate("@name", node); //$NON-NLS-1$
+ } catch (XPathExpressionException e) {
+ e.printStackTrace();
+ }
+ return ""; //$NON-NLS-1$
+ }
- @Override
- public ITopic[] getSubtopics() {
- return subTopics.toArray(new ITopic[subTopics.size()]);
- }
+ @Override
+ public ITopic[] getSubtopics() {
+ return subTopics.toArray(new ITopic[subTopics.size()]);
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LabelFieldEditor.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LabelFieldEditor.java
index aa47c55391..91550be853 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LabelFieldEditor.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LabelFieldEditor.java
@@ -6,16 +6,16 @@ import org.eclipse.swt.widgets.Composite;
// Label class for a preference page.
class LabelFieldEditor extends FieldEditor {
- private Composite parent;
+ private Composite parent;
- public LabelFieldEditor( Composite parent, String title ) {
- this.parent = parent;
- init("org.eclipse.linuxtools.cdt.libhover.dummy", title); //$NON-NLS-1$
- createControl(parent);
- }
+ public LabelFieldEditor( Composite parent, String title ) {
+ this.parent = parent;
+ init("org.eclipse.linuxtools.cdt.libhover.dummy", title); //$NON-NLS-1$
+ createControl(parent);
+ }
- @Override
- protected void adjustForNumColumns( int numColumns ) {
+ @Override
+ protected void adjustForNumColumns( int numColumns ) {
GridData gd = new GridData();
gd.horizontalSpan = numColumns;
// We only grab excess space if we have to
@@ -23,23 +23,23 @@ class LabelFieldEditor extends FieldEditor {
// we assume it is setting the width.
gd.grabExcessHorizontalSpace = gd.horizontalSpan == 1;
getLabelControl(parent).setLayoutData(gd);
- }
+ }
- @Override
- protected void doFillIntoGrid( Composite parent, int numColumns ) {
- getLabelControl(parent);
- }
+ @Override
+ protected void doFillIntoGrid( Composite parent, int numColumns ) {
+ getLabelControl(parent);
+ }
- @Override
- public int getNumberOfControls() { return 1; }
- /**
- * The label field editor is only used to present a text label on a preference page.
- */
- @Override
- protected void doLoad() {}
- @Override
- protected void doLoadDefault() {}
- @Override
- protected void doStore() {}
+ @Override
+ public int getNumberOfControls() { return 1; }
+ /**
+ * The label field editor is only used to present a text label on a preference page.
+ */
+ @Override
+ protected void doLoad() {}
+ @Override
+ protected void doLoadDefault() {}
+ @Override
+ protected void doStore() {}
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LibHoverMessages.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LibHoverMessages.java
index b42d3b3bd0..42312773b9 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LibHoverMessages.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LibHoverMessages.java
@@ -21,41 +21,41 @@ import java.util.ResourceBundle;
*/
public class LibHoverMessages {
- /**
- *
- */
-
- private static final String RESOURCE_BUNDLE= LibHoverMessages.class.getName();
-
- private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);
-
- private LibHoverMessages() {
- }
-
- public static ResourceBundle getResourceBundle() {
- return fgResourceBundle;
- }
-
- public static String getString(String key) {
- try {
- return fgResourceBundle.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- } catch (NullPointerException e) {
- return '#' + key + '#';
- }
- }
-
- /**
- * Returns the formatted string from the resource bundle,
- * or 'key' if not found.
- *
- * @param key the message key
- * @param args an array of substituition strings
- * @return the resource bundle message
- */
- public static String getFormattedString(String key, String[] args) {
- return MessageFormat.format(getString(key), (Object[])args);
- }
+ /**
+ *
+ */
+
+ private static final String RESOURCE_BUNDLE= LibHoverMessages.class.getName();
+
+ private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);
+
+ private LibHoverMessages() {
+ }
+
+ public static ResourceBundle getResourceBundle() {
+ return fgResourceBundle;
+ }
+
+ public static String getString(String key) {
+ try {
+ return fgResourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ } catch (NullPointerException e) {
+ return '#' + key + '#';
+ }
+ }
+
+ /**
+ * Returns the formatted string from the resource bundle,
+ * or 'key' if not found.
+ *
+ * @param key the message key
+ * @param args an array of substituition strings
+ * @return the resource bundle message
+ */
+ public static String getFormattedString(String key, String[] args) {
+ return MessageFormat.format(getString(key), (Object[])args);
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LibHoverPreferencePage.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LibHoverPreferencePage.java
index 194212ee34..c68dae59a7 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LibHoverPreferencePage.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/LibHoverPreferencePage.java
@@ -61,138 +61,138 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
*/
public class LibHoverPreferencePage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
-
- private final static String DEVHELP_DIR = "Libhover.Devhelp.Directory"; //$NON-NLS-1$
- private final static String GENERATE = "Libhover.Devhelp.Generate.lbl"; //$NON-NLS-1$
- private final static String REGENERATE_MSG = "Libhover.Devhelp.Regenerate.msg"; //$NON-NLS-1$
- private final static String TITLE = "Libhover.Devhelp.Preference.title"; //$NON-NLS-1$
-
- private Button generateButton;
-
- public LibHoverPreferencePage() {
- super(GRID);
- setPreferenceStore(DevHelpPlugin.getDefault().getPreferenceStore());
- }
-
- private static class DevhelpStringFieldEditor extends DirectoryFieldEditor {
- public DevhelpStringFieldEditor(String name, String labelText,
- Composite parent) {
- super(name, labelText, parent);
- setFilterPath(new File(DevHelpPlugin.getDefault().getPreferenceStore().getString(name)));
- }
-
- }
-
- private synchronized void regenerate() {
- generateButton.setEnabled(false);
- Job k = new Job(LibHoverMessages.getString(REGENERATE_MSG)) {
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- IPreferenceStore ps = DevHelpPlugin.getDefault().getPreferenceStore();
- ParseDevHelp.DevHelpParser p =
- new ParseDevHelp.DevHelpParser(ps.getString(PreferenceConstants.DEVHELP_DIRECTORY));
- LibHoverInfo hover = p.parse(monitor);
- // Update the devhelp library info if it is on library list
- Collection<LibHoverLibrary> libs = LibHover.getLibraries();
- for (LibHoverLibrary l : libs) {
- if (l.getName().equals("devhelp")) { //$NON-NLS-1$
- l.setHoverinfo(hover);
- break;
- }
- }
- try {
- // Now, output the LibHoverInfo for caching later
- IPath location = LibhoverPlugin.getDefault().getStateLocation().append("C"); //$NON-NLS-1$
- File ldir = new File(location.toOSString());
- ldir.mkdir();
- location = location.append("devhelp.libhover"); //$NON-NLS-1$
- try (FileOutputStream f = new FileOutputStream(
- location.toOSString());
- ObjectOutputStream out = new ObjectOutputStream(f)) {
- out.writeObject(hover);
- }
- monitor.done();
- } catch(IOException e) {
- monitor.done();
- return new Status(IStatus.ERROR, DevHelpPlugin.PLUGIN_ID, e.getLocalizedMessage(), e);
- }
-
-
- return Status.OK_STATUS;
- }
-
- };
- k.setUser(true);
- k.addJobChangeListener(new JobChangeAdapter() {
- @Override
- public void done(IJobChangeEvent event) {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- generateButton.setEnabled(true);
- }
- });
- }
- });
- k.schedule();
- }
-
- @Override
- protected void contributeButtons(Composite parent) {
- ((GridLayout) parent.getLayout()).numColumns++;
- generateButton = new Button(parent, SWT.NONE);
- generateButton.setFont(parent.getFont());
- generateButton.setText(LibHoverMessages.getString(GENERATE));
- generateButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent evt) {
- regenerate();
- }
- });
- generateButton.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent event) {
- generateButton = null;
- }
- });
- GridData gd = new GridData();
+ IWorkbenchPreferencePage {
+
+ private final static String DEVHELP_DIR = "Libhover.Devhelp.Directory"; //$NON-NLS-1$
+ private final static String GENERATE = "Libhover.Devhelp.Generate.lbl"; //$NON-NLS-1$
+ private final static String REGENERATE_MSG = "Libhover.Devhelp.Regenerate.msg"; //$NON-NLS-1$
+ private final static String TITLE = "Libhover.Devhelp.Preference.title"; //$NON-NLS-1$
+
+ private Button generateButton;
+
+ public LibHoverPreferencePage() {
+ super(GRID);
+ setPreferenceStore(DevHelpPlugin.getDefault().getPreferenceStore());
+ }
+
+ private static class DevhelpStringFieldEditor extends DirectoryFieldEditor {
+ public DevhelpStringFieldEditor(String name, String labelText,
+ Composite parent) {
+ super(name, labelText, parent);
+ setFilterPath(new File(DevHelpPlugin.getDefault().getPreferenceStore().getString(name)));
+ }
+
+ }
+
+ private synchronized void regenerate() {
+ generateButton.setEnabled(false);
+ Job k = new Job(LibHoverMessages.getString(REGENERATE_MSG)) {
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ IPreferenceStore ps = DevHelpPlugin.getDefault().getPreferenceStore();
+ ParseDevHelp.DevHelpParser p =
+ new ParseDevHelp.DevHelpParser(ps.getString(PreferenceConstants.DEVHELP_DIRECTORY));
+ LibHoverInfo hover = p.parse(monitor);
+ // Update the devhelp library info if it is on library list
+ Collection<LibHoverLibrary> libs = LibHover.getLibraries();
+ for (LibHoverLibrary l : libs) {
+ if (l.getName().equals("devhelp")) { //$NON-NLS-1$
+ l.setHoverinfo(hover);
+ break;
+ }
+ }
+ try {
+ // Now, output the LibHoverInfo for caching later
+ IPath location = LibhoverPlugin.getDefault().getStateLocation().append("C"); //$NON-NLS-1$
+ File ldir = new File(location.toOSString());
+ ldir.mkdir();
+ location = location.append("devhelp.libhover"); //$NON-NLS-1$
+ try (FileOutputStream f = new FileOutputStream(
+ location.toOSString());
+ ObjectOutputStream out = new ObjectOutputStream(f)) {
+ out.writeObject(hover);
+ }
+ monitor.done();
+ } catch(IOException e) {
+ monitor.done();
+ return new Status(IStatus.ERROR, DevHelpPlugin.PLUGIN_ID, e.getLocalizedMessage(), e);
+ }
+
+
+ return Status.OK_STATUS;
+ }
+
+ };
+ k.setUser(true);
+ k.addJobChangeListener(new JobChangeAdapter() {
+ @Override
+ public void done(IJobChangeEvent event) {
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ generateButton.setEnabled(true);
+ }
+ });
+ }
+ });
+ k.schedule();
+ }
+
+ @Override
+ protected void contributeButtons(Composite parent) {
+ ((GridLayout) parent.getLayout()).numColumns++;
+ generateButton = new Button(parent, SWT.NONE);
+ generateButton.setFont(parent.getFont());
+ generateButton.setText(LibHoverMessages.getString(GENERATE));
+ generateButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent evt) {
+ regenerate();
+ }
+ });
+ generateButton.addDisposeListener(new DisposeListener() {
+ @Override
+ public void widgetDisposed(DisposeEvent event) {
+ generateButton = null;
+ }
+ });
+ GridData gd = new GridData();
gd.horizontalAlignment = GridData.FILL;
int widthHint = convertHorizontalDLUsToPixels(
IDialogConstants.BUTTON_WIDTH);
gd.widthHint = Math.max(widthHint, generateButton.computeSize(
SWT.DEFAULT, SWT.DEFAULT, true).x);
- generateButton.setLayoutData(gd);
+ generateButton.setLayoutData(gd);
}
- /**
- * Creates the field editors. Field editors are abstractions of
- * the common GUI blocks needed to manipulate various types
- * of preferences. Each field editor knows how to save and
- * restore itself.
- */
- @Override
- public void createFieldEditors() {
- addField(
- new LabelFieldEditor(
- getFieldEditorParent(),
- LibHoverMessages.getString(TITLE)));
- addField(
- new DevhelpStringFieldEditor(
- PreferenceConstants.DEVHELP_DIRECTORY,
- LibHoverMessages.getString(DEVHELP_DIR),
- getFieldEditorParent()));
-
-
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- @Override
- public void init(IWorkbench workbench) {
- }
+ /**
+ * Creates the field editors. Field editors are abstractions of
+ * the common GUI blocks needed to manipulate various types
+ * of preferences. Each field editor knows how to save and
+ * restore itself.
+ */
+ @Override
+ public void createFieldEditors() {
+ addField(
+ new LabelFieldEditor(
+ getFieldEditorParent(),
+ LibHoverMessages.getString(TITLE)));
+ addField(
+ new DevhelpStringFieldEditor(
+ PreferenceConstants.DEVHELP_DIRECTORY,
+ LibHoverMessages.getString(DEVHELP_DIR),
+ getFieldEditorParent()));
+
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
+ */
+ @Override
+ public void init(IWorkbench workbench) {
+ }
} \ No newline at end of file
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/PreferenceConstants.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/PreferenceConstants.java
index a4b99109eb..d42b4ac0fc 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/PreferenceConstants.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/PreferenceConstants.java
@@ -15,6 +15,6 @@ package org.eclipse.linuxtools.internal.cdt.libhover.devhelp.preferences;
*/
public class PreferenceConstants {
- public final static String DEVHELP_DIRECTORY = "org.eclipse.linuxtools.cdt.libhover.devhelp.directory"; //$NON-NLS-1$
-
+ public final static String DEVHELP_DIRECTORY = "org.eclipse.linuxtools.cdt.libhover.devhelp.directory"; //$NON-NLS-1$
+
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/PreferenceInitializer.java b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/PreferenceInitializer.java
index a473be8a41..c30fe9d239 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/PreferenceInitializer.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.devhelp/src/org/eclipse/linuxtools/internal/cdt/libhover/devhelp/preferences/PreferenceInitializer.java
@@ -19,15 +19,15 @@ import org.eclipse.linuxtools.internal.cdt.libhover.devhelp.DevHelpPlugin;
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
- */
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = DevHelpPlugin.getDefault().getPreferenceStore();
- store.setDefault(PreferenceConstants.DEVHELP_DIRECTORY, "/usr/share/gtk-doc/html"); //$NON-NLS-1$
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
+ */
+ @Override
+ public void initializeDefaultPreferences() {
+ IPreferenceStore store = DevHelpPlugin.getDefault().getPreferenceStore();
+ store.setDefault(PreferenceConstants.DEVHELP_DIRECTORY, "/usr/share/gtk-doc/html"); //$NON-NLS-1$
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.glibc/data/glibc-2.14.xml b/libhover/org.eclipse.linuxtools.cdt.libhover.glibc/data/glibc-2.14.xml
index db124fb25f..ec144314f9 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.glibc/data/glibc-2.14.xml
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.glibc/data/glibc-2.14.xml
@@ -545,7 +545,7 @@ b. Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
-8.
+8.
You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
@@ -678,23 +678,23 @@ safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
``copyright'' line and a pointer to where the full notice is found.
- one line to give the library's name and an idea of what it does.
- Copyright (C) year name of author
+ one line to give the library's name and an idea of what it does.
+ Copyright (C) year name of author
- This library is free software; you can redistribute it and/or modify it
- under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation; either version 2.1 of the License, or (at
- your option) any later version.
+ This library is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation; either version 2.1 of the License, or (at
+ your option) any later version.
- This library is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Lesser General Public License for more details.
+ This library is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
- You should have received a copy of the GNU Lesser General Public
- License along with this library; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
- USA.
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
+ USA.
Also add information on how to contact you by electronic and paper mail.
@@ -702,11 +702,11 @@ You should also get your employer (if you work as a programmer) or your
school, if any, to sign a ``copyright disclaimer'' for the library, if
necessary. Here is a sample; alter the names:
- Yoyodyne, Inc., hereby disclaims all copyright interest in the library
- `Frob' (a library for tweaking knobs) written by James Random Hacker.
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the library
+ `Frob' (a library for tweaking knobs) written by James Random Hacker.
- signature of Ty Coon, 1 April 1990
- Ty Coon, President of Vice
+ signature of Ty Coon, 1 April 1990
+ Ty Coon, President of Vice
That's all there is to it!
@@ -1102,7 +1102,7 @@ to permit their use in free software.
========================================================================================
A transparent copy of this modified document can be found along-side the binary .libhover file
-in the org.eclipse.cdt.libhover.glibc plug-in jar under the data directory. The plug-in can be
+in the org.eclipse.cdt.libhover.glibc plug-in jar under the data directory. The plug-in can be
unzipped via "unzip". The original un-modified document can be generated from the sources which
can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
@@ -1417,7 +1417,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;ENAMETOOLONG&lt;/CODE&gt;
&lt;DD&gt;
The &lt;VAR&gt;size&lt;/VAR&gt; argument is less than the size of the host name plus one.
-
+
&lt;br&gt;&lt;br&gt; On some systems, there is a symbol for the maximum possible host name
length: &lt;CODE&gt;MAXHOSTNAMELEN&lt;/CODE&gt;. It is defined in &lt;TT&gt;sys/param.h&lt;/TT&gt;.
But you can't count on this to exist, so it is cleaner to handle
@@ -1455,7 +1455,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EPERM&lt;/CODE&gt;
&lt;DD&gt;
This process cannot set the host name because it is not privileged.
-
+
</synopsis>
</function>
</construct>
@@ -1549,7 +1549,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The operating system does not support setting the host ID. On some
systems, the host ID is a meaningless but unique number hard-coded for
each machine.
-
+
</synopsis>
</function>
</construct>
@@ -1596,14 +1596,14 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; Since the value in &lt;CODE&gt;machine&lt;/CODE&gt; is supposed to describe just the
hardware, it consists of the first two parts of the configuration name:
&lt;samp&gt;&lt;VAR&gt;cpu&lt;/VAR&gt;-&lt;VAR&gt;manufacturer&lt;/VAR&gt;&lt;/samp&gt;. For example, it might be one of these:
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;CODE&gt;"sparc-sun"&lt;/CODE&gt;,
&lt;CODE&gt;"i386-&lt;VAR&gt;anything&lt;/VAR&gt;"&lt;/CODE&gt;,
&lt;CODE&gt;"m68k-hp"&lt;/CODE&gt;,
&lt;CODE&gt;"m68k-sony"&lt;/CODE&gt;,
&lt;CODE&gt;"m68k-sun"&lt;/CODE&gt;,
&lt;CODE&gt;"mips-dec"&lt;/CODE&gt;
-
+
&lt;br&gt;&lt;br&gt;
</synopsis>
</element>
@@ -2209,7 +2209,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; MS_NODIRATIME
This bit on specifies that access times of directories shall not be updated
when the directories are accessed while the filesystem in mounted.
- &lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; Any bits not covered by the above masks should be set off; otherwise,
results are undefined.
&lt;br&gt;&lt;br&gt; The meaning of &lt;VAR&gt;data&lt;/VAR&gt; depends on the filesystem type and is controlled
@@ -2269,7 +2269,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The table of dummy devices is full. &lt;CODE&gt;mount&lt;/CODE&gt; needs to create a
dummy device (aka ``unnamed'' device) if the filesystem being mounted is
not one that uses a device.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -2298,7 +2298,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
busy, by making it unbusy first. If the bit is off and the filesystem is
busy, &lt;CODE&gt;umount2&lt;/CODE&gt; fails with &lt;CODE&gt;errno&lt;/CODE&gt; = &lt;CODE&gt;EBUSY&lt;/CODE&gt;. Depending
on the filesystem, this may override all, some, or no busy conditions.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; All other bits in &lt;VAR&gt;flags&lt;/VAR&gt; should be set to zero; otherwise, the result
is undefined.
&lt;br&gt;&lt;br&gt; Example:
@@ -2326,7 +2326,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
&lt;VAR&gt;file&lt;/VAR&gt; validly refers to a file, but that file is neither a mount
point nor a device special file of a currently mounted filesystem.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;/DL&gt;
&lt;br&gt;&lt;br&gt; This function is not available on all systems.
</synopsis>
@@ -2444,7 +2444,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
This value may be returned instead of the more correct &lt;CODE&gt;EINVAL&lt;/CODE&gt; in some
cases where the space provided for the return of the system parameter is too
small.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -2578,7 +2578,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The value of the &lt;VAR&gt;newuid&lt;/VAR&gt; argument is invalid.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EPERM
The process may not change to the specified ID.
-
+
&lt;br&gt;&lt;br&gt; Older systems (those without the &lt;CODE&gt;_POSIX_SAVED_IDS&lt;/CODE&gt; feature) do not
have this function.
</synopsis>
@@ -2633,7 +2633,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DD&gt;
The process does not have the appropriate privileges; you do not
have permission to change to the specified ID.
-
+
</synopsis>
</function>
</construct>
@@ -2725,7 +2725,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EPERM&lt;/CODE&gt;
&lt;DD&gt;
The calling process is not privileged.
-
+
</synopsis>
</function>
</construct>
@@ -3062,7 +3062,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DD&gt;
The process does not have the appropriate privileges; you cannot modify
the user accounting database.
-
+
</synopsis>
</function>
</construct>
@@ -3149,10 +3149,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; The following macros are defined for use as the &lt;VAR&gt;file&lt;/VAR&gt; argument:
&lt;br&gt;&lt;br&gt; Macro {char *} _PATH_UTMP
This macro is used to specify the user accounting database.
-
+
&lt;br&gt;&lt;br&gt; Macro {char *} _PATH_WTMP
This macro is used to specify the user accounting log file.
-
+
&lt;br&gt;&lt;br&gt; The &lt;CODE&gt;utmpname&lt;/CODE&gt; function returns a value of &lt;CODE&gt;0&lt;/CODE&gt; if the new name
was successfully stored, and a value of &lt;CODE&gt;-1&lt;/CODE&gt; to indicate an error.
Note that &lt;CODE&gt;utmpname&lt;/CODE&gt; does not try to open the database, and that
@@ -4095,7 +4095,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
Internet domain, only the super-user is allowed to specify a port number
in the range 0 through &lt;CODE&gt;IPPORT_RESERVED&lt;/CODE&gt; minus one; see
Ports.)
-
+
&lt;br&gt;&lt;br&gt; Additional conditions may be possible depending on the particular namespace
of the socket.
</synopsis>
@@ -4135,7 +4135,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The descriptor &lt;VAR&gt;socket&lt;/VAR&gt; is not a socket.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOBUFS
There are not enough internal buffers available for the operation.
-
+
</synopsis>
</function>
</construct>
@@ -5037,7 +5037,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;VAR&gt;style&lt;/VAR&gt; or &lt;VAR&gt;protocol&lt;/VAR&gt;.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOBUFS
The system ran out of internal buffer space.
-
+
&lt;br&gt;&lt;br&gt; The file descriptor returned by the &lt;CODE&gt;socket&lt;/CODE&gt; function supports both
read and write operations. However, like pipes, sockets do not support file
positioning operations.
@@ -5070,7 +5070,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
sent; don't retransmit it if it is lost.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; 2
Stop both reception and transmission.
-
+
&lt;br&gt;&lt;br&gt; The return value is &lt;CODE&gt;0&lt;/CODE&gt; on success and &lt;CODE&gt;-1&lt;/CODE&gt; on failure. The
following &lt;CODE&gt;errno&lt;/CODE&gt; error conditions are defined for this function:
&lt;br&gt;&lt;br&gt; &lt;DL&gt;
@@ -5081,7 +5081,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;VAR&gt;socket&lt;/VAR&gt; is not a socket.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOTCONN
&lt;VAR&gt;socket&lt;/VAR&gt; is not connected.
-
+
</synopsis>
</function>
</construct>
@@ -5125,7 +5125,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The specified protocol is not supported.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EOPNOTSUPP
The specified protocol does not support the creation of socket pairs.
-
+
</synopsis>
</function>
</construct>
@@ -5184,7 +5184,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EALREADY
The socket &lt;VAR&gt;socket&lt;/VAR&gt; is non-blocking and already has a pending
connection in progress (see &lt;CODE&gt;EINPROGRESS&lt;/CODE&gt; above).
-
+
&lt;br&gt;&lt;br&gt; This function is defined as a cancellation point in multi-threaded
programs, so one has to be prepared for this and make sure that
allocated resources (like memory, files descriptors, semaphores or
@@ -5220,7 +5220,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The argument &lt;VAR&gt;socket&lt;/VAR&gt; is not a socket.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EOPNOTSUPP
The socket &lt;VAR&gt;socket&lt;/VAR&gt; does not support this operation.
-
+
</synopsis>
</function>
</construct>
@@ -5268,7 +5268,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EWOULDBLOCK
&lt;VAR&gt;socket&lt;/VAR&gt; has nonblocking mode set, and there are no pending
connections immediately available.
-
+
&lt;br&gt;&lt;br&gt; This function is defined as a cancellation point in multi-threaded
programs, so one has to be prepared for this and make sure that
allocated resources (like memory, files descriptors, semaphores or
@@ -5307,7 +5307,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The socket &lt;VAR&gt;socket&lt;/VAR&gt; is not connected.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOBUFS
There are not enough internal buffers available.
-
+
</synopsis>
</function>
</construct>
@@ -5360,7 +5360,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
case, &lt;CODE&gt;send&lt;/CODE&gt; generates a &lt;CODE&gt;SIGPIPE&lt;/CODE&gt; signal first; if that
signal is ignored or blocked, or if its handler returns, then
&lt;CODE&gt;send&lt;/CODE&gt; fails with &lt;CODE&gt;EPIPE&lt;/CODE&gt;.
-
+
&lt;br&gt;&lt;br&gt; This function is defined as a cancellation point in multi-threaded
programs, so one has to be prepared for this and make sure that
allocated resources (like memory, files descriptors, semaphores or
@@ -5403,7 +5403,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOTCONN
You never connected this socket.
-
+
&lt;br&gt;&lt;br&gt; This function is defined as a cancellation point in multi-threaded
programs, so one has to be prepared for this and make sure that
allocated resources (like memory, files descriptors, semaphores or
@@ -5553,7 +5553,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The descriptor &lt;VAR&gt;socket&lt;/VAR&gt; is not a socket.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOPROTOOPT
The &lt;VAR&gt;optname&lt;/VAR&gt; doesn't make sense for the given &lt;VAR&gt;level&lt;/VAR&gt;.
-
+
</synopsis>
</function>
</construct>
@@ -5573,11 +5573,11 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
This function is used to set the socket option &lt;VAR&gt;optname&lt;/VAR&gt; at level
&lt;VAR&gt;level&lt;/VAR&gt; for socket &lt;VAR&gt;socket&lt;/VAR&gt;. The value of the option is passed
in the buffer &lt;VAR&gt;optval&lt;/VAR&gt; of size &lt;VAR&gt;optlen&lt;/VAR&gt;.
- &lt;br&gt;&lt;br&gt;
-
+ &lt;br&gt;&lt;br&gt;
+
The return value and error codes for &lt;CODE&gt;setsockopt&lt;/CODE&gt; are the same as
for &lt;CODE&gt;getsockopt&lt;/CODE&gt;.
-
+
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -5732,7 +5732,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<construct id="struct-timeval" type="struct">
<structure>
<synopsis>
-
+
The &lt;CODE&gt;struct timeval&lt;/CODE&gt; structure represents an elapsed time. It is
declared in &lt;TT&gt;sys/time.h&lt;/TT&gt; and has the following members:
&lt;br&gt;&lt;br&gt;
@@ -5750,7 +5750,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<construct id="struct-timespec" type="struct">
<structure>
<synopsis>
-
+
The &lt;CODE&gt;struct timespec&lt;/CODE&gt; structure represents an elapsed time. It is
declared in &lt;TT&gt;time.h&lt;/TT&gt; and has the following members:
&lt;br&gt;&lt;br&gt;
@@ -5885,7 +5885,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EPERM&lt;/CODE&gt;
&lt;DD&gt;
The process is not superuser.
-
+
</synopsis>
</function>
</construct>
@@ -5933,7 +5933,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
support using &lt;CODE&gt;struct timezone&lt;/CODE&gt; to represent time zone
information; that is an obsolete feature of 4.3 BSD.
Instead, use the facilities described in Time Zone Functions.
-
+
</synopsis>
</function>
</construct>
@@ -5976,7 +5976,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOSYS
The operating system does not support setting time zone information, and
&lt;VAR&gt;tzp&lt;/VAR&gt; is not a null pointer.
-
+
</synopsis>
</function>
</construct>
@@ -6012,7 +6012,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EPERM&lt;/CODE&gt;
&lt;DD&gt;
You do not have privilege to set the time.
-
+
</synopsis>
</function>
</construct>
@@ -6321,7 +6321,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The precision clock model is not properly set up at the moment, thus the
clock must be considered unsynchronized, and the values should be
treated with care.
-
+
</synopsis>
</function>
</construct>
@@ -6504,7 +6504,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
are not allowed.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EPERM
The process specified a settings update, but is not superuser.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; For more details see RFC1305 (Network Time Protocol, Version 3) and
related documents.
&lt;br&gt;&lt;br&gt; Portability note: Early versions of the GNU C library did not
@@ -6638,7 +6638,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ^
The output uses uppercase characters, but only if this is possible
.
-
+
&lt;br&gt;&lt;br&gt; The default action is to pad the number with zeros to keep it a constant
width. Numbers that do not have a range indicated below are never
padded, since there is no natural width for them.
@@ -6661,7 +6661,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; O
Use the locale's alternate numeric symbols for numbers. This modifier
applies only to numeric format specifiers.
-
+
&lt;br&gt;&lt;br&gt; If the format supports the modifier but no alternate representation
is available, it is ignored.
&lt;br&gt;&lt;br&gt; The conversion specifier ends with a format specifier taken from the
@@ -6744,7 +6744,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;samp&gt;PM&lt;/samp&gt; and midnight as &lt;samp&gt;AM&lt;/samp&gt;. In most locales
&lt;samp&gt;AM&lt;/samp&gt;/&lt;samp&gt;PM&lt;/samp&gt; format is not supported, in such cases &lt;CODE&gt;"%p"&lt;/CODE&gt;
yields an empty string.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;LI&gt; %P
Either &lt;samp&gt;am&lt;/samp&gt; or &lt;samp&gt;pm&lt;/samp&gt;, according to the given time value; or the
corresponding strings for the current locale, printed in lowercase
@@ -6823,7 +6823,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The time zone abbreviation (empty if the time zone can't be determined).
&lt;br&gt;&lt;br&gt; &lt;LI&gt; %%
A literal &lt;samp&gt;%&lt;/samp&gt; character.
-
+
&lt;br&gt;&lt;br&gt; The &lt;VAR&gt;size&lt;/VAR&gt; parameter can be used to specify the maximum number of
characters to be stored in the array &lt;VAR&gt;s&lt;/VAR&gt;, including the terminating
null character. If the formatted time requires more than &lt;VAR&gt;size&lt;/VAR&gt;
@@ -7103,7 +7103,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
recognized, input is consumed but no field in &lt;VAR&gt;tm&lt;/VAR&gt; is set.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; %%
A literal &lt;samp&gt;%&lt;/samp&gt; character.
-
+
&lt;br&gt;&lt;br&gt; All other characters in the format string must have a matching character
in the input string. Exceptions are white spaces in the input string
which can match zero or more whitespace characters in the format string.
@@ -7313,7 +7313,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EINVAL&lt;/CODE&gt;
&lt;DD&gt;
The timer period is too large.
-
+
</synopsis>
</function>
</construct>
@@ -7407,7 +7407,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The nanosecond value in the &lt;VAR&gt;requested_time&lt;/VAR&gt; parameter contains an
illegal value. Either the value is negative or greater than or equal to
1000 million.
-
+
&lt;br&gt;&lt;br&gt; This function is a cancellation point in multi-threaded programs. This
is a problem if the thread allocates some resources (like memory, file
descriptors, semaphores or whatever) at the time &lt;CODE&gt;nanosleep&lt;/CODE&gt; is
@@ -7518,7 +7518,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOMEM
The process requires more space than the system can supply.
-
+
</synopsis>
</function>
</construct>
@@ -7732,7 +7732,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
is not a child of the calling process.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
An invalid value was provided for the &lt;VAR&gt;options&lt;/VAR&gt; argument.
-
+
</synopsis>
</function>
</construct>
@@ -7868,7 +7868,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
name. You need to allocate a bigger array and try again.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EACCES
Permission to read or search a component of the file name was denied.
-
+
</synopsis>
</function>
</construct>
@@ -7881,7 +7881,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<header filename = "unistd.h"/>
</headers>
<synopsis>
-
+
This &lt;CODE&gt;get_current_dir_name&lt;/CODE&gt; function is basically equivalent to
&lt;CODE&gt;getcwd (NULL, 0)&lt;/CODE&gt;. The only difference is that the value of
the &lt;CODE&gt;PWD&lt;/CODE&gt; variable is returned if this value is correct. This is a
@@ -7939,7 +7939,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The function call was interrupt by a signal.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EIO
An I/O error occurred.
-
+
</synopsis>
</function>
</construct>
@@ -8009,7 +8009,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
</element>
<element content="DT_SOCK">
<synopsis>
- A local-domain socket.
+ A local-domain socket.
&lt;br&gt;&lt;br&gt;
</synopsis>
</element>
@@ -8054,7 +8054,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
(This problem cannot happen on the GNU system.)
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOMEM
Not enough memory available.
-
+
&lt;br&gt;&lt;br&gt; The &lt;CODE&gt;DIR&lt;/CODE&gt; type is typically implemented using a file descriptor,
and the &lt;CODE&gt;opendir&lt;/CODE&gt; function in terms of the &lt;CODE&gt;open&lt;/CODE&gt; function.
. Directory streams and the underlying
@@ -8096,7 +8096,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The descriptor does not allow reading the directory content.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOMEM
Not enough memory available.
-
+
</synopsis>
</function>
</construct>
@@ -8141,7 +8141,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EBADF&lt;/CODE&gt;
&lt;DD&gt;
The &lt;VAR&gt;dirstream&lt;/VAR&gt; argument is not valid.
-
+
&lt;br&gt;&lt;br&gt; &lt;CODE&gt;readdir&lt;/CODE&gt; is not thread safe. Multiple threads using
&lt;CODE&gt;readdir&lt;/CODE&gt; on the same &lt;VAR&gt;dirstream&lt;/VAR&gt; may overwrite the return
value. Use &lt;CODE&gt;readdir_r&lt;/CODE&gt; when this is critical.
@@ -8250,7 +8250,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EBADF&lt;/CODE&gt;
&lt;DD&gt;
The &lt;VAR&gt;dirstream&lt;/VAR&gt; argument is not valid.
-
+
</synopsis>
</function>
</construct>
@@ -8427,7 +8427,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
first parameter points to the file name, the second parameter to an
object of type &lt;CODE&gt;struct stat&lt;/CODE&gt; which is filled in for the file named
in the first parameter.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
The last parameter is a flag giving more information about the current
file. It can have the following values:
&lt;br&gt;&lt;br&gt; &lt;DL&gt;
@@ -8469,8 +8469,8 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
int (*) (const char *, const struct stat *, int, struct FTW *)&lt;br&gt;
&lt;/pre&gt;
- &lt;br&gt;&lt;br&gt;
-
+ &lt;br&gt;&lt;br&gt;
+
The first three arguments are the same as for the &lt;CODE&gt;__ftw_func_t&lt;/CODE&gt;
type. However for the third argument some additional values are defined
to allow finer differentiation:
@@ -8702,7 +8702,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DD&gt;
You are not allowed to write to the directory in which the new link is
to be written.
-
+
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EEXIST
There is already a file named &lt;VAR&gt;newname&lt;/VAR&gt;. If you want to replace
this link with a new link, you must remove the old link explicitly first.
@@ -8728,7 +8728,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
than the existing file.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EIO
A hardware error occurred while trying to read or write the to filesystem.
-
+
</synopsis>
</function>
</construct>
@@ -8760,8 +8760,8 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The directory or file system cannot be extended to make the new link.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EIO
A hardware error occurred while reading or writing data on the disk.
- &lt;br&gt;&lt;br&gt;
-
+ &lt;br&gt;&lt;br&gt;
+
</synopsis>
</function>
</construct>
@@ -8816,7 +8816,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The named file is not a symbolic link.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EIO
A hardware error occurred while reading or writing data on the disk.
-
+
</synopsis>
</function>
</construct>
@@ -8853,7 +8853,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
At least one of the path components does not exist.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ELOOP
More than &lt;CODE&gt;MAXSYMLINKS&lt;/CODE&gt; many symlinks have been followed.
-
+
&lt;br&gt;&lt;br&gt; This function is a GNU extension and is declared in &lt;TT&gt;stdlib.h&lt;/TT&gt;.
</synopsis>
</function>
@@ -8925,7 +8925,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EROFS
The directory containing the file name to be deleted is on a read-only
file system and can't be modified.
-
+
</synopsis>
</function>
</construct>
@@ -8952,7 +8952,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DD&gt;
&lt;LI&gt;x EEXIST
The directory to be deleted is not empty.
-
+
&lt;br&gt;&lt;br&gt; These two error codes are synonymous; some systems use one, and some use
the other. The GNU system always uses &lt;CODE&gt;ENOTEMPTY&lt;/CODE&gt;.
&lt;br&gt;&lt;br&gt; The prototype for this function is declared in the header file
@@ -9050,7 +9050,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EXDEV
The two file names &lt;VAR&gt;newname&lt;/VAR&gt; and &lt;VAR&gt;oldname&lt;/VAR&gt; are on different
file systems.
-
+
</synopsis>
</function>
</construct>
@@ -9092,7 +9092,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EROFS
The parent directory of the directory being created is on a read-only
file system and cannot be modified.
-
+
&lt;br&gt;&lt;br&gt; To use this function, your program should include the header file
&lt;TT&gt;sys/stat.h&lt;/TT&gt;.
</synopsis>
@@ -9198,7 +9198,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
This is the fractional part of the time of the last modification to the
attributes of the file. .
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
</synopsis>
</element>
<element content="blkcnt_t st_blocks">
@@ -9326,7 +9326,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
This is the fractional part of the time of the last modification to the
attributes of the file. .
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
</synopsis>
</element>
<element content="blkcnt64_t st_blocks">
@@ -9393,7 +9393,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;ENOENT&lt;/CODE&gt;
&lt;DD&gt;
The file named by &lt;VAR&gt;filename&lt;/VAR&gt; doesn't exist.
-
+
&lt;br&gt;&lt;br&gt; When the sources are compiled with &lt;CODE&gt;_FILE_OFFSET_BITS == 64&lt;/CODE&gt; this
function is in fact &lt;CODE&gt;stat64&lt;/CODE&gt; since the LFS interface transparently
replaces the normal implementation.
@@ -9441,7 +9441,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EBADF&lt;/CODE&gt;
&lt;DD&gt;
The &lt;VAR&gt;filedes&lt;/VAR&gt; argument is not a valid file descriptor.
-
+
&lt;br&gt;&lt;br&gt; When the sources are compiled with &lt;CODE&gt;_FILE_OFFSET_BITS == 64&lt;/CODE&gt; this
function is in fact &lt;CODE&gt;fstat64&lt;/CODE&gt; since the LFS interface transparently
replaces the normal implementation.
@@ -9544,7 +9544,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;CODE&gt;_POSIX_CHOWN_RESTRICTED&lt;/CODE&gt; macro.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EROFS
The file is on a read-only file system.
-
+
</synopsis>
</function>
</construct>
@@ -9577,7 +9577,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
see &lt;CODE&gt;chmod&lt;/CODE&gt; above.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EROFS
The file resides on a read-only file system.
-
+
</synopsis>
</function>
</construct>
@@ -9604,7 +9604,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
return mask;&lt;br&gt;
}&lt;br&gt;
&lt;/pre&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
However, it is better to use &lt;CODE&gt;getumask&lt;/CODE&gt; if you just want to read
the mask value, because it is reentrant (at least if you use the GNU
operating system).
@@ -9663,7 +9663,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
meaning for non-directory files, so it is always safe to just clear the
bit in &lt;VAR&gt;mode&lt;/VAR&gt; and call &lt;CODE&gt;chmod&lt;/CODE&gt; again. ,
for full details on the sticky bit.
-
+
</synopsis>
</function>
</construct>
@@ -9696,7 +9696,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
of the process) or a privileged user can change them.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EROFS
The file resides on a read-only file system.
-
+
</synopsis>
</function>
</construct>
@@ -9734,7 +9734,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The file doesn't exist.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EROFS
Write permission was requested for a file on a read-only file system.
-
+
</synopsis>
</function>
</construct>
@@ -9795,7 +9795,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
the owner of the file or be a privileged user.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EROFS
The file lives on a read-only file system.
-
+
</synopsis>
</function>
</construct>
@@ -9874,7 +9874,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
the owner of the file or be a privileged user.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EROFS
The file lives on a read-only file system.
-
+
</synopsis>
</function>
</construct>
@@ -9915,7 +9915,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The file is "append-only" or "immutable".
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINTR
The operation was interrupted by a signal.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -9989,7 +9989,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The file is "append-only" or "immutable".
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINTR
The operation was interrupted by a signal.
- &lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -10049,7 +10049,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EEXIST
There is already a file named &lt;VAR&gt;filename&lt;/VAR&gt;. If you want to replace
this file, you must remove the old file explicitly first.
-
+
</synopsis>
</function>
</construct>
@@ -10322,14 +10322,14 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;SIG_DFL&lt;/CODE&gt;
&lt;DD&gt;
-
+
action for a signal
&lt;CODE&gt;SIG_DFL&lt;/CODE&gt; specifies the default action for the particular signal.
The default actions for various kinds of signals are stated in
Standard Signals.
&lt;br&gt;&lt;br&gt; &lt;DT&gt;&lt;CODE&gt;SIG_IGN&lt;/CODE&gt;
&lt;DD&gt;
-
+
action for a signal
&lt;CODE&gt;SIG_IGN&lt;/CODE&gt; specifies that the signal should be ignored.
&lt;br&gt;&lt;br&gt; Your program generally should not ignore signals that represent serious
@@ -10347,7 +10347,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
running this handler as the way to deliver the signal.
&lt;br&gt;&lt;br&gt; For more information about defining signal handler functions,
see Defining Handlers.
-
+
&lt;br&gt;&lt;br&gt; If you set the action for a signal to &lt;CODE&gt;SIG_IGN&lt;/CODE&gt;, or if you set it
to &lt;CODE&gt;SIG_DFL&lt;/CODE&gt; and the default action is to ignore that signal, then
any pending signals of that type are discarded (even if they are
@@ -10365,7 +10365,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;LI&gt; EINVAL
You specified an invalid &lt;VAR&gt;signum&lt;/VAR&gt;; or you tried to ignore or provide
a handler for &lt;CODE&gt;SIGKILL&lt;/CODE&gt; or &lt;CODE&gt;SIGSTOP&lt;/CODE&gt;.
-
+
</synopsis>
</function>
</construct>
@@ -10468,7 +10468,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DD&gt;
The &lt;VAR&gt;signum&lt;/VAR&gt; argument is not valid, or you are trying to
trap or ignore &lt;CODE&gt;SIGKILL&lt;/CODE&gt; or &lt;CODE&gt;SIGSTOP&lt;/CODE&gt;.
-
+
</synopsis>
</function>
</construct>
@@ -10537,7 +10537,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
If the process is privileged, send the signal to all processes except
for some special system processes. Otherwise, send the signal to all
processes with the same effective user ID.
-
+
&lt;br&gt;&lt;br&gt; A process can send a signal to itself with a call like &lt;CODE&gt;kill
(getpid(), &lt;VAR&gt;signum&lt;/VAR&gt;)&lt;/CODE&gt;. If &lt;CODE&gt;kill&lt;/CODE&gt; is used by a process to send
a signal to itself, and the signal is not blocked, then &lt;CODE&gt;kill&lt;/CODE&gt;
@@ -10560,7 +10560,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
the processes in the process group named by &lt;VAR&gt;pid&lt;/VAR&gt;.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ESRCH
The &lt;VAR&gt;pid&lt;/VAR&gt; argument does not refer to an existing process or group.
-
+
</synopsis>
</function>
</construct>
@@ -10632,7 +10632,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EINVAL&lt;/CODE&gt;
&lt;DD&gt;
The &lt;VAR&gt;signum&lt;/VAR&gt; argument doesn't specify a valid signal.
-
+
</synopsis>
</function>
</construct>
@@ -10672,7 +10672,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EINVAL&lt;/CODE&gt;
&lt;DD&gt;
The &lt;VAR&gt;signum&lt;/VAR&gt; argument doesn't specify a valid signal.
-
+
</synopsis>
</function>
</construct>
@@ -10692,20 +10692,20 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
mask is changed, and must be one of the following values:
&lt;br&gt;&lt;br&gt; &lt;DL&gt;
-
+
&lt;DT&gt;&lt;CODE&gt;SIG_BLOCK&lt;/CODE&gt;
&lt;DD&gt;
Block the signals in &lt;CODE&gt;set&lt;/CODE&gt;---add them to the existing mask. In
other words, the new mask is the union of the existing mask and
&lt;VAR&gt;set&lt;/VAR&gt;.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;DT&gt;&lt;CODE&gt;SIG_UNBLOCK&lt;/CODE&gt;
&lt;DD&gt;
Unblock the signals in &lt;VAR&gt;set&lt;/VAR&gt;---remove them from the existing mask.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;LI&gt; SIG_SETMASK
Use &lt;VAR&gt;set&lt;/VAR&gt; for the mask; ignore the previous value of the mask.
-
+
&lt;br&gt;&lt;br&gt; The last argument, &lt;VAR&gt;oldset&lt;/VAR&gt;, is used to return information about the
old process signal mask. If you just want to change the mask without
looking at it, pass a null pointer as the &lt;VAR&gt;oldset&lt;/VAR&gt; argument.
@@ -10728,7 +10728,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;LI&gt; EINVAL
The &lt;VAR&gt;how&lt;/VAR&gt; argument is invalid.
-
+
&lt;br&gt;&lt;br&gt; You can't block the &lt;CODE&gt;SIGKILL&lt;/CODE&gt; and &lt;CODE&gt;SIGSTOP&lt;/CODE&gt; signals, but
if the signal set includes these, &lt;CODE&gt;sigprocmask&lt;/CODE&gt; just ignores
them instead of returning an error status.
@@ -10783,7 +10783,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EINTR&lt;/CODE&gt;
&lt;DD&gt;
The function was interrupted by delivery of a signal.
-
+
&lt;br&gt;&lt;br&gt; If the signal causes program termination, &lt;CODE&gt;pause&lt;/CODE&gt; doesn't return
(obviously).
&lt;br&gt;&lt;br&gt; This function is a cancellation point in multithreaded programs. This
@@ -10909,7 +10909,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOMEM
The size of the alternate stack was too small.
It must be greater than &lt;CODE&gt;MINSIGSTKSZ&lt;/CODE&gt;.
-
+
</synopsis>
</function>
</construct>
@@ -11085,7 +11085,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
There are too many open files in the entire system. ,
for more information about &lt;CODE&gt;ENFILE&lt;/CODE&gt;. This error never occurs in
the GNU system.
-
+
</synopsis>
</function>
</construct>
@@ -11159,7 +11159,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EROFS
The directory that would contain the file resides on a read-only file
system.
-
+
</synopsis>
</function>
</construct>
@@ -11327,7 +11327,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;pre&gt;&lt;br&gt;
error (0, errno, format, the parameters)&lt;br&gt;
&lt;/pre&gt;
-
+
except that the global variables &lt;CODE&gt;error&lt;/CODE&gt; respects and modifies
are not used.
</synopsis>
@@ -11363,7 +11363,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;pre&gt;&lt;br&gt;
error (0, 0, format, the parameters)&lt;br&gt;
&lt;/pre&gt;
-
+
except that the global variables &lt;CODE&gt;error&lt;/CODE&gt; respects and modifies
are not used. The difference to &lt;CODE&gt;warn&lt;/CODE&gt; is that no error number
string is printed.
@@ -11401,7 +11401,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;pre&gt;&lt;br&gt;
error (status, errno, format, the parameters)&lt;br&gt;
&lt;/pre&gt;
-
+
except that the global variables &lt;CODE&gt;error&lt;/CODE&gt; respects and modifies
are not used and that the program is exited even if &lt;VAR&gt;status&lt;/VAR&gt; is zero.
</synopsis>
@@ -11439,7 +11439,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;pre&gt;&lt;br&gt;
error (status, 0, format, the parameters)&lt;br&gt;
&lt;/pre&gt;
-
+
except that the global variables &lt;CODE&gt;error&lt;/CODE&gt; respects and modifies
are not used and that the program is exited even if &lt;VAR&gt;status&lt;/VAR&gt;
is zero. The difference to &lt;CODE&gt;err&lt;/CODE&gt; is that no error number
@@ -11693,10 +11693,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
There was an error opening a directory, and you used the flag
&lt;CODE&gt;GLOB_ERR&lt;/CODE&gt; or your specified &lt;VAR&gt;errfunc&lt;/VAR&gt; returned a nonzero
value.
-
-
+
+
,
-
+
for an explanation of the &lt;CODE&gt;GLOB_ERR&lt;/CODE&gt; flag and &lt;VAR&gt;errfunc&lt;/VAR&gt;.
&lt;br&gt;&lt;br&gt; &lt;DT&gt;&lt;CODE&gt;GLOB_NOMATCH&lt;/CODE&gt;
&lt;DD&gt;
@@ -12009,7 +12009,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; WRDE_SYNTAX
There was a syntax error in the input string. For example, an unmatched
quoting character is a syntax error.
-
+
</synopsis>
</function>
</construct>
@@ -12158,7 +12158,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DD&gt;
The calling process is already a process group leader, or there is
already another process group around that has the same process group ID.
-
+
</synopsis>
</function>
</construct>
@@ -12187,7 +12187,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
different sessions, and the implementation doesn't allow to access the
process group ID of the session leader of the process with ID &lt;VAR&gt;pid&lt;/VAR&gt;
from the calling process.
-
+
</synopsis>
</function>
</construct>
@@ -12227,7 +12227,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ESRCH
The process indicated by the &lt;VAR&gt;pid&lt;/VAR&gt; argument is not the calling
process or a child of the calling process.
-
+
</synopsis>
</function>
</construct>
@@ -12274,7 +12274,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOTTY
The terminal file associated with the &lt;VAR&gt;filedes&lt;/VAR&gt; argument isn't the
controlling terminal of the calling process.
-
+
</synopsis>
</function>
</construct>
@@ -12316,7 +12316,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EPERM
The &lt;VAR&gt;pgid&lt;/VAR&gt; isn't a process group in the same session as the calling
process.
-
+
</synopsis>
</function>
</construct>
@@ -12342,7 +12342,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOTTY
The calling process does not have a controlling terminal, or the file
is not the controlling terminal.
-
+
</synopsis>
</function>
</construct>
@@ -12479,7 +12479,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
horizontal tab
&lt;br&gt;&lt;br&gt; &lt;LI&gt; '\v'
vertical tab
-
+
</synopsis>
</function>
</construct>
@@ -12645,7 +12645,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
some standard properties each locale can define its own ones. In case
no property with the given name is known for the current locale
selected for the &lt;CODE&gt;LC_CTYPE&lt;/CODE&gt; category, the function returns zero.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
The properties known in every locale are:
&lt;br&gt;&lt;br&gt; &lt;DT&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;DD&gt;&lt;br&gt;
@@ -12683,7 +12683,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
character (a letter or number); in other words, if either &lt;CODE&gt;iswalpha&lt;/CODE&gt;
or &lt;CODE&gt;iswdigit&lt;/CODE&gt; is true of a character, then &lt;CODE&gt;iswalnum&lt;/CODE&gt; is also
true.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
iswctype (wc, wctype ("alnum"))&lt;br&gt;
@@ -12708,7 +12708,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;CODE&gt;iswalpha&lt;/CODE&gt; is true---letters which are neither upper case nor lower
case. But in the standard &lt;CODE&gt;"C"&lt;/CODE&gt; locale, there are no such
additional characters.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
iswctype (wc, wctype ("alpha"))&lt;br&gt;
@@ -12728,7 +12728,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
Returns true if &lt;VAR&gt;wc&lt;/VAR&gt; is a control character (that is, a character that
is not a printing character).
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
iswctype (wc, wctype ("cntrl"))&lt;br&gt;
@@ -12780,7 +12780,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
Returns true if &lt;VAR&gt;wc&lt;/VAR&gt; is a graphic character; that is, a character
that has a glyph associated with it. The whitespace characters are not
considered graphic.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
iswctype (wc, wctype ("graph"))&lt;br&gt;
@@ -12800,7 +12800,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
Returns true if &lt;VAR&gt;wc&lt;/VAR&gt; is a lower-case letter. The letter need not be
from the Latin alphabet, any alphabet representable is valid.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
iswctype (wc, wctype ("lower"))&lt;br&gt;
@@ -12820,7 +12820,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
Returns true if &lt;VAR&gt;wc&lt;/VAR&gt; is a printing character. Printing characters
include all the graphic characters, plus the space (&lt;samp&gt; &lt;/samp&gt;) character.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
iswctype (wc, wctype ("print"))&lt;br&gt;
@@ -12841,7 +12841,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
Returns true if &lt;VAR&gt;wc&lt;/VAR&gt; is a punctuation character.
This means any printing character that is not alphanumeric or a space
character.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
iswctype (wc, wctype ("punct"))&lt;br&gt;
@@ -12877,8 +12877,8 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
horizontal tab
&lt;br&gt;&lt;br&gt; &lt;LI&gt; L'\v'
vertical tab
-
- &lt;br&gt;&lt;br&gt;
+
+ &lt;br&gt;&lt;br&gt;
This function can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
iswctype (wc, wctype ("space"))&lt;br&gt;
@@ -12898,7 +12898,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
Returns true if &lt;VAR&gt;wc&lt;/VAR&gt; is an upper-case letter. The letter need not be
from the Latin alphabet, any alphabet representable is valid.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
iswctype (wc, wctype ("upper"))&lt;br&gt;
@@ -12920,7 +12920,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
Hexadecimal digits include the normal decimal digits &lt;samp&gt;0&lt;/samp&gt; through
&lt;samp&gt;9&lt;/samp&gt; and the letters &lt;samp&gt;A&lt;/samp&gt; through &lt;samp&gt;F&lt;/samp&gt; and
&lt;samp&gt;a&lt;/samp&gt; through &lt;samp&gt;f&lt;/samp&gt;.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
iswctype (wc, wctype ("xdigit"))&lt;br&gt;
@@ -12966,7 +12966,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
guaranteed to be available in every locale:
&lt;br&gt;&lt;br&gt; &lt;DT&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;DD&gt;&lt;br&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
These functions are declared in &lt;TT&gt;wctype.h&lt;/TT&gt;.
</synopsis>
</function>
@@ -12985,7 +12985,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
according to the rules of the mapping for which &lt;VAR&gt;desc&lt;/VAR&gt; is a
descriptor, and returns the value it finds. &lt;VAR&gt;desc&lt;/VAR&gt; must be
obtained by a successful call to &lt;CODE&gt;wctrans&lt;/CODE&gt;.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function is declared in &lt;TT&gt;wctype.h&lt;/TT&gt;.
</synopsis>
</function>
@@ -13002,12 +13002,12 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
If &lt;VAR&gt;wc&lt;/VAR&gt; is an upper-case letter, &lt;CODE&gt;towlower&lt;/CODE&gt; returns the corresponding
lower-case letter. If &lt;VAR&gt;wc&lt;/VAR&gt; is not an upper-case letter,
&lt;VAR&gt;wc&lt;/VAR&gt; is returned unchanged.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;CODE&gt;towlower&lt;/CODE&gt; can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
towctrans (wc, wctrans ("tolower"))&lt;br&gt;
&lt;/pre&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function is declared in &lt;TT&gt;wctype.h&lt;/TT&gt;.
</synopsis>
</function>
@@ -13023,12 +13023,12 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
If &lt;VAR&gt;wc&lt;/VAR&gt; is a lower-case letter, &lt;CODE&gt;towupper&lt;/CODE&gt; returns the corresponding
upper-case letter. Otherwise &lt;VAR&gt;wc&lt;/VAR&gt; is returned unchanged.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;CODE&gt;towupper&lt;/CODE&gt; can be implemented using
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
towctrans (wc, wctrans ("toupper"))&lt;br&gt;
&lt;/pre&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
This function is declared in &lt;TT&gt;wctype.h&lt;/TT&gt;.
</synopsis>
</function>
@@ -13154,7 +13154,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
}&lt;br&gt;
}&lt;br&gt;
&lt;/pre&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
When an error occurred the global variable &lt;VAR&gt;errno&lt;/VAR&gt; is set to
&lt;br&gt;&lt;br&gt; &lt;DL&gt;
@@ -13163,7 +13163,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;LI&gt; ENOMSG
The set/message tuple does not name an existing element in the
message catalog.
-
+
&lt;br&gt;&lt;br&gt; While it sometimes can be useful to test for errors programs normally
will avoid any test. If the translation is not available it is no big
problem if the original, untranslated message is printed. Either the
@@ -13723,7 +13723,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The file resides on a read-only file system and any of &lt;CODE&gt;O_WRONLY&lt;/CODE&gt;,
&lt;CODE&gt;O_RDWR&lt;/CODE&gt;, and &lt;CODE&gt;O_TRUNC&lt;/CODE&gt; are set in the &lt;VAR&gt;flags&lt;/VAR&gt; argument,
or &lt;CODE&gt;O_CREAT&lt;/CODE&gt; is set and the file does not already exist.
-
+
&lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt; If on a 32 bit machine the sources are translated with
&lt;CODE&gt;_FILE_OFFSET_BITS == 64&lt;/CODE&gt; the function &lt;CODE&gt;open&lt;/CODE&gt; returns a file
descriptor opened in the large file mode which enables the file handling
@@ -13810,7 +13810,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
When the file is accessed by NFS, these errors from &lt;CODE&gt;write&lt;/CODE&gt; can sometimes
not be detected until &lt;CODE&gt;close&lt;/CODE&gt;. , for details
on their meaning.
-
+
&lt;br&gt;&lt;br&gt; Please note that there is &lt;EM&gt;no&lt;/EM&gt; separate &lt;CODE&gt;close64&lt;/CODE&gt; function.
This is not necessary since this function does not determine nor depend
on the mode of the file. The kernel which performs the &lt;CODE&gt;close&lt;/CODE&gt;
@@ -13896,7 +13896,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
In some systems, when reading from a character or block device, position
and size offsets must be aligned to a particular block size. This error
indicates that the offsets were not properly aligned.
-
+
&lt;br&gt;&lt;br&gt; Please note that there is no function named &lt;CODE&gt;read64&lt;/CODE&gt;. This is not
necessary since this function does not directly modify or handle the
possibly wide file offset. Since the kernel handles this state
@@ -13947,7 +13947,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ESPIPE
The file descriptor &lt;VAR&gt;filedes&lt;/VAR&gt; is associate with a pipe or a FIFO and
this device does not allow positioning of the file pointer.
-
+
&lt;br&gt;&lt;br&gt; The function is an extension defined in the Unix Single Specification
version 2.
</synopsis>
@@ -14054,7 +14054,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
In some systems, when writing to a character or block device, position
and size offsets must be aligned to a particular block size. This error
indicates that the offsets were not properly aligned.
-
+
&lt;br&gt;&lt;br&gt; Unless you have arranged to prevent &lt;CODE&gt;EINTR&lt;/CODE&gt; failures, you should
check &lt;CODE&gt;errno&lt;/CODE&gt; after each failing call to &lt;CODE&gt;write&lt;/CODE&gt;, and if the
error was &lt;CODE&gt;EINTR&lt;/CODE&gt;, you should simply repeat the call.
@@ -14113,7 +14113,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ESPIPE
The file descriptor &lt;VAR&gt;filedes&lt;/VAR&gt; is associated with a pipe or a FIFO and
this device does not allow positioning of the file pointer.
-
+
&lt;br&gt;&lt;br&gt; The function is an extension defined in the Unix Single Specification
version 2.
</synopsis>
@@ -14178,7 +14178,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
current end. If you set the position past the current end, and
actually write data, you will extend the file with zeros up to that
position.
-
+
&lt;br&gt;&lt;br&gt; The return value from &lt;CODE&gt;lseek&lt;/CODE&gt; is normally the resulting file
position, measured in bytes from the beginning of the file.
You can use this feature together with &lt;CODE&gt;SEEK_CUR&lt;/CODE&gt; to read the
@@ -14213,7 +14213,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
such as a pipe, FIFO or terminal device. (POSIX.1 specifies this error
only for pipes and FIFOs, but in the GNU system, you always get
&lt;CODE&gt;ESPIPE&lt;/CODE&gt; if the object is not seekable.)
-
+
&lt;br&gt;&lt;br&gt; When the source file is compiled with &lt;CODE&gt;_FILE_OFFSET_BITS == 64&lt;/CODE&gt; the
&lt;CODE&gt;lseek&lt;/CODE&gt; function is in fact &lt;CODE&gt;lseek64&lt;/CODE&gt; and the type
&lt;CODE&gt;off_t&lt;/CODE&gt; has 64 bits which makes it possible to handle files up to
@@ -14427,9 +14427,9 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;CODE&gt;NULL&lt;/CODE&gt; expresses no preference. Any previous mapping at that
address is automatically removed. The address you give may still be
changed, unless you use the &lt;CODE&gt;MAP_FIXED&lt;/CODE&gt; flag.
- &lt;br&gt;&lt;br&gt;
-
-
+ &lt;br&gt;&lt;br&gt;
+
+
&lt;VAR&gt;protect&lt;/VAR&gt; contains flags that control what kind of access is
permitted. They include &lt;CODE&gt;PROT_READ&lt;/CODE&gt;, &lt;CODE&gt;PROT_WRITE&lt;/CODE&gt;, and
&lt;CODE&gt;PROT_EXEC&lt;/CODE&gt;, which permit reading, writing, and execution,
@@ -14495,8 +14495,8 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; This file is of a type that doesn't support mapping.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOEXEC
&lt;br&gt;&lt;br&gt; The file is on a filesystem that doesn't support mapping.
- &lt;br&gt;&lt;br&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -14551,7 +14551,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DD&gt;
The memory range given was outside the user mmap range or wasn't page
aligned.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -14596,7 +14596,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
An invalid region was given, or the &lt;VAR&gt;flags&lt;/VAR&gt; were invalid.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EFAULT
There is no existing mapping in at least part of the given region.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -14638,7 +14638,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
available to extend it. Also, this error will occur if
&lt;CODE&gt;MREMAP_MAYMOVE&lt;/CODE&gt; is not given and the extension would collide with
another mapped region.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
</synopsis>
</function>
</construct>
@@ -14678,7 +14678,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The region is no longer needed. The kernel may free these pages,
causing any changes to the pages to be lost, as well as swapped
out pages to be discarded.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; The POSIX names are slightly different, but with the same meanings:
&lt;br&gt;&lt;br&gt; &lt;DL&gt;
@@ -14692,7 +14692,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
This corresponds with BSD's &lt;CODE&gt;MADV_WILLNEED&lt;/CODE&gt;.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; POSIX_MADV_DONTNEED
This corresponds with BSD's &lt;CODE&gt;MADV_DONTNEED&lt;/CODE&gt;.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; &lt;CODE&gt;msync&lt;/CODE&gt; returns 0 for success and -1 for
error. Errors include:
&lt;DL&gt;
@@ -14701,7 +14701,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
An invalid region was given, or the &lt;VAR&gt;advice&lt;/VAR&gt; was invalid.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EFAULT
There is no existing mapping in at least part of the given region.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
</synopsis>
</function>
</construct>
@@ -14779,7 +14779,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
The &lt;VAR&gt;timeout&lt;/VAR&gt; argument is invalid; one of the components is negative
or too large.
-
+
</synopsis>
</function>
</construct>
@@ -14831,7 +14831,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The descriptor &lt;VAR&gt;fildes&lt;/VAR&gt; is not valid.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
No synchronization is possible since the system does not implement this.
-
+
</synopsis>
</function>
</construct>
@@ -14862,7 +14862,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The descriptor &lt;VAR&gt;fildes&lt;/VAR&gt; is not valid.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
No synchronization is possible since the system does not implement this.
-
+
</synopsis>
</function>
</construct>
@@ -15065,7 +15065,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The &lt;CODE&gt;aiocbp-&gt;aio_offset&lt;/CODE&gt; or &lt;CODE&gt;aiocbp-&gt;aio_reqpiro&lt;/CODE&gt; value is
invalid. This condition need not be recognized before enqueueing the
request and so this error might also be signaled asynchronously.
-
+
&lt;br&gt;&lt;br&gt; If &lt;CODE&gt;aio_read&lt;/CODE&gt; returns zero, the current status of the request
can be queried using &lt;CODE&gt;aio_error&lt;/CODE&gt; and &lt;CODE&gt;aio_return&lt;/CODE&gt; functions.
As long as the value returned by &lt;CODE&gt;aio_error&lt;/CODE&gt; is &lt;CODE&gt;EINPROGRESS&lt;/CODE&gt;
@@ -15081,10 +15081,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The &lt;CODE&gt;aiocbp-&gt;aio_fildes&lt;/CODE&gt; descriptor is not valid.
&lt;LI&gt; ECANCELED
The operation was canceled before the operation was finished
-
+
&lt;LI&gt; EINVAL
The &lt;CODE&gt;aiocbp-&gt;aio_offset&lt;/CODE&gt; value is invalid.
-
+
&lt;br&gt;&lt;br&gt; When the sources are compiled with &lt;CODE&gt;_FILE_OFFSET_BITS == 64&lt;/CODE&gt; this
function is in fact &lt;CODE&gt;aio_read64&lt;/CODE&gt; since the LFS interface transparently
replaces the normal implementation.
@@ -15153,7 +15153,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The &lt;CODE&gt;aiocbp-&gt;aio_offset&lt;/CODE&gt; or &lt;CODE&gt;aiocbp-&gt;aio_reqprio&lt;/CODE&gt; value is
invalid. This condition may not be recognized before enqueueing the
request and so this error might also be signaled asynchronously.
-
+
&lt;br&gt;&lt;br&gt; In the case &lt;CODE&gt;aio_write&lt;/CODE&gt; returns zero, the current status of the
request can be queried using &lt;CODE&gt;aio_error&lt;/CODE&gt; and &lt;CODE&gt;aio_return&lt;/CODE&gt;
functions. As long as the value returned by &lt;CODE&gt;aio_error&lt;/CODE&gt; is
@@ -15170,10 +15170,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The &lt;CODE&gt;aiocbp-&gt;aio_fildes&lt;/CODE&gt; descriptor is not valid.
&lt;LI&gt; ECANCELED
The operation was canceled before the operation was finished.
-
+
&lt;LI&gt; EINVAL
The &lt;CODE&gt;aiocbp-&gt;aio_offset&lt;/CODE&gt; value is invalid.
-
+
&lt;br&gt;&lt;br&gt; When the sources are compiled with &lt;CODE&gt;_FILE_OFFSET_BITS == 64&lt;/CODE&gt;, this
function is in fact &lt;CODE&gt;aio_write64&lt;/CODE&gt; since the LFS interface transparently
replaces the normal implementation.
@@ -15274,7 +15274,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
each request should be checked to determine which one failed.
&lt;LI&gt; ENOSYS
The &lt;CODE&gt;lio_listio&lt;/CODE&gt; function is not supported.
-
+
&lt;br&gt;&lt;br&gt; If the &lt;VAR&gt;mode&lt;/VAR&gt; parameter is &lt;CODE&gt;LIO_NOWAIT&lt;/CODE&gt; and the caller cancels
a request, the error status for this request returned by
&lt;CODE&gt;aio_error&lt;/CODE&gt; is &lt;CODE&gt;ECANCELED&lt;/CODE&gt;.
@@ -15446,7 +15446,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
parameter is other than &lt;CODE&gt;O_DSYNC&lt;/CODE&gt; and &lt;CODE&gt;O_SYNC&lt;/CODE&gt;.
&lt;LI&gt; ENOSYS
This function is not implemented.
-
+
&lt;br&gt;&lt;br&gt; When the sources are compiled with &lt;CODE&gt;_FILE_OFFSET_BITS == 64&lt;/CODE&gt; this
function is in fact &lt;CODE&gt;aio_fsync64&lt;/CODE&gt; since the LFS interface
transparently replaces the normal implementation.
@@ -15511,7 +15511,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
of one of the requests.
&lt;LI&gt; ENOSYS
The &lt;CODE&gt;aio_suspend&lt;/CODE&gt; function is not implemented.
-
+
&lt;br&gt;&lt;br&gt; When the sources are compiled with &lt;CODE&gt;_FILE_OFFSET_BITS == 64&lt;/CODE&gt; this
function is in fact &lt;CODE&gt;aio_suspend64&lt;/CODE&gt; since the LFS interface
transparently replaces the normal implementation.
@@ -15583,7 +15583,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The file descriptor &lt;VAR&gt;fildes&lt;/VAR&gt; is not valid.
&lt;LI&gt; ENOSYS
&lt;CODE&gt;aio_cancel&lt;/CODE&gt; is not implemented.
-
+
&lt;br&gt;&lt;br&gt; When the sources are compiled with &lt;CODE&gt;_FILE_OFFSET_BITS == 64&lt;/CODE&gt;, this
function is in fact &lt;CODE&gt;aio_cancel64&lt;/CODE&gt; since the LFS interface
transparently replaces the normal implementation.
@@ -15720,7 +15720,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; F_SETOWN
Set process or process group ID to receive &lt;CODE&gt;SIGIO&lt;/CODE&gt; signals.
.
-
+
&lt;br&gt;&lt;br&gt; This function is a cancellation point in multi-threaded programs. This
is a problem if the thread allocates some resources (like memory, file
descriptors, semaphores or whatever) at the time &lt;CODE&gt;fcntl&lt;/CODE&gt; is
@@ -16719,7 +16719,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
determined by the currently selected locale. In the standard &lt;CODE&gt;"C"&lt;/CODE&gt;
locale the characters "A and "a do not match but in a locale which
regards these characters as parts of the alphabet they do match.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;CODE&gt;strcasecmp&lt;/CODE&gt; is derived from BSD.
</synopsis>
</function>
@@ -16739,7 +16739,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
determined by the currently selected locale. In the standard &lt;CODE&gt;"C"&lt;/CODE&gt;
locale the characters "A and "a do not match but in a locale which
regards these characters as parts of the alphabet they do match.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;CODE&gt;wcscasecmp&lt;/CODE&gt; is a GNU extension.
</synopsis>
</function>
@@ -16794,7 +16794,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
This function is like &lt;CODE&gt;strncmp&lt;/CODE&gt;, except that differences in case
are ignored. Like &lt;CODE&gt;strcasecmp&lt;/CODE&gt;, it is locale dependent how
uppercase and lowercase characters are related.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;CODE&gt;strncasecmp&lt;/CODE&gt; is a GNU extension.
</synopsis>
</function>
@@ -16813,7 +16813,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
This function is like &lt;CODE&gt;wcsncmp&lt;/CODE&gt;, except that differences in case
are ignored. Like &lt;CODE&gt;wcscasecmp&lt;/CODE&gt;, it is locale dependent how
uppercase and lowercase characters are related.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;CODE&gt;wcsncasecmp&lt;/CODE&gt; is a GNU extension.
</synopsis>
</function>
@@ -17049,7 +17049,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
rawmemchr (str, '\0')&lt;br&gt;
&lt;/pre&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
will never go beyond the end of the string.
&lt;br&gt;&lt;br&gt; This function is a GNU extension.
</synopsis>
@@ -18331,7 +18331,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
app -foo&lt;br&gt;
&lt;/pre&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
the &lt;CODE&gt;getopt_long_only&lt;/CODE&gt; will first look for a long option named
&lt;samp&gt;foo&lt;/samp&gt;. If this is not found, the short options &lt;samp&gt;f&lt;/samp&gt;, &lt;samp&gt;o&lt;/samp&gt;,
and again &lt;samp&gt;o&lt;/samp&gt; are recognized.
@@ -18375,7 +18375,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
div_t result;&lt;br&gt;
result = div (20, -6);&lt;br&gt;
&lt;/pre&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
Now &lt;CODE&gt;result.quot&lt;/CODE&gt; is &lt;CODE&gt;-3&lt;/CODE&gt; and &lt;CODE&gt;result.rem&lt;/CODE&gt; is &lt;CODE&gt;2&lt;/CODE&gt;.
</synopsis>
</function>
@@ -20475,7 +20475,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<header filename = "math.h"/>
</headers>
<synopsis>
-
+
The &lt;CODE&gt;fma&lt;/CODE&gt; function performs floating-point multiply-add. This is
the operation (&lt;VAR&gt;x&lt;/VAR&gt; &lt;VAR&gt;y&lt;/VAR&gt;) + &lt;VAR&gt;z&lt;/VAR&gt;, but the
intermediate result is not rounded to the destination type. This can
@@ -20485,7 +20485,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
directly, because the expression &lt;samp&gt;x*y + z&lt;/samp&gt; is defined to round the
intermediate result. &lt;CODE&gt;fma&lt;/CODE&gt; lets you choose when you want to round
only once.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
On processors which do not implement multiply-add in hardware,
&lt;CODE&gt;fma&lt;/CODE&gt; can be very slow since it must avoid intermediate rounding.
&lt;TT&gt;math.h&lt;/TT&gt; defines the symbols &lt;CODE&gt;FP_FAST_FMA&lt;/CODE&gt;,
@@ -20507,7 +20507,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<header filename = "math.h"/>
</headers>
<synopsis>
-
+
The &lt;CODE&gt;fma&lt;/CODE&gt; function performs floating-point multiply-add. This is
the operation (&lt;VAR&gt;x&lt;/VAR&gt; &lt;VAR&gt;y&lt;/VAR&gt;) + &lt;VAR&gt;z&lt;/VAR&gt;, but the
intermediate result is not rounded to the destination type. This can
@@ -20517,7 +20517,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
directly, because the expression &lt;samp&gt;x*y + z&lt;/samp&gt; is defined to round the
intermediate result. &lt;CODE&gt;fma&lt;/CODE&gt; lets you choose when you want to round
only once.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
On processors which do not implement multiply-add in hardware,
&lt;CODE&gt;fma&lt;/CODE&gt; can be very slow since it must avoid intermediate rounding.
&lt;TT&gt;math.h&lt;/TT&gt; defines the symbols &lt;CODE&gt;FP_FAST_FMA&lt;/CODE&gt;,
@@ -20539,7 +20539,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<header filename = "math.h"/>
</headers>
<synopsis>
-
+
The &lt;CODE&gt;fma&lt;/CODE&gt; function performs floating-point multiply-add. This is
the operation (&lt;VAR&gt;x&lt;/VAR&gt; &lt;VAR&gt;y&lt;/VAR&gt;) + &lt;VAR&gt;z&lt;/VAR&gt;, but the
intermediate result is not rounded to the destination type. This can
@@ -20549,7 +20549,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
directly, because the expression &lt;samp&gt;x*y + z&lt;/samp&gt; is defined to round the
intermediate result. &lt;CODE&gt;fma&lt;/CODE&gt; lets you choose when you want to round
only once.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
On processors which do not implement multiply-add in hardware,
&lt;CODE&gt;fma&lt;/CODE&gt; can be very slow since it must avoid intermediate rounding.
&lt;TT&gt;math.h&lt;/TT&gt; defines the symbols &lt;CODE&gt;FP_FAST_FMA&lt;/CODE&gt;,
@@ -21663,7 +21663,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<header filename = "wchar.h"/>
</headers>
<synopsis>
-
+
The &lt;CODE&gt;mbrtowc&lt;/CODE&gt; function (``multibyte restartable to wide
character'') converts the next multibyte character in the string pointed
to by &lt;VAR&gt;s&lt;/VAR&gt; into a wide character and stores it in the wide character
@@ -21749,7 +21749,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
wcrtombs (temp_buf, L'\0', ps)&lt;br&gt;
&lt;/pre&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
since, if &lt;VAR&gt;s&lt;/VAR&gt; is a null pointer, &lt;CODE&gt;wcrtomb&lt;/CODE&gt; performs as if it
writes into an internal buffer, which is guaranteed to be large enough.
&lt;br&gt;&lt;br&gt; If &lt;VAR&gt;wc&lt;/VAR&gt; is the NUL wide character, &lt;CODE&gt;wcrtomb&lt;/CODE&gt; emits, if
@@ -22130,7 +22130,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
Not enough memory to carry out the operation.
&lt;LI&gt; EINVAL
The conversion from &lt;VAR&gt;fromcode&lt;/VAR&gt; to &lt;VAR&gt;tocode&lt;/VAR&gt; is not supported.
-
+
&lt;br&gt;&lt;br&gt; It is not possible to use the same descriptor in different threads to
perform independent conversions. The data structures associated
with the descriptor include information about the conversion state.
@@ -22183,7 +22183,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EBADF&lt;/CODE&gt;
&lt;DD&gt;
The conversion descriptor is invalid.
-
+
&lt;br&gt;&lt;br&gt; The &lt;CODE&gt;iconv_close&lt;/CODE&gt; function was introduced together with the rest
of the &lt;CODE&gt;iconv&lt;/CODE&gt; functions in XPG2 and is declared in &lt;TT&gt;iconv.h&lt;/TT&gt;.
</synopsis>
@@ -22202,7 +22202,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<header filename = "iconv.h"/>
</headers>
<synopsis>
-
+
The &lt;CODE&gt;iconv&lt;/CODE&gt; function converts the text in the input buffer
according to the rules associated with the descriptor &lt;VAR&gt;cd&lt;/VAR&gt; and
stores the result in the output buffer. It is possible to call the
@@ -22272,7 +22272,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
of the input buffer.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EBADF
The &lt;VAR&gt;cd&lt;/VAR&gt; argument is invalid.
-
+
&lt;br&gt;&lt;br&gt; The &lt;CODE&gt;iconv&lt;/CODE&gt; function was introduced in the XPG2 standard and is
declared in the &lt;TT&gt;iconv.h&lt;/TT&gt; header.
</synopsis>
@@ -23035,7 +23035,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
low order bits of this parameter when they are allocated (except when
allocated by &lt;CODE&gt;calloc&lt;/CODE&gt;) and freed. This can be used to debug the
use of uninitialized or freed heap memory.
-
+
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -23670,7 +23670,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DD&gt;
The request would cause the data segment to overlap another segment or
exceed the process' data storage limit.
-
+
&lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -23716,7 +23716,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;VAR&gt;len&lt;/VAR&gt; is not positive.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOSYS
The kernel does not provide &lt;CODE&gt;mlock&lt;/CODE&gt; capability.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; You can lock &lt;EM&gt;all&lt;/EM&gt; a process' memory with &lt;CODE&gt;mlockall&lt;/CODE&gt;. You
unlock memory with &lt;CODE&gt;munlock&lt;/CODE&gt; or &lt;CODE&gt;munlockall&lt;/CODE&gt;.
&lt;br&gt;&lt;br&gt; To avoid all page faults in a C program, you have to use
@@ -23774,7 +23774,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
affect future address spaces owned by the same process so exec, which
replaces a process' address space, wipes out &lt;CODE&gt;MCL_FUTURE&lt;/CODE&gt;.
.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; When the function returns successfully, and you specified
&lt;CODE&gt;MCL_CURRENT&lt;/CODE&gt;, all of the process' pages are backed by (connected
to) real frames (they are resident) and are marked to stay that way.
@@ -23808,7 +23808,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
Undefined bits in &lt;VAR&gt;flags&lt;/VAR&gt; are not zero.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOSYS
The kernel does not provide &lt;CODE&gt;mlockall&lt;/CODE&gt; capability.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; You can lock just specific pages with &lt;CODE&gt;mlock&lt;/CODE&gt;. You unlock pages
with &lt;CODE&gt;munlockall&lt;/CODE&gt; and &lt;CODE&gt;munlock&lt;/CODE&gt;.
&lt;br&gt;&lt;br&gt;
@@ -23856,7 +23856,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;DT&gt;&lt;CODE&gt;RUSAGE_CHILDREN&lt;/CODE&gt;
&lt;DD&gt;
All child processes (direct and indirect) that have already terminated.
-
+
&lt;br&gt;&lt;br&gt; In the GNU system, you can also inquire about a particular child process
by specifying its process ID.
&lt;br&gt;&lt;br&gt; The return value of &lt;CODE&gt;getrusage&lt;/CODE&gt; is zero for success, and &lt;CODE&gt;-1&lt;/CODE&gt;
@@ -23865,7 +23865,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;LI&gt; EINVAL
The argument &lt;VAR&gt;processes&lt;/VAR&gt; is not valid.
-
+
</synopsis>
</function>
</construct>
@@ -24025,8 +24025,8 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
Disk reads. Analogous to &lt;CODE&gt;ru_inblk&lt;/CODE&gt; in &lt;CODE&gt;struct rusage&lt;/CODE&gt;
&lt;LI&gt; vm_oublk
Disk writes. Analogous to &lt;CODE&gt;ru_oublk&lt;/CODE&gt; in &lt;CODE&gt;struct rusage&lt;/CODE&gt;
-
-
+
+
&lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt; The return value is zero if the function succeeds; &lt;CODE&gt;-1&lt;/CODE&gt; otherwise.
&lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt;
</synopsis>
@@ -24096,7 +24096,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt;
The process tried to raise a maximum limit, but is not superuser.
&lt;/OL&gt;
-
+
&lt;br&gt;&lt;br&gt; When the sources are compiled with &lt;CODE&gt;_FILE_OFFSET_BITS == 64&lt;/CODE&gt; on a
32-bit system this function is in fact &lt;CODE&gt;setrlimit64&lt;/CODE&gt;. Thus, the
LFS interface transparently replaces the old interface.
@@ -24186,7 +24186,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DD&gt;
Set the current and maximum limit on the size of a file to &lt;VAR&gt;limit&lt;/VAR&gt; *
512 bytes.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; There are also some other &lt;VAR&gt;cmd&lt;/VAR&gt; values that may do things on some
systems, but they are not supported.
&lt;br&gt;&lt;br&gt; Only the superuser may increase a maximum limit.
@@ -24198,7 +24198,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;LI&gt; EPERM
A process tried to increase a maximum limit, but is not superuser.
-
+
&lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -24231,14 +24231,14 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
Maximum core file size. Same as &lt;CODE&gt;RLIMIT_COR&lt;/CODE&gt; for &lt;CODE&gt;setrlimit&lt;/CODE&gt;.
&lt;LI&gt; LIM_MAXRSS
Maximum physical memory. Same as &lt;CODE&gt;RLIMIT_RSS&lt;/CODE&gt; for &lt;CODE&gt;setrlimit&lt;/CODE&gt;.
-
+
&lt;br&gt;&lt;br&gt; The return value is zero for success, and &lt;CODE&gt;-1&lt;/CODE&gt; with &lt;CODE&gt;errno&lt;/CODE&gt; set
accordingly for failure:
&lt;br&gt;&lt;br&gt; &lt;DL&gt;
&lt;LI&gt; EPERM
The process tried to set its current limit beyond its maximum limit.
-
+
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -24278,7 +24278,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
First In First Out
&lt;LI&gt; SCHED_RR
Round Robin
-
+
&lt;br&gt;&lt;br&gt; &lt;br&gt;&lt;br&gt; On success, the return value is &lt;CODE&gt;0&lt;/CODE&gt;. Otherwise, it is &lt;CODE&gt;-1&lt;/CODE&gt;
and &lt;CODE&gt;ERRNO&lt;/CODE&gt; is set accordingly. The &lt;CODE&gt;errno&lt;/CODE&gt; values specific
to this function are:
@@ -24311,7 +24311,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt;
&lt;VAR&gt;pid&lt;/VAR&gt; is negative.
&lt;/OL&gt;
-
+
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -24339,7 +24339,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
There is no process with pid &lt;VAR&gt;pid&lt;/VAR&gt; and it is not zero.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
&lt;VAR&gt;pid&lt;/VAR&gt; is negative.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; Note that this function is not an exact mate to &lt;CODE&gt;sched_setscheduler&lt;/CODE&gt;
because while that function sets the scheduling policy and the absolute
priority, this function gets only the scheduling policy. To get the
@@ -24390,7 +24390,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
There is no process with pid &lt;VAR&gt;pid&lt;/VAR&gt; and it is not zero.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
&lt;VAR&gt;pid&lt;/VAR&gt; is negative.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -24415,7 +24415,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EINVAL&lt;/CODE&gt;
&lt;DD&gt;
&lt;VAR&gt;policy&lt;/VAR&gt; does not identify an existing scheduling policy.
-
+
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -24440,7 +24440,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EINVAL&lt;/CODE&gt;
&lt;DD&gt;
&lt;VAR&gt;policy&lt;/VAR&gt; does not identify an existing scheduling policy.
-
+
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -24525,7 +24525,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
process.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
The value of &lt;VAR&gt;class&lt;/VAR&gt; is not valid.
-
+
&lt;br&gt;&lt;br&gt; If the return value is &lt;CODE&gt;-1&lt;/CODE&gt;, it could indicate failure, or it could
be the nice value. The only way to make certain is to set &lt;CODE&gt;errno =
0&lt;/CODE&gt; before calling &lt;CODE&gt;getpriority&lt;/CODE&gt;, then use &lt;CODE&gt;errno != 0&lt;/CODE&gt;
@@ -24565,7 +24565,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EACCES
The call would lower the process' nice value and the process does not have
&lt;CODE&gt;CAP_SYS_NICE&lt;/CODE&gt; permission.
-
+
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -24629,7 +24629,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
No process or thread with the given ID found.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EFAULT
The pointer &lt;VAR&gt;cpuset&lt;/VAR&gt; is does not point to a valid object.
-
+
&lt;br&gt;&lt;br&gt; This function is a GNU extension and is declared in &lt;TT&gt;sched.h&lt;/TT&gt;.
</synopsis>
</function>
@@ -24661,7 +24661,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
The bitset is not valid. This might mean that the affinity set might
not leave a processor for the process or thread to run on.
-
+
&lt;br&gt;&lt;br&gt; This function is a GNU extension and is declared in &lt;TT&gt;sched.h&lt;/TT&gt;.
</synopsis>
</function>
@@ -24820,7 +24820,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ERANGE
The buffer length &lt;VAR&gt;len&lt;/VAR&gt; is too small to store the string to be
returned.
-
+
</synopsis>
</function>
</construct>
@@ -24890,7 +24890,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The &lt;VAR&gt;filedes&lt;/VAR&gt; argument is not a valid file descriptor.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOTTY
The &lt;VAR&gt;filedes&lt;/VAR&gt; is not associated with a terminal.
-
+
</synopsis>
</function>
</construct>
@@ -24914,19 +24914,19 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;TCSANOW&lt;/CODE&gt;
&lt;DD&gt;
-
+
Make the change immediately.
&lt;br&gt;&lt;br&gt; &lt;DT&gt;&lt;CODE&gt;TCSADRAIN&lt;/CODE&gt;
&lt;DD&gt;
-
+
Make the change after waiting until all queued output has been written.
You should usually use this option when changing parameters that affect
output.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; TCSAFLUSH
-
+
This is like &lt;CODE&gt;TCSADRAIN&lt;/CODE&gt;, but also discards any queued input.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; TCSASOFT
-
+
This is a flag bit that you can add to any of the above alternatives.
Its meaning is to inhibit alteration of the state of the terminal
hardware. It is a BSD extension; it is only supported on BSD systems
@@ -24934,7 +24934,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; Using &lt;CODE&gt;TCSASOFT&lt;/CODE&gt; is exactly the same as setting the &lt;CODE&gt;CIGNORE&lt;/CODE&gt;
bit in the &lt;CODE&gt;c_cflag&lt;/CODE&gt; member of the structure &lt;VAR&gt;termios-p&lt;/VAR&gt; points
to. , for a description of &lt;CODE&gt;CIGNORE&lt;/CODE&gt;.
-
+
&lt;br&gt;&lt;br&gt; If this function is called from a background process on its controlling
terminal, normally all processes in the process group are sent a
&lt;CODE&gt;SIGTTOU&lt;/CODE&gt; signal, in the same way as if the process were trying to
@@ -24953,7 +24953,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
Either the value of the &lt;CODE&gt;when&lt;/CODE&gt; argument is not valid, or there is
something wrong with the data in the &lt;VAR&gt;termios-p&lt;/VAR&gt; argument.
-
+
</synopsis>
</function>
</construct>
@@ -25157,7 +25157,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The &lt;VAR&gt;filedes&lt;/VAR&gt; is not a valid file descriptor.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; ENOTTY
The &lt;VAR&gt;filedes&lt;/VAR&gt; is not associated with a terminal device.
-
+
</synopsis>
</function>
</construct>
@@ -25191,7 +25191,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINTR
The operation was interrupted by delivery of a signal.
.
-
+
</synopsis>
</function>
</construct>
@@ -25211,18 +25211,18 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
following values:
&lt;br&gt;&lt;br&gt; &lt;DL&gt;
-
+
&lt;DT&gt;&lt;CODE&gt;TCIFLUSH&lt;/CODE&gt;
&lt;DD&gt;
&lt;br&gt;&lt;br&gt; Clear any input data received, but not yet read.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;DT&gt;&lt;CODE&gt;TCOFLUSH&lt;/CODE&gt;
&lt;DD&gt;
&lt;br&gt;&lt;br&gt; Clear any output data written, but not yet transmitted.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;LI&gt; TCIOFLUSH
&lt;br&gt;&lt;br&gt; Clear both queued input and output.
-
+
&lt;br&gt;&lt;br&gt; The return value is normally zero. In the event of an error, a value
of -1 is returned. The following &lt;CODE&gt;errno&lt;/CODE&gt; error conditions
are defined for this function:
@@ -25234,7 +25234,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
The &lt;VAR&gt;filedes&lt;/VAR&gt; is not associated with a terminal device.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
A bad value was supplied as the &lt;VAR&gt;queue&lt;/VAR&gt; argument.
-
+
&lt;br&gt;&lt;br&gt; It is unfortunate that this function is named &lt;CODE&gt;tcflush&lt;/CODE&gt;, because
the term ``flush'' is normally used for quite another operation---waiting
until all output is transmitted---and using it for discarding input or
@@ -25259,21 +25259,21 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
be one of the following values:
&lt;br&gt;&lt;br&gt; &lt;DL&gt;
-
+
&lt;DT&gt;&lt;CODE&gt;TCOOFF&lt;/CODE&gt;
&lt;DD&gt;
Suspend transmission of output.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;DT&gt;&lt;CODE&gt;TCOON&lt;/CODE&gt;
&lt;DD&gt;
Restart transmission of output.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;LI&gt; TCIOFF
Transmit a STOP character.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;LI&gt; TCION
Transmit a START character.
-
+
&lt;br&gt;&lt;br&gt; For more information about the STOP and START characters, see Special
Characters.
&lt;br&gt;&lt;br&gt; The return value is normally zero. In the event of an error, a value
@@ -25281,16 +25281,16 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
are defined for this function:
&lt;br&gt;&lt;br&gt; &lt;DL&gt;
-
+
&lt;LI&gt; EBADF
The &lt;VAR&gt;filedes&lt;/VAR&gt; is not a valid file descriptor.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;LI&gt; ENOTTY
The &lt;VAR&gt;filedes&lt;/VAR&gt; is not associated with a terminal device.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;LI&gt; EINVAL
A bad value was supplied as the &lt;VAR&gt;action&lt;/VAR&gt; argument.
-
+
</synopsis>
</function>
</construct>
@@ -25313,7 +25313,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;ENOENT&lt;/CODE&gt;
&lt;DD&gt;
There are no free master pseudo-terminals available.
-
+
&lt;br&gt;&lt;br&gt; This function is a GNU extension.
</synopsis>
</function>
@@ -25354,7 +25354,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EACCES
The slave pseudo-terminal device corresponding to the master associated
with &lt;VAR&gt;filedes&lt;/VAR&gt; could not be accessed.
-
+
&lt;br&gt;&lt;br&gt;
</synopsis>
</function>
@@ -25384,7 +25384,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
The &lt;VAR&gt;filedes&lt;/VAR&gt; argument is not associated with a master pseudo-terminal
device.
-
+
</synopsis>
</function>
</construct>
@@ -25454,7 +25454,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;ENOENT&lt;/CODE&gt;
&lt;DD&gt;
There are no free pseudo-terminal pairs available.
-
+
&lt;br&gt;&lt;br&gt; Warning: Using the &lt;CODE&gt;openpty&lt;/CODE&gt; function with &lt;VAR&gt;name&lt;/VAR&gt; not
set to &lt;CODE&gt;NULL&lt;/CODE&gt; is very dangerous because it provides no
protection against overflowing the string &lt;VAR&gt;name&lt;/VAR&gt;. You should use
@@ -25576,7 +25576,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
exactly the opposite.
&lt;br&gt;&lt;br&gt; &lt;LI&gt; LOG_ODELAY
This bit does nothing. It exists for backward compatibility.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; If any other bit in &lt;VAR&gt;options&lt;/VAR&gt; is on, the result is undefined.
&lt;br&gt;&lt;br&gt; &lt;VAR&gt;facility&lt;/VAR&gt; is the default facility code for this connection. A
&lt;CODE&gt;syslog&lt;/CODE&gt; on this connection that specifies default facility causes
@@ -25994,7 +25994,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
system call failed. In that case, &lt;CODE&gt;syscall&lt;/CODE&gt; returns &lt;CODE&gt;-1&lt;/CODE&gt; and
sets &lt;CODE&gt;errno&lt;/CODE&gt; to an error code that the system call returned. Note
that system calls do not return &lt;CODE&gt;-1&lt;/CODE&gt; when they succeed.
-
+
&lt;br&gt;&lt;br&gt; If you specify an invalid &lt;VAR&gt;sysno&lt;/VAR&gt;, &lt;CODE&gt;syscall&lt;/CODE&gt; returns &lt;CODE&gt;-1&lt;/CODE&gt;
with &lt;CODE&gt;errno&lt;/CODE&gt; = &lt;CODE&gt;ENOSYS&lt;/CODE&gt;.
&lt;br&gt;&lt;br&gt; Example:
@@ -26336,10 +26336,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the complex sine of &lt;VAR&gt;z&lt;/VAR&gt;.
The mathematical definition of the complex sine is
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
sin (z) = 1/(2*i) * (exp (z*i) - exp (-z*i)).
-
-
+
+
</synopsis>
</function>
</construct>
@@ -26354,10 +26354,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the complex sine of &lt;VAR&gt;z&lt;/VAR&gt;.
The mathematical definition of the complex sine is
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
sin (z) = 1/(2*i) * (exp (z*i) - exp (-z*i)).
-
-
+
+
</synopsis>
</function>
</construct>
@@ -26372,10 +26372,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the complex sine of &lt;VAR&gt;z&lt;/VAR&gt;.
The mathematical definition of the complex sine is
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
sin (z) = 1/(2*i) * (exp (z*i) - exp (-z*i)).
-
-
+
+
</synopsis>
</function>
</construct>
@@ -26390,10 +26390,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the complex cosine of &lt;VAR&gt;z&lt;/VAR&gt;.
The mathematical definition of the complex cosine is
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
cos (z) = 1/2 * (exp (z*i) + exp (-z*i))
-
-
+
+
</synopsis>
</function>
</construct>
@@ -26408,10 +26408,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the complex cosine of &lt;VAR&gt;z&lt;/VAR&gt;.
The mathematical definition of the complex cosine is
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
cos (z) = 1/2 * (exp (z*i) + exp (-z*i))
-
-
+
+
</synopsis>
</function>
</construct>
@@ -26426,10 +26426,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the complex cosine of &lt;VAR&gt;z&lt;/VAR&gt;.
The mathematical definition of the complex cosine is
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
cos (z) = 1/2 * (exp (z*i) + exp (-z*i))
-
-
+
+
</synopsis>
</function>
</construct>
@@ -26444,11 +26444,11 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the complex tangent of &lt;VAR&gt;z&lt;/VAR&gt;.
The mathematical definition of the complex tangent is
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
tan (z) = -i * (exp (z*i) - exp (-z*i)) / (exp (z*i) + exp (-z*i))
-
-
- &lt;br&gt;&lt;br&gt;
+
+
+ &lt;br&gt;&lt;br&gt;
The complex tangent has poles at pi/2 + 2n, where n is an
integer. &lt;CODE&gt;ctan&lt;/CODE&gt; may signal overflow if &lt;VAR&gt;z&lt;/VAR&gt; is too close to a
pole.
@@ -26466,11 +26466,11 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the complex tangent of &lt;VAR&gt;z&lt;/VAR&gt;.
The mathematical definition of the complex tangent is
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
tan (z) = -i * (exp (z*i) - exp (-z*i)) / (exp (z*i) + exp (-z*i))
-
-
- &lt;br&gt;&lt;br&gt;
+
+
+ &lt;br&gt;&lt;br&gt;
The complex tangent has poles at pi/2 + 2n, where n is an
integer. &lt;CODE&gt;ctan&lt;/CODE&gt; may signal overflow if &lt;VAR&gt;z&lt;/VAR&gt; is too close to a
pole.
@@ -26488,11 +26488,11 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the complex tangent of &lt;VAR&gt;z&lt;/VAR&gt;.
The mathematical definition of the complex tangent is
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
tan (z) = -i * (exp (z*i) - exp (-z*i)) / (exp (z*i) + exp (-z*i))
-
-
- &lt;br&gt;&lt;br&gt;
+
+
+ &lt;br&gt;&lt;br&gt;
The complex tangent has poles at pi/2 + 2n, where n is an
integer. &lt;CODE&gt;ctan&lt;/CODE&gt; may signal overflow if &lt;VAR&gt;z&lt;/VAR&gt; is too close to a
pole.
@@ -27603,10 +27603,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
These functions return &lt;CODE&gt;e&lt;/CODE&gt; (the base of natural
logarithms) raised to the power of &lt;VAR&gt;z&lt;/VAR&gt;.
Mathematically, this corresponds to the value
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
exp (z) = exp (creal (z)) * (cos (cimag (z)) + I * sin (cimag (z)))
-
-
+
+
</synopsis>
</function>
</construct>
@@ -27622,10 +27622,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
These functions return &lt;CODE&gt;e&lt;/CODE&gt; (the base of natural
logarithms) raised to the power of &lt;VAR&gt;z&lt;/VAR&gt;.
Mathematically, this corresponds to the value
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
exp (z) = exp (creal (z)) * (cos (cimag (z)) + I * sin (cimag (z)))
-
-
+
+
</synopsis>
</function>
</construct>
@@ -27641,10 +27641,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
These functions return &lt;CODE&gt;e&lt;/CODE&gt; (the base of natural
logarithms) raised to the power of &lt;VAR&gt;z&lt;/VAR&gt;.
Mathematically, this corresponds to the value
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
exp (z) = exp (creal (z)) * (cos (cimag (z)) + I * sin (cimag (z)))
-
-
+
+
</synopsis>
</function>
</construct>
@@ -27659,11 +27659,11 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the natural logarithm of &lt;VAR&gt;z&lt;/VAR&gt;.
Mathematically, this corresponds to the value
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
log (z) = log (cabs (z)) + I * carg (z)
-
-
- &lt;br&gt;&lt;br&gt;
+
+
+ &lt;br&gt;&lt;br&gt;
&lt;CODE&gt;clog&lt;/CODE&gt; has a pole at 0, and will signal overflow if &lt;VAR&gt;z&lt;/VAR&gt; equals
or is very close to 0. It is well-defined for all other values of
&lt;VAR&gt;z&lt;/VAR&gt;.
@@ -27681,11 +27681,11 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the natural logarithm of &lt;VAR&gt;z&lt;/VAR&gt;.
Mathematically, this corresponds to the value
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
log (z) = log (cabs (z)) + I * carg (z)
-
-
- &lt;br&gt;&lt;br&gt;
+
+
+ &lt;br&gt;&lt;br&gt;
&lt;CODE&gt;clog&lt;/CODE&gt; has a pole at 0, and will signal overflow if &lt;VAR&gt;z&lt;/VAR&gt; equals
or is very close to 0. It is well-defined for all other values of
&lt;VAR&gt;z&lt;/VAR&gt;.
@@ -27703,11 +27703,11 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the natural logarithm of &lt;VAR&gt;z&lt;/VAR&gt;.
Mathematically, this corresponds to the value
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
log (z) = log (cabs (z)) + I * carg (z)
-
-
- &lt;br&gt;&lt;br&gt;
+
+
+ &lt;br&gt;&lt;br&gt;
&lt;CODE&gt;clog&lt;/CODE&gt; has a pole at 0, and will signal overflow if &lt;VAR&gt;z&lt;/VAR&gt; equals
or is very close to 0. It is well-defined for all other values of
&lt;VAR&gt;z&lt;/VAR&gt;.
@@ -27725,10 +27725,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the base 10 logarithm of the complex value
&lt;VAR&gt;z&lt;/VAR&gt;. Mathematically, this corresponds to the value
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
log (z) = log10 (cabs (z)) + I * carg (z)
-
-
+
+
&lt;br&gt;&lt;br&gt; These functions are GNU extensions.
</synopsis>
</function>
@@ -27744,10 +27744,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the base 10 logarithm of the complex value
&lt;VAR&gt;z&lt;/VAR&gt;. Mathematically, this corresponds to the value
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
log (z) = log10 (cabs (z)) + I * carg (z)
-
-
+
+
&lt;br&gt;&lt;br&gt; These functions are GNU extensions.
</synopsis>
</function>
@@ -27763,10 +27763,10 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
These functions return the base 10 logarithm of the complex value
&lt;VAR&gt;z&lt;/VAR&gt;. Mathematically, this corresponds to the value
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
log (z) = log10 (cabs (z)) + I * carg (z)
-
-
+
+
&lt;br&gt;&lt;br&gt; These functions are GNU extensions.
</synopsis>
</function>
@@ -28400,12 +28400,12 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
&lt;CODE&gt;erf&lt;/CODE&gt; returns the error function of &lt;VAR&gt;x&lt;/VAR&gt;. The error
function is defined as
-
-
+
+
&lt;pre&gt;&lt;br&gt;
erf (x) = 2/sqrt(pi) * integral from 0 to x of exp(-t^2) dt&lt;br&gt;
&lt;/pre&gt;
-
+
</synopsis>
</function>
</construct>
@@ -28420,12 +28420,12 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
&lt;CODE&gt;erf&lt;/CODE&gt; returns the error function of &lt;VAR&gt;x&lt;/VAR&gt;. The error
function is defined as
-
-
+
+
&lt;pre&gt;&lt;br&gt;
erf (x) = 2/sqrt(pi) * integral from 0 to x of exp(-t^2) dt&lt;br&gt;
&lt;/pre&gt;
-
+
</synopsis>
</function>
</construct>
@@ -28440,12 +28440,12 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
&lt;CODE&gt;erf&lt;/CODE&gt; returns the error function of &lt;VAR&gt;x&lt;/VAR&gt;. The error
function is defined as
-
-
+
+
&lt;pre&gt;&lt;br&gt;
erf (x) = 2/sqrt(pi) * integral from 0 to x of exp(-t^2) dt&lt;br&gt;
&lt;/pre&gt;
-
+
</synopsis>
</function>
</construct>
@@ -28502,8 +28502,8 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
&lt;CODE&gt;lgamma&lt;/CODE&gt; returns the natural logarithm of the absolute value of
the gamma function of &lt;VAR&gt;x&lt;/VAR&gt;. The gamma function is defined as
-
-
+
+
&lt;pre&gt;&lt;br&gt;
gamma (x) = integral from 0 to infinity{} of t^(x-1) e^-t dt&lt;br&gt;
&lt;/pre&gt;&lt;br&gt;
@@ -28536,8 +28536,8 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
&lt;CODE&gt;lgamma&lt;/CODE&gt; returns the natural logarithm of the absolute value of
the gamma function of &lt;VAR&gt;x&lt;/VAR&gt;. The gamma function is defined as
-
-
+
+
&lt;pre&gt;&lt;br&gt;
gamma (x) = integral from 0 to infinity{} of t^(x-1) e^-t dt&lt;br&gt;
&lt;/pre&gt;&lt;br&gt;
@@ -28570,8 +28570,8 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
&lt;CODE&gt;lgamma&lt;/CODE&gt; returns the natural logarithm of the absolute value of
the gamma function of &lt;VAR&gt;x&lt;/VAR&gt;. The gamma function is defined as
-
-
+
+
&lt;pre&gt;&lt;br&gt;
gamma (x) = integral from 0 to infinity{} of t^(x-1) e^-t dt&lt;br&gt;
&lt;/pre&gt;&lt;br&gt;
@@ -28700,12 +28700,12 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
&lt;CODE&gt;tgamma&lt;/CODE&gt; applies the gamma function to &lt;VAR&gt;x&lt;/VAR&gt;. The gamma
function is defined as
-
-
+
+
&lt;pre&gt;&lt;br&gt;
gamma (x) = integral from 0 to infinity{} of t^(x-1) e^-t dt&lt;br&gt;
&lt;/pre&gt;
-
+
&lt;br&gt;&lt;br&gt; This function was introduced in ISO C99.
</synopsis>
</function>
@@ -28721,12 +28721,12 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
&lt;CODE&gt;tgamma&lt;/CODE&gt; applies the gamma function to &lt;VAR&gt;x&lt;/VAR&gt;. The gamma
function is defined as
-
-
+
+
&lt;pre&gt;&lt;br&gt;
gamma (x) = integral from 0 to infinity{} of t^(x-1) e^-t dt&lt;br&gt;
&lt;/pre&gt;
-
+
&lt;br&gt;&lt;br&gt; This function was introduced in ISO C99.
</synopsis>
</function>
@@ -28742,12 +28742,12 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
<synopsis>
&lt;CODE&gt;tgamma&lt;/CODE&gt; applies the gamma function to &lt;VAR&gt;x&lt;/VAR&gt;. The gamma
function is defined as
-
-
+
+
&lt;pre&gt;&lt;br&gt;
gamma (x) = integral from 0 to infinity{} of t^(x-1) e^-t dt&lt;br&gt;
&lt;/pre&gt;
-
+
&lt;br&gt;&lt;br&gt; This function was introduced in ISO C99.
</synopsis>
</function>
@@ -29625,7 +29625,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EINVAL&lt;/CODE&gt;
&lt;DD&gt;
The value of the &lt;VAR&gt;parameter&lt;/VAR&gt; is invalid.
-
+
</synopsis>
</function>
</construct>
@@ -29662,7 +29662,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DD&gt;
The value of &lt;VAR&gt;parameter&lt;/VAR&gt; is invalid, or the implementation doesn't
support the &lt;VAR&gt;parameter&lt;/VAR&gt; for the specific file.
-
+
</synopsis>
</function>
</construct>
@@ -29688,7 +29688,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; EINVAL
The value of &lt;VAR&gt;parameter&lt;/VAR&gt; is invalid, or the implementation doesn't
support the &lt;VAR&gt;parameter&lt;/VAR&gt; for the specific file.
-
+
</synopsis>
</function>
</construct>
@@ -29723,7 +29723,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DT&gt;&lt;CODE&gt;EINVAL&lt;/CODE&gt;
&lt;DD&gt;
The value of the &lt;VAR&gt;parameter&lt;/VAR&gt; is invalid.
-
+
</synopsis>
</function>
</construct>
@@ -30221,7 +30221,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;LI&gt; -1
The answer matched neither the &lt;CODE&gt;YESEXPR&lt;/CODE&gt; nor the &lt;CODE&gt;NOEXPR&lt;/CODE&gt;
regular expression.
-
+
&lt;br&gt;&lt;br&gt; This function is not standardized but available beside in GNU libc at
least also in the IBM AIX library.
</synopsis>
@@ -30843,7 +30843,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
fputs ("you ", stdout);&lt;br&gt;
fputs ("hungry?\n", stdout);&lt;br&gt;
&lt;/pre&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
outputs the text &lt;samp&gt;Are you hungry?&lt;/samp&gt; followed by a newline.
</synopsis>
</function>
@@ -30917,7 +30917,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
puts ("This is a message.");&lt;br&gt;
&lt;/pre&gt;
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
outputs the text &lt;samp&gt;This is a message.&lt;/samp&gt; followed by a newline.
</synopsis>
</function>
@@ -31597,19 +31597,19 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
return NULL;&lt;br&gt;
&lt;br&gt;&lt;br&gt; /* Try to print in the allocated space. */&lt;br&gt;
nchars = snprintf (buffer, size, "value of %s is %s",&lt;br&gt;
- name, value);&lt;br&gt;
+ name, value);&lt;br&gt;
&lt;br&gt;
&lt;br&gt;
if (nchars &gt;= size)&lt;br&gt;
{&lt;br&gt;
/* Reallocate buffer now that we know&lt;br&gt;
- how much space is needed. */&lt;br&gt;
+ how much space is needed. */&lt;br&gt;
size = nchars + 1;&lt;br&gt;
buffer = (char *) xrealloc (buffer, size);&lt;br&gt;
&lt;br&gt;&lt;br&gt; if (buffer != NULL)&lt;br&gt;
- /* Try again. */&lt;br&gt;
- snprintf (buffer, size, "value of %s is %s",&lt;br&gt;
- name, value);&lt;br&gt;
+ /* Try again. */&lt;br&gt;
+ snprintf (buffer, size, "value of %s is %s",&lt;br&gt;
+ name, value);&lt;br&gt;
}&lt;br&gt;
/* The last call worked, return the string. */&lt;br&gt;
return buffer;&lt;br&gt;
@@ -31883,7 +31883,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;CODE&gt;parse_printf_format&lt;/CODE&gt; when this conversion appears in a
template string. , for information
about this.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;br&gt;&lt;br&gt; Attention: In the GNU C library versions before 2.0 the
&lt;VAR&gt;arginfo-function&lt;/VAR&gt; function did not need to be installed unless
the user used the &lt;CODE&gt;parse_printf_format&lt;/CODE&gt; function. This has changed.
@@ -32041,7 +32041,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
1000 is used.
&lt;br&gt;&lt;br&gt; The postfix tag corresponds to bytes, kilobytes, megabytes, gigabytes,
etc. The full table is:
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
&lt;DL&gt;
&lt;DT&gt;&lt;pre&gt;low Multiplier From Upper Multiplier&lt;/pre&gt;
&lt;DD&gt;&lt;br&gt; &lt;DT&gt;&lt;pre&gt;' ' 1 ' ' 1&lt;/pre&gt;
@@ -32054,8 +32054,8 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;DD&gt;&lt;br&gt; &lt;DT&gt;&lt;pre&gt;z 2^70 zetta Z 10^21&lt;/pre&gt;
&lt;DD&gt;&lt;br&gt; &lt;DT&gt;&lt;pre&gt;y 2^80 yotta Y 10^24&lt;/pre&gt;
&lt;DD&gt;&lt;br&gt; &lt;/DL&gt;
-
-
+
+
&lt;br&gt;&lt;br&gt; The default precision is 3, i.e., 1024 is printed with a lower-case
format character as if it were &lt;CODE&gt;%.3fk&lt;/CODE&gt; and will yield &lt;CODE&gt;1.000k&lt;/CODE&gt;.
</synopsis>
@@ -33095,7 +33095,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;CODE&gt;addseverity&lt;/CODE&gt; function one can add more severity levels with their
corresponding string to print. This is described below
.
- &lt;br&gt;&lt;br&gt;
+ &lt;br&gt;&lt;br&gt;
If no parameter is ignored the output looks like this:
&lt;br&gt;&lt;br&gt; &lt;pre&gt;&lt;br&gt;
&lt;VAR&gt;label&lt;/VAR&gt;: &lt;VAR&gt;severity-string&lt;/VAR&gt;: &lt;VAR&gt;text&lt;/VAR&gt;&lt;br&gt;
@@ -33458,7 +33458,7 @@ can be found at: http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gz
&lt;LI&gt; ESRCH
The &lt;VAR&gt;action&lt;/VAR&gt; parameter is &lt;CODE&gt;FIND&lt;/CODE&gt; and no corresponding element
is found in the table.
-
+
</synopsis>
</function>
</construct>
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.glibc/toc.xml b/libhover/org.eclipse.linuxtools.cdt.libhover.glibc/toc.xml
index 65e6fbb10c..790286714f 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.glibc/toc.xml
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.glibc/toc.xml
@@ -2,6 +2,6 @@
<?NLS TYPE="org.eclipse.help.toc"?>
<toc label="glibc library" link_to="../org.eclipse.linuxtools.cdt.libhover.library.docs/libraries.xml#moreclibdocs">
- <topic href="http://www.gnu.org/software/libc/manual/html_node/index.html" label="glibc">
+ <topic href="http://www.gnu.org/software/libc/manual/html_node/index.html" label="glibc">
</topic>
</toc>
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.library.docs/build-helper.xml b/libhover/org.eclipse.linuxtools.cdt.libhover.library.docs/build-helper.xml
index 42980cb90e..7774fb6fe8 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.library.docs/build-helper.xml
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.library.docs/build-helper.xml
@@ -1,62 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="org.eclipse.linuxtools.cdt.libhover.library-docs" default="all">
- <description>
+ <description>
Generate Eclipse help content for the Linux Tools Libhover Developers guide
</description>
- <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
+ <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
- <path id="tasks.classpath" path="bin" />
- <path id="wikitext.tasks.classpath">
- <!-- Replace dir with the dir you have wikitext installed into.-->
- <fileset dir="/notnfs/jjohnstn/helios/eclipse/plugins">
- <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
- </fileset>
- </path>
+ <path id="tasks.classpath" path="bin" />
+ <path id="wikitext.tasks.classpath">
+ <!-- Replace dir with the dir you have wikitext installed into.-->
+ <fileset dir="/notnfs/jjohnstn/helios/eclipse/plugins">
+ <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
+ </fileset>
+ </path>
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
- <target name="all" description="Generate Eclipse help content for the Linux Tools changelog user guide">
- <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="Libhover Developer's Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
+ <target name="all" description="Generate Eclipse help content for the Linux Tools changelog user guide">
+ <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="Libhover Developer's Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
- <path name="Linux_Tools_Project/Libhover/Developers_Guide" title="Libhover Developer's Guide" generateToc="false" />
- <stylesheet url="book.css" />
- <pageAppendum>
- = Updating This Document =
+ <path name="Linux_Tools_Project/Libhover/Developers_Guide" title="Libhover Developer's Guide" generateToc="false" />
+ <stylesheet url="book.css" />
+ <pageAppendum>
+ = Updating This Document =
- This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
- http://wiki.eclipse.org/Linux_Tools_Project/Libhover/Developers_Guide .
- </pageAppendum>
- </mediawiki-to-eclipse-help>
- <antcall target="test" />
- </target>
+ This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
+ http://wiki.eclipse.org/Linux_Tools_Project/Libhover/Developers_Guide .
+ </pageAppendum>
+ </mediawiki-to-eclipse-help>
+ <antcall target="test" />
+ </target>
- <target name="test" description="verify that all of the HTML files are well-formed XML">
- <echo level="info">
+ <target name="test" description="verify that all of the HTML files are well-formed XML">
+ <echo level="info">
Validating help content XML and HTML files: The Eclipse help system expects well-formed XML
-
+
If validation fails it is because either:
-
+
* the userguide source code is poorly formed, or
* the WikiText MediaWiki parser has a bug
-
+
Problems with userguide source are usually caused by improper use of HTML markup in the MediaWiki source,
or inadvertently starting a line with a space character (in MediaWiki this starts a preformatted block)
- </echo>
-
- <!--
- Don't bother with DTD validation: we only care if the files are well-formed.
- We therefore provide an empty DTD
- -->
- <mkdir dir="tmp"/>
- <echo file="tmp/__empty.dtd" message="" />
- <xmlvalidate lenient="true">
- <fileset dir="Linux_Tools_Project">
- <include name="**/*.html" />
- </fileset>
- <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
- </xmlvalidate>
- <delete dir="tmp" />
- </target>
+ </echo>
+
+ <!--
+ Don't bother with DTD validation: we only care if the files are well-formed.
+ We therefore provide an empty DTD
+ -->
+ <mkdir dir="tmp"/>
+ <echo file="tmp/__empty.dtd" message="" />
+ <xmlvalidate lenient="true">
+ <fileset dir="Linux_Tools_Project">
+ <include name="**/*.html" />
+ </fileset>
+ <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
+ </xmlvalidate>
+ <delete dir="tmp" />
+ </target>
</project>
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.library.docs/toc.xml b/libhover/org.eclipse.linuxtools.cdt.libhover.library.docs/toc.xml
index 28e1784acf..10b6302f5c 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.library.docs/toc.xml
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.library.docs/toc.xml
@@ -1,14 +1,14 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html" label="Libhover Developer's Guide">
- <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html" label="Libhover Developer's Guide">
- <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html" label="Introduction"></topic>
- <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#Libhover_Extension" label="Libhover Extension"></topic>
- <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#Libhover_Data" label="Libhover Data"></topic>
- <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#C_Library_Data" label="C Library Data">
- <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#C_Library_Hover_Utility" label="C Library Hover Utility"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#C.2B.2B_Library_Hover" label="C++ Library Hover"></topic>
- <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#Libhover_Logic" label="Libhover Logic"></topic>
- <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
- </topic>
+ <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html" label="Libhover Developer's Guide">
+ <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html" label="Introduction"></topic>
+ <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#Libhover_Extension" label="Libhover Extension"></topic>
+ <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#Libhover_Data" label="Libhover Data"></topic>
+ <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#C_Library_Data" label="C Library Data">
+ <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#C_Library_Hover_Utility" label="C Library Hover Utility"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#C.2B.2B_Library_Hover" label="C++ Library Hover"></topic>
+ <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Developers-Guide.html#Libhover_Logic" label="Libhover Logic"></topic>
+ <topic href="Linux_Tools_Project/Libhover/Developers_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
+ </topic>
</toc> \ No newline at end of file
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.libstdcxx/src/org/eclipse/linuxtools/internal/cdt/libhover/libstdcxx/DoxygenCPPInfo.java b/libhover/org.eclipse.linuxtools.cdt.libhover.libstdcxx/src/org/eclipse/linuxtools/internal/cdt/libhover/libstdcxx/DoxygenCPPInfo.java
index 1065ed51d6..701a83aef9 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.libstdcxx/src/org/eclipse/linuxtools/internal/cdt/libhover/libstdcxx/DoxygenCPPInfo.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.libstdcxx/src/org/eclipse/linuxtools/internal/cdt/libhover/libstdcxx/DoxygenCPPInfo.java
@@ -223,7 +223,7 @@ public class DoxygenCPPInfo {
} else {
// We probably have a template that needs resolution
String baseClassName = n2.getTextContent();
-// System.out.println("base class name is " + baseClassName);
+// System.out.println("base class name is " + baseClassName);
baseClass = getClassInfo(baseClassName);
}
if (d != null && baseClass != null)
@@ -492,7 +492,7 @@ public class DoxygenCPPInfo {
* Create LibHoverInfo serialized output
*
* @param args (args[0] = location of Doxygen xml document to parse (file or URL),
- * args[1] = name of file to put serialized LibHoverInfo
+ * args[1] = name of file to put serialized LibHoverInfo
*/
public static void main(String[] args) {
URI acDoc;
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.libstdcxx/toc.xml b/libhover/org.eclipse.linuxtools.cdt.libhover.libstdcxx/toc.xml
index a4fc261cfd..9832a42561 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.libstdcxx/toc.xml
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.libstdcxx/toc.xml
@@ -2,6 +2,6 @@
<?NLS TYPE="org.eclipse.help.toc"?>
<toc label="libstdc++ library" link_to="../org.eclipse.linuxtools.cdt.libhover.library.docs/libraries.xml#moreclibdocs">
- <topic href="http://gcc.gnu.org/onlinedocs/libstdc++/manual/spine.html" label="libstdc++">
+ <topic href="http://gcc.gnu.org/onlinedocs/libstdc++/manual/spine.html" label="libstdc++">
</topic>
</toc>
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.newlib/toc.xml b/libhover/org.eclipse.linuxtools.cdt.libhover.newlib/toc.xml
index 706fa13083..cafe07363a 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.newlib/toc.xml
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.newlib/toc.xml
@@ -2,7 +2,7 @@
<?NLS TYPE="org.eclipse.help.toc"?>
<toc label="newlib library" link_to="../org.eclipse.linuxtools.cdt.libhover.library.docs/libraries.xml#moreclibdocs">
- <topic href="http://www.sourceware.org/newlib/libc.html" label="newlib libc">
+ <topic href="http://www.sourceware.org/newlib/libc.html" label="newlib libc">
</topic>
<topic href="http://www.sourceware.org/newlib/libm.html" label="newlib libm">
</topic>
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/build.xml b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/build.xml
index 9abc931009..77b8969e07 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/build.xml
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/build.xml
@@ -12,4 +12,3 @@
<javac srcdir="${src}" destdir="${build}" />
</target>
</project>
- \ No newline at end of file
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseAutoconfTexinfo.java b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseAutoconfTexinfo.java
index 00234c09b5..75ec68636e 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseAutoconfTexinfo.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseAutoconfTexinfo.java
@@ -32,614 +32,614 @@ import java.util.regex.Pattern;
public class ParseAutoconfTexinfo {
- static final boolean DEBUG = false;
-
- static final String ATcmd = "(@\\w*)";
-
- // 0
- static final String Defmac = "@defmac";
- static final String Defmacx = "@defmacx";
-
- // 1
- static final String MacroName = "(\\w*)";
- static final int MacroNameIndex = 1;
-
- // 2 3
- static final String Parms = "(\\((.*)\\))";
- static final int ParmsIndex = 2;
-
- static final String rest = ".*";
-
- static final String WhiteSpace = "\\s*";
-
- static final Pattern MacroPattern
- = Pattern.compile("^" + Defmac + WhiteSpace +
- MacroName + WhiteSpace +
- Parms +
- rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- static final Pattern MacroPattern2
- = Pattern.compile("^" + Defmac + WhiteSpace + MacroName + rest,
- Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- static final Pattern MacroPatternx
- = Pattern.compile("^" + Defmacx + WhiteSpace +
- MacroName + WhiteSpace +
- Parms +
- rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- static final Pattern MacroPatternx2
- = Pattern.compile("^" + Defmacx + WhiteSpace + MacroName + rest,
- Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- static final Pattern ParmBracketPattern = Pattern.compile("\\((.*)\\)");
- static final Pattern IndexPattern = Pattern.compile("@\\w*index\\s+[a-zA-Z0-9_@\\{\\}]*");
- static final Pattern IndexPattern2 = Pattern.compile("@\\w*index\\{[a-zA-Z0-9_@\\{\\}]*\\}");
- static final Pattern ExamplePattern = Pattern.compile("@example");
- static final Pattern EndExamplePattern = Pattern.compile("@end\\s+example");
- static final Pattern EnumeratePattern = Pattern.compile("@enumerate");
- static final Pattern EndEnumeratePattern = Pattern.compile("@end\\s+enumerate");
- static final Pattern VerbatimPattern = Pattern.compile("@verbatim");
- static final Pattern ItemPattern = Pattern.compile("@item");
- static final Pattern NoIndentPattern = Pattern.compile("@noindent");
- static final Pattern BRPattern = Pattern.compile("&lt;br&gt;");
- static final Pattern EOLPattern = Pattern.compile("&lt;eol&gt;");
- static final Pattern EndVerbatimPattern = Pattern.compile("@end\\s+verbatim");
- static final Pattern TableSampItemPattern = Pattern.compile("(@table\\s*@samp.*)@item\\s*([a-zA-Z_0-9+\\-<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
- static final Pattern TableAsisItemPattern = Pattern.compile("(@table\\s*@asis.*)@item\\s*([a-zA-Z_0-9+\\-,<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
- static final Pattern TableSampPattern = Pattern.compile("@table\\s*@samp", Pattern.MULTILINE);
- static final Pattern TableAsisPattern = Pattern.compile("@table\\s*@asis", Pattern.MULTILINE);
- static final Pattern EndTablePattern = Pattern.compile("@end\\s+table");
- static final Pattern DotsPattern = Pattern.compile("@dots\\{\\}");
- static final Pattern ItemizeMinusPattern= Pattern.compile("@itemize\\s+@minus" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
- static final Pattern ItemizeBulletPattern= Pattern.compile("@itemize\\s+@bullet" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
- static final Pattern XrefPattern = Pattern.compile("@xref\\{[^\\}]*\\}", Pattern.MULTILINE);
- static final Pattern CommandPattern = Pattern.compile("@command\\{([^\\}]*)\\}");
- static final Pattern KbdPattern = Pattern.compile("@kbd\\{([^\\}]*)\\}");
- static final Pattern RPattern = Pattern.compile("@r\\{([^\\}]*)\\}");
- static final Pattern FilePattern = Pattern.compile("@file\\{([^\\}]*)\\}");
- static final Pattern VarPattern = Pattern.compile("@var\\{([^\\}]*)\\}");
- static final Pattern OVarPattern = Pattern.compile("@ovar\\{([^\\}]*)\\}");
- static final Pattern DVarPattern = Pattern.compile("@dvar\\{([^\\},\\,]*),([^\\}]*)\\}");
- static final Pattern CodePattern = Pattern.compile("@code\\{([^\\}]*)\\}");
- static final Pattern EmphPattern = Pattern.compile("@emph\\{([^\\}]*)\\}");
- static final Pattern SampPattern = Pattern.compile("@samp\\{([^\\}]*)\\}");
- static final Pattern OptionPattern = Pattern.compile("@option\\{([^\\}]*)\\}");
- static final Pattern TagPattern = Pattern.compile("@\\w*\\{([^\\}]*)\\}");
- static final Pattern AmpersandPattern = Pattern.compile("&");
- static final Pattern LeftAnglePattern = Pattern.compile("<");
- static final Pattern RightAnglePattern = Pattern.compile(">");
-
-
- private static Map<String, MacroDef> macroMap;
-
- static class MacroParms {
- String[] parms;
- MacroParms nextParms = null;
-
- public MacroParms(String[] parms) {
- this.parms = parms;
- }
- }
-
- static class MacroDef {
- String MacroName;
- MacroParms Parameters;
- }
-
- static class TPElement {
- String Content;
- String Synopsis;
- }
-
- static class TPDef {
- String TPType;
- String TPName;
- String TPSynopsis;
- TPElement[] TPElements;
- Object[] IncludeList;
- }
-
- private static String killTagsParms(String tt) {
- Matcher mm;
-
- mm = ParmBracketPattern.matcher(tt);
- tt= mm.replaceAll("$1");
-
- mm = OVarPattern.matcher(tt);
- tt = mm.replaceAll("[$1]");
-
- mm = DVarPattern.matcher(tt);
- tt = mm.replaceAll("[$1=$2]");
-
- mm = VarPattern.matcher(tt);
- tt = mm.replaceAll("$1");
-
- mm = RPattern.matcher(tt);
- tt = mm.replaceAll("$1");
-
- mm = DotsPattern.matcher(tt);
- tt = mm.replaceAll("...");
-
- return tt;
- }
-
-
- private static String killTags(String tt) {
- Matcher mm;
- String ss = "";
-
- while (ss != tt) {
- mm = XrefPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = IndexPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = IndexPattern2.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = NoIndentPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = VarPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<VAR>$1</VAR>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = DotsPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<small>...</small>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = CommandPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<CODE>$1</CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = CodePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<CODE>$1</CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = KbdPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<KBD>$1</KBD>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EmphPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<EM>$1</EM>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = FilePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<TT>$1</TT>");
- }
-
-
- ss = "";
- while (ss != tt) {
- mm = VerbatimPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndVerbatimPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = SampPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<samp>$1</samp>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = OptionPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<samp>$1</samp>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = ExamplePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<TABLE><tr><td>&nbsp;</td><td class=example><pre>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndExamplePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</pre></td></tr></table>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EnumeratePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<OL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndEnumeratePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</OL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableSampItemPattern.matcher(tt);
- ss = tt;
- if (mm.matches()) {
- System.out.println("group 1 is " + mm.group(1));
- System.out.println("group 2 is " + mm.group(2));
- System.out.println("group 3 is " + mm.group(3));
- }
- tt = mm.replaceAll("$1<DT>'<SAMP>$2</SAMP>'\n<DD>$3");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableAsisItemPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1<DT>$2\n<DD>$3");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableSampPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<DL>\n");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableAsisPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<DL>\n");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndTablePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</DL>");
- }
-
- //FIXME: if there ever is a @itemize @bullet within a
- // @itemize @minus or vice-versa, the following
- // logic will get it wrong.
- ss = "";
- while (ss != tt) {
- mm = ItemizeMinusPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<UL>$1</UL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = ItemizeBulletPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<OL>$1</OL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = ItemPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<LI>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TagPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1");
- }
-
- mm = AmpersandPattern.matcher(tt);
- tt = mm.replaceAll("&amp;");
-
- mm = LeftAnglePattern.matcher(tt);
- tt = mm.replaceAll("&lt;");
-
- mm = RightAnglePattern.matcher(tt);
- tt = mm.replaceAll("&gt;");
-
- // Clean up the eol markers we used to mark end of line for items
- mm = EOLPattern.matcher(tt);
- tt = mm.replaceAll("");
-
- return tt;
- }
-
- private static MacroDef BuildMacroDef(Matcher m) {
- MacroDef md = new MacroDef();
-
- md.MacroName = m.group(MacroNameIndex);
-
- if (null != m.group(ParmsIndex)) {
- String tt = killTagsParms(m.group(ParmsIndex));
- String[] parms = tt.split(",\\s");
- md.Parameters = new MacroParms(parms);
- }
- return md;
- }
-
- private static MacroParms AddMacroDefxParms(MacroParms mp, Matcher mx) {
- if (null != mx.group(ParmsIndex)) {
- String tt = killTagsParms(mx.group(ParmsIndex));
- String[] parms = tt.split(",\\s");
- MacroParms mpnew = new MacroParms(parms);
- mp.nextParms = mpnew;
- return mpnew;
- }
- return null;
- }
-
- private static MacroDef HandleMacroDef(BufferedReader is, String s) throws IOException {
- MacroDef fd = null;
-
- Matcher m = MacroPattern.matcher(s);
-
- if (m.matches()) {
- fd = BuildMacroDef(m);
- }
- else { // assume the line got split and retry
- is.mark(100);
- String il = is.readLine();
- m = MacroPattern.matcher(s + il);
- if (m.matches()) fd = BuildMacroDef(m);
- else {
- is.reset();
- m = MacroPattern2.matcher(s);
- if (m.matches()) {
- fd = new MacroDef();
- fd.MacroName = m.group(MacroNameIndex);
- fd.Parameters = new MacroParms(new String[0]);
- }
- }
- }
-
- if (fd != null) {
- // Look for @defmacx which are alternate prototypes for the macro
- is.mark(100);
- String il = is.readLine();
- if (il != null) {
- Matcher mx = MacroPatternx.matcher(il);
- Matcher mx2 = MacroPatternx2.matcher(il);
- MacroParms mp = fd.Parameters;
- while (mx.matches() || mx2.matches()) {
- if (mx.matches())
- mp = AddMacroDefxParms(mp, mx);
- else {
- MacroParms mpnew = new MacroParms(new String[0]);
- mp.nextParms = mpnew;
- mp = mpnew;
- }
- is.mark(100);
- il = is.readLine();
- if (il != null) {
- mx = MacroPatternx.matcher(il);
- mx2 = MacroPatternx2.matcher(il);
- }
- }
- is.reset();
- }
-
- if (macroMap.get(fd.MacroName) != null)
- return null;
- macroMap.put(fd.MacroName, fd);
- }
-
- return fd;
- }
-
- private static void WriteString(BufferedWriter os, String s) throws IOException {
- // System.out.println(s);
- os.write(s+"\n", 0, 1+s.length());
- }
-
+ static final boolean DEBUG = false;
+
+ static final String ATcmd = "(@\\w*)";
+
+ // 0
+ static final String Defmac = "@defmac";
+ static final String Defmacx = "@defmacx";
+
+ // 1
+ static final String MacroName = "(\\w*)";
+ static final int MacroNameIndex = 1;
+
+ // 2 3
+ static final String Parms = "(\\((.*)\\))";
+ static final int ParmsIndex = 2;
+
+ static final String rest = ".*";
+
+ static final String WhiteSpace = "\\s*";
+
+ static final Pattern MacroPattern
+ = Pattern.compile("^" + Defmac + WhiteSpace +
+ MacroName + WhiteSpace +
+ Parms +
+ rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ static final Pattern MacroPattern2
+ = Pattern.compile("^" + Defmac + WhiteSpace + MacroName + rest,
+ Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ static final Pattern MacroPatternx
+ = Pattern.compile("^" + Defmacx + WhiteSpace +
+ MacroName + WhiteSpace +
+ Parms +
+ rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ static final Pattern MacroPatternx2
+ = Pattern.compile("^" + Defmacx + WhiteSpace + MacroName + rest,
+ Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ static final Pattern ParmBracketPattern = Pattern.compile("\\((.*)\\)");
+ static final Pattern IndexPattern = Pattern.compile("@\\w*index\\s+[a-zA-Z0-9_@\\{\\}]*");
+ static final Pattern IndexPattern2 = Pattern.compile("@\\w*index\\{[a-zA-Z0-9_@\\{\\}]*\\}");
+ static final Pattern ExamplePattern = Pattern.compile("@example");
+ static final Pattern EndExamplePattern = Pattern.compile("@end\\s+example");
+ static final Pattern EnumeratePattern = Pattern.compile("@enumerate");
+ static final Pattern EndEnumeratePattern = Pattern.compile("@end\\s+enumerate");
+ static final Pattern VerbatimPattern = Pattern.compile("@verbatim");
+ static final Pattern ItemPattern = Pattern.compile("@item");
+ static final Pattern NoIndentPattern = Pattern.compile("@noindent");
+ static final Pattern BRPattern = Pattern.compile("&lt;br&gt;");
+ static final Pattern EOLPattern = Pattern.compile("&lt;eol&gt;");
+ static final Pattern EndVerbatimPattern = Pattern.compile("@end\\s+verbatim");
+ static final Pattern TableSampItemPattern = Pattern.compile("(@table\\s*@samp.*)@item\\s*([a-zA-Z_0-9+\\-<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
+ static final Pattern TableAsisItemPattern = Pattern.compile("(@table\\s*@asis.*)@item\\s*([a-zA-Z_0-9+\\-,<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
+ static final Pattern TableSampPattern = Pattern.compile("@table\\s*@samp", Pattern.MULTILINE);
+ static final Pattern TableAsisPattern = Pattern.compile("@table\\s*@asis", Pattern.MULTILINE);
+ static final Pattern EndTablePattern = Pattern.compile("@end\\s+table");
+ static final Pattern DotsPattern = Pattern.compile("@dots\\{\\}");
+ static final Pattern ItemizeMinusPattern= Pattern.compile("@itemize\\s+@minus" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
+ static final Pattern ItemizeBulletPattern= Pattern.compile("@itemize\\s+@bullet" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
+ static final Pattern XrefPattern = Pattern.compile("@xref\\{[^\\}]*\\}", Pattern.MULTILINE);
+ static final Pattern CommandPattern = Pattern.compile("@command\\{([^\\}]*)\\}");
+ static final Pattern KbdPattern = Pattern.compile("@kbd\\{([^\\}]*)\\}");
+ static final Pattern RPattern = Pattern.compile("@r\\{([^\\}]*)\\}");
+ static final Pattern FilePattern = Pattern.compile("@file\\{([^\\}]*)\\}");
+ static final Pattern VarPattern = Pattern.compile("@var\\{([^\\}]*)\\}");
+ static final Pattern OVarPattern = Pattern.compile("@ovar\\{([^\\}]*)\\}");
+ static final Pattern DVarPattern = Pattern.compile("@dvar\\{([^\\},\\,]*),([^\\}]*)\\}");
+ static final Pattern CodePattern = Pattern.compile("@code\\{([^\\}]*)\\}");
+ static final Pattern EmphPattern = Pattern.compile("@emph\\{([^\\}]*)\\}");
+ static final Pattern SampPattern = Pattern.compile("@samp\\{([^\\}]*)\\}");
+ static final Pattern OptionPattern = Pattern.compile("@option\\{([^\\}]*)\\}");
+ static final Pattern TagPattern = Pattern.compile("@\\w*\\{([^\\}]*)\\}");
+ static final Pattern AmpersandPattern = Pattern.compile("&");
+ static final Pattern LeftAnglePattern = Pattern.compile("<");
+ static final Pattern RightAnglePattern = Pattern.compile(">");
+
+
+ private static Map<String, MacroDef> macroMap;
+
+ static class MacroParms {
+ String[] parms;
+ MacroParms nextParms = null;
+
+ public MacroParms(String[] parms) {
+ this.parms = parms;
+ }
+ }
+
+ static class MacroDef {
+ String MacroName;
+ MacroParms Parameters;
+ }
+
+ static class TPElement {
+ String Content;
+ String Synopsis;
+ }
+
+ static class TPDef {
+ String TPType;
+ String TPName;
+ String TPSynopsis;
+ TPElement[] TPElements;
+ Object[] IncludeList;
+ }
+
+ private static String killTagsParms(String tt) {
+ Matcher mm;
+
+ mm = ParmBracketPattern.matcher(tt);
+ tt= mm.replaceAll("$1");
+
+ mm = OVarPattern.matcher(tt);
+ tt = mm.replaceAll("[$1]");
+
+ mm = DVarPattern.matcher(tt);
+ tt = mm.replaceAll("[$1=$2]");
+
+ mm = VarPattern.matcher(tt);
+ tt = mm.replaceAll("$1");
+
+ mm = RPattern.matcher(tt);
+ tt = mm.replaceAll("$1");
+
+ mm = DotsPattern.matcher(tt);
+ tt = mm.replaceAll("...");
+
+ return tt;
+ }
+
+
+ private static String killTags(String tt) {
+ Matcher mm;
+ String ss = "";
+
+ while (ss != tt) {
+ mm = XrefPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = IndexPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = IndexPattern2.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = NoIndentPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = VarPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<VAR>$1</VAR>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = DotsPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<small>...</small>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = CommandPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<CODE>$1</CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = CodePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<CODE>$1</CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = KbdPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<KBD>$1</KBD>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EmphPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<EM>$1</EM>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = FilePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<TT>$1</TT>");
+ }
+
+
+ ss = "";
+ while (ss != tt) {
+ mm = VerbatimPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndVerbatimPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = SampPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<samp>$1</samp>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = OptionPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<samp>$1</samp>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = ExamplePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<TABLE><tr><td>&nbsp;</td><td class=example><pre>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndExamplePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</pre></td></tr></table>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EnumeratePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<OL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndEnumeratePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</OL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableSampItemPattern.matcher(tt);
+ ss = tt;
+ if (mm.matches()) {
+ System.out.println("group 1 is " + mm.group(1));
+ System.out.println("group 2 is " + mm.group(2));
+ System.out.println("group 3 is " + mm.group(3));
+ }
+ tt = mm.replaceAll("$1<DT>'<SAMP>$2</SAMP>'\n<DD>$3");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableAsisItemPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1<DT>$2\n<DD>$3");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableSampPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<DL>\n");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableAsisPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<DL>\n");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndTablePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</DL>");
+ }
+
+ //FIXME: if there ever is a @itemize @bullet within a
+ // @itemize @minus or vice-versa, the following
+ // logic will get it wrong.
+ ss = "";
+ while (ss != tt) {
+ mm = ItemizeMinusPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<UL>$1</UL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = ItemizeBulletPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<OL>$1</OL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = ItemPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<LI>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TagPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1");
+ }
+
+ mm = AmpersandPattern.matcher(tt);
+ tt = mm.replaceAll("&amp;");
+
+ mm = LeftAnglePattern.matcher(tt);
+ tt = mm.replaceAll("&lt;");
+
+ mm = RightAnglePattern.matcher(tt);
+ tt = mm.replaceAll("&gt;");
+
+ // Clean up the eol markers we used to mark end of line for items
+ mm = EOLPattern.matcher(tt);
+ tt = mm.replaceAll("");
+
+ return tt;
+ }
+
+ private static MacroDef BuildMacroDef(Matcher m) {
+ MacroDef md = new MacroDef();
+
+ md.MacroName = m.group(MacroNameIndex);
+
+ if (null != m.group(ParmsIndex)) {
+ String tt = killTagsParms(m.group(ParmsIndex));
+ String[] parms = tt.split(",\\s");
+ md.Parameters = new MacroParms(parms);
+ }
+ return md;
+ }
+
+ private static MacroParms AddMacroDefxParms(MacroParms mp, Matcher mx) {
+ if (null != mx.group(ParmsIndex)) {
+ String tt = killTagsParms(mx.group(ParmsIndex));
+ String[] parms = tt.split(",\\s");
+ MacroParms mpnew = new MacroParms(parms);
+ mp.nextParms = mpnew;
+ return mpnew;
+ }
+ return null;
+ }
+
+ private static MacroDef HandleMacroDef(BufferedReader is, String s) throws IOException {
+ MacroDef fd = null;
+
+ Matcher m = MacroPattern.matcher(s);
+
+ if (m.matches()) {
+ fd = BuildMacroDef(m);
+ }
+ else { // assume the line got split and retry
+ is.mark(100);
+ String il = is.readLine();
+ m = MacroPattern.matcher(s + il);
+ if (m.matches()) fd = BuildMacroDef(m);
+ else {
+ is.reset();
+ m = MacroPattern2.matcher(s);
+ if (m.matches()) {
+ fd = new MacroDef();
+ fd.MacroName = m.group(MacroNameIndex);
+ fd.Parameters = new MacroParms(new String[0]);
+ }
+ }
+ }
+
+ if (fd != null) {
+ // Look for @defmacx which are alternate prototypes for the macro
+ is.mark(100);
+ String il = is.readLine();
+ if (il != null) {
+ Matcher mx = MacroPatternx.matcher(il);
+ Matcher mx2 = MacroPatternx2.matcher(il);
+ MacroParms mp = fd.Parameters;
+ while (mx.matches() || mx2.matches()) {
+ if (mx.matches())
+ mp = AddMacroDefxParms(mp, mx);
+ else {
+ MacroParms mpnew = new MacroParms(new String[0]);
+ mp.nextParms = mpnew;
+ mp = mpnew;
+ }
+ is.mark(100);
+ il = is.readLine();
+ if (il != null) {
+ mx = MacroPatternx.matcher(il);
+ mx2 = MacroPatternx2.matcher(il);
+ }
+ }
+ is.reset();
+ }
+
+ if (macroMap.get(fd.MacroName) != null)
+ return null;
+ macroMap.put(fd.MacroName, fd);
+ }
+
+ return fd;
+ }
+
+ private static void WriteString(BufferedWriter os, String s) throws IOException {
+ // System.out.println(s);
+ os.write(s+"\n", 0, 1+s.length());
+ }
+
private static void CreateHeader(BufferedWriter os) throws IOException {
- WriteString(os, "<!-- This file automatically generated by ParseAutoconfTexinfo utility -->");
- WriteString(os, "<!-- cvs -d:pserver:anonymous@sources.redhat.com:/cvs/eclipse \\ -->");
- WriteString(os, "<!-- co autotools/ParseTexinfo -->");
- WriteString(os, "<!DOCTYPE macros [");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT macros (macro)*>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT macro (prototype*,synopsis)>");
- WriteString(os, " <!ATTLIST macro");
- WriteString(os, " id ID #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT synopsis (#PCDATA)*>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT prototype (parameter+)?>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT parameter (#PCDATA)*>");
- WriteString(os, " <!ATTLIST parameter");
- WriteString(os, " content CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, "]>");
- WriteString(os, "");
+ WriteString(os, "<!-- This file automatically generated by ParseAutoconfTexinfo utility -->");
+ WriteString(os, "<!-- cvs -d:pserver:anonymous@sources.redhat.com:/cvs/eclipse \\ -->");
+ WriteString(os, "<!-- co autotools/ParseTexinfo -->");
+ WriteString(os, "<!DOCTYPE macros [");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT macros (macro)*>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT macro (prototype*,synopsis)>");
+ WriteString(os, " <!ATTLIST macro");
+ WriteString(os, " id ID #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT synopsis (#PCDATA)*>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT prototype (parameter+)?>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT parameter (#PCDATA)*>");
+ WriteString(os, " <!ATTLIST parameter");
+ WriteString(os, " content CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, "]>");
+ WriteString(os, "");
}
- private static void CreateTrailer(BufferedWriter os) throws IOException {
- WriteString(os, "</macros>");
- }
-
- private static void WriteSynopsis(BufferedWriter os, String Synopsis, boolean indent) throws IOException {
- String ss = killTags(Synopsis);
- String[] tt = ss.split("\\s");
- String aa = "";
- String spaces = indent ? " " : " ";
- WriteString(os, spaces + "<synopsis>");
- if (null != Synopsis) {
- for (int pp = 0; pp < tt.length; pp++) {
- if (tt[pp].equals("&lt;br&gt;")) {
- WriteString(os, spaces + aa + "&lt;/P&gt;&lt;P&gt;\n");
- aa = "";
- }
- else {
- if ((aa.length() + tt[pp].length()) > 64) {
- WriteString(os, spaces + aa);
- aa = "";
- }
- aa = aa + " " + tt[pp];
- }
- }
- }
- if (aa.length() > 0) WriteString(os, " " + aa);
- WriteString(os, spaces + "</synopsis>");
- }
-
- private static void HandleDefmacro(BufferedWriter os, BufferedReader is, String s) throws IOException {
- String il;
- MacroDef md;
- List<MacroDef> FDefs = new ArrayList<MacroDef>();
- String Synopsis = null;
-
- if (null != (md = HandleMacroDef(is, s))) FDefs.add(md);
-
- while (null != (il = is.readLine())) {
- if (il.startsWith("@defmac")) {
- if (null != (md = HandleMacroDef(is, il))) FDefs.add(md);
- }
- else if (il.startsWith("@comment") ||
- il.startsWith("@c ")) { // comment -- ignore it
- }
- else if (il.startsWith("@end defmac")) {
- for (int kk = 0; kk < FDefs.size(); kk++) {
- md = (MacroDef)FDefs.get(kk);
-
- WriteString(os, " <macro id=\"" + md.MacroName + "\">");
-
- MacroParms mp = md.Parameters;
- do {
- WriteString(os, " <prototype>");
- String[] parms = mp.parms;
- for (int i = 0; i < parms.length; i++) {
- WriteString(os, " <parameter content=\"" + parms[i] + "\"/>");
- }
- WriteString(os, " </prototype>");
- mp = mp.nextParms;
- } while (mp != null);
-
- if (null != Synopsis) WriteSynopsis(os, Synopsis, false);
-
- WriteString(os, " </macro>");
- }
- return;
- }
- else {
- Synopsis = ((Synopsis == null) ? "" : Synopsis + " " ) + ((il.length() == 0) ? "<br>" :
- il.startsWith("@item") ? il + "<eol>" : il);
-
- }
- }
- FDefs.clear();
-
- }
-
- private static class OnlyTexi implements FilenameFilter {
- public boolean accept(File dir, String s) {
- return (s.endsWith(".texi")) ? true : false;
- }
- }
-
- public static void BuildXMLFromTexinfo(String srcdir, String dstdir) {
- try {
- macroMap = new HashMap<String, MacroDef>();
- BufferedWriter os = new BufferedWriter(new FileWriter(dstdir));
-
- CreateHeader(os);
-// CreateLicense(os);
-
- WriteString(os, "<macros>");
-
- try {
- String[] dir = new java.io.File(srcdir).list(new OnlyTexi());
- for (int i = 0; i < dir.length; i++) {
- String qFile = srcdir.endsWith("/")
- ? srcdir + dir[i]
- : srcdir + "/" + dir[i];
-
- try {
- BufferedReader is = new BufferedReader(new FileReader(qFile));
- String il;
-
- while (null != (il = is.readLine())) {
- if (il.startsWith("@defmac")) { // handle @defmac x]
- HandleDefmacro(os, is, il);
- }
- }
- is.close();
- }
- catch (IOException e) {
- System.out.println("Input File IOException: " + e);
- return;
- }
- }
- }
- catch (NullPointerException e) {
- System.out.println("NullPointerException: " + e);
- return;
- }
-
- CreateTrailer(os);
-
- os.close();
- }
- catch (IOException e) {
- System.out.println("Output File IOException: " + e);
- return;
- }
- }
-
- public static void main(String[] args) {
- // arg[0] is input directory containing .texi documents to read
- // arg[1] is output xml file to create
- BuildXMLFromTexinfo(args[0], args[1]);
- }
+ private static void CreateTrailer(BufferedWriter os) throws IOException {
+ WriteString(os, "</macros>");
+ }
+
+ private static void WriteSynopsis(BufferedWriter os, String Synopsis, boolean indent) throws IOException {
+ String ss = killTags(Synopsis);
+ String[] tt = ss.split("\\s");
+ String aa = "";
+ String spaces = indent ? " " : " ";
+ WriteString(os, spaces + "<synopsis>");
+ if (null != Synopsis) {
+ for (int pp = 0; pp < tt.length; pp++) {
+ if (tt[pp].equals("&lt;br&gt;")) {
+ WriteString(os, spaces + aa + "&lt;/P&gt;&lt;P&gt;\n");
+ aa = "";
+ }
+ else {
+ if ((aa.length() + tt[pp].length()) > 64) {
+ WriteString(os, spaces + aa);
+ aa = "";
+ }
+ aa = aa + " " + tt[pp];
+ }
+ }
+ }
+ if (aa.length() > 0) WriteString(os, " " + aa);
+ WriteString(os, spaces + "</synopsis>");
+ }
+
+ private static void HandleDefmacro(BufferedWriter os, BufferedReader is, String s) throws IOException {
+ String il;
+ MacroDef md;
+ List<MacroDef> FDefs = new ArrayList<MacroDef>();
+ String Synopsis = null;
+
+ if (null != (md = HandleMacroDef(is, s))) FDefs.add(md);
+
+ while (null != (il = is.readLine())) {
+ if (il.startsWith("@defmac")) {
+ if (null != (md = HandleMacroDef(is, il))) FDefs.add(md);
+ }
+ else if (il.startsWith("@comment") ||
+ il.startsWith("@c ")) { // comment -- ignore it
+ }
+ else if (il.startsWith("@end defmac")) {
+ for (int kk = 0; kk < FDefs.size(); kk++) {
+ md = (MacroDef)FDefs.get(kk);
+
+ WriteString(os, " <macro id=\"" + md.MacroName + "\">");
+
+ MacroParms mp = md.Parameters;
+ do {
+ WriteString(os, " <prototype>");
+ String[] parms = mp.parms;
+ for (int i = 0; i < parms.length; i++) {
+ WriteString(os, " <parameter content=\"" + parms[i] + "\"/>");
+ }
+ WriteString(os, " </prototype>");
+ mp = mp.nextParms;
+ } while (mp != null);
+
+ if (null != Synopsis) WriteSynopsis(os, Synopsis, false);
+
+ WriteString(os, " </macro>");
+ }
+ return;
+ }
+ else {
+ Synopsis = ((Synopsis == null) ? "" : Synopsis + " " ) + ((il.length() == 0) ? "<br>" :
+ il.startsWith("@item") ? il + "<eol>" : il);
+
+ }
+ }
+ FDefs.clear();
+
+ }
+
+ private static class OnlyTexi implements FilenameFilter {
+ public boolean accept(File dir, String s) {
+ return (s.endsWith(".texi")) ? true : false;
+ }
+ }
+
+ public static void BuildXMLFromTexinfo(String srcdir, String dstdir) {
+ try {
+ macroMap = new HashMap<String, MacroDef>();
+ BufferedWriter os = new BufferedWriter(new FileWriter(dstdir));
+
+ CreateHeader(os);
+// CreateLicense(os);
+
+ WriteString(os, "<macros>");
+
+ try {
+ String[] dir = new java.io.File(srcdir).list(new OnlyTexi());
+ for (int i = 0; i < dir.length; i++) {
+ String qFile = srcdir.endsWith("/")
+ ? srcdir + dir[i]
+ : srcdir + "/" + dir[i];
+
+ try {
+ BufferedReader is = new BufferedReader(new FileReader(qFile));
+ String il;
+
+ while (null != (il = is.readLine())) {
+ if (il.startsWith("@defmac")) { // handle @defmac x]
+ HandleDefmacro(os, is, il);
+ }
+ }
+ is.close();
+ }
+ catch (IOException e) {
+ System.out.println("Input File IOException: " + e);
+ return;
+ }
+ }
+ }
+ catch (NullPointerException e) {
+ System.out.println("NullPointerException: " + e);
+ return;
+ }
+
+ CreateTrailer(os);
+
+ os.close();
+ }
+ catch (IOException e) {
+ System.out.println("Output File IOException: " + e);
+ return;
+ }
+ }
+
+ public static void main(String[] args) {
+ // arg[0] is input directory containing .texi documents to read
+ // arg[1] is output xml file to create
+ BuildXMLFromTexinfo(args[0], args[1]);
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseAutomakeTexinfo.java b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseAutomakeTexinfo.java
index c61adc026a..602ccf3ec4 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseAutomakeTexinfo.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseAutomakeTexinfo.java
@@ -32,630 +32,630 @@ import java.util.regex.Pattern;
public class ParseAutomakeTexinfo {
- static final boolean DEBUG = false;
-
- static final String ATcmd = "(@\\w*)";
-
- // Currently in automake docs, the macro section starts with
- // a subsection as below and a table which contains macros which
- // are item and itemx entries.
- static final String MacrosStart = "@subsection\\sPublic\\smacros";
- static final String OldMacrosStart = "@section\\sAutoconf\\smacros.*";
- static final Pattern MacroSection1 = Pattern.compile(MacrosStart);
- static final Pattern MacroSection2 = Pattern.compile(OldMacrosStart);
- // 0
- static final String Defmac = "@item";
- static final String Defmacx = "@itemx";
-
- // 1
- static final String MacroName = "(\\w*)";
- static final int MacroNameIndex = 1;
-
- // 2 3
- static final String Parms = "(\\((.*)\\))";
- static final int ParmsIndex = 2;
-
- static final String rest = ".*";
-
- static final String WhiteSpace = "\\s*";
-
- static final Pattern MacroPattern
- = Pattern.compile("^" + Defmac + WhiteSpace +
- MacroName + WhiteSpace +
- Parms +
- rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- static final Pattern MacroPattern2
- = Pattern.compile("^" + Defmac + WhiteSpace + MacroName + rest,
- Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- static final Pattern MacroPatternx
- = Pattern.compile("^" + Defmacx + WhiteSpace +
- MacroName + WhiteSpace +
- Parms +
- rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- static final Pattern MacroPatternx2
- = Pattern.compile("^" + Defmacx + WhiteSpace + MacroName + rest,
- Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- static final Pattern ParmBracketPattern = Pattern.compile("\\((.*)\\)");
- static final Pattern IndexPattern = Pattern.compile("@\\w*index.*");
- static final Pattern IndexPattern2 = Pattern.compile("@\\w*index\\{[a-zA-Z0-9_@\\{\\}]*\\}");
- static final Pattern ExamplePattern = Pattern.compile("@example");
- static final Pattern EndExamplePattern = Pattern.compile("@end\\s+example");
- static final Pattern EnumeratePattern = Pattern.compile("@enumerate");
- static final Pattern EndEnumeratePattern = Pattern.compile("@end\\s+enumerate");
- static final Pattern VerbatimPattern = Pattern.compile("@verbatim");
- static final Pattern ItemPattern = Pattern.compile("@item");
- static final Pattern NoIndentPattern = Pattern.compile("@noindent");
- static final Pattern BRPattern = Pattern.compile("&lt;br&gt;");
- static final Pattern EOLPattern = Pattern.compile("&lt;eol&gt;");
- static final Pattern EndVerbatimPattern = Pattern.compile("@end\\s+verbatim");
- static final Pattern TableSampItemPattern = Pattern.compile("(@table\\s*@samp.*)@item\\s*([a-zA-Z_0-9+\\-<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
- static final Pattern TableAsisItemPattern = Pattern.compile("(@table\\s*@asis.*)@item\\s*([a-zA-Z_0-9+\\-,<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
- static final Pattern TableSampPattern = Pattern.compile("@table\\s*@samp", Pattern.MULTILINE);
- static final Pattern TableAsisPattern = Pattern.compile("@table\\s*@asis", Pattern.MULTILINE);
- static final Pattern EndTablePattern = Pattern.compile("@end\\s+table");
- static final Pattern DotsPattern = Pattern.compile("@dots\\{\\}");
- static final Pattern ItemizeMinusPattern= Pattern.compile("@itemize\\s+@minus" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
- static final Pattern ItemizeBulletPattern= Pattern.compile("@itemize\\s+@bullet" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
- static final Pattern XrefPattern = Pattern.compile("@xref\\{[^\\}]*\\}", Pattern.MULTILINE);
- static final Pattern CommandPattern = Pattern.compile("@command\\{([^\\}]*)\\}");
- static final Pattern KbdPattern = Pattern.compile("@kbd\\{([^\\}]*)\\}");
- static final Pattern RPattern = Pattern.compile("@r\\{([^\\}]*)\\}");
- static final Pattern FilePattern = Pattern.compile("@file\\{([^\\}]*)\\}");
- static final Pattern VarPattern = Pattern.compile("@var\\{([^\\}]*)\\}");
- static final Pattern OVarPattern = Pattern.compile("@ovar\\{([^\\}]*)\\}");
- static final Pattern DVarPattern = Pattern.compile("@dvar\\{([^\\},\\,]*),([^\\}]*)\\}");
- static final Pattern CodePattern = Pattern.compile("@code\\{([^\\}]*)\\}");
- static final Pattern EmphPattern = Pattern.compile("@emph\\{([^\\}]*)\\}");
- static final Pattern SampPattern = Pattern.compile("@samp\\{([^\\}]*)\\}");
- static final Pattern OptionPattern = Pattern.compile("@option\\{([^\\}]*)\\}");
- static final Pattern UrefPattern = Pattern.compile("@uref\\{([^,]*),\\s+([^\\}]*)\\}");
- static final Pattern TagPattern = Pattern.compile("@\\w*\\{([^\\}]*)\\}");
- static final Pattern AmpersandPattern = Pattern.compile("&");
- static final Pattern LeftAnglePattern = Pattern.compile("<");
- static final Pattern RightAnglePattern = Pattern.compile(">");
-
-
- private static Map macroMap;
-
- static class MacroParms {
- String[] parms;
- MacroParms nextParms = null;
-
- public MacroParms(String[] parms) {
- this.parms = parms;
- }
- }
-
- static class MacroDef {
- String MacroName;
- MacroParms Parameters;
- String Synopsis;
- }
-
- static class TPElement {
- String Content;
- String Synopsis;
- }
-
- static class TPDef {
- String TPType;
- String TPName;
- String TPSynopsis;
- TPElement[] TPElements;
- Object[] IncludeList;
- }
-
- private static String killTagsParms(String tt) {
- Matcher mm;
-
- mm = ParmBracketPattern.matcher(tt);
- tt= mm.replaceAll("$1");
-
- mm = OVarPattern.matcher(tt);
- tt = mm.replaceAll("[$1]");
-
- mm = DVarPattern.matcher(tt);
- tt = mm.replaceAll("[$1=$2]");
-
- mm = VarPattern.matcher(tt);
- tt = mm.replaceAll("$1");
-
- mm = RPattern.matcher(tt);
- tt = mm.replaceAll("$1");
-
- mm = DotsPattern.matcher(tt);
- tt = mm.replaceAll("...");
-
- return tt;
- }
-
-
- private static String killTags(String tt) {
- Matcher mm;
- String ss = "";
-
- while (ss != tt) {
- mm = XrefPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = IndexPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = IndexPattern2.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = NoIndentPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = VarPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<VAR>$1</VAR>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = DotsPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<small>...</small>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = CommandPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<CODE>$1</CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = CodePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<CODE>$1</CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = UrefPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<A HREF=\"$1>$2</A>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = KbdPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<KBD>$1</KBD>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EmphPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<EM>$1</EM>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = FilePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<TT>$1</TT>");
- }
-
-
- ss = "";
- while (ss != tt) {
- mm = VerbatimPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndVerbatimPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = SampPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<samp>$1</samp>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = OptionPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<samp>$1</samp>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = ExamplePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<TABLE><tr><td>&nbsp;</td><td class=example><pre>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndExamplePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</pre></td></tr></table>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EnumeratePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<OL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndEnumeratePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</OL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableSampItemPattern.matcher(tt);
- ss = tt;
- if (mm.matches()) {
- System.out.println("group 1 is " + mm.group(1));
- System.out.println("group 2 is " + mm.group(2));
- System.out.println("group 3 is " + mm.group(3));
- }
- tt = mm.replaceAll("$1<DT>'<SAMP>$2</SAMP>'\n<DD>$3");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableAsisItemPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1<DT>$2\n<DD>$3");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableSampPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<DL>\n");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableAsisPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<DL>\n");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndTablePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</DL>");
- }
-
- //FIXME: if there ever is a @itemize @bullet within a
- // @itemize @minus or vice-versa, the following
- // logic will get it wrong.
- ss = "";
- while (ss != tt) {
- mm = ItemizeMinusPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<UL>$1</UL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = ItemizeBulletPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<OL>$1</OL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = ItemPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<LI>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TagPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1");
- }
-
- mm = AmpersandPattern.matcher(tt);
- tt = mm.replaceAll("&amp;");
-
- mm = LeftAnglePattern.matcher(tt);
- tt = mm.replaceAll("&lt;");
-
- mm = RightAnglePattern.matcher(tt);
- tt = mm.replaceAll("&gt;");
-
- // Clean up the eol markers we used to mark end of line for items
- mm = EOLPattern.matcher(tt);
- tt = mm.replaceAll("");
-
- return tt;
- }
-
- private static MacroDef BuildMacroDef(Matcher m) {
- MacroDef md = new MacroDef();
-
- md.MacroName = m.group(MacroNameIndex);
-
- if (null != m.group(ParmsIndex)) {
- String tt = killTagsParms(m.group(ParmsIndex));
- String[] parms = tt.split(",\\s");
- md.Parameters = new MacroParms(parms);
- }
- return md;
- }
-
- private static MacroParms AddMacroDefxParms(MacroParms mp, Matcher mx) {
- if (null != mx.group(ParmsIndex)) {
- String tt = killTagsParms(mx.group(ParmsIndex));
- String[] parms = tt.split(",\\s");
- MacroParms mpnew = new MacroParms(parms);
- mp.nextParms = mpnew;
- return mpnew;
- }
- return null;
- }
-
- private static MacroDef HandleMacroDef(BufferedReader is, String s) throws IOException {
- MacroDef fd = null;
-
- Matcher m = MacroPattern.matcher(s);
-
- if (m.matches()) {
- fd = BuildMacroDef(m);
- }
- else { // assume the line got split and retry
- is.mark(100);
- String il = is.readLine();
- m = MacroPattern.matcher(s + il);
- if (m.matches()) fd = BuildMacroDef(m);
- else {
- is.reset();
- m = MacroPattern2.matcher(s);
- if (m.matches()) {
- fd = new MacroDef();
- fd.MacroName = m.group(MacroNameIndex);
- fd.Parameters = new MacroParms(new String[0]);
- }
- }
- }
-
- if (fd != null) {
- // Look for @defmacx which are alternate prototypes for the macro
- is.mark(100);
- String il = is.readLine();
- if (il != null) {
- Matcher mx = MacroPatternx.matcher(il);
- Matcher mx2 = MacroPatternx2.matcher(il);
- MacroParms mp = fd.Parameters;
- while (mx.matches() || mx2.matches()) {
- if (mx.matches())
- mp = AddMacroDefxParms(mp, mx);
- else {
- MacroParms mpnew = new MacroParms(new String[0]);
- mp.nextParms = mpnew;
- mp = mpnew;
- }
- is.mark(100);
- il = is.readLine();
- if (il != null) {
- mx = MacroPatternx.matcher(il);
- mx2 = MacroPatternx2.matcher(il);
- }
- }
- is.reset();
- }
-
- if (macroMap.get(fd.MacroName) != null)
- return null;
- macroMap.put(fd.MacroName, fd);
- }
-
- return fd;
- }
-
- private static void WriteString(BufferedWriter os, String s) throws IOException {
- // System.out.println(s);
- os.write(s+"\n", 0, 1+s.length());
- }
-
+ static final boolean DEBUG = false;
+
+ static final String ATcmd = "(@\\w*)";
+
+ // Currently in automake docs, the macro section starts with
+ // a subsection as below and a table which contains macros which
+ // are item and itemx entries.
+ static final String MacrosStart = "@subsection\\sPublic\\smacros";
+ static final String OldMacrosStart = "@section\\sAutoconf\\smacros.*";
+ static final Pattern MacroSection1 = Pattern.compile(MacrosStart);
+ static final Pattern MacroSection2 = Pattern.compile(OldMacrosStart);
+ // 0
+ static final String Defmac = "@item";
+ static final String Defmacx = "@itemx";
+
+ // 1
+ static final String MacroName = "(\\w*)";
+ static final int MacroNameIndex = 1;
+
+ // 2 3
+ static final String Parms = "(\\((.*)\\))";
+ static final int ParmsIndex = 2;
+
+ static final String rest = ".*";
+
+ static final String WhiteSpace = "\\s*";
+
+ static final Pattern MacroPattern
+ = Pattern.compile("^" + Defmac + WhiteSpace +
+ MacroName + WhiteSpace +
+ Parms +
+ rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ static final Pattern MacroPattern2
+ = Pattern.compile("^" + Defmac + WhiteSpace + MacroName + rest,
+ Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ static final Pattern MacroPatternx
+ = Pattern.compile("^" + Defmacx + WhiteSpace +
+ MacroName + WhiteSpace +
+ Parms +
+ rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ static final Pattern MacroPatternx2
+ = Pattern.compile("^" + Defmacx + WhiteSpace + MacroName + rest,
+ Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ static final Pattern ParmBracketPattern = Pattern.compile("\\((.*)\\)");
+ static final Pattern IndexPattern = Pattern.compile("@\\w*index.*");
+ static final Pattern IndexPattern2 = Pattern.compile("@\\w*index\\{[a-zA-Z0-9_@\\{\\}]*\\}");
+ static final Pattern ExamplePattern = Pattern.compile("@example");
+ static final Pattern EndExamplePattern = Pattern.compile("@end\\s+example");
+ static final Pattern EnumeratePattern = Pattern.compile("@enumerate");
+ static final Pattern EndEnumeratePattern = Pattern.compile("@end\\s+enumerate");
+ static final Pattern VerbatimPattern = Pattern.compile("@verbatim");
+ static final Pattern ItemPattern = Pattern.compile("@item");
+ static final Pattern NoIndentPattern = Pattern.compile("@noindent");
+ static final Pattern BRPattern = Pattern.compile("&lt;br&gt;");
+ static final Pattern EOLPattern = Pattern.compile("&lt;eol&gt;");
+ static final Pattern EndVerbatimPattern = Pattern.compile("@end\\s+verbatim");
+ static final Pattern TableSampItemPattern = Pattern.compile("(@table\\s*@samp.*)@item\\s*([a-zA-Z_0-9+\\-<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
+ static final Pattern TableAsisItemPattern = Pattern.compile("(@table\\s*@asis.*)@item\\s*([a-zA-Z_0-9+\\-,<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
+ static final Pattern TableSampPattern = Pattern.compile("@table\\s*@samp", Pattern.MULTILINE);
+ static final Pattern TableAsisPattern = Pattern.compile("@table\\s*@asis", Pattern.MULTILINE);
+ static final Pattern EndTablePattern = Pattern.compile("@end\\s+table");
+ static final Pattern DotsPattern = Pattern.compile("@dots\\{\\}");
+ static final Pattern ItemizeMinusPattern= Pattern.compile("@itemize\\s+@minus" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
+ static final Pattern ItemizeBulletPattern= Pattern.compile("@itemize\\s+@bullet" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
+ static final Pattern XrefPattern = Pattern.compile("@xref\\{[^\\}]*\\}", Pattern.MULTILINE);
+ static final Pattern CommandPattern = Pattern.compile("@command\\{([^\\}]*)\\}");
+ static final Pattern KbdPattern = Pattern.compile("@kbd\\{([^\\}]*)\\}");
+ static final Pattern RPattern = Pattern.compile("@r\\{([^\\}]*)\\}");
+ static final Pattern FilePattern = Pattern.compile("@file\\{([^\\}]*)\\}");
+ static final Pattern VarPattern = Pattern.compile("@var\\{([^\\}]*)\\}");
+ static final Pattern OVarPattern = Pattern.compile("@ovar\\{([^\\}]*)\\}");
+ static final Pattern DVarPattern = Pattern.compile("@dvar\\{([^\\},\\,]*),([^\\}]*)\\}");
+ static final Pattern CodePattern = Pattern.compile("@code\\{([^\\}]*)\\}");
+ static final Pattern EmphPattern = Pattern.compile("@emph\\{([^\\}]*)\\}");
+ static final Pattern SampPattern = Pattern.compile("@samp\\{([^\\}]*)\\}");
+ static final Pattern OptionPattern = Pattern.compile("@option\\{([^\\}]*)\\}");
+ static final Pattern UrefPattern = Pattern.compile("@uref\\{([^,]*),\\s+([^\\}]*)\\}");
+ static final Pattern TagPattern = Pattern.compile("@\\w*\\{([^\\}]*)\\}");
+ static final Pattern AmpersandPattern = Pattern.compile("&");
+ static final Pattern LeftAnglePattern = Pattern.compile("<");
+ static final Pattern RightAnglePattern = Pattern.compile(">");
+
+
+ private static Map macroMap;
+
+ static class MacroParms {
+ String[] parms;
+ MacroParms nextParms = null;
+
+ public MacroParms(String[] parms) {
+ this.parms = parms;
+ }
+ }
+
+ static class MacroDef {
+ String MacroName;
+ MacroParms Parameters;
+ String Synopsis;
+ }
+
+ static class TPElement {
+ String Content;
+ String Synopsis;
+ }
+
+ static class TPDef {
+ String TPType;
+ String TPName;
+ String TPSynopsis;
+ TPElement[] TPElements;
+ Object[] IncludeList;
+ }
+
+ private static String killTagsParms(String tt) {
+ Matcher mm;
+
+ mm = ParmBracketPattern.matcher(tt);
+ tt= mm.replaceAll("$1");
+
+ mm = OVarPattern.matcher(tt);
+ tt = mm.replaceAll("[$1]");
+
+ mm = DVarPattern.matcher(tt);
+ tt = mm.replaceAll("[$1=$2]");
+
+ mm = VarPattern.matcher(tt);
+ tt = mm.replaceAll("$1");
+
+ mm = RPattern.matcher(tt);
+ tt = mm.replaceAll("$1");
+
+ mm = DotsPattern.matcher(tt);
+ tt = mm.replaceAll("...");
+
+ return tt;
+ }
+
+
+ private static String killTags(String tt) {
+ Matcher mm;
+ String ss = "";
+
+ while (ss != tt) {
+ mm = XrefPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = IndexPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = IndexPattern2.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = NoIndentPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = VarPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<VAR>$1</VAR>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = DotsPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<small>...</small>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = CommandPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<CODE>$1</CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = CodePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<CODE>$1</CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = UrefPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<A HREF=\"$1>$2</A>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = KbdPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<KBD>$1</KBD>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EmphPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<EM>$1</EM>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = FilePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<TT>$1</TT>");
+ }
+
+
+ ss = "";
+ while (ss != tt) {
+ mm = VerbatimPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndVerbatimPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = SampPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<samp>$1</samp>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = OptionPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<samp>$1</samp>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = ExamplePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<TABLE><tr><td>&nbsp;</td><td class=example><pre>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndExamplePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</pre></td></tr></table>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EnumeratePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<OL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndEnumeratePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</OL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableSampItemPattern.matcher(tt);
+ ss = tt;
+ if (mm.matches()) {
+ System.out.println("group 1 is " + mm.group(1));
+ System.out.println("group 2 is " + mm.group(2));
+ System.out.println("group 3 is " + mm.group(3));
+ }
+ tt = mm.replaceAll("$1<DT>'<SAMP>$2</SAMP>'\n<DD>$3");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableAsisItemPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1<DT>$2\n<DD>$3");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableSampPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<DL>\n");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableAsisPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<DL>\n");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndTablePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</DL>");
+ }
+
+ //FIXME: if there ever is a @itemize @bullet within a
+ // @itemize @minus or vice-versa, the following
+ // logic will get it wrong.
+ ss = "";
+ while (ss != tt) {
+ mm = ItemizeMinusPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<UL>$1</UL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = ItemizeBulletPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<OL>$1</OL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = ItemPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<LI>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TagPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1");
+ }
+
+ mm = AmpersandPattern.matcher(tt);
+ tt = mm.replaceAll("&amp;");
+
+ mm = LeftAnglePattern.matcher(tt);
+ tt = mm.replaceAll("&lt;");
+
+ mm = RightAnglePattern.matcher(tt);
+ tt = mm.replaceAll("&gt;");
+
+ // Clean up the eol markers we used to mark end of line for items
+ mm = EOLPattern.matcher(tt);
+ tt = mm.replaceAll("");
+
+ return tt;
+ }
+
+ private static MacroDef BuildMacroDef(Matcher m) {
+ MacroDef md = new MacroDef();
+
+ md.MacroName = m.group(MacroNameIndex);
+
+ if (null != m.group(ParmsIndex)) {
+ String tt = killTagsParms(m.group(ParmsIndex));
+ String[] parms = tt.split(",\\s");
+ md.Parameters = new MacroParms(parms);
+ }
+ return md;
+ }
+
+ private static MacroParms AddMacroDefxParms(MacroParms mp, Matcher mx) {
+ if (null != mx.group(ParmsIndex)) {
+ String tt = killTagsParms(mx.group(ParmsIndex));
+ String[] parms = tt.split(",\\s");
+ MacroParms mpnew = new MacroParms(parms);
+ mp.nextParms = mpnew;
+ return mpnew;
+ }
+ return null;
+ }
+
+ private static MacroDef HandleMacroDef(BufferedReader is, String s) throws IOException {
+ MacroDef fd = null;
+
+ Matcher m = MacroPattern.matcher(s);
+
+ if (m.matches()) {
+ fd = BuildMacroDef(m);
+ }
+ else { // assume the line got split and retry
+ is.mark(100);
+ String il = is.readLine();
+ m = MacroPattern.matcher(s + il);
+ if (m.matches()) fd = BuildMacroDef(m);
+ else {
+ is.reset();
+ m = MacroPattern2.matcher(s);
+ if (m.matches()) {
+ fd = new MacroDef();
+ fd.MacroName = m.group(MacroNameIndex);
+ fd.Parameters = new MacroParms(new String[0]);
+ }
+ }
+ }
+
+ if (fd != null) {
+ // Look for @defmacx which are alternate prototypes for the macro
+ is.mark(100);
+ String il = is.readLine();
+ if (il != null) {
+ Matcher mx = MacroPatternx.matcher(il);
+ Matcher mx2 = MacroPatternx2.matcher(il);
+ MacroParms mp = fd.Parameters;
+ while (mx.matches() || mx2.matches()) {
+ if (mx.matches())
+ mp = AddMacroDefxParms(mp, mx);
+ else {
+ MacroParms mpnew = new MacroParms(new String[0]);
+ mp.nextParms = mpnew;
+ mp = mpnew;
+ }
+ is.mark(100);
+ il = is.readLine();
+ if (il != null) {
+ mx = MacroPatternx.matcher(il);
+ mx2 = MacroPatternx2.matcher(il);
+ }
+ }
+ is.reset();
+ }
+
+ if (macroMap.get(fd.MacroName) != null)
+ return null;
+ macroMap.put(fd.MacroName, fd);
+ }
+
+ return fd;
+ }
+
+ private static void WriteString(BufferedWriter os, String s) throws IOException {
+ // System.out.println(s);
+ os.write(s+"\n", 0, 1+s.length());
+ }
+
private static void CreateHeader(BufferedWriter os) throws IOException {
- WriteString(os, "<!-- This file automatically generated by ParseAutomakeTexinfo utility -->");
- WriteString(os, "<!-- cvs -d:pserver:anonymous@sources.redhat.com:/cvs/eclipse \\ -->");
- WriteString(os, "<!-- co autotools/ParseTexinfo -->");
- WriteString(os, "<!DOCTYPE macros [");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT macros (macro)*>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT macro (prototype*,synopsis)>");
- WriteString(os, " <!ATTLIST macro");
- WriteString(os, " id ID #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT synopsis (#PCDATA)*>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT prototype (parameter+)?>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT parameter (#PCDATA)*>");
- WriteString(os, " <!ATTLIST parameter");
- WriteString(os, " content CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, "]>");
- WriteString(os, "");
+ WriteString(os, "<!-- This file automatically generated by ParseAutomakeTexinfo utility -->");
+ WriteString(os, "<!-- cvs -d:pserver:anonymous@sources.redhat.com:/cvs/eclipse \\ -->");
+ WriteString(os, "<!-- co autotools/ParseTexinfo -->");
+ WriteString(os, "<!DOCTYPE macros [");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT macros (macro)*>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT macro (prototype*,synopsis)>");
+ WriteString(os, " <!ATTLIST macro");
+ WriteString(os, " id ID #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT synopsis (#PCDATA)*>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT prototype (parameter+)?>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT parameter (#PCDATA)*>");
+ WriteString(os, " <!ATTLIST parameter");
+ WriteString(os, " content CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, "]>");
+ WriteString(os, "");
}
- private static void CreateTrailer(BufferedWriter os) throws IOException {
- WriteString(os, "</macros>");
- }
-
- private static void WriteSynopsis(BufferedWriter os, String Synopsis, boolean indent) throws IOException {
- String ss = Synopsis;
- String[] tt = ss.split("\\s");
- String aa = "";
- String spaces = indent ? " " : " ";
- WriteString(os, spaces + "<synopsis>");
- if (null != Synopsis) {
- for (int pp = 0; pp < tt.length; pp++) {
- if (tt[pp].equals("&lt;br&gt;")) {
- WriteString(os, spaces + aa + "&lt;/P&gt;&lt;P&gt;\n");
- aa = "";
- }
- else {
- if ((aa.length() + tt[pp].length()) > 64) {
- WriteString(os, spaces + aa);
- aa = "";
- }
- aa = aa + " " + tt[pp];
- }
- }
- }
- if (aa.length() > 0) WriteString(os, " " + aa);
- WriteString(os, spaces + "</synopsis>");
- }
-
- private static void HandleDefmacro(BufferedWriter os, BufferedReader is, String s) throws IOException {
- String il;
- MacroDef md = null;
- List FDefs = new ArrayList();
-
- while (null != (il = is.readLine())) {
- if (il.startsWith(Defmac)) {
- if (null != (md = HandleMacroDef(is, il))) FDefs.add(md);
- }
- else if (il.startsWith("@comment") ||
- il.startsWith("@c ")) { // comment -- ignore it
- }
- else if (il.startsWith("@subsection") ||
- il.startsWith("@section")) {
- for (int kk = 0; kk < FDefs.size(); kk++) {
- md = (MacroDef)FDefs.get(kk);
-
- WriteString(os, " <macro id=\"" + md.MacroName + "\">");
-
- MacroParms mp = md.Parameters;
- do {
- WriteString(os, " <prototype>");
- String[] parms = mp.parms;
- for (int i = 0; i < parms.length; i++) {
- WriteString(os, " <parameter content=\"" + parms[i] + "\"/>");
- }
- WriteString(os, " </prototype>");
- mp = mp.nextParms;
- } while (mp != null);
-
- if (null != md.Synopsis) WriteSynopsis(os, md.Synopsis, false);
-
- WriteString(os, " </macro>");
- }
- return;
- }
- else {
- if (md != null)
- md.Synopsis = ((md.Synopsis == null) ? "" : md.Synopsis + " " ) + ((il.length() == 0) ? "&lt;br&gt;&lt;br&gt;" :
- il.startsWith("@item") ? killTags(il) + "<eol>" : killTags(il));
- }
- }
- FDefs.clear();
-
- }
-
- private static class OnlyTexi implements FilenameFilter {
- public boolean accept(File dir, String s) {
- return (s.endsWith(".texi")) ? true : false;
- }
- }
-
- public static void BuildXMLFromTexinfo(String srcdir, String dstdir) {
- try {
- macroMap = new HashMap();
- BufferedWriter os = new BufferedWriter(new FileWriter(dstdir));
-
- CreateHeader(os);
-// CreateLicense(os);
-
- WriteString(os, "<macros>");
-
- try {
- String[] dir = new java.io.File(srcdir).list(new OnlyTexi());
- for (int i = 0; i < dir.length; i++) {
- String qFile = srcdir.endsWith("/")
- ? srcdir + dir[i]
- : srcdir + "/" + dir[i];
-
- try {
- BufferedReader is = new BufferedReader(new FileReader(qFile));
- String il;
-
- while (null != (il = is.readLine())) {
- Matcher mm1 = MacroSection1.matcher(il);
- Matcher mm2 = MacroSection2.matcher(il);
- if (mm1.matches() || mm2.matches()) {
- HandleDefmacro(os, is, il);
- }
- }
- is.close();
- }
- catch (IOException e) {
- System.out.println("Input File IOException: " + e);
- return;
- }
- }
- }
- catch (NullPointerException e) {
- System.out.println("NullPointerException: " + e);
- return;
- }
-
- CreateTrailer(os);
-
- os.close();
- }
- catch (IOException e) {
- System.out.println("Output File IOException: " + e);
- return;
- }
- }
-
- public static void main(String[] args) {
- // arg[0] is input directory containing .texi documents to read
- // arg[1] is output xml file to create
- BuildXMLFromTexinfo(args[0], args[1]);
- }
+ private static void CreateTrailer(BufferedWriter os) throws IOException {
+ WriteString(os, "</macros>");
+ }
+
+ private static void WriteSynopsis(BufferedWriter os, String Synopsis, boolean indent) throws IOException {
+ String ss = Synopsis;
+ String[] tt = ss.split("\\s");
+ String aa = "";
+ String spaces = indent ? " " : " ";
+ WriteString(os, spaces + "<synopsis>");
+ if (null != Synopsis) {
+ for (int pp = 0; pp < tt.length; pp++) {
+ if (tt[pp].equals("&lt;br&gt;")) {
+ WriteString(os, spaces + aa + "&lt;/P&gt;&lt;P&gt;\n");
+ aa = "";
+ }
+ else {
+ if ((aa.length() + tt[pp].length()) > 64) {
+ WriteString(os, spaces + aa);
+ aa = "";
+ }
+ aa = aa + " " + tt[pp];
+ }
+ }
+ }
+ if (aa.length() > 0) WriteString(os, " " + aa);
+ WriteString(os, spaces + "</synopsis>");
+ }
+
+ private static void HandleDefmacro(BufferedWriter os, BufferedReader is, String s) throws IOException {
+ String il;
+ MacroDef md = null;
+ List FDefs = new ArrayList();
+
+ while (null != (il = is.readLine())) {
+ if (il.startsWith(Defmac)) {
+ if (null != (md = HandleMacroDef(is, il))) FDefs.add(md);
+ }
+ else if (il.startsWith("@comment") ||
+ il.startsWith("@c ")) { // comment -- ignore it
+ }
+ else if (il.startsWith("@subsection") ||
+ il.startsWith("@section")) {
+ for (int kk = 0; kk < FDefs.size(); kk++) {
+ md = (MacroDef)FDefs.get(kk);
+
+ WriteString(os, " <macro id=\"" + md.MacroName + "\">");
+
+ MacroParms mp = md.Parameters;
+ do {
+ WriteString(os, " <prototype>");
+ String[] parms = mp.parms;
+ for (int i = 0; i < parms.length; i++) {
+ WriteString(os, " <parameter content=\"" + parms[i] + "\"/>");
+ }
+ WriteString(os, " </prototype>");
+ mp = mp.nextParms;
+ } while (mp != null);
+
+ if (null != md.Synopsis) WriteSynopsis(os, md.Synopsis, false);
+
+ WriteString(os, " </macro>");
+ }
+ return;
+ }
+ else {
+ if (md != null)
+ md.Synopsis = ((md.Synopsis == null) ? "" : md.Synopsis + " " ) + ((il.length() == 0) ? "&lt;br&gt;&lt;br&gt;" :
+ il.startsWith("@item") ? killTags(il) + "<eol>" : killTags(il));
+ }
+ }
+ FDefs.clear();
+
+ }
+
+ private static class OnlyTexi implements FilenameFilter {
+ public boolean accept(File dir, String s) {
+ return (s.endsWith(".texi")) ? true : false;
+ }
+ }
+
+ public static void BuildXMLFromTexinfo(String srcdir, String dstdir) {
+ try {
+ macroMap = new HashMap();
+ BufferedWriter os = new BufferedWriter(new FileWriter(dstdir));
+
+ CreateHeader(os);
+// CreateLicense(os);
+
+ WriteString(os, "<macros>");
+
+ try {
+ String[] dir = new java.io.File(srcdir).list(new OnlyTexi());
+ for (int i = 0; i < dir.length; i++) {
+ String qFile = srcdir.endsWith("/")
+ ? srcdir + dir[i]
+ : srcdir + "/" + dir[i];
+
+ try {
+ BufferedReader is = new BufferedReader(new FileReader(qFile));
+ String il;
+
+ while (null != (il = is.readLine())) {
+ Matcher mm1 = MacroSection1.matcher(il);
+ Matcher mm2 = MacroSection2.matcher(il);
+ if (mm1.matches() || mm2.matches()) {
+ HandleDefmacro(os, is, il);
+ }
+ }
+ is.close();
+ }
+ catch (IOException e) {
+ System.out.println("Input File IOException: " + e);
+ return;
+ }
+ }
+ }
+ catch (NullPointerException e) {
+ System.out.println("NullPointerException: " + e);
+ return;
+ }
+
+ CreateTrailer(os);
+
+ os.close();
+ }
+ catch (IOException e) {
+ System.out.println("Output File IOException: " + e);
+ return;
+ }
+ }
+
+ public static void main(String[] args) {
+ // arg[0] is input directory containing .texi documents to read
+ // arg[1] is output xml file to create
+ BuildXMLFromTexinfo(args[0], args[1]);
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseGlibcTexinfo.java b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseGlibcTexinfo.java
index 7a8e965f92..af109d7d86 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseGlibcTexinfo.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseGlibcTexinfo.java
@@ -21,869 +21,869 @@ import java.util.*;
//arguments: ${glibc_source_path}/manual glibc.xml
public class ParseGlibcTexinfo {
- static final boolean DEBUG = false;
-
- // 1
- static final String ATcmd = "(@\\w*)";
-
-
- // 3 4
- static final String RtnTypeM = "(\\{([^\\}]*)\\})";
- static final int RtnTypeMIndex = 4;
-
- // 5
- static final String RtnTypeS = "(\\w*)";
- static final int RtnTypeSIndex = 5;
-
- // 2
- static final String RtnType = "(" + RtnTypeM + "|" + RtnTypeS + ")";
- // 6
- static final String FunctionName = "(\\w*)";
- static final int FunctionNameIndex = 6;
-
- // 7 8
- static final String Parms = "(\\((.*)\\))";
- static final int ParmsIndex = 8;
-
- static final String rest = ".*";
-
- static final String WhiteSpace = "\\s*";
-
- static final Pattern DeftypefunPattern
- = Pattern.compile("^" + ATcmd + WhiteSpace +
- RtnType + WhiteSpace +
- FunctionName + WhiteSpace +
- Parms +
- rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- static final String TPDataType = "\\{[^\\}]*\\}";
-
-
- // 3 4
- static final String TPTypeM = "(\\{([^\\}]*)\\})";
- static final int TPTypeMIndex = 4;
-
- // 5
- static final String TPTypeS = "(\\w*)";
- static final int TPTypeSIndex = 5;
-
- // 2
- static final String TPType = "(" + TPTypeM + "|" + TPTypeS + ")";
-
- static final Pattern DeftpPattern
- = Pattern.compile("^" + ATcmd + WhiteSpace + TPDataType + WhiteSpace + TPType + rest,
- Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- static final Pattern IncludePattern = Pattern.compile("^@comment ((\\w*/)*\\w*\\.h\\s*)*\\s*$");
- static final Pattern PindexPattern = Pattern.compile("^@pindex\\s*\\w*\\s*$");
- static final Pattern ParmBracketPattern = Pattern.compile("\\((.*)\\)");
- static final Pattern IndexPattern = Pattern.compile("@\\w*index\\s+[a-zA-Z0-9_@\\{\\}]*");
- static final Pattern IndexPattern2 = Pattern.compile("@\\w*index\\{[a-zA-Z0-9_@\\{\\}]*\\}");
- static final Pattern ExamplePattern = Pattern.compile("@example");
- static final Pattern EndExamplePattern = Pattern.compile("@end\\s+example");
- static final Pattern EnumeratePattern = Pattern.compile("@enumerate");
- static final Pattern EndEnumeratePattern = Pattern.compile("@end\\s+enumerate");
- static final Pattern VerbatimPattern = Pattern.compile("@verbatim");
- static final Pattern ItemPattern = Pattern.compile("@item");
- static final Pattern NoIndentPattern = Pattern.compile("@noindent");
- static final Pattern BRPattern = Pattern.compile("&lt;br&gt;");
- static final Pattern EOLPattern = Pattern.compile("&lt;eol&gt;");
- static final Pattern EndVerbatimPattern = Pattern.compile("@end\\s+verbatim");
- static final Pattern TableSampItemPattern = Pattern.compile("(@table\\s*@samp.*)@item\\s*([a-zA-Z_0-9+\\-<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
- static final Pattern TableAsisItemPattern = Pattern.compile("(@table\\s*@asis.*)@item\\s*([a-zA-Z_0-9+\\-,<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
- static final Pattern TableSampPattern = Pattern.compile("@table\\s*@samp", Pattern.MULTILINE);
- static final Pattern TableAsisPattern = Pattern.compile("@table\\s*@asis", Pattern.MULTILINE);
- static final Pattern EndTablePattern = Pattern.compile("@end\\s+table");
- static final Pattern DotsPattern = Pattern.compile("@dots\\{\\}");
- static final Pattern ItemizeMinusPattern= Pattern.compile("@itemize\\s+@minus" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
- static final Pattern ItemizeBulletPattern= Pattern.compile("@itemize\\s+@bullet" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
- static final Pattern XrefPattern = Pattern.compile("@xref\\{[^\\}]*\\}", Pattern.MULTILINE);
- static final Pattern CommandPattern = Pattern.compile("@command\\{([^\\}]*)\\}");
- static final Pattern KbdPattern = Pattern.compile("@kbd\\{([^\\}]*)\\}");
- static final Pattern RPattern = Pattern.compile("@r\\{([^\\}]*)\\}");
- static final Pattern FilePattern = Pattern.compile("@file\\{([^\\}]*)\\}");
- static final Pattern VarPattern = Pattern.compile("@var\\{([^\\}]*)\\}");
- static final Pattern OVarPattern = Pattern.compile("@ovar\\{([^\\}]*)\\}");
- static final Pattern DVarPattern = Pattern.compile("@dvar\\{([^\\},\\,]*),([^\\}]*)\\}");
- static final Pattern CodePattern = Pattern.compile("@code\\{([^\\}]*)\\}");
- static final Pattern EmphPattern = Pattern.compile("@emph\\{([^\\}]*)\\}");
- static final Pattern SampPattern = Pattern.compile("@samp\\{([^\\}]*)\\}");
- static final Pattern OptionPattern = Pattern.compile("@option\\{([^\\}]*)\\}");
- static final Pattern TagPattern = Pattern.compile("@\\w*\\{([^\\}]*)\\}");
- static final Pattern AmpersandPattern = Pattern.compile("&");
- static final Pattern LeftAnglePattern = Pattern.compile("<");
- static final Pattern RightAnglePattern = Pattern.compile(">");
-
- static List IncludeList = new ArrayList();
-
-
- static class FunctionDef {
- String ReturnType;
- String FunctionName;
- String[] Parameters;
- Object[] IncludeList;
- }
-
- static class TPElement {
- String Content;
- String Synopsis;
- }
-
- static class TPDef {
- String TPType;
- String TPName;
- String TPSynopsis;
- TPElement[] TPElements;
- Object[] IncludeList;
- }
-
- private static FunctionDef BuildFunctionDef(Matcher m) {
- FunctionDef fd = new FunctionDef();
-
- fd.ReturnType = ((null != m.group(RtnTypeSIndex))
- ? m.group(RtnTypeSIndex)
- : m.group(RtnTypeMIndex));
- fd.FunctionName = m.group(FunctionNameIndex);
-
- if (null != m.group(ParmsIndex)) {
- String tt = TexinfoUtils.stripProtoTags(m.group(ParmsIndex));
- String[] parms = tt.split(",\\s");
- fd.Parameters = parms;
- }
-
- if (IncludeList.size() > 0) {
- fd.IncludeList = IncludeList.toArray();
- IncludeList.clear();
- }
- return fd;
- }
-
- private static void HandleDeftp(BufferedWriter os, BufferedReader is, String s) throws IOException {
- TPDef td = new TPDef();
- String il;
- String Synopsis = null;
- boolean ItemsAccumulating = false;
- TPElement tpe = new TPElement();
- List ElementList = new ArrayList();
-
- Matcher m = DeftpPattern.matcher(s);
- if (m.matches()) {
- if (null != m.group(TPTypeMIndex)) {
- String[] ss = m.group(TPTypeMIndex).split("\\s");
- switch(ss.length) {
- case 0:
- td.TPType = "";
- td.TPName = "type";
- break;
- case 1:
- td.TPType = "type";
- td.TPName = ss[0];
- break;
- case 2:
- td.TPType = ss[0];
- td.TPName = ss[1];
- break;
- default:
- td.TPType = "type";
- td.TPName = ss[ss.length - 1];
- break;
- }
- }
- else {
- td.TPType = "dtype";
- td.TPName = m.group(TPTypeSIndex);
- }
-
- while (null != (il = is.readLine())) {
- if (il.startsWith("@end deftp")) {
- WriteString(os, " <construct id=\"" + td.TPType + "-" + td.TPName
- + "\" type=\"" + td.TPType + "\">");
- WriteString(os, " <structure>");
- if (null != td.TPSynopsis) WriteSynopsis(os, td.TPSynopsis, false);
- if (ElementList.size() > 0) {
- WriteString(os, " <elements>");
- for (int ee = 0; ee < ElementList.size(); ee++) {
- TPElement ttt = (TPElement)ElementList.get(ee);
- WriteString(os, " <element content=\"" + ttt.Content + "\">");
- if (null != ttt.Synopsis) WriteSynopsis(os, ttt.Synopsis, true);
- WriteString(os, " </element>");
- }
- WriteString(os, " </elements>");
- }
- WriteString(os, " </structure>");
- WriteString(os, " </construct>");
- return;
- }
- else if (il.startsWith("@item")) {
- if (ItemsAccumulating) {
- tpe.Synopsis = Synopsis;
- ElementList.add(tpe);
- }
- else {
- td.TPSynopsis = Synopsis;
- ItemsAccumulating = true;
- }
- Synopsis = null;
- tpe = new TPElement();
- tpe.Content = TexinfoUtils.transformTags(il.replaceFirst("@item ", ""));
- }
- else {
- if (!il.startsWith("@table"))
- Synopsis = ((Synopsis == null) ? "" : Synopsis + " " ) + ((il.length() == 0) ? "<br><br>" :
- il + "<eol>");
- }
- }
- }
- }
-
- private static FunctionDef HandleFunctionDef(BufferedReader is, String s) throws IOException {
- FunctionDef fd;
-
- Matcher m = DeftypefunPattern.matcher(s);
-
- if (m.matches()) fd = BuildFunctionDef(m);
- else { // assume the line got split and retry
- String il = is.readLine();
- m = DeftypefunPattern.matcher(s + il);
- if (m.matches()) fd = BuildFunctionDef(m);
- else fd = null;
- }
-
- return fd;
- }
-
- private static void WriteString(BufferedWriter os, String s) throws IOException {
- // System.out.println(s);
- os.write(s+"\n", 0, 1+s.length());
- }
-
- private static void CreateHeader(BufferedWriter os) throws IOException {
- WriteString(os, "<!-- This file automatically generated by an Eclipse utility -->");
- WriteString(os, "<!DOCTYPE descriptions [");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT descriptions (construct)*>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT construct (structure|function)*>");
- WriteString(os, " <!ATTLIST construct");
- WriteString(os, " id ID #REQUIRED");
- WriteString(os, " type CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT structure (synopsis?, elements?)?>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT elements (element*)>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT element (synopsis*)>");
- WriteString(os, " <!ATTLIST element");
- WriteString(os, " content CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT synopsis (#PCDATA)*>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT function (prototype,headers?,synopsis)>");
- WriteString(os, " <!ATTLIST function");
- WriteString(os, " returntype CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT prototype (parameter+)?>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT parameter (#PCDATA)*>");
- WriteString(os, " <!ATTLIST parameter");
- WriteString(os, " content CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT headers (header+)?>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT header (#PCDATA)*>");
- WriteString(os, " <!ATTLIST header");
- WriteString(os, " filename CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, "]>");
- WriteString(os, "");
- }
+ static final boolean DEBUG = false;
+
+ // 1
+ static final String ATcmd = "(@\\w*)";
+
+
+ // 3 4
+ static final String RtnTypeM = "(\\{([^\\}]*)\\})";
+ static final int RtnTypeMIndex = 4;
+
+ // 5
+ static final String RtnTypeS = "(\\w*)";
+ static final int RtnTypeSIndex = 5;
+
+ // 2
+ static final String RtnType = "(" + RtnTypeM + "|" + RtnTypeS + ")";
+ // 6
+ static final String FunctionName = "(\\w*)";
+ static final int FunctionNameIndex = 6;
+
+ // 7 8
+ static final String Parms = "(\\((.*)\\))";
+ static final int ParmsIndex = 8;
+
+ static final String rest = ".*";
+
+ static final String WhiteSpace = "\\s*";
+
+ static final Pattern DeftypefunPattern
+ = Pattern.compile("^" + ATcmd + WhiteSpace +
+ RtnType + WhiteSpace +
+ FunctionName + WhiteSpace +
+ Parms +
+ rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ static final String TPDataType = "\\{[^\\}]*\\}";
+
+
+ // 3 4
+ static final String TPTypeM = "(\\{([^\\}]*)\\})";
+ static final int TPTypeMIndex = 4;
+
+ // 5
+ static final String TPTypeS = "(\\w*)";
+ static final int TPTypeSIndex = 5;
+
+ // 2
+ static final String TPType = "(" + TPTypeM + "|" + TPTypeS + ")";
+
+ static final Pattern DeftpPattern
+ = Pattern.compile("^" + ATcmd + WhiteSpace + TPDataType + WhiteSpace + TPType + rest,
+ Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ static final Pattern IncludePattern = Pattern.compile("^@comment ((\\w*/)*\\w*\\.h\\s*)*\\s*$");
+ static final Pattern PindexPattern = Pattern.compile("^@pindex\\s*\\w*\\s*$");
+ static final Pattern ParmBracketPattern = Pattern.compile("\\((.*)\\)");
+ static final Pattern IndexPattern = Pattern.compile("@\\w*index\\s+[a-zA-Z0-9_@\\{\\}]*");
+ static final Pattern IndexPattern2 = Pattern.compile("@\\w*index\\{[a-zA-Z0-9_@\\{\\}]*\\}");
+ static final Pattern ExamplePattern = Pattern.compile("@example");
+ static final Pattern EndExamplePattern = Pattern.compile("@end\\s+example");
+ static final Pattern EnumeratePattern = Pattern.compile("@enumerate");
+ static final Pattern EndEnumeratePattern = Pattern.compile("@end\\s+enumerate");
+ static final Pattern VerbatimPattern = Pattern.compile("@verbatim");
+ static final Pattern ItemPattern = Pattern.compile("@item");
+ static final Pattern NoIndentPattern = Pattern.compile("@noindent");
+ static final Pattern BRPattern = Pattern.compile("&lt;br&gt;");
+ static final Pattern EOLPattern = Pattern.compile("&lt;eol&gt;");
+ static final Pattern EndVerbatimPattern = Pattern.compile("@end\\s+verbatim");
+ static final Pattern TableSampItemPattern = Pattern.compile("(@table\\s*@samp.*)@item\\s*([a-zA-Z_0-9+\\-<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
+ static final Pattern TableAsisItemPattern = Pattern.compile("(@table\\s*@asis.*)@item\\s*([a-zA-Z_0-9+\\-,<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
+ static final Pattern TableSampPattern = Pattern.compile("@table\\s*@samp", Pattern.MULTILINE);
+ static final Pattern TableAsisPattern = Pattern.compile("@table\\s*@asis", Pattern.MULTILINE);
+ static final Pattern EndTablePattern = Pattern.compile("@end\\s+table");
+ static final Pattern DotsPattern = Pattern.compile("@dots\\{\\}");
+ static final Pattern ItemizeMinusPattern= Pattern.compile("@itemize\\s+@minus" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
+ static final Pattern ItemizeBulletPattern= Pattern.compile("@itemize\\s+@bullet" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
+ static final Pattern XrefPattern = Pattern.compile("@xref\\{[^\\}]*\\}", Pattern.MULTILINE);
+ static final Pattern CommandPattern = Pattern.compile("@command\\{([^\\}]*)\\}");
+ static final Pattern KbdPattern = Pattern.compile("@kbd\\{([^\\}]*)\\}");
+ static final Pattern RPattern = Pattern.compile("@r\\{([^\\}]*)\\}");
+ static final Pattern FilePattern = Pattern.compile("@file\\{([^\\}]*)\\}");
+ static final Pattern VarPattern = Pattern.compile("@var\\{([^\\}]*)\\}");
+ static final Pattern OVarPattern = Pattern.compile("@ovar\\{([^\\}]*)\\}");
+ static final Pattern DVarPattern = Pattern.compile("@dvar\\{([^\\},\\,]*),([^\\}]*)\\}");
+ static final Pattern CodePattern = Pattern.compile("@code\\{([^\\}]*)\\}");
+ static final Pattern EmphPattern = Pattern.compile("@emph\\{([^\\}]*)\\}");
+ static final Pattern SampPattern = Pattern.compile("@samp\\{([^\\}]*)\\}");
+ static final Pattern OptionPattern = Pattern.compile("@option\\{([^\\}]*)\\}");
+ static final Pattern TagPattern = Pattern.compile("@\\w*\\{([^\\}]*)\\}");
+ static final Pattern AmpersandPattern = Pattern.compile("&");
+ static final Pattern LeftAnglePattern = Pattern.compile("<");
+ static final Pattern RightAnglePattern = Pattern.compile(">");
+
+ static List IncludeList = new ArrayList();
+
+
+ static class FunctionDef {
+ String ReturnType;
+ String FunctionName;
+ String[] Parameters;
+ Object[] IncludeList;
+ }
+
+ static class TPElement {
+ String Content;
+ String Synopsis;
+ }
+
+ static class TPDef {
+ String TPType;
+ String TPName;
+ String TPSynopsis;
+ TPElement[] TPElements;
+ Object[] IncludeList;
+ }
+
+ private static FunctionDef BuildFunctionDef(Matcher m) {
+ FunctionDef fd = new FunctionDef();
+
+ fd.ReturnType = ((null != m.group(RtnTypeSIndex))
+ ? m.group(RtnTypeSIndex)
+ : m.group(RtnTypeMIndex));
+ fd.FunctionName = m.group(FunctionNameIndex);
+
+ if (null != m.group(ParmsIndex)) {
+ String tt = TexinfoUtils.stripProtoTags(m.group(ParmsIndex));
+ String[] parms = tt.split(",\\s");
+ fd.Parameters = parms;
+ }
+
+ if (IncludeList.size() > 0) {
+ fd.IncludeList = IncludeList.toArray();
+ IncludeList.clear();
+ }
+ return fd;
+ }
+
+ private static void HandleDeftp(BufferedWriter os, BufferedReader is, String s) throws IOException {
+ TPDef td = new TPDef();
+ String il;
+ String Synopsis = null;
+ boolean ItemsAccumulating = false;
+ TPElement tpe = new TPElement();
+ List ElementList = new ArrayList();
+
+ Matcher m = DeftpPattern.matcher(s);
+ if (m.matches()) {
+ if (null != m.group(TPTypeMIndex)) {
+ String[] ss = m.group(TPTypeMIndex).split("\\s");
+ switch(ss.length) {
+ case 0:
+ td.TPType = "";
+ td.TPName = "type";
+ break;
+ case 1:
+ td.TPType = "type";
+ td.TPName = ss[0];
+ break;
+ case 2:
+ td.TPType = ss[0];
+ td.TPName = ss[1];
+ break;
+ default:
+ td.TPType = "type";
+ td.TPName = ss[ss.length - 1];
+ break;
+ }
+ }
+ else {
+ td.TPType = "dtype";
+ td.TPName = m.group(TPTypeSIndex);
+ }
+
+ while (null != (il = is.readLine())) {
+ if (il.startsWith("@end deftp")) {
+ WriteString(os, " <construct id=\"" + td.TPType + "-" + td.TPName
+ + "\" type=\"" + td.TPType + "\">");
+ WriteString(os, " <structure>");
+ if (null != td.TPSynopsis) WriteSynopsis(os, td.TPSynopsis, false);
+ if (ElementList.size() > 0) {
+ WriteString(os, " <elements>");
+ for (int ee = 0; ee < ElementList.size(); ee++) {
+ TPElement ttt = (TPElement)ElementList.get(ee);
+ WriteString(os, " <element content=\"" + ttt.Content + "\">");
+ if (null != ttt.Synopsis) WriteSynopsis(os, ttt.Synopsis, true);
+ WriteString(os, " </element>");
+ }
+ WriteString(os, " </elements>");
+ }
+ WriteString(os, " </structure>");
+ WriteString(os, " </construct>");
+ return;
+ }
+ else if (il.startsWith("@item")) {
+ if (ItemsAccumulating) {
+ tpe.Synopsis = Synopsis;
+ ElementList.add(tpe);
+ }
+ else {
+ td.TPSynopsis = Synopsis;
+ ItemsAccumulating = true;
+ }
+ Synopsis = null;
+ tpe = new TPElement();
+ tpe.Content = TexinfoUtils.transformTags(il.replaceFirst("@item ", ""));
+ }
+ else {
+ if (!il.startsWith("@table"))
+ Synopsis = ((Synopsis == null) ? "" : Synopsis + " " ) + ((il.length() == 0) ? "<br><br>" :
+ il + "<eol>");
+ }
+ }
+ }
+ }
+
+ private static FunctionDef HandleFunctionDef(BufferedReader is, String s) throws IOException {
+ FunctionDef fd;
+
+ Matcher m = DeftypefunPattern.matcher(s);
+
+ if (m.matches()) fd = BuildFunctionDef(m);
+ else { // assume the line got split and retry
+ String il = is.readLine();
+ m = DeftypefunPattern.matcher(s + il);
+ if (m.matches()) fd = BuildFunctionDef(m);
+ else fd = null;
+ }
+
+ return fd;
+ }
+
+ private static void WriteString(BufferedWriter os, String s) throws IOException {
+ // System.out.println(s);
+ os.write(s+"\n", 0, 1+s.length());
+ }
+
+ private static void CreateHeader(BufferedWriter os) throws IOException {
+ WriteString(os, "<!-- This file automatically generated by an Eclipse utility -->");
+ WriteString(os, "<!DOCTYPE descriptions [");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT descriptions (construct)*>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT construct (structure|function)*>");
+ WriteString(os, " <!ATTLIST construct");
+ WriteString(os, " id ID #REQUIRED");
+ WriteString(os, " type CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT structure (synopsis?, elements?)?>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT elements (element*)>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT element (synopsis*)>");
+ WriteString(os, " <!ATTLIST element");
+ WriteString(os, " content CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT synopsis (#PCDATA)*>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT function (prototype,headers?,synopsis)>");
+ WriteString(os, " <!ATTLIST function");
+ WriteString(os, " returntype CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT prototype (parameter+)?>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT parameter (#PCDATA)*>");
+ WriteString(os, " <!ATTLIST parameter");
+ WriteString(os, " content CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT headers (header+)?>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT header (#PCDATA)*>");
+ WriteString(os, " <!ATTLIST header");
+ WriteString(os, " filename CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, "]>");
+ WriteString(os, "");
+ }
// // For now we will use an aggregate document license instead of one per
// // document.
-// private static void CreateLicense(BufferedWriter os) throws IOException {
-// WriteString(os, "<!--");
-// WriteString(os, "A.1 GNU Free Documentation License");
-// WriteString(os,"Version 1.2, November 2002");
-// WriteString(os, "");
-// WriteString(os, "Copyright &copy; 2000,2001,2002 Free Software Foundation, Inc.");
-// WriteString(os, "59 Temple Place, Suite 330, Boston, MA 02111-1307, USA");
-// WriteString(os, "");
-// WriteString(os, "Everyone is permitted to copy and distribute verbatim copies");
-// WriteString(os, "of this license document, but changing it is not allowed.");
-// WriteString(os, "");
-// WriteString(os, "1. PREAMBLE");
-// WriteString(os, "");
-// WriteString(os, "The purpose of this License is to make a manual, textbook, or other");
-// WriteString(os, "functional and useful document free in the sense of freedom: to");
-// WriteString(os, "assure everyone the effective freedom to copy and redistribute it,");
-// WriteString(os, "with or without modifying it, either commercially or noncommercially.");
-// WriteString(os, "Secondarily, this License preserves for the author and publisher a way");
-// WriteString(os, "to get credit for their work, while not being considered responsible");
-// WriteString(os, "for modifications made by others.");
-// WriteString(os, "");
-// WriteString(os, "This License is a kind of \"copyleft\", which means that derivative");
-// WriteString(os, "works of the document must themselves be free in the same sense. It");
-// WriteString(os, "complements the GNU General Public License, which is a copyleft");
-// WriteString(os, "license designed for free software.");
-// WriteString(os, "");
-// WriteString(os, "We have designed this License in order to use it for manuals for free");
-// WriteString(os, "software, because free software needs free documentation: a free");
-// WriteString(os, "program should come with manuals providing the same freedoms that the");
-// WriteString(os, "software does. But this License is not limited to software manuals;");
-// WriteString(os, "it can be used for any textual work, regardless of subject matter or");
-// WriteString(os, "whether it is published as a printed book. We recommend this License");
-// WriteString(os, "principally for works whose purpose is instruction or reference.");
-// WriteString(os, "");
-// WriteString(os, "2. APPLICABILITY AND DEFINITIONS");
-// WriteString(os, "");
-// WriteString(os, "This License applies to any manual or other work, in any medium, that");
-// WriteString(os, "contains a notice placed by the copyright holder saying it can be");
-// WriteString(os, "distributed under the terms of this License. Such a notice grants a");
-// WriteString(os, "world-wide, royalty-free license, unlimited in duration, to use that");
-// WriteString(os, "work under the conditions stated herein. The \"Document\", below,");
-// WriteString(os, "refers to any such manual or work. Any member of the public is a");
-// WriteString(os, "licensee, and is addressed as \"you\". You accept the license if you");
-// WriteString(os, "copy, modify or distribute the work in a way requiring permission");
-// WriteString(os, "under copyright law.");
-// WriteString(os, "");
-// WriteString(os, "A \"Modified Version\" of the Document means any work containing the");
-// WriteString(os, "Document or a portion of it, either copied verbatim, or with");
-// WriteString(os, "modifications and/or translated into another language.");
-// WriteString(os, "");
-// WriteString(os, "A \"Secondary Section\" is a named appendix or a front-matter section");
-// WriteString(os, "of the Document that deals exclusively with the relationship of the");
-// WriteString(os, "publishers or authors of the Document to the Document's overall");
-// WriteString(os, "subject (or to related matters) and contains nothing that could fall");
-// WriteString(os, "directly within that overall subject. (Thus, if the Document is in");
-// WriteString(os, "part a textbook of mathematics, a Secondary Section may not explain");
-// WriteString(os, "any mathematics.) The relationship could be a matter of historical");
-// WriteString(os, "connection with the subject or with related matters, or of legal,");
-// WriteString(os, "commercial, philosophical, ethical or political position regarding");
-// WriteString(os, "them.");
-// WriteString(os, "");
-// WriteString(os, "The \"Invariant Sections\" are certain Secondary Sections whose titles");
-// WriteString(os, "are designated, as being those of Invariant Sections, in the notice");
-// WriteString(os, "that says that the Document is released under this License. If a");
-// WriteString(os, "section does not fit the above definition of Secondary then it is not");
-// WriteString(os, "allowed to be designated as Invariant. The Document may contain zero");
-// WriteString(os, "Invariant Sections. If the Document does not identify any Invariant");
-// WriteString(os, "Sections then there are none.");
-// WriteString(os, "");
-// WriteString(os, "The \"Cover Texts\" are certain short passages of text that are listed,");
-// WriteString(os, "as Front-Cover Texts or Back-Cover Texts, in the notice that says that");
-// WriteString(os, "the Document is released under this License. A Front-Cover Text may");
-// WriteString(os, "be at most 5 words, and a Back-Cover Text may be at most 25 words.");
-// WriteString(os, "");
-// WriteString(os, "A \"Transparent\" copy of the Document means a machine-readable copy,");
-// WriteString(os, "represented in a format whose specification is available to the");
-// WriteString(os, "general public, that is suitable for revising the document");
-// WriteString(os, "straightforwardly with generic text editors or (for images composed of");
-// WriteString(os, "pixels) generic paint programs or (for drawings) some widely available");
-// WriteString(os, "drawing editor, and that is suitable for input to text formatters or");
-// WriteString(os, "for automatic translation to a variety of formats suitable for input");
-// WriteString(os, "to text formatters. A copy made in an otherwise Transparent file");
-// WriteString(os, "format whose markup, or absence of markup, has been arranged to thwart");
-// WriteString(os, "or discourage subsequent modification by readers is not Transparent.");
-// WriteString(os, "An image format is not Transparent if used for any substantial amount");
-// WriteString(os, "of text. A copy that is not \"Transparent\" is called \"Opaque\".");
-// WriteString(os, "");
-// WriteString(os, "Examples of suitable formats for Transparent copies include plain");
-// WriteString(os, "ASCII without markup, Texinfo input format, LaTeX input");
-// WriteString(os, "format, SGML or XML using a publicly available");
-// WriteString(os, "DTD, and standard-conforming simple HTML,");
-// WriteString(os, "PostScript or PDF designed for human modification. Examples");
-// WriteString(os, "of transparent image formats include PNG, XCF and");
-// WriteString(os, "JPG. Opaque formats include proprietary formats that can be");
-// WriteString(os, "read and edited only by proprietary word processors, SGML or");
-// WriteString(os, "XML for which the DTD and/or processing tools are");
-// WriteString(os, "not generally available, and the machine-generated HTML,");
-// WriteString(os, "PostScript or PDF produced by some word processors for");
-// WriteString(os, "output purposes only.");
-// WriteString(os, "");
-// WriteString(os, "The \"Title Page\" means, for a printed book, the title page itself,");
-// WriteString(os, "plus such following pages as are needed to hold, legibly, the material");
-// WriteString(os, "this License requires to appear in the title page. For works in");
-// WriteString(os, "formats which do not have any title page as such, \"Title Page\" means");
-// WriteString(os, "the text near the most prominent appearance of the work's title,");
-// WriteString(os, "preceding the beginning of the body of the text.");
-// WriteString(os, "");
-// WriteString(os, "A section \"Entitled XYZ\" means a named subunit of the Document whose");
-// WriteString(os, "title either is precisely XYZ or contains XYZ in parentheses following");
-// WriteString(os, "text that translates XYZ in another language. (Here XYZ stands for a");
-// WriteString(os, "specific section name mentioned below, such as \"Acknowledgements\",");
-// WriteString(os, "\"Dedications\", \"Endorsements\", or \"History\".) To \"Preserve the Title\"");
-// WriteString(os, "of such a section when you modify the Document means that it remains a");
-// WriteString(os, "section \"Entitled XYZ\" according to this definition.");
-// WriteString(os, "");
-// WriteString(os, "The Document may include Warranty Disclaimers next to the notice which");
-// WriteString(os, "states that this License applies to the Document. These Warranty");
-// WriteString(os, "Disclaimers are considered to be included by reference in this");
-// WriteString(os, "License, but only as regards disclaiming warranties: any other");
-// WriteString(os, "implication that these Warranty Disclaimers may have is void and has");
-// WriteString(os, "no effect on the meaning of this License.");
-// WriteString(os, "");
-// WriteString(os, "3. VERBATIM COPYING");
-// WriteString(os, "");
-// WriteString(os, "You may copy and distribute the Document in any medium, either");
-// WriteString(os, "commercially or noncommercially, provided that this License, the");
-// WriteString(os, "copyright notices, and the license notice saying this License applies");
-// WriteString(os, "to the Document are reproduced in all copies, and that you add no other");
-// WriteString(os, "conditions whatsoever to those of this License. You may not use");
-// WriteString(os, "technical measures to obstruct or control the reading or further");
-// WriteString(os, "copying of the copies you make or distribute. However, you may accept");
-// WriteString(os, "compensation in exchange for copies. If you distribute a large enough");
-// WriteString(os, "number of copies you must also follow the conditions in section 3.");
-// WriteString(os, "");
-// WriteString(os, "You may also lend copies, under the same conditions stated above, and");
-// WriteString(os, "you may publicly display copies.");
-// WriteString(os, "");
-// WriteString(os, "4. COPYING IN QUANTITY");
-// WriteString(os, "");
-// WriteString(os, "If you publish printed copies (or copies in media that commonly have");
-// WriteString(os, "printed covers) of the Document, numbering more than 100, and the");
-// WriteString(os, "Document's license notice requires Cover Texts, you must enclose the");
-// WriteString(os, "copies in covers that carry, clearly and legibly, all these Cover");
-// WriteString(os, "Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on");
-// WriteString(os, "the back cover. Both covers must also clearly and legibly identify");
-// WriteString(os, "you as the publisher of these copies. The front cover must present");
-// WriteString(os, "the full title with all words of the title equally prominent and");
-// WriteString(os, "visible. You may add other material on the covers in addition.");
-// WriteString(os, "Copying with changes limited to the covers, as long as they preserve");
-// WriteString(os, "the title of the Document and satisfy these conditions, can be treated");
-// WriteString(os, "as verbatim copying in other respects.");
-// WriteString(os, "");
-// WriteString(os, "If the required texts for either cover are too voluminous to fit");
-// WriteString(os, "legibly, you should put the first ones listed (as many as fit");
-// WriteString(os, "reasonably) on the actual cover, and continue the rest onto adjacent");
-// WriteString(os, "pages.");
-// WriteString(os, "");
-// WriteString(os, "If you publish or distribute Opaque copies of the Document numbering");
-// WriteString(os, "more than 100, you must either include a machine-readable Transparent");
-// WriteString(os, "copy along with each Opaque copy, or state in or with each Opaque copy");
-// WriteString(os, "a computer-network location from which the general network-using");
-// WriteString(os, "public has access to download using public-standard network protocols");
-// WriteString(os, "a complete Transparent copy of the Document, free of added material.");
-// WriteString(os, "If you use the latter option, you must take reasonably prudent steps,");
-// WriteString(os, "when you begin distribution of Opaque copies in quantity, to ensure");
-// WriteString(os, "that this Transparent copy will remain thus accessible at the stated");
-// WriteString(os, "location until at least one year after the last time you distribute an");
-// WriteString(os, "Opaque copy (directly or through your agents or retailers) of that");
-// WriteString(os, "edition to the public.");
-// WriteString(os, "");
-// WriteString(os, "It is requested, but not required, that you contact the authors of the");
-// WriteString(os, "Document well before redistributing any large number of copies, to give");
-// WriteString(os, "them a chance to provide you with an updated version of the Document.");
-// WriteString(os, "");
-// WriteString(os, "5. MODIFICATIONS");
-// WriteString(os, "");
-// WriteString(os, "You may copy and distribute a Modified Version of the Document under");
-// WriteString(os, "the conditions of sections 2 and 3 above, provided that you release");
-// WriteString(os, "the Modified Version under precisely this License, with the Modified");
-// WriteString(os, "Version filling the role of the Document, thus licensing distribution");
-// WriteString(os, "and modification of the Modified Version to whoever possesses a copy");
-// WriteString(os, "of it. In addition, you must do these things in the Modified Version:");
-// WriteString(os, "");
-// WriteString(os, " 1. Use in the Title Page (and on the covers, if any) a title distinct");
-// WriteString(os, " from that of the Document, and from those of previous versions");
-// WriteString(os, " (which should, if there were any, be listed in the History section");
-// WriteString(os, " of the Document). You may use the same title as a previous version");
-// WriteString(os, " if the original publisher of that version gives permission.");
-// WriteString(os, "");
-// WriteString(os, " 2. List on the Title Page, as authors, one or more persons or entities");
-// WriteString(os, " responsible for authorship of the modifications in the Modified");
-// WriteString(os, " Version, together with at least five of the principal authors of the");
-// WriteString(os, " Document (all of its principal authors, if it has fewer than five),");
-// WriteString(os, " unless they release you from this requirement.");
-// WriteString(os, "");
-// WriteString(os, " 3. State on the Title page the name of the publisher of the");
-// WriteString(os, " Modified Version, as the publisher.");
-// WriteString(os, "");
-// WriteString(os, " 4. Preserve all the copyright notices of the Document.");
-// WriteString(os, "");
-// WriteString(os, " 5. Add an appropriate copyright notice for your modifications");
-// WriteString(os, " adjacent to the other copyright notices.");
-// WriteString(os, "");
-// WriteString(os, " 6. Include, immediately after the copyright notices, a license notice");
-// WriteString(os, " giving the public permission to use the Modified Version under the");
-// WriteString(os, " terms of this License, in the form shown in the Addendum below.");
-// WriteString(os, "");
-// WriteString(os, " 7. Preserve in that license notice the full lists of Invariant Sections");
-// WriteString(os, " and required Cover Texts given in the Document's license notice.");
-// WriteString(os, "");
-// WriteString(os, " 8. Include an unaltered copy of this License.");
-// WriteString(os, "");
-// WriteString(os, " 9. Preserve the section Entitled \"History\", Preserve its Title, and add");
-// WriteString(os, " to it an item stating at least the title, year, new authors, and");
-// WriteString(os, " publisher of the Modified Version as given on the Title Page. If");
-// WriteString(os, " there is no section Entitled \"History\" in the Document, create one");
-// WriteString(os, " stating the title, year, authors, and publisher of the Document as");
-// WriteString(os, " given on its Title Page, then add an item describing the Modified");
-// WriteString(os, " Version as stated in the previous sentence.");
-// WriteString(os, "");
-// WriteString(os, " 10. Preserve the network location, if any, given in the Document for");
-// WriteString(os, " public access to a Transparent copy of the Document, and likewise");
-// WriteString(os, " the network locations given in the Document for previous versions");
-// WriteString(os, " it was based on. These may be placed in the \"History\" section.");
-// WriteString(os, " You may omit a network location for a work that was published at");
-// WriteString(os, " least four years before the Document itself, or if the original");
-// WriteString(os, " publisher of the version it refers to gives permission.");
-// WriteString(os, "");
-// WriteString(os, " 11. For any section Entitled \"Acknowledgements\" or \"Dedications\", Preserve");
-// WriteString(os, " the Title of the section, and preserve in the section all the");
-// WriteString(os, " substance and tone of each of the contributor acknowledgements and/or");
-// WriteString(os, " dedications given therein.");
-// WriteString(os, "");
-// WriteString(os, " 12. Preserve all the Invariant Sections of the Document,");
-// WriteString(os, " unaltered in their text and in their titles. Section numbers");
-// WriteString(os, " or the equivalent are not considered part of the section titles.");
-// WriteString(os, "");
-// WriteString(os, " 13. Delete any section Entitled \"Endorsements\". Such a section");
-// WriteString(os, " may not be included in the Modified Version.");
-// WriteString(os, "");
-// WriteString(os, " 14. Do not retitle any existing section to be Entitled \"Endorsements\" or");
-// WriteString(os, " to conflict in title with any Invariant Section.");
-// WriteString(os, "");
-// WriteString(os, " 15. Preserve any Warranty Disclaimers.");
-// WriteString(os, "");
-// WriteString(os, "");
-// WriteString(os, "If the Modified Version includes new front-matter sections or");
-// WriteString(os, "appendices that qualify as Secondary Sections and contain no material");
-// WriteString(os, "copied from the Document, you may at your option designate some or all");
-// WriteString(os, "of these sections as invariant. To do this, add their titles to the");
-// WriteString(os, "list of Invariant Sections in the Modified Version's license notice.");
-// WriteString(os, "These titles must be distinct from any other section titles.");
-// WriteString(os, "");
-// WriteString(os, "You may add a section Entitled \"Endorsements\", provided it contains");
-// WriteString(os, "nothing but endorsements of your Modified Version by various");
-// WriteString(os, "parties - for example, statements of peer review or that the text has");
-// WriteString(os, "been approved by an organization as the authoritative definition of a");
-// WriteString(os, "standard.");
-// WriteString(os, "");
-// WriteString(os, "You may add a passage of up to five words as a Front-Cover Text, and a");
-// WriteString(os, "passage of up to 25 words as a Back-Cover Text, to the end of the list");
-// WriteString(os, "of Cover Texts in the Modified Version. Only one passage of");
-// WriteString(os, "Front-Cover Text and one of Back-Cover Text may be added by (or");
-// WriteString(os, "through arrangements made by) any one entity. If the Document already");
-// WriteString(os, "includes a cover text for the same cover, previously added by you or");
-// WriteString(os, "by arrangement made by the same entity you are acting on behalf of,");
-// WriteString(os, "you may not add another; but you may replace the old one, on explicit");
-// WriteString(os, "permission from the previous publisher that added the old one.");
-// WriteString(os, "");
-// WriteString(os, "The author(s) and publisher(s) of the Document do not by this License");
-// WriteString(os, "give permission to use their names for publicity for or to assert or");
-// WriteString(os, "imply endorsement of any Modified Version.");
-// WriteString(os, "");
-// WriteString(os, "6. COMBINING DOCUMENTS");
-// WriteString(os, "");
-// WriteString(os, "You may combine the Document with other documents released under this");
-// WriteString(os, "License, under the terms defined in section 4 above for modified");
-// WriteString(os, "versions, provided that you include in the combination all of the");
-// WriteString(os, "Invariant Sections of all of the original documents, unmodified, and");
-// WriteString(os, "list them all as Invariant Sections of your combined work in its");
-// WriteString(os, "license notice, and that you preserve all their Warranty Disclaimers.");
-// WriteString(os, "");
-// WriteString(os, "The combined work need only contain one copy of this License, and");
-// WriteString(os, "multiple identical Invariant Sections may be replaced with a single");
-// WriteString(os, "copy. If there are multiple Invariant Sections with the same name but");
-// WriteString(os, "different contents, make the title of each such section unique by");
-// WriteString(os, "adding at the end of it, in parentheses, the name of the original");
-// WriteString(os, "author or publisher of that section if known, or else a unique number.");
-// WriteString(os, "Make the same adjustment to the section titles in the list of");
-// WriteString(os, "Invariant Sections in the license notice of the combined work.");
-// WriteString(os, "");
-// WriteString(os, "In the combination, you must combine any sections Entitled \"History\"");
-// WriteString(os, "in the various original documents, forming one section Entitled");
-// WriteString(os, "\"History\"; likewise combine any sections Entitled \"Acknowledgements\",");
-// WriteString(os, "and any sections Entitled \"Dedications\". You must delete all");
-// WriteString(os, "sections Entitled \"Endorsements.\"");
-// WriteString(os, "");
-// WriteString(os, "7. COLLECTIONS OF DOCUMENTS");
-// WriteString(os, "");
-// WriteString(os, "You may make a collection consisting of the Document and other documents");
-// WriteString(os, "released under this License, and replace the individual copies of this");
-// WriteString(os, "License in the various documents with a single copy that is included in");
-// WriteString(os, "the collection, provided that you follow the rules of this License for");
-// WriteString(os, "verbatim copying of each of the documents in all other respects.");
-// WriteString(os, "");
-// WriteString(os, "You may extract a single document from such a collection, and distribute");
-// WriteString(os, "it individually under this License, provided you insert a copy of this");
-// WriteString(os, "License into the extracted document, and follow this License in all");
-// WriteString(os, "other respects regarding verbatim copying of that document.");
-// WriteString(os, "");
-// WriteString(os, "8. AGGREGATION WITH INDEPENDENT WORKS");
-// WriteString(os, "");
-// WriteString(os, "A compilation of the Document or its derivatives with other separate");
-// WriteString(os, "and independent documents or works, in or on a volume of a storage or");
-// WriteString(os, "distribution medium, is called an \"aggregate\" if the copyright");
-// WriteString(os, "resulting from the compilation is not used to limit the legal rights");
-// WriteString(os, "of the compilation's users beyond what the individual works permit.");
-// WriteString(os, "When the Document is included an aggregate, this License does not");
-// WriteString(os, "apply to the other works in the aggregate which are not themselves");
-// WriteString(os, "derivative works of the Document.");
-// WriteString(os, "");
-// WriteString(os, "If the Cover Text requirement of section 3 is applicable to these");
-// WriteString(os, "copies of the Document, then if the Document is less than one half of");
-// WriteString(os, "the entire aggregate, the Document's Cover Texts may be placed on");
-// WriteString(os, "covers that bracket the Document within the aggregate, or the");
-// WriteString(os, "electronic equivalent of covers if the Document is in electronic form.");
-// WriteString(os, "Otherwise they must appear on printed covers that bracket the whole");
-// WriteString(os, "aggregate.");
-// WriteString(os, "");
-// WriteString(os, "9. TRANSLATION");
-// WriteString(os, "");
-// WriteString(os, "Translation is considered a kind of modification, so you may");
-// WriteString(os, "distribute translations of the Document under the terms of section 4.");
-// WriteString(os, "Replacing Invariant Sections with translations requires special");
-// WriteString(os, "permission from their copyright holders, but you may include");
-// WriteString(os, "translations of some or all Invariant Sections in addition to the");
-// WriteString(os, "original versions of these Invariant Sections. You may include a");
-// WriteString(os, "translation of this License, and all the license notices in the");
-// WriteString(os, "Document, and any Warrany Disclaimers, provided that you also include");
-// WriteString(os, "the original English version of this License and the original versions");
-// WriteString(os, "of those notices and disclaimers. In case of a disagreement between");
-// WriteString(os, "the translation and the original version of this License or a notice");
-// WriteString(os, "or disclaimer, the original version will prevail.");
-// WriteString(os, "");
-// WriteString(os, "If a section in the Document is Entitled \"Acknowledgements\",");
-// WriteString(os, "\"Dedications\", or \"History\", the requirement (section 4) to Preserve");
-// WriteString(os, "its Title (section 1) will typically require changing the actual");
-// WriteString(os, "title.");
-// WriteString(os, "");
-// WriteString(os, "10. TERMINATION");
-// WriteString(os, "");
-// WriteString(os, "You may not copy, modify, sublicense, or distribute the Document except");
-// WriteString(os, "as expressly provided for under this License. Any other attempt to");
-// WriteString(os, "copy, modify, sublicense or distribute the Document is void, and will");
-// WriteString(os, "automatically terminate your rights under this License. However,");
-// WriteString(os, "parties who have received copies, or rights, from you under this");
-// WriteString(os, "License will not have their licenses terminated so long as such");
-// WriteString(os, "parties remain in full compliance.");
-// WriteString(os, "");
-// WriteString(os, "11. FUTURE REVISIONS OF THIS LICENSE");
-// WriteString(os, "");
-// WriteString(os, "The Free Software Foundation may publish new, revised versions");
-// WriteString(os, "of the GNU Free Documentation License from time to time. Such new");
-// WriteString(os, "versions will be similar in spirit to the present version, but may");
-// WriteString(os, "differ in detail to address new problems or concerns. See");
-// WriteString(os, "http://www.gnu.org/copyleft/.");
-// WriteString(os, "");
-// WriteString(os, "Each version of the License is given a distinguishing version number.");
-// WriteString(os, "If the Document specifies that a particular numbered version of this");
-// WriteString(os, "License \"or any later version\" applies to it, you have the option of");
-// WriteString(os, "following the terms and conditions either of that specified version or");
-// WriteString(os, "of any later version that has been published (not as a draft) by the");
-// WriteString(os, "Free Software Foundation. If the Document does not specify a version");
-// WriteString(os, "number of this License, you may choose any version ever published (not");
-// WriteString(os, "as a draft) by the Free Software Foundation.");
-// WriteString(os, "-->");
-// }
-
- private static void CreateTrailer(BufferedWriter os) throws IOException {
- WriteString(os, "</descriptions>");
- }
-
- private static void WriteSynopsis(BufferedWriter os, String Synopsis, boolean indent) throws IOException {
- String ss = TexinfoUtils.transformTags(Synopsis);
- String[] tt = ss.split("<eol>");
- String aa = "";
- String spaces = indent ? " " : " ";
- WriteString(os, spaces + "<synopsis>");
- if (null != Synopsis) {
- for (int pp = 0; pp < tt.length; pp++) {
- WriteString(os, spaces + tt[pp]);
-// if (tt[pp].equals("<br>")) {
-// WriteString(os, spaces + aa + "\n");
-// aa = "";
-// }
-// else {
-// if ((aa.length() + tt[pp].length()) > 64) {
-// WriteString(os, spaces + aa);
-// aa = "";
-// }
-// aa = aa + " " + tt[pp];
-// }
- }
- }
- if (aa.length() > 0) WriteString(os, " " + aa);
- WriteString(os, spaces + "</synopsis>");
- }
-
- private static String HandleInclude (String srcdir, String line, String Synopsis) {
- Pattern p = Pattern.compile("@include\\s+(.*?)\\.texi");
- Matcher mm = p.matcher(line);
- if (mm.find()) {
- String il;
- BufferedReader is = null;
- try {
- String fileName = (srcdir.endsWith("/") ? srcdir : srcdir + "/") + mm.replaceAll("examples/$1");
- is = new BufferedReader(new FileReader(fileName));
- while (null != (il = is.readLine())) {
- // C Help does not ignore "<" or ">" inside a <pre> or <samp> tag
- // so we have to prepare for two levels of indirection. The
- // first is for xml to interpret and the second is for the
- // C Help processor to interpret. So, we put &lt; and &gt; which
- // will be transformed into &amp;lt; by the tag transformer.
- Pattern p1 = Pattern.compile("<");
- Pattern p2 = Pattern.compile(">");
- Matcher mm1 = p1.matcher(il);
- il = mm1.replaceAll("&lt;");
- Matcher mm2 = p2.matcher(il);
- il = mm2.replaceAll("&gt;");
- Synopsis = ((Synopsis == null) ? "" : Synopsis + " " ) + ((il.length() == 0) ? "<br><br>" :
- il + "<eol>");
- }
- } catch (IOException e) {
- System.out.println("IOException reading example file");
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- }
- }
- }
- }
- return Synopsis;
- }
- private static void HandleDeftypefun(BufferedWriter os, BufferedReader is, String s, String srcdir) throws IOException {
- String il;
- FunctionDef fd;
- List FDefs = new ArrayList();
- String Synopsis = null;
-
- if (null != (fd = HandleFunctionDef(is, s))) FDefs.add(fd);
-
- while (null != (il = is.readLine())) {
- Matcher mm = IncludePattern.matcher(il);
- if (il.startsWith("@deftypefunx")) {
- if (null != (fd = HandleFunctionDef(is, il))) FDefs.add(fd);
- }
- else if (mm.matches()) {
- if (!IncludeList.contains(mm.group(1)))
- IncludeList.add(mm.group(1));
- }
- else if (il.startsWith("@comment") ||
- il.startsWith("@c ") ||
- il.startsWith("@pindex")) { // ignore
- }
- else if (il.startsWith("@include") && fd != null) {
- Synopsis = HandleInclude(srcdir, il, Synopsis);
- }
- else if (il.startsWith("@end deftypefun")) {
- for (int kk = 0; kk < FDefs.size(); kk++) {
- fd = (FunctionDef)FDefs.get(kk);
-
- WriteString(os, " <construct id=\"function-" + fd.FunctionName + "\" type=\"function\">");
-
- WriteString(os, " <function returntype=\"" + fd.ReturnType + "\">");
-
- WriteString(os, " <prototype>");
- String[] parms = fd.Parameters;
- for (int i = 0; i < parms.length; i++) {
- String parm = TexinfoUtils.stripProtoTags(parms[i]);
- WriteString(os, " <parameter content=\"" + parm + "\"/>");
- }
- WriteString(os, " </prototype>");
-
- if (fd.IncludeList != null) {
- WriteString(os, " <headers>");
- Object[] incs = fd.IncludeList;
- for (int j = 0; j < incs.length; j++) {
- String inc = (String)incs[j];
- WriteString(os, " <header filename = \"" + inc + "\"/>");
- }
- WriteString(os, " </headers>");
- }
-
- if (null != Synopsis) WriteSynopsis(os, Synopsis, false);
-
- WriteString(os, " </function>");
- WriteString(os, " </construct>");
- }
- return;
- }
- else {
- Synopsis = ((Synopsis == null) ? "" : Synopsis + " " ) + ((il.length() == 0) ? "<br><br>" :
- il + "<eol>");
- }
- }
- FDefs.clear();
-
- }
-
- private static class OnlyTexi implements FilenameFilter {
- public boolean accept(File dir, String s) {
- return (s.endsWith(".texi")) ? true : false;
- }
- }
-
- public static void BuildXMLFromTexinfo(String srcdir, String dstdir) {
- try {
- BufferedWriter os = new BufferedWriter(new FileWriter(dstdir));
-
- CreateHeader(os);
-// CreateLicense(os);
-
- WriteString(os, "<descriptions>");
-
- try {
- String[] dir = new java.io.File(srcdir).list(new OnlyTexi());
- for (int i = 0; i < dir.length; i++) {
- String qFile = srcdir.endsWith("/")
- ? srcdir + dir[i]
- : srcdir + "/" + dir[i];
-
- try {
- BufferedReader is = new BufferedReader(new FileReader(qFile));
- String il;
-
- while (null != (il = is.readLine())) {
- Matcher mm = IncludePattern.matcher(il);
- if (il.startsWith("@deftypefun")) { // handle @deftypefun[x]
- HandleDeftypefun(os, is, il, srcdir);
- }
- else if (il.startsWith("@deftp")) { // handle @deftp
- HandleDeftp(os, is, il);
- }
- else if (mm.matches()) { // handle @comment <include_file>
- if (!IncludeList.contains(mm.group(1)))
- IncludeList.add(mm.group(1));
- }
- else if (il.startsWith("@end deftypefn"))
- // Handle accumulated header file comments that are in
- // constructs we aren't parsing.
- IncludeList.clear();
- }
- is.close();
- }
- catch (IOException e) {
- System.out.println("Input File IOException: " + e);
- return;
- }
- }
- }
- catch (NullPointerException e) {
- System.out.println("NullPointerException: " + e);
- return;
- }
-
- CreateTrailer(os);
-
- os.close();
- }
- catch (IOException e) {
- System.out.println("Output File IOException: " + e);
- return;
- }
- }
-
- public static void main(String[] args) {
- BuildXMLFromTexinfo(args[0], args[1]);
- }
+// private static void CreateLicense(BufferedWriter os) throws IOException {
+// WriteString(os, "<!--");
+// WriteString(os, "A.1 GNU Free Documentation License");
+// WriteString(os,"Version 1.2, November 2002");
+// WriteString(os, "");
+// WriteString(os, "Copyright &copy; 2000,2001,2002 Free Software Foundation, Inc.");
+// WriteString(os, "59 Temple Place, Suite 330, Boston, MA 02111-1307, USA");
+// WriteString(os, "");
+// WriteString(os, "Everyone is permitted to copy and distribute verbatim copies");
+// WriteString(os, "of this license document, but changing it is not allowed.");
+// WriteString(os, "");
+// WriteString(os, "1. PREAMBLE");
+// WriteString(os, "");
+// WriteString(os, "The purpose of this License is to make a manual, textbook, or other");
+// WriteString(os, "functional and useful document free in the sense of freedom: to");
+// WriteString(os, "assure everyone the effective freedom to copy and redistribute it,");
+// WriteString(os, "with or without modifying it, either commercially or noncommercially.");
+// WriteString(os, "Secondarily, this License preserves for the author and publisher a way");
+// WriteString(os, "to get credit for their work, while not being considered responsible");
+// WriteString(os, "for modifications made by others.");
+// WriteString(os, "");
+// WriteString(os, "This License is a kind of \"copyleft\", which means that derivative");
+// WriteString(os, "works of the document must themselves be free in the same sense. It");
+// WriteString(os, "complements the GNU General Public License, which is a copyleft");
+// WriteString(os, "license designed for free software.");
+// WriteString(os, "");
+// WriteString(os, "We have designed this License in order to use it for manuals for free");
+// WriteString(os, "software, because free software needs free documentation: a free");
+// WriteString(os, "program should come with manuals providing the same freedoms that the");
+// WriteString(os, "software does. But this License is not limited to software manuals;");
+// WriteString(os, "it can be used for any textual work, regardless of subject matter or");
+// WriteString(os, "whether it is published as a printed book. We recommend this License");
+// WriteString(os, "principally for works whose purpose is instruction or reference.");
+// WriteString(os, "");
+// WriteString(os, "2. APPLICABILITY AND DEFINITIONS");
+// WriteString(os, "");
+// WriteString(os, "This License applies to any manual or other work, in any medium, that");
+// WriteString(os, "contains a notice placed by the copyright holder saying it can be");
+// WriteString(os, "distributed under the terms of this License. Such a notice grants a");
+// WriteString(os, "world-wide, royalty-free license, unlimited in duration, to use that");
+// WriteString(os, "work under the conditions stated herein. The \"Document\", below,");
+// WriteString(os, "refers to any such manual or work. Any member of the public is a");
+// WriteString(os, "licensee, and is addressed as \"you\". You accept the license if you");
+// WriteString(os, "copy, modify or distribute the work in a way requiring permission");
+// WriteString(os, "under copyright law.");
+// WriteString(os, "");
+// WriteString(os, "A \"Modified Version\" of the Document means any work containing the");
+// WriteString(os, "Document or a portion of it, either copied verbatim, or with");
+// WriteString(os, "modifications and/or translated into another language.");
+// WriteString(os, "");
+// WriteString(os, "A \"Secondary Section\" is a named appendix or a front-matter section");
+// WriteString(os, "of the Document that deals exclusively with the relationship of the");
+// WriteString(os, "publishers or authors of the Document to the Document's overall");
+// WriteString(os, "subject (or to related matters) and contains nothing that could fall");
+// WriteString(os, "directly within that overall subject. (Thus, if the Document is in");
+// WriteString(os, "part a textbook of mathematics, a Secondary Section may not explain");
+// WriteString(os, "any mathematics.) The relationship could be a matter of historical");
+// WriteString(os, "connection with the subject or with related matters, or of legal,");
+// WriteString(os, "commercial, philosophical, ethical or political position regarding");
+// WriteString(os, "them.");
+// WriteString(os, "");
+// WriteString(os, "The \"Invariant Sections\" are certain Secondary Sections whose titles");
+// WriteString(os, "are designated, as being those of Invariant Sections, in the notice");
+// WriteString(os, "that says that the Document is released under this License. If a");
+// WriteString(os, "section does not fit the above definition of Secondary then it is not");
+// WriteString(os, "allowed to be designated as Invariant. The Document may contain zero");
+// WriteString(os, "Invariant Sections. If the Document does not identify any Invariant");
+// WriteString(os, "Sections then there are none.");
+// WriteString(os, "");
+// WriteString(os, "The \"Cover Texts\" are certain short passages of text that are listed,");
+// WriteString(os, "as Front-Cover Texts or Back-Cover Texts, in the notice that says that");
+// WriteString(os, "the Document is released under this License. A Front-Cover Text may");
+// WriteString(os, "be at most 5 words, and a Back-Cover Text may be at most 25 words.");
+// WriteString(os, "");
+// WriteString(os, "A \"Transparent\" copy of the Document means a machine-readable copy,");
+// WriteString(os, "represented in a format whose specification is available to the");
+// WriteString(os, "general public, that is suitable for revising the document");
+// WriteString(os, "straightforwardly with generic text editors or (for images composed of");
+// WriteString(os, "pixels) generic paint programs or (for drawings) some widely available");
+// WriteString(os, "drawing editor, and that is suitable for input to text formatters or");
+// WriteString(os, "for automatic translation to a variety of formats suitable for input");
+// WriteString(os, "to text formatters. A copy made in an otherwise Transparent file");
+// WriteString(os, "format whose markup, or absence of markup, has been arranged to thwart");
+// WriteString(os, "or discourage subsequent modification by readers is not Transparent.");
+// WriteString(os, "An image format is not Transparent if used for any substantial amount");
+// WriteString(os, "of text. A copy that is not \"Transparent\" is called \"Opaque\".");
+// WriteString(os, "");
+// WriteString(os, "Examples of suitable formats for Transparent copies include plain");
+// WriteString(os, "ASCII without markup, Texinfo input format, LaTeX input");
+// WriteString(os, "format, SGML or XML using a publicly available");
+// WriteString(os, "DTD, and standard-conforming simple HTML,");
+// WriteString(os, "PostScript or PDF designed for human modification. Examples");
+// WriteString(os, "of transparent image formats include PNG, XCF and");
+// WriteString(os, "JPG. Opaque formats include proprietary formats that can be");
+// WriteString(os, "read and edited only by proprietary word processors, SGML or");
+// WriteString(os, "XML for which the DTD and/or processing tools are");
+// WriteString(os, "not generally available, and the machine-generated HTML,");
+// WriteString(os, "PostScript or PDF produced by some word processors for");
+// WriteString(os, "output purposes only.");
+// WriteString(os, "");
+// WriteString(os, "The \"Title Page\" means, for a printed book, the title page itself,");
+// WriteString(os, "plus such following pages as are needed to hold, legibly, the material");
+// WriteString(os, "this License requires to appear in the title page. For works in");
+// WriteString(os, "formats which do not have any title page as such, \"Title Page\" means");
+// WriteString(os, "the text near the most prominent appearance of the work's title,");
+// WriteString(os, "preceding the beginning of the body of the text.");
+// WriteString(os, "");
+// WriteString(os, "A section \"Entitled XYZ\" means a named subunit of the Document whose");
+// WriteString(os, "title either is precisely XYZ or contains XYZ in parentheses following");
+// WriteString(os, "text that translates XYZ in another language. (Here XYZ stands for a");
+// WriteString(os, "specific section name mentioned below, such as \"Acknowledgements\",");
+// WriteString(os, "\"Dedications\", \"Endorsements\", or \"History\".) To \"Preserve the Title\"");
+// WriteString(os, "of such a section when you modify the Document means that it remains a");
+// WriteString(os, "section \"Entitled XYZ\" according to this definition.");
+// WriteString(os, "");
+// WriteString(os, "The Document may include Warranty Disclaimers next to the notice which");
+// WriteString(os, "states that this License applies to the Document. These Warranty");
+// WriteString(os, "Disclaimers are considered to be included by reference in this");
+// WriteString(os, "License, but only as regards disclaiming warranties: any other");
+// WriteString(os, "implication that these Warranty Disclaimers may have is void and has");
+// WriteString(os, "no effect on the meaning of this License.");
+// WriteString(os, "");
+// WriteString(os, "3. VERBATIM COPYING");
+// WriteString(os, "");
+// WriteString(os, "You may copy and distribute the Document in any medium, either");
+// WriteString(os, "commercially or noncommercially, provided that this License, the");
+// WriteString(os, "copyright notices, and the license notice saying this License applies");
+// WriteString(os, "to the Document are reproduced in all copies, and that you add no other");
+// WriteString(os, "conditions whatsoever to those of this License. You may not use");
+// WriteString(os, "technical measures to obstruct or control the reading or further");
+// WriteString(os, "copying of the copies you make or distribute. However, you may accept");
+// WriteString(os, "compensation in exchange for copies. If you distribute a large enough");
+// WriteString(os, "number of copies you must also follow the conditions in section 3.");
+// WriteString(os, "");
+// WriteString(os, "You may also lend copies, under the same conditions stated above, and");
+// WriteString(os, "you may publicly display copies.");
+// WriteString(os, "");
+// WriteString(os, "4. COPYING IN QUANTITY");
+// WriteString(os, "");
+// WriteString(os, "If you publish printed copies (or copies in media that commonly have");
+// WriteString(os, "printed covers) of the Document, numbering more than 100, and the");
+// WriteString(os, "Document's license notice requires Cover Texts, you must enclose the");
+// WriteString(os, "copies in covers that carry, clearly and legibly, all these Cover");
+// WriteString(os, "Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on");
+// WriteString(os, "the back cover. Both covers must also clearly and legibly identify");
+// WriteString(os, "you as the publisher of these copies. The front cover must present");
+// WriteString(os, "the full title with all words of the title equally prominent and");
+// WriteString(os, "visible. You may add other material on the covers in addition.");
+// WriteString(os, "Copying with changes limited to the covers, as long as they preserve");
+// WriteString(os, "the title of the Document and satisfy these conditions, can be treated");
+// WriteString(os, "as verbatim copying in other respects.");
+// WriteString(os, "");
+// WriteString(os, "If the required texts for either cover are too voluminous to fit");
+// WriteString(os, "legibly, you should put the first ones listed (as many as fit");
+// WriteString(os, "reasonably) on the actual cover, and continue the rest onto adjacent");
+// WriteString(os, "pages.");
+// WriteString(os, "");
+// WriteString(os, "If you publish or distribute Opaque copies of the Document numbering");
+// WriteString(os, "more than 100, you must either include a machine-readable Transparent");
+// WriteString(os, "copy along with each Opaque copy, or state in or with each Opaque copy");
+// WriteString(os, "a computer-network location from which the general network-using");
+// WriteString(os, "public has access to download using public-standard network protocols");
+// WriteString(os, "a complete Transparent copy of the Document, free of added material.");
+// WriteString(os, "If you use the latter option, you must take reasonably prudent steps,");
+// WriteString(os, "when you begin distribution of Opaque copies in quantity, to ensure");
+// WriteString(os, "that this Transparent copy will remain thus accessible at the stated");
+// WriteString(os, "location until at least one year after the last time you distribute an");
+// WriteString(os, "Opaque copy (directly or through your agents or retailers) of that");
+// WriteString(os, "edition to the public.");
+// WriteString(os, "");
+// WriteString(os, "It is requested, but not required, that you contact the authors of the");
+// WriteString(os, "Document well before redistributing any large number of copies, to give");
+// WriteString(os, "them a chance to provide you with an updated version of the Document.");
+// WriteString(os, "");
+// WriteString(os, "5. MODIFICATIONS");
+// WriteString(os, "");
+// WriteString(os, "You may copy and distribute a Modified Version of the Document under");
+// WriteString(os, "the conditions of sections 2 and 3 above, provided that you release");
+// WriteString(os, "the Modified Version under precisely this License, with the Modified");
+// WriteString(os, "Version filling the role of the Document, thus licensing distribution");
+// WriteString(os, "and modification of the Modified Version to whoever possesses a copy");
+// WriteString(os, "of it. In addition, you must do these things in the Modified Version:");
+// WriteString(os, "");
+// WriteString(os, " 1. Use in the Title Page (and on the covers, if any) a title distinct");
+// WriteString(os, " from that of the Document, and from those of previous versions");
+// WriteString(os, " (which should, if there were any, be listed in the History section");
+// WriteString(os, " of the Document). You may use the same title as a previous version");
+// WriteString(os, " if the original publisher of that version gives permission.");
+// WriteString(os, "");
+// WriteString(os, " 2. List on the Title Page, as authors, one or more persons or entities");
+// WriteString(os, " responsible for authorship of the modifications in the Modified");
+// WriteString(os, " Version, together with at least five of the principal authors of the");
+// WriteString(os, " Document (all of its principal authors, if it has fewer than five),");
+// WriteString(os, " unless they release you from this requirement.");
+// WriteString(os, "");
+// WriteString(os, " 3. State on the Title page the name of the publisher of the");
+// WriteString(os, " Modified Version, as the publisher.");
+// WriteString(os, "");
+// WriteString(os, " 4. Preserve all the copyright notices of the Document.");
+// WriteString(os, "");
+// WriteString(os, " 5. Add an appropriate copyright notice for your modifications");
+// WriteString(os, " adjacent to the other copyright notices.");
+// WriteString(os, "");
+// WriteString(os, " 6. Include, immediately after the copyright notices, a license notice");
+// WriteString(os, " giving the public permission to use the Modified Version under the");
+// WriteString(os, " terms of this License, in the form shown in the Addendum below.");
+// WriteString(os, "");
+// WriteString(os, " 7. Preserve in that license notice the full lists of Invariant Sections");
+// WriteString(os, " and required Cover Texts given in the Document's license notice.");
+// WriteString(os, "");
+// WriteString(os, " 8. Include an unaltered copy of this License.");
+// WriteString(os, "");
+// WriteString(os, " 9. Preserve the section Entitled \"History\", Preserve its Title, and add");
+// WriteString(os, " to it an item stating at least the title, year, new authors, and");
+// WriteString(os, " publisher of the Modified Version as given on the Title Page. If");
+// WriteString(os, " there is no section Entitled \"History\" in the Document, create one");
+// WriteString(os, " stating the title, year, authors, and publisher of the Document as");
+// WriteString(os, " given on its Title Page, then add an item describing the Modified");
+// WriteString(os, " Version as stated in the previous sentence.");
+// WriteString(os, "");
+// WriteString(os, " 10. Preserve the network location, if any, given in the Document for");
+// WriteString(os, " public access to a Transparent copy of the Document, and likewise");
+// WriteString(os, " the network locations given in the Document for previous versions");
+// WriteString(os, " it was based on. These may be placed in the \"History\" section.");
+// WriteString(os, " You may omit a network location for a work that was published at");
+// WriteString(os, " least four years before the Document itself, or if the original");
+// WriteString(os, " publisher of the version it refers to gives permission.");
+// WriteString(os, "");
+// WriteString(os, " 11. For any section Entitled \"Acknowledgements\" or \"Dedications\", Preserve");
+// WriteString(os, " the Title of the section, and preserve in the section all the");
+// WriteString(os, " substance and tone of each of the contributor acknowledgements and/or");
+// WriteString(os, " dedications given therein.");
+// WriteString(os, "");
+// WriteString(os, " 12. Preserve all the Invariant Sections of the Document,");
+// WriteString(os, " unaltered in their text and in their titles. Section numbers");
+// WriteString(os, " or the equivalent are not considered part of the section titles.");
+// WriteString(os, "");
+// WriteString(os, " 13. Delete any section Entitled \"Endorsements\". Such a section");
+// WriteString(os, " may not be included in the Modified Version.");
+// WriteString(os, "");
+// WriteString(os, " 14. Do not retitle any existing section to be Entitled \"Endorsements\" or");
+// WriteString(os, " to conflict in title with any Invariant Section.");
+// WriteString(os, "");
+// WriteString(os, " 15. Preserve any Warranty Disclaimers.");
+// WriteString(os, "");
+// WriteString(os, "");
+// WriteString(os, "If the Modified Version includes new front-matter sections or");
+// WriteString(os, "appendices that qualify as Secondary Sections and contain no material");
+// WriteString(os, "copied from the Document, you may at your option designate some or all");
+// WriteString(os, "of these sections as invariant. To do this, add their titles to the");
+// WriteString(os, "list of Invariant Sections in the Modified Version's license notice.");
+// WriteString(os, "These titles must be distinct from any other section titles.");
+// WriteString(os, "");
+// WriteString(os, "You may add a section Entitled \"Endorsements\", provided it contains");
+// WriteString(os, "nothing but endorsements of your Modified Version by various");
+// WriteString(os, "parties - for example, statements of peer review or that the text has");
+// WriteString(os, "been approved by an organization as the authoritative definition of a");
+// WriteString(os, "standard.");
+// WriteString(os, "");
+// WriteString(os, "You may add a passage of up to five words as a Front-Cover Text, and a");
+// WriteString(os, "passage of up to 25 words as a Back-Cover Text, to the end of the list");
+// WriteString(os, "of Cover Texts in the Modified Version. Only one passage of");
+// WriteString(os, "Front-Cover Text and one of Back-Cover Text may be added by (or");
+// WriteString(os, "through arrangements made by) any one entity. If the Document already");
+// WriteString(os, "includes a cover text for the same cover, previously added by you or");
+// WriteString(os, "by arrangement made by the same entity you are acting on behalf of,");
+// WriteString(os, "you may not add another; but you may replace the old one, on explicit");
+// WriteString(os, "permission from the previous publisher that added the old one.");
+// WriteString(os, "");
+// WriteString(os, "The author(s) and publisher(s) of the Document do not by this License");
+// WriteString(os, "give permission to use their names for publicity for or to assert or");
+// WriteString(os, "imply endorsement of any Modified Version.");
+// WriteString(os, "");
+// WriteString(os, "6. COMBINING DOCUMENTS");
+// WriteString(os, "");
+// WriteString(os, "You may combine the Document with other documents released under this");
+// WriteString(os, "License, under the terms defined in section 4 above for modified");
+// WriteString(os, "versions, provided that you include in the combination all of the");
+// WriteString(os, "Invariant Sections of all of the original documents, unmodified, and");
+// WriteString(os, "list them all as Invariant Sections of your combined work in its");
+// WriteString(os, "license notice, and that you preserve all their Warranty Disclaimers.");
+// WriteString(os, "");
+// WriteString(os, "The combined work need only contain one copy of this License, and");
+// WriteString(os, "multiple identical Invariant Sections may be replaced with a single");
+// WriteString(os, "copy. If there are multiple Invariant Sections with the same name but");
+// WriteString(os, "different contents, make the title of each such section unique by");
+// WriteString(os, "adding at the end of it, in parentheses, the name of the original");
+// WriteString(os, "author or publisher of that section if known, or else a unique number.");
+// WriteString(os, "Make the same adjustment to the section titles in the list of");
+// WriteString(os, "Invariant Sections in the license notice of the combined work.");
+// WriteString(os, "");
+// WriteString(os, "In the combination, you must combine any sections Entitled \"History\"");
+// WriteString(os, "in the various original documents, forming one section Entitled");
+// WriteString(os, "\"History\"; likewise combine any sections Entitled \"Acknowledgements\",");
+// WriteString(os, "and any sections Entitled \"Dedications\". You must delete all");
+// WriteString(os, "sections Entitled \"Endorsements.\"");
+// WriteString(os, "");
+// WriteString(os, "7. COLLECTIONS OF DOCUMENTS");
+// WriteString(os, "");
+// WriteString(os, "You may make a collection consisting of the Document and other documents");
+// WriteString(os, "released under this License, and replace the individual copies of this");
+// WriteString(os, "License in the various documents with a single copy that is included in");
+// WriteString(os, "the collection, provided that you follow the rules of this License for");
+// WriteString(os, "verbatim copying of each of the documents in all other respects.");
+// WriteString(os, "");
+// WriteString(os, "You may extract a single document from such a collection, and distribute");
+// WriteString(os, "it individually under this License, provided you insert a copy of this");
+// WriteString(os, "License into the extracted document, and follow this License in all");
+// WriteString(os, "other respects regarding verbatim copying of that document.");
+// WriteString(os, "");
+// WriteString(os, "8. AGGREGATION WITH INDEPENDENT WORKS");
+// WriteString(os, "");
+// WriteString(os, "A compilation of the Document or its derivatives with other separate");
+// WriteString(os, "and independent documents or works, in or on a volume of a storage or");
+// WriteString(os, "distribution medium, is called an \"aggregate\" if the copyright");
+// WriteString(os, "resulting from the compilation is not used to limit the legal rights");
+// WriteString(os, "of the compilation's users beyond what the individual works permit.");
+// WriteString(os, "When the Document is included an aggregate, this License does not");
+// WriteString(os, "apply to the other works in the aggregate which are not themselves");
+// WriteString(os, "derivative works of the Document.");
+// WriteString(os, "");
+// WriteString(os, "If the Cover Text requirement of section 3 is applicable to these");
+// WriteString(os, "copies of the Document, then if the Document is less than one half of");
+// WriteString(os, "the entire aggregate, the Document's Cover Texts may be placed on");
+// WriteString(os, "covers that bracket the Document within the aggregate, or the");
+// WriteString(os, "electronic equivalent of covers if the Document is in electronic form.");
+// WriteString(os, "Otherwise they must appear on printed covers that bracket the whole");
+// WriteString(os, "aggregate.");
+// WriteString(os, "");
+// WriteString(os, "9. TRANSLATION");
+// WriteString(os, "");
+// WriteString(os, "Translation is considered a kind of modification, so you may");
+// WriteString(os, "distribute translations of the Document under the terms of section 4.");
+// WriteString(os, "Replacing Invariant Sections with translations requires special");
+// WriteString(os, "permission from their copyright holders, but you may include");
+// WriteString(os, "translations of some or all Invariant Sections in addition to the");
+// WriteString(os, "original versions of these Invariant Sections. You may include a");
+// WriteString(os, "translation of this License, and all the license notices in the");
+// WriteString(os, "Document, and any Warrany Disclaimers, provided that you also include");
+// WriteString(os, "the original English version of this License and the original versions");
+// WriteString(os, "of those notices and disclaimers. In case of a disagreement between");
+// WriteString(os, "the translation and the original version of this License or a notice");
+// WriteString(os, "or disclaimer, the original version will prevail.");
+// WriteString(os, "");
+// WriteString(os, "If a section in the Document is Entitled \"Acknowledgements\",");
+// WriteString(os, "\"Dedications\", or \"History\", the requirement (section 4) to Preserve");
+// WriteString(os, "its Title (section 1) will typically require changing the actual");
+// WriteString(os, "title.");
+// WriteString(os, "");
+// WriteString(os, "10. TERMINATION");
+// WriteString(os, "");
+// WriteString(os, "You may not copy, modify, sublicense, or distribute the Document except");
+// WriteString(os, "as expressly provided for under this License. Any other attempt to");
+// WriteString(os, "copy, modify, sublicense or distribute the Document is void, and will");
+// WriteString(os, "automatically terminate your rights under this License. However,");
+// WriteString(os, "parties who have received copies, or rights, from you under this");
+// WriteString(os, "License will not have their licenses terminated so long as such");
+// WriteString(os, "parties remain in full compliance.");
+// WriteString(os, "");
+// WriteString(os, "11. FUTURE REVISIONS OF THIS LICENSE");
+// WriteString(os, "");
+// WriteString(os, "The Free Software Foundation may publish new, revised versions");
+// WriteString(os, "of the GNU Free Documentation License from time to time. Such new");
+// WriteString(os, "versions will be similar in spirit to the present version, but may");
+// WriteString(os, "differ in detail to address new problems or concerns. See");
+// WriteString(os, "http://www.gnu.org/copyleft/.");
+// WriteString(os, "");
+// WriteString(os, "Each version of the License is given a distinguishing version number.");
+// WriteString(os, "If the Document specifies that a particular numbered version of this");
+// WriteString(os, "License \"or any later version\" applies to it, you have the option of");
+// WriteString(os, "following the terms and conditions either of that specified version or");
+// WriteString(os, "of any later version that has been published (not as a draft) by the");
+// WriteString(os, "Free Software Foundation. If the Document does not specify a version");
+// WriteString(os, "number of this License, you may choose any version ever published (not");
+// WriteString(os, "as a draft) by the Free Software Foundation.");
+// WriteString(os, "-->");
+// }
+
+ private static void CreateTrailer(BufferedWriter os) throws IOException {
+ WriteString(os, "</descriptions>");
+ }
+
+ private static void WriteSynopsis(BufferedWriter os, String Synopsis, boolean indent) throws IOException {
+ String ss = TexinfoUtils.transformTags(Synopsis);
+ String[] tt = ss.split("<eol>");
+ String aa = "";
+ String spaces = indent ? " " : " ";
+ WriteString(os, spaces + "<synopsis>");
+ if (null != Synopsis) {
+ for (int pp = 0; pp < tt.length; pp++) {
+ WriteString(os, spaces + tt[pp]);
+// if (tt[pp].equals("<br>")) {
+// WriteString(os, spaces + aa + "\n");
+// aa = "";
+// }
+// else {
+// if ((aa.length() + tt[pp].length()) > 64) {
+// WriteString(os, spaces + aa);
+// aa = "";
+// }
+// aa = aa + " " + tt[pp];
+// }
+ }
+ }
+ if (aa.length() > 0) WriteString(os, " " + aa);
+ WriteString(os, spaces + "</synopsis>");
+ }
+
+ private static String HandleInclude (String srcdir, String line, String Synopsis) {
+ Pattern p = Pattern.compile("@include\\s+(.*?)\\.texi");
+ Matcher mm = p.matcher(line);
+ if (mm.find()) {
+ String il;
+ BufferedReader is = null;
+ try {
+ String fileName = (srcdir.endsWith("/") ? srcdir : srcdir + "/") + mm.replaceAll("examples/$1");
+ is = new BufferedReader(new FileReader(fileName));
+ while (null != (il = is.readLine())) {
+ // C Help does not ignore "<" or ">" inside a <pre> or <samp> tag
+ // so we have to prepare for two levels of indirection. The
+ // first is for xml to interpret and the second is for the
+ // C Help processor to interpret. So, we put &lt; and &gt; which
+ // will be transformed into &amp;lt; by the tag transformer.
+ Pattern p1 = Pattern.compile("<");
+ Pattern p2 = Pattern.compile(">");
+ Matcher mm1 = p1.matcher(il);
+ il = mm1.replaceAll("&lt;");
+ Matcher mm2 = p2.matcher(il);
+ il = mm2.replaceAll("&gt;");
+ Synopsis = ((Synopsis == null) ? "" : Synopsis + " " ) + ((il.length() == 0) ? "<br><br>" :
+ il + "<eol>");
+ }
+ } catch (IOException e) {
+ System.out.println("IOException reading example file");
+ } finally {
+ if (is != null) {
+ try {
+ is.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ }
+ return Synopsis;
+ }
+ private static void HandleDeftypefun(BufferedWriter os, BufferedReader is, String s, String srcdir) throws IOException {
+ String il;
+ FunctionDef fd;
+ List FDefs = new ArrayList();
+ String Synopsis = null;
+
+ if (null != (fd = HandleFunctionDef(is, s))) FDefs.add(fd);
+
+ while (null != (il = is.readLine())) {
+ Matcher mm = IncludePattern.matcher(il);
+ if (il.startsWith("@deftypefunx")) {
+ if (null != (fd = HandleFunctionDef(is, il))) FDefs.add(fd);
+ }
+ else if (mm.matches()) {
+ if (!IncludeList.contains(mm.group(1)))
+ IncludeList.add(mm.group(1));
+ }
+ else if (il.startsWith("@comment") ||
+ il.startsWith("@c ") ||
+ il.startsWith("@pindex")) { // ignore
+ }
+ else if (il.startsWith("@include") && fd != null) {
+ Synopsis = HandleInclude(srcdir, il, Synopsis);
+ }
+ else if (il.startsWith("@end deftypefun")) {
+ for (int kk = 0; kk < FDefs.size(); kk++) {
+ fd = (FunctionDef)FDefs.get(kk);
+
+ WriteString(os, " <construct id=\"function-" + fd.FunctionName + "\" type=\"function\">");
+
+ WriteString(os, " <function returntype=\"" + fd.ReturnType + "\">");
+
+ WriteString(os, " <prototype>");
+ String[] parms = fd.Parameters;
+ for (int i = 0; i < parms.length; i++) {
+ String parm = TexinfoUtils.stripProtoTags(parms[i]);
+ WriteString(os, " <parameter content=\"" + parm + "\"/>");
+ }
+ WriteString(os, " </prototype>");
+
+ if (fd.IncludeList != null) {
+ WriteString(os, " <headers>");
+ Object[] incs = fd.IncludeList;
+ for (int j = 0; j < incs.length; j++) {
+ String inc = (String)incs[j];
+ WriteString(os, " <header filename = \"" + inc + "\"/>");
+ }
+ WriteString(os, " </headers>");
+ }
+
+ if (null != Synopsis) WriteSynopsis(os, Synopsis, false);
+
+ WriteString(os, " </function>");
+ WriteString(os, " </construct>");
+ }
+ return;
+ }
+ else {
+ Synopsis = ((Synopsis == null) ? "" : Synopsis + " " ) + ((il.length() == 0) ? "<br><br>" :
+ il + "<eol>");
+ }
+ }
+ FDefs.clear();
+
+ }
+
+ private static class OnlyTexi implements FilenameFilter {
+ public boolean accept(File dir, String s) {
+ return (s.endsWith(".texi")) ? true : false;
+ }
+ }
+
+ public static void BuildXMLFromTexinfo(String srcdir, String dstdir) {
+ try {
+ BufferedWriter os = new BufferedWriter(new FileWriter(dstdir));
+
+ CreateHeader(os);
+// CreateLicense(os);
+
+ WriteString(os, "<descriptions>");
+
+ try {
+ String[] dir = new java.io.File(srcdir).list(new OnlyTexi());
+ for (int i = 0; i < dir.length; i++) {
+ String qFile = srcdir.endsWith("/")
+ ? srcdir + dir[i]
+ : srcdir + "/" + dir[i];
+
+ try {
+ BufferedReader is = new BufferedReader(new FileReader(qFile));
+ String il;
+
+ while (null != (il = is.readLine())) {
+ Matcher mm = IncludePattern.matcher(il);
+ if (il.startsWith("@deftypefun")) { // handle @deftypefun[x]
+ HandleDeftypefun(os, is, il, srcdir);
+ }
+ else if (il.startsWith("@deftp")) { // handle @deftp
+ HandleDeftp(os, is, il);
+ }
+ else if (mm.matches()) { // handle @comment <include_file>
+ if (!IncludeList.contains(mm.group(1)))
+ IncludeList.add(mm.group(1));
+ }
+ else if (il.startsWith("@end deftypefn"))
+ // Handle accumulated header file comments that are in
+ // constructs we aren't parsing.
+ IncludeList.clear();
+ }
+ is.close();
+ }
+ catch (IOException e) {
+ System.out.println("Input File IOException: " + e);
+ return;
+ }
+ }
+ }
+ catch (NullPointerException e) {
+ System.out.println("NullPointerException: " + e);
+ return;
+ }
+
+ CreateTrailer(os);
+
+ os.close();
+ }
+ catch (IOException e) {
+ System.out.println("Output File IOException: " + e);
+ return;
+ }
+ }
+
+ public static void main(String[] args) {
+ BuildXMLFromTexinfo(args[0], args[1]);
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseNewlibTexinfo.java b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseNewlibTexinfo.java
index eecce6431a..dadf341e69 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseNewlibTexinfo.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/ParseNewlibTexinfo.java
@@ -21,544 +21,544 @@ import java.util.*;
//arguments: ${glibc_source_path}/manual glibc.xml
public class ParseNewlibTexinfo {
- static final boolean DEBUG = false;
-
- // 1, 2, 3
- static final String RtnType = "(\\w+\\s+(\\w+\\s+)?(\\w+\\s+)?\\**)";
- static final int RtnTypeSIndex = 1;
-
- // 4
- static final String FunctionName = "(\\w+)\\s*\\(";
- static final int FunctionNameIndex = 4;
-
- // 5 and 6
- static final String Parms = "((.*)\\))";
- static final int ParmsIndex = 6;
-
- static final String rest = ".*";
-
- static final String WhiteSpace = "\\s*";
-
- static final Pattern DeftypefunPattern
- = Pattern.compile("^" + WhiteSpace +
- RtnType + WhiteSpace +
- FunctionName + WhiteSpace +
- Parms +
- rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- // 1, 2, 3
- static final String RtnType2 = "(\\w*\\s*(\\w*\\*?\\s+)?(\\w*\\*?\\s+)?\\**\\s*)\\(\\*";
- static final int RtnType2Index = 1;
-
- // 4
- static final String FunctionName2 = "(\\w+)\\s*\\(";
- static final int FunctionName2Index = 4;
-
- // 5 and 6
- static final String Parms2 = "((.*)\\)\\)\\s*)";
- static final int Parms2Index = 6;
-
- // 7
- static final String RtnTypeParms = "(\\(.*\\))";
- static final int RtnTypeParmsIndex = 7;
-
- static final Pattern DeftypefunPattern2
- = Pattern.compile("^" + WhiteSpace +
- RtnType2 + WhiteSpace +
- FunctionName2 + WhiteSpace +
- Parms2 + RtnTypeParms +
- rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- // For va_arg, the prototype is @var{type} so we create a third type of function definition
- // and we make it so the return type ends up taking as many groups as the normal RtnType so
- // the BuildFunctionDef routine can be used without modification.
- // 1, 2, 3
- static final String RtnTypeVar = "@var\\{(\\w+)(\\})(\\s)";
-
- static final Pattern DeftypefunPattern3
- = Pattern.compile("^" + WhiteSpace +
- RtnTypeVar + WhiteSpace +
- FunctionName + WhiteSpace +
- Parms +
- rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
-
- static final Pattern IncludePattern = Pattern.compile("^#include\\s*<((\\w*/)*\\w*\\.h)>\\s*$");
- static final Pattern PindexPattern = Pattern.compile("^@pindex\\s*\\w*\\s*$");
- static final Pattern FindexPattern = Pattern.compile("^@findex\\s*(\\w*)\\s*$");
- static final Pattern SynopsisPattern = Pattern.compile("^\\s*@strong\\{Synopsis\\}\\s*");
- static final Pattern ParmBracketPattern = Pattern.compile("\\((.*)\\)");
- static final Pattern IndexPattern = Pattern.compile("@\\w*index\\s+[a-zA-Z0-9_@\\{\\}]*");
- static final Pattern IndexPattern2 = Pattern.compile("@\\w*index\\{[a-zA-Z0-9_@\\{\\}]*\\}");
- static final Pattern ExamplePattern = Pattern.compile("@example");
- static final Pattern EndExamplePattern = Pattern.compile("@end\\s+example");
- static final Pattern EnumeratePattern = Pattern.compile("@enumerate");
- static final Pattern EndEnumeratePattern = Pattern.compile("@end\\s+enumerate");
- static final Pattern VerbatimPattern = Pattern.compile("@verbatim");
- static final Pattern ItemPattern = Pattern.compile("@item");
- static final Pattern NoIndentPattern = Pattern.compile("@noindent");
- static final Pattern BRPattern = Pattern.compile("&lt;br&gt;");
- static final Pattern EOLPattern = Pattern.compile("&lt;eol&gt;");
- static final Pattern EndVerbatimPattern = Pattern.compile("@end\\s+verbatim");
- static final Pattern TableSampItemPattern = Pattern.compile("(@table\\s*@samp.*)@item\\s*([a-zA-Z_0-9+\\-<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
- static final Pattern TableAsisItemPattern = Pattern.compile("(@table\\s*@asis.*)@item\\s*([a-zA-Z_0-9+\\-,<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
- static final Pattern TableSampPattern = Pattern.compile("@table\\s*@samp", Pattern.MULTILINE);
- static final Pattern TableAsisPattern = Pattern.compile("@table\\s*@asis", Pattern.MULTILINE);
- static final Pattern EndTablePattern = Pattern.compile("@end\\s+table");
- static final Pattern DotsPattern = Pattern.compile("@dots\\{\\}");
- static final Pattern ItemizeMinusPattern= Pattern.compile("@itemize\\s+@minus" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
- static final Pattern ItemizeBulletPattern= Pattern.compile("@itemize\\s+@bullet" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
- static final Pattern XrefPattern = Pattern.compile("@xref\\{[^\\}]*\\}", Pattern.MULTILINE);
- static final Pattern CommandPattern = Pattern.compile("@command\\{([^\\}]*)\\}");
- static final Pattern KbdPattern = Pattern.compile("@kbd\\{([^\\}]*)\\}");
- static final Pattern RPattern = Pattern.compile("@r\\{([^\\}]*)\\}");
- static final Pattern FilePattern = Pattern.compile("@file\\{([^\\}]*)\\}");
- static final Pattern VarPattern = Pattern.compile("@var\\{([^\\}]*)\\}");
- static final Pattern OVarPattern = Pattern.compile("@ovar\\{([^\\}]*)\\}");
- static final Pattern DVarPattern = Pattern.compile("@dvar\\{([^\\},\\,]*),([^\\}]*)\\}");
- static final Pattern CodePattern = Pattern.compile("@code\\{([^\\}]*)\\}");
- static final Pattern EmphPattern = Pattern.compile("@emph\\{([^\\}]*)\\}");
- static final Pattern SampPattern = Pattern.compile("@samp\\{([^\\}]*)\\}");
- static final Pattern OptionPattern = Pattern.compile("@option\\{([^\\}]*)\\}");
- static final Pattern TagPattern = Pattern.compile("@\\w*\\{([^\\}]*)\\}");
- static final Pattern AmpersandPattern = Pattern.compile("&");
- static final Pattern LeftAnglePattern = Pattern.compile("<");
- static final Pattern RightAnglePattern = Pattern.compile(">");
-
- static List IncludeList = new ArrayList();
- static Stack readers = new Stack();
-
- static class FunctionDef {
- String ReturnType;
- String FunctionName;
- String[] Parameters;
- Object[] IncludeList;
- }
-
- static class TPElement {
- String Content;
- String Synopsis;
- }
-
- static class TPDef {
- String TPType;
- String TPName;
- String TPSynopsis;
- TPElement[] TPElements;
- Object[] IncludeList;
- }
-
- private static FunctionDef FindFunctionDef(String name, List FDefs) {
- for (Iterator iterator = FDefs.iterator(); iterator.hasNext();) {
- FunctionDef k = (FunctionDef) iterator.next();
- if (k.FunctionName.equals(name))
- return k;
- }
- return null;
- }
-
- private static FunctionDef BuildFunctionDef(Matcher m, FunctionDef fd) {
- fd.ReturnType = m.group(RtnTypeSIndex);
- fd.FunctionName = m.group(FunctionNameIndex);
-
- if (null != m.group(ParmsIndex)) {
- String tt = TexinfoUtils.stripProtoTags(m.group(ParmsIndex));
- String[] parms = tt.split(",\\s");
- fd.Parameters = parms;
- }
-
- if (IncludeList.size() > 0) {
- fd.IncludeList = IncludeList.toArray();
- }
- return fd;
- }
-
- private static FunctionDef BuildFunctionDef2(Matcher m, FunctionDef fd) {
- fd.ReturnType = m.group(RtnType2Index) + "(*)" + m.group(RtnTypeParmsIndex);
- fd.FunctionName = m.group(FunctionName2Index);
-
- if (null != m.group(Parms2Index)) {
- String tt = TexinfoUtils.stripProtoTags(m.group(Parms2Index));
- String[] parms = tt.split(",\\s");
- fd.Parameters = parms;
- }
-
- if (IncludeList.size() > 0) {
- fd.IncludeList = IncludeList.toArray();
- }
- return fd;
- }
-
- private static void HandleFunctionDefs(BufferedReader is, List FDefs) throws IOException {
- FunctionDef fd;
- String il = null;
- boolean preRead = false;
-
- while (preRead || (il = is.readLine()) != null) {
- preRead = false;
- if (il.startsWith("@end example"))
- return;
-
- Matcher m = DeftypefunPattern.matcher(il);
- Matcher m2 = DeftypefunPattern2.matcher(il);
- Matcher m3 = DeftypefunPattern3.matcher(il);
- Matcher mm = IncludePattern.matcher(il);
-
- if (mm.matches()) {
- if (!IncludeList.contains(mm.group(1)))
- IncludeList.add(mm.group(1));
- }
- else if (m.matches()) {
- fd = FindFunctionDef(m.group(FunctionNameIndex), FDefs);
- if (fd != null)
- BuildFunctionDef(m, fd);
- else
- System.out.println("Missing findex for " + m.group(FunctionNameIndex));
- }
- else if (m2.matches()) {
- fd = FindFunctionDef(m2.group(FunctionName2Index), FDefs);
- if (fd != null)
- BuildFunctionDef2(m2, fd);
- else
- System.out.println("Missing findex for " + m2.group(FunctionName2Index));
- }
- else if (m3.matches()) {
- fd = FindFunctionDef(m3.group(FunctionNameIndex), FDefs);
- if (fd != null)
- BuildFunctionDef(m3, fd);
- else
- System.out.println("Missing findex for " + m3.group(FunctionName2Index));
- }
- else if (il.trim().length() > 0) {
- il = il.trim();
- while (il.endsWith(",")) { // assume prototype extends more than one line
- preRead = true;
- String il2 = is.readLine().trim();
- if (il2 != null && il2.startsWith("@")) { // something wrong, just look at new line fetched
- il = il2;
- continue;
- }
- il = il + il2; // concatenate
- }
- }
- }
- }
-
- private static void WriteString(BufferedWriter os, String s) throws IOException {
- // System.out.println(s);
- os.write(s+"\n", 0, 1+s.length());
- }
-
- private static void CreateHeader(BufferedWriter os) throws IOException {
- WriteString(os, "<!-- This file automatically generated by an Eclipse utility -->");
- WriteString(os, "<!DOCTYPE descriptions [");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT descriptions (construct)*>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT construct (structure|function|synopsis)*>");
- WriteString(os, " <!ATTLIST construct");
- WriteString(os, " id ID #REQUIRED");
- WriteString(os, " type CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT structure (synopsis?, elements?)?>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT elements (element*)>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT element (synopsis*)>");
- WriteString(os, " <!ATTLIST element");
- WriteString(os, " content CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT synopsis (#PCDATA)*>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT function (prototype,headers?,groupsynopsis?,synopsis)>");
- WriteString(os, " <!ATTLIST function");
- WriteString(os, " returntype CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT prototype (parameter+)?>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT parameter (#PCDATA)*>");
- WriteString(os, " <!ATTLIST parameter");
- WriteString(os, " content CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT headers (header+)?>");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT header (#PCDATA)*>");
- WriteString(os, " <!ATTLIST header");
- WriteString(os, " filename CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, " <!ELEMENT groupsynopsis (#PCDATA)*>");
- WriteString(os, " <!ATTLIST groupsynopsis");
- WriteString(os, " id CDATA #REQUIRED");
- WriteString(os, " >");
- WriteString(os, "");
- WriteString(os, "]>");
- WriteString(os, "");
- }
-
- private static void CreateTrailer(BufferedWriter os) throws IOException {
- WriteString(os, "</descriptions>");
- }
-
- private static void WriteDescription(BufferedWriter os, String Synopsis, boolean indent) throws IOException {
- String ss = TexinfoUtils.transformTags(Synopsis);
- String[] tt = ss.split("<eol>");
- String aa = "";
- String spaces = indent ? " " : " ";
- WriteString(os, spaces + "<synopsis>");
- if (null != Synopsis) {
- for (int pp = 0; pp < tt.length; pp++) {
- WriteString(os, spaces + tt[pp]);
-// if (tt[pp].equals("<br>")) {
-// WriteString(os, spaces + aa + "\n");
-// aa = "";
-// }
-// else {
-// if ((aa.length() + tt[pp].length()) > 64) {
-// WriteString(os, spaces + aa);
-// aa = "";
-// }
-// aa = aa + " " + tt[pp];
-// }
- }
- }
- if (aa.length() > 0) WriteString(os, " " + aa);
- WriteString(os, spaces + "</synopsis>");
- }
-
- private static BufferedReader HandleInclude (BufferedReader is, String srcdir, String line) {
- Pattern p = Pattern.compile("@include\\s+(.*?)");
- Matcher mm = p.matcher(line.trim());
- BufferedReader is2 = null;
- if (mm.find()) {
- String fileName = (srcdir.endsWith("/") ? srcdir : srcdir + "/") + mm.replaceAll("$1");
- try {
- is2 = new BufferedReader(new FileReader(fileName));
- readers.push(is);
- } catch (FileNotFoundException e) {
- System.out.println("include " + fileName + " not found");
- // do nothing and return null
- }
- }
- return is2 == null ? is : is2;
- }
-
- private static String HandleDescription(BufferedReader is) throws IOException {
- String Description = null;
- String il;
-
- while (null != (il = is.readLine())) {
- if (il.startsWith("@page") ||
- il.startsWith("@section") ||
- il.startsWith("@node"))
- break;
- Description = ((Description == null) ? "" : Description + " " ) + ((il.length() == 0) ? "<br><br>" :
- il + "<eol>");
- }
-
- return Description;
- }
-
- private static void HandleFunction(BufferedWriter os, BufferedReader is, String s, String builddir) throws IOException {
- String il;
- FunctionDef fd;
- List FDefs = new ArrayList();
- String Description = null;
- boolean synopsisMarker = false;
-
- IncludeList.clear();
+ static final boolean DEBUG = false;
+
+ // 1, 2, 3
+ static final String RtnType = "(\\w+\\s+(\\w+\\s+)?(\\w+\\s+)?\\**)";
+ static final int RtnTypeSIndex = 1;
+
+ // 4
+ static final String FunctionName = "(\\w+)\\s*\\(";
+ static final int FunctionNameIndex = 4;
+
+ // 5 and 6
+ static final String Parms = "((.*)\\))";
+ static final int ParmsIndex = 6;
+
+ static final String rest = ".*";
+
+ static final String WhiteSpace = "\\s*";
+
+ static final Pattern DeftypefunPattern
+ = Pattern.compile("^" + WhiteSpace +
+ RtnType + WhiteSpace +
+ FunctionName + WhiteSpace +
+ Parms +
+ rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ // 1, 2, 3
+ static final String RtnType2 = "(\\w*\\s*(\\w*\\*?\\s+)?(\\w*\\*?\\s+)?\\**\\s*)\\(\\*";
+ static final int RtnType2Index = 1;
+
+ // 4
+ static final String FunctionName2 = "(\\w+)\\s*\\(";
+ static final int FunctionName2Index = 4;
+
+ // 5 and 6
+ static final String Parms2 = "((.*)\\)\\)\\s*)";
+ static final int Parms2Index = 6;
+
+ // 7
+ static final String RtnTypeParms = "(\\(.*\\))";
+ static final int RtnTypeParmsIndex = 7;
+
+ static final Pattern DeftypefunPattern2
+ = Pattern.compile("^" + WhiteSpace +
+ RtnType2 + WhiteSpace +
+ FunctionName2 + WhiteSpace +
+ Parms2 + RtnTypeParms +
+ rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ // For va_arg, the prototype is @var{type} so we create a third type of function definition
+ // and we make it so the return type ends up taking as many groups as the normal RtnType so
+ // the BuildFunctionDef routine can be used without modification.
+ // 1, 2, 3
+ static final String RtnTypeVar = "@var\\{(\\w+)(\\})(\\s)";
+
+ static final Pattern DeftypefunPattern3
+ = Pattern.compile("^" + WhiteSpace +
+ RtnTypeVar + WhiteSpace +
+ FunctionName + WhiteSpace +
+ Parms +
+ rest, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
+
+ static final Pattern IncludePattern = Pattern.compile("^#include\\s*<((\\w*/)*\\w*\\.h)>\\s*$");
+ static final Pattern PindexPattern = Pattern.compile("^@pindex\\s*\\w*\\s*$");
+ static final Pattern FindexPattern = Pattern.compile("^@findex\\s*(\\w*)\\s*$");
+ static final Pattern SynopsisPattern = Pattern.compile("^\\s*@strong\\{Synopsis\\}\\s*");
+ static final Pattern ParmBracketPattern = Pattern.compile("\\((.*)\\)");
+ static final Pattern IndexPattern = Pattern.compile("@\\w*index\\s+[a-zA-Z0-9_@\\{\\}]*");
+ static final Pattern IndexPattern2 = Pattern.compile("@\\w*index\\{[a-zA-Z0-9_@\\{\\}]*\\}");
+ static final Pattern ExamplePattern = Pattern.compile("@example");
+ static final Pattern EndExamplePattern = Pattern.compile("@end\\s+example");
+ static final Pattern EnumeratePattern = Pattern.compile("@enumerate");
+ static final Pattern EndEnumeratePattern = Pattern.compile("@end\\s+enumerate");
+ static final Pattern VerbatimPattern = Pattern.compile("@verbatim");
+ static final Pattern ItemPattern = Pattern.compile("@item");
+ static final Pattern NoIndentPattern = Pattern.compile("@noindent");
+ static final Pattern BRPattern = Pattern.compile("&lt;br&gt;");
+ static final Pattern EOLPattern = Pattern.compile("&lt;eol&gt;");
+ static final Pattern EndVerbatimPattern = Pattern.compile("@end\\s+verbatim");
+ static final Pattern TableSampItemPattern = Pattern.compile("(@table\\s*@samp.*)@item\\s*([a-zA-Z_0-9+\\-<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
+ static final Pattern TableAsisItemPattern = Pattern.compile("(@table\\s*@asis.*)@item\\s*([a-zA-Z_0-9+\\-,<>/ ]*)<eol>(.*@end\\s*table)", Pattern.DOTALL);
+ static final Pattern TableSampPattern = Pattern.compile("@table\\s*@samp", Pattern.MULTILINE);
+ static final Pattern TableAsisPattern = Pattern.compile("@table\\s*@asis", Pattern.MULTILINE);
+ static final Pattern EndTablePattern = Pattern.compile("@end\\s+table");
+ static final Pattern DotsPattern = Pattern.compile("@dots\\{\\}");
+ static final Pattern ItemizeMinusPattern= Pattern.compile("@itemize\\s+@minus" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
+ static final Pattern ItemizeBulletPattern= Pattern.compile("@itemize\\s+@bullet" + "(.*)" + "@end\\s+itemize", Pattern.MULTILINE);
+ static final Pattern XrefPattern = Pattern.compile("@xref\\{[^\\}]*\\}", Pattern.MULTILINE);
+ static final Pattern CommandPattern = Pattern.compile("@command\\{([^\\}]*)\\}");
+ static final Pattern KbdPattern = Pattern.compile("@kbd\\{([^\\}]*)\\}");
+ static final Pattern RPattern = Pattern.compile("@r\\{([^\\}]*)\\}");
+ static final Pattern FilePattern = Pattern.compile("@file\\{([^\\}]*)\\}");
+ static final Pattern VarPattern = Pattern.compile("@var\\{([^\\}]*)\\}");
+ static final Pattern OVarPattern = Pattern.compile("@ovar\\{([^\\}]*)\\}");
+ static final Pattern DVarPattern = Pattern.compile("@dvar\\{([^\\},\\,]*),([^\\}]*)\\}");
+ static final Pattern CodePattern = Pattern.compile("@code\\{([^\\}]*)\\}");
+ static final Pattern EmphPattern = Pattern.compile("@emph\\{([^\\}]*)\\}");
+ static final Pattern SampPattern = Pattern.compile("@samp\\{([^\\}]*)\\}");
+ static final Pattern OptionPattern = Pattern.compile("@option\\{([^\\}]*)\\}");
+ static final Pattern TagPattern = Pattern.compile("@\\w*\\{([^\\}]*)\\}");
+ static final Pattern AmpersandPattern = Pattern.compile("&");
+ static final Pattern LeftAnglePattern = Pattern.compile("<");
+ static final Pattern RightAnglePattern = Pattern.compile(">");
+
+ static List IncludeList = new ArrayList();
+ static Stack readers = new Stack();
+
+ static class FunctionDef {
+ String ReturnType;
+ String FunctionName;
+ String[] Parameters;
+ Object[] IncludeList;
+ }
+
+ static class TPElement {
+ String Content;
+ String Synopsis;
+ }
+
+ static class TPDef {
+ String TPType;
+ String TPName;
+ String TPSynopsis;
+ TPElement[] TPElements;
+ Object[] IncludeList;
+ }
+
+ private static FunctionDef FindFunctionDef(String name, List FDefs) {
+ for (Iterator iterator = FDefs.iterator(); iterator.hasNext();) {
+ FunctionDef k = (FunctionDef) iterator.next();
+ if (k.FunctionName.equals(name))
+ return k;
+ }
+ return null;
+ }
+
+ private static FunctionDef BuildFunctionDef(Matcher m, FunctionDef fd) {
+ fd.ReturnType = m.group(RtnTypeSIndex);
+ fd.FunctionName = m.group(FunctionNameIndex);
+
+ if (null != m.group(ParmsIndex)) {
+ String tt = TexinfoUtils.stripProtoTags(m.group(ParmsIndex));
+ String[] parms = tt.split(",\\s");
+ fd.Parameters = parms;
+ }
+
+ if (IncludeList.size() > 0) {
+ fd.IncludeList = IncludeList.toArray();
+ }
+ return fd;
+ }
+
+ private static FunctionDef BuildFunctionDef2(Matcher m, FunctionDef fd) {
+ fd.ReturnType = m.group(RtnType2Index) + "(*)" + m.group(RtnTypeParmsIndex);
+ fd.FunctionName = m.group(FunctionName2Index);
+
+ if (null != m.group(Parms2Index)) {
+ String tt = TexinfoUtils.stripProtoTags(m.group(Parms2Index));
+ String[] parms = tt.split(",\\s");
+ fd.Parameters = parms;
+ }
+
+ if (IncludeList.size() > 0) {
+ fd.IncludeList = IncludeList.toArray();
+ }
+ return fd;
+ }
+
+ private static void HandleFunctionDefs(BufferedReader is, List FDefs) throws IOException {
+ FunctionDef fd;
+ String il = null;
+ boolean preRead = false;
+
+ while (preRead || (il = is.readLine()) != null) {
+ preRead = false;
+ if (il.startsWith("@end example"))
+ return;
+
+ Matcher m = DeftypefunPattern.matcher(il);
+ Matcher m2 = DeftypefunPattern2.matcher(il);
+ Matcher m3 = DeftypefunPattern3.matcher(il);
+ Matcher mm = IncludePattern.matcher(il);
+
+ if (mm.matches()) {
+ if (!IncludeList.contains(mm.group(1)))
+ IncludeList.add(mm.group(1));
+ }
+ else if (m.matches()) {
+ fd = FindFunctionDef(m.group(FunctionNameIndex), FDefs);
+ if (fd != null)
+ BuildFunctionDef(m, fd);
+ else
+ System.out.println("Missing findex for " + m.group(FunctionNameIndex));
+ }
+ else if (m2.matches()) {
+ fd = FindFunctionDef(m2.group(FunctionName2Index), FDefs);
+ if (fd != null)
+ BuildFunctionDef2(m2, fd);
+ else
+ System.out.println("Missing findex for " + m2.group(FunctionName2Index));
+ }
+ else if (m3.matches()) {
+ fd = FindFunctionDef(m3.group(FunctionNameIndex), FDefs);
+ if (fd != null)
+ BuildFunctionDef(m3, fd);
+ else
+ System.out.println("Missing findex for " + m3.group(FunctionName2Index));
+ }
+ else if (il.trim().length() > 0) {
+ il = il.trim();
+ while (il.endsWith(",")) { // assume prototype extends more than one line
+ preRead = true;
+ String il2 = is.readLine().trim();
+ if (il2 != null && il2.startsWith("@")) { // something wrong, just look at new line fetched
+ il = il2;
+ continue;
+ }
+ il = il + il2; // concatenate
+ }
+ }
+ }
+ }
+
+ private static void WriteString(BufferedWriter os, String s) throws IOException {
+ // System.out.println(s);
+ os.write(s+"\n", 0, 1+s.length());
+ }
+
+ private static void CreateHeader(BufferedWriter os) throws IOException {
+ WriteString(os, "<!-- This file automatically generated by an Eclipse utility -->");
+ WriteString(os, "<!DOCTYPE descriptions [");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT descriptions (construct)*>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT construct (structure|function|synopsis)*>");
+ WriteString(os, " <!ATTLIST construct");
+ WriteString(os, " id ID #REQUIRED");
+ WriteString(os, " type CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT structure (synopsis?, elements?)?>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT elements (element*)>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT element (synopsis*)>");
+ WriteString(os, " <!ATTLIST element");
+ WriteString(os, " content CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT synopsis (#PCDATA)*>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT function (prototype,headers?,groupsynopsis?,synopsis)>");
+ WriteString(os, " <!ATTLIST function");
+ WriteString(os, " returntype CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT prototype (parameter+)?>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT parameter (#PCDATA)*>");
+ WriteString(os, " <!ATTLIST parameter");
+ WriteString(os, " content CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT headers (header+)?>");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT header (#PCDATA)*>");
+ WriteString(os, " <!ATTLIST header");
+ WriteString(os, " filename CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, " <!ELEMENT groupsynopsis (#PCDATA)*>");
+ WriteString(os, " <!ATTLIST groupsynopsis");
+ WriteString(os, " id CDATA #REQUIRED");
+ WriteString(os, " >");
+ WriteString(os, "");
+ WriteString(os, "]>");
+ WriteString(os, "");
+ }
+
+ private static void CreateTrailer(BufferedWriter os) throws IOException {
+ WriteString(os, "</descriptions>");
+ }
+
+ private static void WriteDescription(BufferedWriter os, String Synopsis, boolean indent) throws IOException {
+ String ss = TexinfoUtils.transformTags(Synopsis);
+ String[] tt = ss.split("<eol>");
+ String aa = "";
+ String spaces = indent ? " " : " ";
+ WriteString(os, spaces + "<synopsis>");
+ if (null != Synopsis) {
+ for (int pp = 0; pp < tt.length; pp++) {
+ WriteString(os, spaces + tt[pp]);
+// if (tt[pp].equals("<br>")) {
+// WriteString(os, spaces + aa + "\n");
+// aa = "";
+// }
+// else {
+// if ((aa.length() + tt[pp].length()) > 64) {
+// WriteString(os, spaces + aa);
+// aa = "";
+// }
+// aa = aa + " " + tt[pp];
+// }
+ }
+ }
+ if (aa.length() > 0) WriteString(os, " " + aa);
+ WriteString(os, spaces + "</synopsis>");
+ }
+
+ private static BufferedReader HandleInclude (BufferedReader is, String srcdir, String line) {
+ Pattern p = Pattern.compile("@include\\s+(.*?)");
+ Matcher mm = p.matcher(line.trim());
+ BufferedReader is2 = null;
+ if (mm.find()) {
+ String fileName = (srcdir.endsWith("/") ? srcdir : srcdir + "/") + mm.replaceAll("$1");
+ try {
+ is2 = new BufferedReader(new FileReader(fileName));
+ readers.push(is);
+ } catch (FileNotFoundException e) {
+ System.out.println("include " + fileName + " not found");
+ // do nothing and return null
+ }
+ }
+ return is2 == null ? is : is2;
+ }
+
+ private static String HandleDescription(BufferedReader is) throws IOException {
+ String Description = null;
+ String il;
+
+ while (null != (il = is.readLine())) {
+ if (il.startsWith("@page") ||
+ il.startsWith("@section") ||
+ il.startsWith("@node"))
+ break;
+ Description = ((Description == null) ? "" : Description + " " ) + ((il.length() == 0) ? "<br><br>" :
+ il + "<eol>");
+ }
+
+ return Description;
+ }
+
+ private static void HandleFunction(BufferedWriter os, BufferedReader is, String s, String builddir) throws IOException {
+ String il;
+ FunctionDef fd;
+ List FDefs = new ArrayList();
+ String Description = null;
+ boolean synopsisMarker = false;
+
+ IncludeList.clear();
Matcher mmf = FindexPattern.matcher(s);
- fd = new FunctionDef();
- if (mmf.matches())
- fd.FunctionName = mmf.group(1);
- else
- return;
- FDefs.add(fd);
-
- while (null != (il = is.readLine())) {
- Matcher syn = SynopsisPattern.matcher(il);
- if (il.startsWith("@findex")) {
- synopsisMarker = false;
- Matcher mm2 = FindexPattern.matcher(il);
- FunctionDef fd2 = new FunctionDef();
- if (mm2.matches()) {
- fd2.FunctionName = mm2.group(1);
- FDefs.add(fd2);
- }
- }
- else if (il.startsWith("@example") && synopsisMarker) {
- HandleFunctionDefs(is, FDefs);
- synopsisMarker = false;
- }
- else if (il.startsWith("@include") && fd != null) {
- is = HandleInclude(is, builddir, il);
- }
- else if (syn.matches()) {
- synopsisMarker = true;
- }
- else if (il.startsWith("@strong{Description}")) {
- synopsisMarker = false;
- Description = HandleDescription(is);
- break; // we are done after description has been fetched
- }
- // otherwise ignore line
- }
-
- String name = ((FunctionDef)FDefs.get(0)).FunctionName;
-
+ fd = new FunctionDef();
+ if (mmf.matches())
+ fd.FunctionName = mmf.group(1);
+ else
+ return;
+ FDefs.add(fd);
+
+ while (null != (il = is.readLine())) {
+ Matcher syn = SynopsisPattern.matcher(il);
+ if (il.startsWith("@findex")) {
+ synopsisMarker = false;
+ Matcher mm2 = FindexPattern.matcher(il);
+ FunctionDef fd2 = new FunctionDef();
+ if (mm2.matches()) {
+ fd2.FunctionName = mm2.group(1);
+ FDefs.add(fd2);
+ }
+ }
+ else if (il.startsWith("@example") && synopsisMarker) {
+ HandleFunctionDefs(is, FDefs);
+ synopsisMarker = false;
+ }
+ else if (il.startsWith("@include") && fd != null) {
+ is = HandleInclude(is, builddir, il);
+ }
+ else if (syn.matches()) {
+ synopsisMarker = true;
+ }
+ else if (il.startsWith("@strong{Description}")) {
+ synopsisMarker = false;
+ Description = HandleDescription(is);
+ break; // we are done after description has been fetched
+ }
+ // otherwise ignore line
+ }
+
+ String name = ((FunctionDef)FDefs.get(0)).FunctionName;
+
if (FDefs.size() > 1) {
- for (int kk = 0; kk < FDefs.size(); kk++) {
- fd = (FunctionDef)FDefs.get(kk);
-
- WriteString(os, " <construct id=\"function-" + fd.FunctionName + "\" type=\"function\">");
-
- WriteString(os, " <function returntype=\"" + fd.ReturnType + "\">");
-
- WriteString(os, " <prototype>");
- String[] parms = fd.Parameters;
- if (parms == null)
- System.out.println("null parms for findex " + fd.FunctionName);
- else {
- for (int i = 0; i < parms.length; i++) {
- String parm = TexinfoUtils.stripProtoTags(parms[i]);
- WriteString(os, " <parameter content=\"" + parm + "\"/>");
- }
- }
- WriteString(os, " </prototype>");
-
- if (fd.IncludeList != null) {
- WriteString(os, " <headers>");
- Object[] incs = fd.IncludeList;
- for (int j = 0; j < incs.length; j++) {
- String inc = (String)incs[j];
- WriteString(os, " <header filename = \"" + inc + "\"/>");
- }
- WriteString(os, " </headers>");
- }
-
- if (null != Description)
- WriteString(os, " <groupsynopsis id=\"group-" + name + "\"/>");
-
-
- WriteString(os, " </function>");
- WriteString(os, " </construct>");
- }
-
- if (null != Description) {
- WriteString(os, " <construct id=\"group-" + name + "\" type=\"groupsynopsis\">");
- WriteDescription(os, Description, false);
- WriteString(os, " </construct>");
- }
- }
+ for (int kk = 0; kk < FDefs.size(); kk++) {
+ fd = (FunctionDef)FDefs.get(kk);
+
+ WriteString(os, " <construct id=\"function-" + fd.FunctionName + "\" type=\"function\">");
+
+ WriteString(os, " <function returntype=\"" + fd.ReturnType + "\">");
+
+ WriteString(os, " <prototype>");
+ String[] parms = fd.Parameters;
+ if (parms == null)
+ System.out.println("null parms for findex " + fd.FunctionName);
+ else {
+ for (int i = 0; i < parms.length; i++) {
+ String parm = TexinfoUtils.stripProtoTags(parms[i]);
+ WriteString(os, " <parameter content=\"" + parm + "\"/>");
+ }
+ }
+ WriteString(os, " </prototype>");
+
+ if (fd.IncludeList != null) {
+ WriteString(os, " <headers>");
+ Object[] incs = fd.IncludeList;
+ for (int j = 0; j < incs.length; j++) {
+ String inc = (String)incs[j];
+ WriteString(os, " <header filename = \"" + inc + "\"/>");
+ }
+ WriteString(os, " </headers>");
+ }
+
+ if (null != Description)
+ WriteString(os, " <groupsynopsis id=\"group-" + name + "\"/>");
+
+
+ WriteString(os, " </function>");
+ WriteString(os, " </construct>");
+ }
+
+ if (null != Description) {
+ WriteString(os, " <construct id=\"group-" + name + "\" type=\"groupsynopsis\">");
+ WriteDescription(os, Description, false);
+ WriteString(os, " </construct>");
+ }
+ }
else {
- fd = (FunctionDef)FDefs.get(0);
-
- WriteString(os, " <construct id=\"function-" + fd.FunctionName + "\" type=\"function\">");
-
- WriteString(os, " <function returntype=\"" + fd.ReturnType + "\">");
-
- WriteString(os, " <prototype>");
- String[] parms = fd.Parameters;
- if (parms == null)
- System.out.println("null parms for findex " + fd.FunctionName);
- else {
- for (int i = 0; i < parms.length; i++) {
- String parm = TexinfoUtils.stripProtoTags(parms[i]);
- WriteString(os, " <parameter content=\"" + parm + "\"/>");
- }
- }
- WriteString(os, " </prototype>");
-
- if (fd.IncludeList != null) {
- WriteString(os, " <headers>");
- Object[] incs = fd.IncludeList;
- for (int j = 0; j < incs.length; j++) {
- String inc = (String)incs[j];
- WriteString(os, " <header filename = \"" + inc + "\"/>");
- }
- WriteString(os, " </headers>");
- }
-
- if (null != Description) WriteDescription(os, Description, false);
-
- WriteString(os, " </function>");
- WriteString(os, " </construct>");
- }
- FDefs.clear();
- }
-
- public static void BuildXMLFromTexinfo2(String srcdir, String builddir, BufferedWriter os, String lib) {
- try {
- srcdir = srcdir.endsWith("/") ? srcdir + lib : srcdir + "/" + lib;
- builddir = builddir.endsWith("/") ? builddir + lib : builddir + "/" + lib;
- String qFile = srcdir + "/" + lib + ".texinfo";
-
- try {
- BufferedReader is = new BufferedReader(new FileReader(qFile));
- String il;
- boolean ignore = false;
-
- while (is != null) {
- while (null != (il = is.readLine())) {
- if (!ignore && il.startsWith("@findex")) {
- HandleFunction(os, is, il, builddir);
- }
- else if (!ignore && il.startsWith("@include")) {
- is = HandleInclude(is, builddir, il);
- }
- else if (il.startsWith("@ignore")) {
- ignore = true;
- }
- else if (il.startsWith("@end ignore"))
- ignore = false;
- }
- is.close();
- is = (BufferedReader)readers.pop();
- }
- }
- catch (IOException e) {
- System.out.println("Input File IOException: " + e);
- return;
- }
- catch (EmptyStackException f) {
- // ok, we expect to get here
- }
- }
- catch (NullPointerException e) {
- e.printStackTrace();
- System.out.println("NullPointerException: " + e);
- return;
- }
-
- }
-
- public static void BuildXMLFromTexinfo(String srcdir, String builddir, String dstdir) {
- try {
- BufferedWriter os = new BufferedWriter(new FileWriter(dstdir));
-
- CreateHeader(os);
-// CreateLicense(os);
-
- WriteString(os, "<descriptions>");
- BuildXMLFromTexinfo2(srcdir, builddir, os, "libc");
- BuildXMLFromTexinfo2(srcdir, builddir, os, "libm");
-
-
- CreateTrailer(os);
-
- os.close();
- }
- catch (IOException e) {
- System.out.println("Output File IOException: " + e);
- return;
- }
- }
-
- public static void main(String[] args) {
- BuildXMLFromTexinfo(args[0], args[1], args[2]);
- }
+ fd = (FunctionDef)FDefs.get(0);
+
+ WriteString(os, " <construct id=\"function-" + fd.FunctionName + "\" type=\"function\">");
+
+ WriteString(os, " <function returntype=\"" + fd.ReturnType + "\">");
+
+ WriteString(os, " <prototype>");
+ String[] parms = fd.Parameters;
+ if (parms == null)
+ System.out.println("null parms for findex " + fd.FunctionName);
+ else {
+ for (int i = 0; i < parms.length; i++) {
+ String parm = TexinfoUtils.stripProtoTags(parms[i]);
+ WriteString(os, " <parameter content=\"" + parm + "\"/>");
+ }
+ }
+ WriteString(os, " </prototype>");
+
+ if (fd.IncludeList != null) {
+ WriteString(os, " <headers>");
+ Object[] incs = fd.IncludeList;
+ for (int j = 0; j < incs.length; j++) {
+ String inc = (String)incs[j];
+ WriteString(os, " <header filename = \"" + inc + "\"/>");
+ }
+ WriteString(os, " </headers>");
+ }
+
+ if (null != Description) WriteDescription(os, Description, false);
+
+ WriteString(os, " </function>");
+ WriteString(os, " </construct>");
+ }
+ FDefs.clear();
+ }
+
+ public static void BuildXMLFromTexinfo2(String srcdir, String builddir, BufferedWriter os, String lib) {
+ try {
+ srcdir = srcdir.endsWith("/") ? srcdir + lib : srcdir + "/" + lib;
+ builddir = builddir.endsWith("/") ? builddir + lib : builddir + "/" + lib;
+ String qFile = srcdir + "/" + lib + ".texinfo";
+
+ try {
+ BufferedReader is = new BufferedReader(new FileReader(qFile));
+ String il;
+ boolean ignore = false;
+
+ while (is != null) {
+ while (null != (il = is.readLine())) {
+ if (!ignore && il.startsWith("@findex")) {
+ HandleFunction(os, is, il, builddir);
+ }
+ else if (!ignore && il.startsWith("@include")) {
+ is = HandleInclude(is, builddir, il);
+ }
+ else if (il.startsWith("@ignore")) {
+ ignore = true;
+ }
+ else if (il.startsWith("@end ignore"))
+ ignore = false;
+ }
+ is.close();
+ is = (BufferedReader)readers.pop();
+ }
+ }
+ catch (IOException e) {
+ System.out.println("Input File IOException: " + e);
+ return;
+ }
+ catch (EmptyStackException f) {
+ // ok, we expect to get here
+ }
+ }
+ catch (NullPointerException e) {
+ e.printStackTrace();
+ System.out.println("NullPointerException: " + e);
+ return;
+ }
+
+ }
+
+ public static void BuildXMLFromTexinfo(String srcdir, String builddir, String dstdir) {
+ try {
+ BufferedWriter os = new BufferedWriter(new FileWriter(dstdir));
+
+ CreateHeader(os);
+// CreateLicense(os);
+
+ WriteString(os, "<descriptions>");
+ BuildXMLFromTexinfo2(srcdir, builddir, os, "libc");
+ BuildXMLFromTexinfo2(srcdir, builddir, os, "libm");
+
+
+ CreateTrailer(os);
+
+ os.close();
+ }
+ catch (IOException e) {
+ System.out.println("Output File IOException: " + e);
+ return;
+ }
+ }
+
+ public static void main(String[] args) {
+ BuildXMLFromTexinfo(args[0], args[1], args[2]);
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/TexinfoUtils.java b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/TexinfoUtils.java
index ceb3d91d30..61d8c5e05c 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/TexinfoUtils.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover.texinfoparsers/src/org/eclipse/linuxtools/cdt/libhover/texinfoparsers/TexinfoUtils.java
@@ -14,720 +14,720 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TexinfoUtils {
-
- static final Pattern ParmBracketPattern = Pattern.compile("\\((.*?)\\)");
- static final Pattern IndexPattern = Pattern.compile("@\\w*index\\s+[a-zA-Z0-9_@\\{\\}]*");
- static final Pattern IndexPattern2 = Pattern.compile("@\\w*index\\{[a-zA-Z0-9_@\\{\\}]*\\}");
- static final Pattern ExampleItem = Pattern.compile("(@example)((.*?<br><eol>)*+.*?)(<eol>.*@end\\s+example)");
- static final Pattern ExamplePattern = Pattern.compile("@example");
- static final Pattern EndExamplePattern = Pattern.compile("@end\\s+example");
- static final Pattern SmallExampleItem = Pattern.compile("(@smallexample)((.*?<br><eol>)*+.*?)(<eol>.*@end\\s+smallexample)");
- static final Pattern SmallExamplePattern = Pattern.compile("@smallexample");
- static final Pattern StrongPattern = Pattern.compile("@strong\\{(\\w*)\\}(@\\*)?");
- static final Pattern EndSmallExamplePattern = Pattern.compile("@end\\s+smallexample");
- static final Pattern EnumeratePattern = Pattern.compile("@enumerate");
- static final Pattern EndEnumeratePattern = Pattern.compile("@end\\s+enumerate");
- static final Pattern VerbatimPattern = Pattern.compile("@verbatim");
- static final Pattern ItemPattern = Pattern.compile("@item");
- static final Pattern RefillPattern = Pattern.compile("@refill");
- static final Pattern NoIndentPattern = Pattern.compile("@noindent");
- static final Pattern QuotationPattern = Pattern.compile("@quotation");
- static final Pattern EndQuotation = Pattern.compile("@end\\s+quotation");
- static final Pattern GroupPattern = Pattern.compile("@group");
- static final Pattern TabPattern = Pattern.compile("@tab");
- static final Pattern DeftpPattern = Pattern.compile("@deftp\\s+\\{([^\\}]*?)\\}\\s*\\{([^\\}]*?)\\}");
- static final Pattern EndDeftpPattern = Pattern.compile("@end\\s+deftp");
- static final Pattern CommentPattern = Pattern.compile("@c<eol>|@c\\s+.*?<eol>");
- static final Pattern EndGroupPattern = Pattern.compile("@end\\s+group");
- static final Pattern BracketRefPattern = Pattern.compile("\\(@.?.?ref\\{[^\\}]*\\}\\)");
- static final Pattern BRPattern = Pattern.compile("&lt;br&gt;");
- static final Pattern EOLPattern = Pattern.compile("&lt;eol&gt;");
- static final Pattern EndVerbatimPattern = Pattern.compile("@end\\s+verbatim");
- static final Pattern TableSampItemPattern = Pattern.compile("(@table\\s*@samp.*?)@item\\s+(.*?)(<eol>.*@end\\s+table)", Pattern.DOTALL);
- static final Pattern TableAsisItemPattern = Pattern.compile("(@table\\s*@asis.*?)@item\\s+(.*?)(<eol>.*@end\\+table)", Pattern.DOTALL);
- static final Pattern TableCodeItemPattern = Pattern.compile("(@table\\s*@code.*?)@item\\s+(.*?)(<eol>.*?)(@end\\s+table)", Pattern.DOTALL);
- static final Pattern TableVarItemPattern = Pattern.compile("(@table\\s*@var.*?)@item\\s+(.*?)(<eol>.*@end\\s+table)", Pattern.DOTALL);
- static final Pattern VtableCodeItemPattern = Pattern.compile("(@vtable\\s*@code.*?)@item\\s+(.*?)(<eol>.*@end\\s+vtable)", Pattern.DOTALL);
- static final Pattern MultitableItemPattern = Pattern.compile("(@multitable.*)@item\\s+(.*?)<eol>(.*?@end\\s+multitable)" +
- "|(@multitable.*)@item\\s*<eol>(.*?)<eol>(.*?@end\\s+multitable)", Pattern.DOTALL);
- static final Pattern TableCodeMatchPattern = Pattern.compile("(@table\\s+@code)(.*?)(@end\\s+table)", Pattern.DOTALL);
- static final Pattern TableSampMatchPattern = Pattern.compile("(@table\\s+@samp)(.*?)(@end\\s+table)", Pattern.DOTALL);
- static final Pattern TableAsisMatchPattern = Pattern.compile("(@table\\s+@asis)(.*?)(@end\\s+table)", Pattern.DOTALL);
- static final Pattern TableVarMatchPattern = Pattern.compile("(@table\\s+@var)(.*?)(@end\\s+table)", Pattern.DOTALL);
- static final Pattern TableSampPattern = Pattern.compile("@table\\s*@samp", Pattern.MULTILINE);
- static final Pattern TableAsisPattern = Pattern.compile("@table\\s*@asis", Pattern.MULTILINE);
- static final Pattern TableCodePattern = Pattern.compile("@table\\s*@code", Pattern.MULTILINE);
- static final Pattern TableVarPattern = Pattern.compile("@table\\s*@var", Pattern.MULTILINE);
- static final Pattern VtableCodePattern = Pattern.compile("@vtable\\s*@code", Pattern.MULTILINE);
- static final Pattern MultitablePattern = Pattern.compile("@multitable.*?<DT>", Pattern.DOTALL);
- static final Pattern EndTablePattern = Pattern.compile("@end\\s+table");
- static final Pattern EndVtablePattern = Pattern.compile("@end\\s+vtable");
- static final Pattern EndMultitablePattern = Pattern.compile("@end\\s+multitable");
- static final Pattern DotsPattern = Pattern.compile("@dots\\{\\}");
- static final Pattern ItemizeMinusPattern= Pattern.compile("@itemize\\s+@minus" + "(.*?)" + "@end\\s+itemize", Pattern.DOTALL);
- static final Pattern ItemizeBulletPattern= Pattern.compile("@itemize\\s+@bullet" + "(.*?)" + "@end\\s+itemize", Pattern.DOTALL);
- static final Pattern InfoOnlyPattern = Pattern.compile("@ifinfo.*?@end\\s+ifinfo", Pattern.DOTALL);
- static final Pattern TexOnlyPattern = Pattern.compile("@iftex.*?@end\\s+iftex", Pattern.DOTALL);
- static final Pattern TexPattern = Pattern.compile("@tex.*?@end\\s+tex", Pattern.DOTALL);
- static final Pattern IgnorePattern = Pattern.compile("@ignore.*?@end\\s+ignore", Pattern.DOTALL);
- static final Pattern IfInfoPattern = Pattern.compile("@ifinfo");
- static final Pattern InfinityPattern = Pattern.compile("@infinity");
- static final Pattern EndIfInfoPattern = Pattern.compile("@end\\s+ifinfo");
- static final Pattern NotTexPattern = Pattern.compile("@ifnottex");
- static final Pattern EndNotTexPattern = Pattern.compile("@end\\s+ifnottex");
- static final Pattern DeftypevrPattern = Pattern.compile("@deftypevr\\s+");
- static final Pattern EndDeftypevr = Pattern.compile("@end\\s+deftypevr");
- static final Pattern XrefPattern = Pattern.compile("@xref\\{[^\\}]*\\}", Pattern.MULTILINE);
- static final Pattern PxrefPattern = Pattern.compile("@pxref\\{[^\\}]*\\}", Pattern.MULTILINE);
- static final Pattern AtTPattern = Pattern.compile("@t\\{([^\\}]*)\\}");
- static final Pattern CommandPattern = Pattern.compile("@command\\{([^\\}]*)\\}");
- static final Pattern KbdPattern = Pattern.compile("@kbd\\{([^\\}]*)\\}");
- static final Pattern RPattern = Pattern.compile("@r\\{([^\\}]*)\\}");
- static final Pattern FilePattern = Pattern.compile("@file\\{([^\\}]*)\\}");
- static final Pattern VarPattern = Pattern.compile("@var\\{([^\\}]*)\\}");
- static final Pattern OVarPattern = Pattern.compile("@ovar\\{([^\\}]*)\\}");
- static final Pattern DVarPattern = Pattern.compile("@dvar\\{([^\\},\\,]*),([^\\}]*)\\}");
- static final Pattern AnyVarPattern = Pattern.compile("@[a-z]*var\\{([^\\}]*)\\}");
- static final Pattern CodePattern = Pattern.compile("@code\\{([^\\}]*)\\}");
- static final Pattern EmphPattern = Pattern.compile("@emph\\{([^\\}]*)\\}");
- static final Pattern SampPattern = Pattern.compile("@samp\\{([^\\}]*)\\}");
- static final Pattern OptionPattern = Pattern.compile("@option\\{([^\\}]*)\\}");
- static final Pattern TagPattern = Pattern.compile("@\\w+\\{([^\\}]*)\\}");
- static final Pattern TagCharPattern = Pattern.compile("@([\\{\\}\\:\\*\"])");
- static final Pattern StrandedPeriod = Pattern.compile("(\\w)\\s+\\.\\s+");
- static final Pattern LeftOverPeriod = Pattern.compile("^\\.\\s+<eol>");
- static final Pattern AmpersandPattern = Pattern.compile("&");
- static final Pattern LeftAnglePattern = Pattern.compile("<");
- static final Pattern RightAnglePattern = Pattern.compile(">");
-
- public static String stripProtoTags(String tt) {
- Matcher mm;
- String ss = "";
-
- ss = "";
- while (ss != tt) {
- mm = AnyVarPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1");
- }
-
- ss = "";
- while (ss != tt) {
- mm = DotsPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("...");
- }
-
- ss = "";
- while (ss != tt) {
- mm = CodePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1");
- }
-
- ss = "";
- while (ss != tt) {
- mm = AtTPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TagPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TagCharPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- return tt;
- }
-
- public static String transformTags(String tt) {
- Matcher mm;
- String ss = "";
- int endtableIndex = Integer.MAX_VALUE;
-
- ss = "";
- while (ss != tt) {
- mm = BracketRefPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = XrefPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = CommentPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<eol>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = PxrefPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = DeftypevrPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = StrongPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<h3>$1</h3>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndDeftypevr.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = IndexPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = IndexPattern2.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = NoIndentPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = GroupPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndGroupPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = QuotationPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndQuotation.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = InfinityPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("infinity");
- }
-
- ss = "";
- while (ss != tt) {
- mm = DeftpPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<h4>$1 - $2</h4>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndDeftpPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = RefillPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = VarPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<VAR>$1</VAR>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = DotsPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<small>...</small>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = CommandPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<CODE>$1</CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = CodePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<CODE>$1</CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = KbdPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<KBD>$1</KBD>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EmphPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<EM>$1</EM>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = FilePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<TT>$1</TT>");
- }
-
-
- ss = "";
- while (ss != tt) {
- mm = VerbatimPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndVerbatimPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</CODE>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = SampPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<samp>$1</samp>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = OptionPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<samp>$1</samp>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = ExampleItem.matcher(tt);
- ss = tt;
- // We want to add a break at the end of each example line to preserve
- // formatting when Eclipse processes the xml (e.g. C code lines).
- tt = mm.replaceAll("$1$2<br>$4");
- }
-
- ss = "";
- while (ss != tt) {
- mm = ExamplePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<TABLE><tr><td>&nbsp;</td><td class=example><pre>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndExamplePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</pre></td></tr></table>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = SmallExampleItem.matcher(tt);
- ss = tt;
- // We want to add a break at the end of each example line to preserve
- // formatting when Eclipse processes the xml (e.g. C code lines).
- tt = mm.replaceAll("$1$2<br>$4");
- }
-
- ss = "";
- while (ss != tt) {
- mm = SmallExamplePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<pre>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndSmallExamplePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</pre>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EnumeratePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<OL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndEnumeratePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</OL>");
- }
-
-// ss = "";
-// while (ss != tt) {
-// mm = InfoOnlyPattern.matcher(tt);
-// ss = tt;
-// tt = mm.replaceAll("");
-// }
-
- ss = "";
- while (ss != tt) {
- mm = TexOnlyPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TexPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = IgnorePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = NotTexPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndNotTexPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- // We will treat ifinfo the same as ifnottex which we pass through.
- ss = "";
- while (ss != tt) {
- mm = IfInfoPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndIfInfoPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- endtableIndex = Integer.MAX_VALUE;
- while (ss != tt) {
- mm = TableSampItemPattern.matcher(tt);
- ss = tt;
- if (mm.find()) {
- if (mm.start(4) > endtableIndex) {
- // We try and find the last @[table samp] marker we can find with an @item before @[end table].
- // The end marker has moved forward to make the match which means we have exhausted all @item markers
- // from the last @[table samp] and @[end table] we were using prior to this iteration of the loop.
- // If we change the table markers now, we avoid the prior table from
- // matching any @item marker that sits between tables.
- Matcher mm2 = TableSampMatchPattern.matcher(tt);
- tt = mm2.replaceFirst("<DL>\n$2\n</DL>");
- mm2 = TableSampMatchPattern.matcher(tt);
- if (mm2.find())
- endtableIndex = mm2.start(3);
- }
- else {
- tt = mm.replaceFirst("$1<DT><SAMP>$2</SAMP>\n<DD>$3$4");
- endtableIndex = mm.end(1) + 10 + mm.group(2).length() + 12 + mm.group(3).length();
- }
- }
- }
-
- //FIXME: This parser assumes that a table does not have an @itemize element
- // inside it. It allows the opposite to be true (i.e. a table inside
- // an @itemize element.
-
- ss = "";
- endtableIndex = Integer.MAX_VALUE;
- while (ss != tt) {
- mm = TableAsisItemPattern.matcher(tt);
- ss = tt;
- if (mm.find()) {
- if (mm.start(4) > endtableIndex) {
- // We try and find the last @[table asis] marker we can find with an @item before @[end table].
- // The end marker has moved forward to make the match which means we have exhausted all @item markers
- // from the last @[table asis] and @[end table] we were using prior to this iteration of the loop.
- // If we change the table markers now, we avoid the prior table from
- // matching any @item marker that sits between tables.
- Matcher mm2 = TableAsisMatchPattern.matcher(tt);
- tt = mm2.replaceFirst("<DL>\n$2\n</DL>");
- mm2 = TableAsisMatchPattern.matcher(tt);
- if (mm2.find())
- endtableIndex = mm2.start(3);
- }
- else {
- tt = mm.replaceFirst("$1<DT>$2\n<DD>$3$4");
- endtableIndex = mm.end(1) + 10 + mm.group(2).length() + 12 + mm.group(3).length();
- }
- }
- }
-
- ss = "";
- endtableIndex = Integer.MAX_VALUE;
- while (ss != tt) {
- mm = TableCodeItemPattern.matcher(tt);
- ss = tt;
- if (mm.find()) {
- if (mm.start(4) > endtableIndex) {
- // We try and find the last @[table code] marker we can find with an @item before @[end table].
- // The end marker has moved forward to make the match which means we have exhausted all @item markers
- // from the last @[table code] and @[end table] we were using prior to this iteration of the loop.
- // If we change the table markers now, we avoid the prior table from
- // matching any @item marker that sits between tables.
- Matcher mm2 = TableCodeMatchPattern.matcher(tt);
- tt = mm2.replaceFirst("<DL>\n$2\n</DL>");
- mm2 = TableCodeMatchPattern.matcher(tt);
- if (mm2.find())
- endtableIndex = mm2.start(3);
- }
- else {
- tt = mm.replaceFirst("$1<DT><CODE>$2</CODE>\n<DD>$3$4");
- endtableIndex = mm.end(1) + 10 + mm.group(2).length() + 12 + mm.group(3).length();
- }
- }
- }
-
- ss = "";
- endtableIndex = Integer.MAX_VALUE;
- while (ss != tt) {
- mm = TableVarItemPattern.matcher(tt);
- ss = tt;
- if (mm.find()) {
- if (mm.start(4) > endtableIndex) {
- // We try and find the last @[table var] marker we can find with an @item before @[end table].
- // The end marker has moved forward to make the match which means we have exhausted all @item markers
- // from the last @[table var] and @[end table] we were using prior to this iteration of the loop.
- // If we change the table markers now, we avoid the prior table from
- // matching any @item marker that sits between tables.
- Matcher mm2 = TableVarMatchPattern.matcher(tt);
- tt = mm2.replaceFirst("<DL>\n$2\n</DL>");
- mm2 = TableVarMatchPattern.matcher(tt);
- if (mm2.find())
- endtableIndex = mm2.start(3);
- }
- else {
- tt = mm.replaceFirst("$1<DT><VAR>$2</VAR>\n<DD>$3$4");
- endtableIndex = mm.end(1) + 10 + mm.group(2).length() + 12 + mm.group(3).length();
- }
- }
- }
-
- ss = "";
- while (ss != tt) {
- mm = VtableCodeItemPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1<DT><CODE>$2</CODE>\n<DD>$3");
- }
-
- ss = "";
- while (ss != tt) {
- mm = MultitableItemPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1<DT><pre>$2</pre>\n<DD><br>$3");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableSampPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<DL>\n");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableAsisPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<DL>\n");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableVarPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<DL>\n");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TableCodePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<DL>\n");
- }
-
- ss = "";
- while (ss != tt) {
- mm = VtableCodePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<DL>\n");
- }
-
- ss = "";
- while (ss != tt) {
- mm = MultitablePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<DL>\n<DT>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndTablePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</DL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndVtablePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</DL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = EndMultitablePattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("</DL>");
- }
-
- //FIXME: if there ever is a @itemize @bullet within a
- // @itemize @minus or vice-versa, the following
- // logic will get it wrong.
- ss = "";
- while (ss != tt) {
- mm = ItemizeMinusPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<UL>$1</UL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = ItemizeBulletPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<OL>$1</OL>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = ItemPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("<LI>");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TagPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TagCharPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1");
- }
-
- ss = "";
- while (ss != tt) {
- mm = StrandedPeriod.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("$1. ");
- }
-
- ss = "";
- while (ss != tt) {
- mm = LeftOverPeriod.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- ss = "";
- while (ss != tt) {
- mm = TabPattern.matcher(tt);
- ss = tt;
- tt = mm.replaceAll("");
- }
-
- mm = AmpersandPattern.matcher(tt);
- tt = mm.replaceAll("&amp;");
-
- mm = LeftAnglePattern.matcher(tt);
- tt = mm.replaceAll("&lt;");
-
- mm = RightAnglePattern.matcher(tt);
- tt = mm.replaceAll("&gt;");
-
- // Put back all the eol markers
- mm = EOLPattern.matcher(tt);
- tt = mm.replaceAll("<eol>");
-
- return tt;
- }
+
+ static final Pattern ParmBracketPattern = Pattern.compile("\\((.*?)\\)");
+ static final Pattern IndexPattern = Pattern.compile("@\\w*index\\s+[a-zA-Z0-9_@\\{\\}]*");
+ static final Pattern IndexPattern2 = Pattern.compile("@\\w*index\\{[a-zA-Z0-9_@\\{\\}]*\\}");
+ static final Pattern ExampleItem = Pattern.compile("(@example)((.*?<br><eol>)*+.*?)(<eol>.*@end\\s+example)");
+ static final Pattern ExamplePattern = Pattern.compile("@example");
+ static final Pattern EndExamplePattern = Pattern.compile("@end\\s+example");
+ static final Pattern SmallExampleItem = Pattern.compile("(@smallexample)((.*?<br><eol>)*+.*?)(<eol>.*@end\\s+smallexample)");
+ static final Pattern SmallExamplePattern = Pattern.compile("@smallexample");
+ static final Pattern StrongPattern = Pattern.compile("@strong\\{(\\w*)\\}(@\\*)?");
+ static final Pattern EndSmallExamplePattern = Pattern.compile("@end\\s+smallexample");
+ static final Pattern EnumeratePattern = Pattern.compile("@enumerate");
+ static final Pattern EndEnumeratePattern = Pattern.compile("@end\\s+enumerate");
+ static final Pattern VerbatimPattern = Pattern.compile("@verbatim");
+ static final Pattern ItemPattern = Pattern.compile("@item");
+ static final Pattern RefillPattern = Pattern.compile("@refill");
+ static final Pattern NoIndentPattern = Pattern.compile("@noindent");
+ static final Pattern QuotationPattern = Pattern.compile("@quotation");
+ static final Pattern EndQuotation = Pattern.compile("@end\\s+quotation");
+ static final Pattern GroupPattern = Pattern.compile("@group");
+ static final Pattern TabPattern = Pattern.compile("@tab");
+ static final Pattern DeftpPattern = Pattern.compile("@deftp\\s+\\{([^\\}]*?)\\}\\s*\\{([^\\}]*?)\\}");
+ static final Pattern EndDeftpPattern = Pattern.compile("@end\\s+deftp");
+ static final Pattern CommentPattern = Pattern.compile("@c<eol>|@c\\s+.*?<eol>");
+ static final Pattern EndGroupPattern = Pattern.compile("@end\\s+group");
+ static final Pattern BracketRefPattern = Pattern.compile("\\(@.?.?ref\\{[^\\}]*\\}\\)");
+ static final Pattern BRPattern = Pattern.compile("&lt;br&gt;");
+ static final Pattern EOLPattern = Pattern.compile("&lt;eol&gt;");
+ static final Pattern EndVerbatimPattern = Pattern.compile("@end\\s+verbatim");
+ static final Pattern TableSampItemPattern = Pattern.compile("(@table\\s*@samp.*?)@item\\s+(.*?)(<eol>.*@end\\s+table)", Pattern.DOTALL);
+ static final Pattern TableAsisItemPattern = Pattern.compile("(@table\\s*@asis.*?)@item\\s+(.*?)(<eol>.*@end\\+table)", Pattern.DOTALL);
+ static final Pattern TableCodeItemPattern = Pattern.compile("(@table\\s*@code.*?)@item\\s+(.*?)(<eol>.*?)(@end\\s+table)", Pattern.DOTALL);
+ static final Pattern TableVarItemPattern = Pattern.compile("(@table\\s*@var.*?)@item\\s+(.*?)(<eol>.*@end\\s+table)", Pattern.DOTALL);
+ static final Pattern VtableCodeItemPattern = Pattern.compile("(@vtable\\s*@code.*?)@item\\s+(.*?)(<eol>.*@end\\s+vtable)", Pattern.DOTALL);
+ static final Pattern MultitableItemPattern = Pattern.compile("(@multitable.*)@item\\s+(.*?)<eol>(.*?@end\\s+multitable)" +
+ "|(@multitable.*)@item\\s*<eol>(.*?)<eol>(.*?@end\\s+multitable)", Pattern.DOTALL);
+ static final Pattern TableCodeMatchPattern = Pattern.compile("(@table\\s+@code)(.*?)(@end\\s+table)", Pattern.DOTALL);
+ static final Pattern TableSampMatchPattern = Pattern.compile("(@table\\s+@samp)(.*?)(@end\\s+table)", Pattern.DOTALL);
+ static final Pattern TableAsisMatchPattern = Pattern.compile("(@table\\s+@asis)(.*?)(@end\\s+table)", Pattern.DOTALL);
+ static final Pattern TableVarMatchPattern = Pattern.compile("(@table\\s+@var)(.*?)(@end\\s+table)", Pattern.DOTALL);
+ static final Pattern TableSampPattern = Pattern.compile("@table\\s*@samp", Pattern.MULTILINE);
+ static final Pattern TableAsisPattern = Pattern.compile("@table\\s*@asis", Pattern.MULTILINE);
+ static final Pattern TableCodePattern = Pattern.compile("@table\\s*@code", Pattern.MULTILINE);
+ static final Pattern TableVarPattern = Pattern.compile("@table\\s*@var", Pattern.MULTILINE);
+ static final Pattern VtableCodePattern = Pattern.compile("@vtable\\s*@code", Pattern.MULTILINE);
+ static final Pattern MultitablePattern = Pattern.compile("@multitable.*?<DT>", Pattern.DOTALL);
+ static final Pattern EndTablePattern = Pattern.compile("@end\\s+table");
+ static final Pattern EndVtablePattern = Pattern.compile("@end\\s+vtable");
+ static final Pattern EndMultitablePattern = Pattern.compile("@end\\s+multitable");
+ static final Pattern DotsPattern = Pattern.compile("@dots\\{\\}");
+ static final Pattern ItemizeMinusPattern= Pattern.compile("@itemize\\s+@minus" + "(.*?)" + "@end\\s+itemize", Pattern.DOTALL);
+ static final Pattern ItemizeBulletPattern= Pattern.compile("@itemize\\s+@bullet" + "(.*?)" + "@end\\s+itemize", Pattern.DOTALL);
+ static final Pattern InfoOnlyPattern = Pattern.compile("@ifinfo.*?@end\\s+ifinfo", Pattern.DOTALL);
+ static final Pattern TexOnlyPattern = Pattern.compile("@iftex.*?@end\\s+iftex", Pattern.DOTALL);
+ static final Pattern TexPattern = Pattern.compile("@tex.*?@end\\s+tex", Pattern.DOTALL);
+ static final Pattern IgnorePattern = Pattern.compile("@ignore.*?@end\\s+ignore", Pattern.DOTALL);
+ static final Pattern IfInfoPattern = Pattern.compile("@ifinfo");
+ static final Pattern InfinityPattern = Pattern.compile("@infinity");
+ static final Pattern EndIfInfoPattern = Pattern.compile("@end\\s+ifinfo");
+ static final Pattern NotTexPattern = Pattern.compile("@ifnottex");
+ static final Pattern EndNotTexPattern = Pattern.compile("@end\\s+ifnottex");
+ static final Pattern DeftypevrPattern = Pattern.compile("@deftypevr\\s+");
+ static final Pattern EndDeftypevr = Pattern.compile("@end\\s+deftypevr");
+ static final Pattern XrefPattern = Pattern.compile("@xref\\{[^\\}]*\\}", Pattern.MULTILINE);
+ static final Pattern PxrefPattern = Pattern.compile("@pxref\\{[^\\}]*\\}", Pattern.MULTILINE);
+ static final Pattern AtTPattern = Pattern.compile("@t\\{([^\\}]*)\\}");
+ static final Pattern CommandPattern = Pattern.compile("@command\\{([^\\}]*)\\}");
+ static final Pattern KbdPattern = Pattern.compile("@kbd\\{([^\\}]*)\\}");
+ static final Pattern RPattern = Pattern.compile("@r\\{([^\\}]*)\\}");
+ static final Pattern FilePattern = Pattern.compile("@file\\{([^\\}]*)\\}");
+ static final Pattern VarPattern = Pattern.compile("@var\\{([^\\}]*)\\}");
+ static final Pattern OVarPattern = Pattern.compile("@ovar\\{([^\\}]*)\\}");
+ static final Pattern DVarPattern = Pattern.compile("@dvar\\{([^\\},\\,]*),([^\\}]*)\\}");
+ static final Pattern AnyVarPattern = Pattern.compile("@[a-z]*var\\{([^\\}]*)\\}");
+ static final Pattern CodePattern = Pattern.compile("@code\\{([^\\}]*)\\}");
+ static final Pattern EmphPattern = Pattern.compile("@emph\\{([^\\}]*)\\}");
+ static final Pattern SampPattern = Pattern.compile("@samp\\{([^\\}]*)\\}");
+ static final Pattern OptionPattern = Pattern.compile("@option\\{([^\\}]*)\\}");
+ static final Pattern TagPattern = Pattern.compile("@\\w+\\{([^\\}]*)\\}");
+ static final Pattern TagCharPattern = Pattern.compile("@([\\{\\}\\:\\*\"])");
+ static final Pattern StrandedPeriod = Pattern.compile("(\\w)\\s+\\.\\s+");
+ static final Pattern LeftOverPeriod = Pattern.compile("^\\.\\s+<eol>");
+ static final Pattern AmpersandPattern = Pattern.compile("&");
+ static final Pattern LeftAnglePattern = Pattern.compile("<");
+ static final Pattern RightAnglePattern = Pattern.compile(">");
+
+ public static String stripProtoTags(String tt) {
+ Matcher mm;
+ String ss = "";
+
+ ss = "";
+ while (ss != tt) {
+ mm = AnyVarPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = DotsPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("...");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = CodePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = AtTPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TagPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TagCharPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ return tt;
+ }
+
+ public static String transformTags(String tt) {
+ Matcher mm;
+ String ss = "";
+ int endtableIndex = Integer.MAX_VALUE;
+
+ ss = "";
+ while (ss != tt) {
+ mm = BracketRefPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = XrefPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = CommentPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<eol>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = PxrefPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = DeftypevrPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = StrongPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<h3>$1</h3>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndDeftypevr.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = IndexPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = IndexPattern2.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = NoIndentPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = GroupPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndGroupPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = QuotationPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndQuotation.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = InfinityPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("infinity");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = DeftpPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<h4>$1 - $2</h4>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndDeftpPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = RefillPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = VarPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<VAR>$1</VAR>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = DotsPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<small>...</small>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = CommandPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<CODE>$1</CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = CodePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<CODE>$1</CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = KbdPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<KBD>$1</KBD>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EmphPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<EM>$1</EM>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = FilePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<TT>$1</TT>");
+ }
+
+
+ ss = "";
+ while (ss != tt) {
+ mm = VerbatimPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndVerbatimPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</CODE>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = SampPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<samp>$1</samp>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = OptionPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<samp>$1</samp>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = ExampleItem.matcher(tt);
+ ss = tt;
+ // We want to add a break at the end of each example line to preserve
+ // formatting when Eclipse processes the xml (e.g. C code lines).
+ tt = mm.replaceAll("$1$2<br>$4");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = ExamplePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<TABLE><tr><td>&nbsp;</td><td class=example><pre>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndExamplePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</pre></td></tr></table>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = SmallExampleItem.matcher(tt);
+ ss = tt;
+ // We want to add a break at the end of each example line to preserve
+ // formatting when Eclipse processes the xml (e.g. C code lines).
+ tt = mm.replaceAll("$1$2<br>$4");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = SmallExamplePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<pre>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndSmallExamplePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</pre>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EnumeratePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<OL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndEnumeratePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</OL>");
+ }
+
+// ss = "";
+// while (ss != tt) {
+// mm = InfoOnlyPattern.matcher(tt);
+// ss = tt;
+// tt = mm.replaceAll("");
+// }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TexOnlyPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TexPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = IgnorePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = NotTexPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndNotTexPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ // We will treat ifinfo the same as ifnottex which we pass through.
+ ss = "";
+ while (ss != tt) {
+ mm = IfInfoPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndIfInfoPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ endtableIndex = Integer.MAX_VALUE;
+ while (ss != tt) {
+ mm = TableSampItemPattern.matcher(tt);
+ ss = tt;
+ if (mm.find()) {
+ if (mm.start(4) > endtableIndex) {
+ // We try and find the last @[table samp] marker we can find with an @item before @[end table].
+ // The end marker has moved forward to make the match which means we have exhausted all @item markers
+ // from the last @[table samp] and @[end table] we were using prior to this iteration of the loop.
+ // If we change the table markers now, we avoid the prior table from
+ // matching any @item marker that sits between tables.
+ Matcher mm2 = TableSampMatchPattern.matcher(tt);
+ tt = mm2.replaceFirst("<DL>\n$2\n</DL>");
+ mm2 = TableSampMatchPattern.matcher(tt);
+ if (mm2.find())
+ endtableIndex = mm2.start(3);
+ }
+ else {
+ tt = mm.replaceFirst("$1<DT><SAMP>$2</SAMP>\n<DD>$3$4");
+ endtableIndex = mm.end(1) + 10 + mm.group(2).length() + 12 + mm.group(3).length();
+ }
+ }
+ }
+
+ //FIXME: This parser assumes that a table does not have an @itemize element
+ // inside it. It allows the opposite to be true (i.e. a table inside
+ // an @itemize element.
+
+ ss = "";
+ endtableIndex = Integer.MAX_VALUE;
+ while (ss != tt) {
+ mm = TableAsisItemPattern.matcher(tt);
+ ss = tt;
+ if (mm.find()) {
+ if (mm.start(4) > endtableIndex) {
+ // We try and find the last @[table asis] marker we can find with an @item before @[end table].
+ // The end marker has moved forward to make the match which means we have exhausted all @item markers
+ // from the last @[table asis] and @[end table] we were using prior to this iteration of the loop.
+ // If we change the table markers now, we avoid the prior table from
+ // matching any @item marker that sits between tables.
+ Matcher mm2 = TableAsisMatchPattern.matcher(tt);
+ tt = mm2.replaceFirst("<DL>\n$2\n</DL>");
+ mm2 = TableAsisMatchPattern.matcher(tt);
+ if (mm2.find())
+ endtableIndex = mm2.start(3);
+ }
+ else {
+ tt = mm.replaceFirst("$1<DT>$2\n<DD>$3$4");
+ endtableIndex = mm.end(1) + 10 + mm.group(2).length() + 12 + mm.group(3).length();
+ }
+ }
+ }
+
+ ss = "";
+ endtableIndex = Integer.MAX_VALUE;
+ while (ss != tt) {
+ mm = TableCodeItemPattern.matcher(tt);
+ ss = tt;
+ if (mm.find()) {
+ if (mm.start(4) > endtableIndex) {
+ // We try and find the last @[table code] marker we can find with an @item before @[end table].
+ // The end marker has moved forward to make the match which means we have exhausted all @item markers
+ // from the last @[table code] and @[end table] we were using prior to this iteration of the loop.
+ // If we change the table markers now, we avoid the prior table from
+ // matching any @item marker that sits between tables.
+ Matcher mm2 = TableCodeMatchPattern.matcher(tt);
+ tt = mm2.replaceFirst("<DL>\n$2\n</DL>");
+ mm2 = TableCodeMatchPattern.matcher(tt);
+ if (mm2.find())
+ endtableIndex = mm2.start(3);
+ }
+ else {
+ tt = mm.replaceFirst("$1<DT><CODE>$2</CODE>\n<DD>$3$4");
+ endtableIndex = mm.end(1) + 10 + mm.group(2).length() + 12 + mm.group(3).length();
+ }
+ }
+ }
+
+ ss = "";
+ endtableIndex = Integer.MAX_VALUE;
+ while (ss != tt) {
+ mm = TableVarItemPattern.matcher(tt);
+ ss = tt;
+ if (mm.find()) {
+ if (mm.start(4) > endtableIndex) {
+ // We try and find the last @[table var] marker we can find with an @item before @[end table].
+ // The end marker has moved forward to make the match which means we have exhausted all @item markers
+ // from the last @[table var] and @[end table] we were using prior to this iteration of the loop.
+ // If we change the table markers now, we avoid the prior table from
+ // matching any @item marker that sits between tables.
+ Matcher mm2 = TableVarMatchPattern.matcher(tt);
+ tt = mm2.replaceFirst("<DL>\n$2\n</DL>");
+ mm2 = TableVarMatchPattern.matcher(tt);
+ if (mm2.find())
+ endtableIndex = mm2.start(3);
+ }
+ else {
+ tt = mm.replaceFirst("$1<DT><VAR>$2</VAR>\n<DD>$3$4");
+ endtableIndex = mm.end(1) + 10 + mm.group(2).length() + 12 + mm.group(3).length();
+ }
+ }
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = VtableCodeItemPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1<DT><CODE>$2</CODE>\n<DD>$3");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = MultitableItemPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1<DT><pre>$2</pre>\n<DD><br>$3");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableSampPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<DL>\n");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableAsisPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<DL>\n");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableVarPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<DL>\n");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TableCodePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<DL>\n");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = VtableCodePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<DL>\n");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = MultitablePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<DL>\n<DT>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndTablePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</DL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndVtablePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</DL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = EndMultitablePattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("</DL>");
+ }
+
+ //FIXME: if there ever is a @itemize @bullet within a
+ // @itemize @minus or vice-versa, the following
+ // logic will get it wrong.
+ ss = "";
+ while (ss != tt) {
+ mm = ItemizeMinusPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<UL>$1</UL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = ItemizeBulletPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<OL>$1</OL>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = ItemPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("<LI>");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TagPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TagCharPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = StrandedPeriod.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("$1. ");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = LeftOverPeriod.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ ss = "";
+ while (ss != tt) {
+ mm = TabPattern.matcher(tt);
+ ss = tt;
+ tt = mm.replaceAll("");
+ }
+
+ mm = AmpersandPattern.matcher(tt);
+ tt = mm.replaceAll("&amp;");
+
+ mm = LeftAnglePattern.matcher(tt);
+ tt = mm.replaceAll("&lt;");
+
+ mm = RightAnglePattern.matcher(tt);
+ tt = mm.replaceAll("&gt;");
+
+ // Put back all the eol markers
+ mm = EOLPattern.matcher(tt);
+ tt = mm.replaceAll("<eol>");
+
+ return tt;
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/ClassInfo.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/ClassInfo.java
index 0a7ac19696..5f860ff75c 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/ClassInfo.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/ClassInfo.java
@@ -17,70 +17,70 @@ import org.w3c.dom.Node;
public class ClassInfo implements Serializable {
- private static final long serialVersionUID = 1L;
- private String templateParms[] = new String[0];
- private boolean templateParmsFilled = false;
- private String className;
- private String include;
- private ArrayList<ClassInfo> baseClasses = new ArrayList<>();
- private HashMap<String, MemberInfo> members = new HashMap<>();
- public transient Node classNode;
- private ArrayList<ClassInfo> children = null;
- public ClassInfo(String className, String id, Node classNode) {
- this.className = className;
- this.classNode = classNode;
- }
- public String getClassName() {
- return className;
- }
- public void setClassName(String newName) {
- className = newName;
- }
- public void addTemplate(ClassInfo child) {
- if (children == null) {
- children = new ArrayList<>();
- }
- children.add(child);
- }
- public boolean areTemplateParmsFilled() {
- return templateParmsFilled;
- }
-
- public String[] getTemplateParms() {
- return templateParms;
- }
-
- public void setTemplateParms(String[] templateParms) {
- templateParmsFilled = true;
- this.templateParms = templateParms;
- }
-
- public String getInclude() {
- return include;
- }
-
- public void setInclude(String include) {
- this.include = include;
- }
-
- public ArrayList<ClassInfo> getChildren() {
- return children;
- }
-
- public MemberInfo getMember(String name) {
- return members.get(name);
- }
-
- public void addMember(MemberInfo info) {
- String name = info.getName();
- MemberInfo member = members.get(name);
- if (member != null)
- member.addChild(info);
- else
- members.put(name, info);
- }
-
- public void addBaseClass(ClassInfo info) {
- baseClasses.add(info);
- }
+ private static final long serialVersionUID = 1L;
+ private String templateParms[] = new String[0];
+ private boolean templateParmsFilled = false;
+ private String className;
+ private String include;
+ private ArrayList<ClassInfo> baseClasses = new ArrayList<>();
+ private HashMap<String, MemberInfo> members = new HashMap<>();
+ public transient Node classNode;
+ private ArrayList<ClassInfo> children = null;
+ public ClassInfo(String className, String id, Node classNode) {
+ this.className = className;
+ this.classNode = classNode;
+ }
+ public String getClassName() {
+ return className;
+ }
+ public void setClassName(String newName) {
+ className = newName;
+ }
+ public void addTemplate(ClassInfo child) {
+ if (children == null) {
+ children = new ArrayList<>();
+ }
+ children.add(child);
+ }
+ public boolean areTemplateParmsFilled() {
+ return templateParmsFilled;
+ }
+
+ public String[] getTemplateParms() {
+ return templateParms;
+ }
+
+ public void setTemplateParms(String[] templateParms) {
+ templateParmsFilled = true;
+ this.templateParms = templateParms;
+ }
+
+ public String getInclude() {
+ return include;
+ }
+
+ public void setInclude(String include) {
+ this.include = include;
+ }
+
+ public ArrayList<ClassInfo> getChildren() {
+ return children;
+ }
+
+ public MemberInfo getMember(String name) {
+ return members.get(name);
+ }
+
+ public void addMember(MemberInfo info) {
+ String name = info.getName();
+ MemberInfo member = members.get(name);
+ if (member != null)
+ member.addChild(info);
+ else
+ members.put(name, info);
+ }
+
+ public void addBaseClass(ClassInfo info) {
+ baseClasses.add(info);
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/FunctionInfo.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/FunctionInfo.java
index 89f3c6ba49..5b50f51700 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/FunctionInfo.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/FunctionInfo.java
@@ -14,100 +14,100 @@ import java.io.Serializable;
import java.util.ArrayList;
public class FunctionInfo implements Serializable {
- private static final long serialVersionUID = 1L;
- private String name;
- private String prototype;
- private String desc;
- private String returnType;
- private ArrayList<String> headers = new ArrayList<>();
-
- /**
- * Constructor for function.
- *
- * @param name
- */
- public FunctionInfo(String name) {
- this.name = name;
- }
-
- /**
- * Get function name.
- *
- * @return function name
- */
- public String getName() {
- return name;
- }
-
- /**
- * Get prototype for function.
- *
- * @return prototype string or null
- */
- public String getPrototype() {
- return prototype;
- }
-
- /**
- * Set prototype string.
- *
- * @param prototype
- */
- public void setPrototype(String prototype) {
- this.prototype = prototype;
- }
-
- /**
- * Get description for function.
- *
- * @return description string or null
- */
- public String getDescription() {
- return desc;
- }
-
- /**
- * Set description string for function.
- *
- * @param desc
- */
- public void setDescription(String desc) {
- this.desc = desc;
- }
+ private static final long serialVersionUID = 1L;
+ private String name;
+ private String prototype;
+ private String desc;
+ private String returnType;
+ private ArrayList<String> headers = new ArrayList<>();
- /**
- * Get return type for function.
- *
- * @return return type as string or null
- */
- public String getReturnType() {
- return returnType;
- }
+ /**
+ * Constructor for function.
+ *
+ * @param name
+ */
+ public FunctionInfo(String name) {
+ this.name = name;
+ }
- /**
- * Set return type for function.
- *
- * @param returnType
- */
- public void setReturnType(String returnType) {
- this.returnType = returnType;
- }
+ /**
+ * Get function name.
+ *
+ * @return function name
+ */
+ public String getName() {
+ return name;
+ }
- /**
- * Get the headers that need including for this function.
- *
- * @return list of header strings
- */
- public ArrayList<String> getHeaders() {
- return headers;
- }
-
- /**
- * Add a header to the list of headers needed for this function.
- *
- * @param header the name of the header file to add
- */
- public void addHeader(String header) {
- headers.add(header);
- }
+ /**
+ * Get prototype for function.
+ *
+ * @return prototype string or null
+ */
+ public String getPrototype() {
+ return prototype;
+ }
+
+ /**
+ * Set prototype string.
+ *
+ * @param prototype
+ */
+ public void setPrototype(String prototype) {
+ this.prototype = prototype;
+ }
+
+ /**
+ * Get description for function.
+ *
+ * @return description string or null
+ */
+ public String getDescription() {
+ return desc;
+ }
+
+ /**
+ * Set description string for function.
+ *
+ * @param desc
+ */
+ public void setDescription(String desc) {
+ this.desc = desc;
+ }
+
+ /**
+ * Get return type for function.
+ *
+ * @return return type as string or null
+ */
+ public String getReturnType() {
+ return returnType;
+ }
+
+ /**
+ * Set return type for function.
+ *
+ * @param returnType
+ */
+ public void setReturnType(String returnType) {
+ this.returnType = returnType;
+ }
+
+ /**
+ * Get the headers that need including for this function.
+ *
+ * @return list of header strings
+ */
+ public ArrayList<String> getHeaders() {
+ return headers;
+ }
+
+ /**
+ * Add a header to the list of headers needed for this function.
+ *
+ * @param header the name of the header file to add
+ */
+ public void addHeader(String header) {
+ headers.add(header);
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/HelpBook.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/HelpBook.java
index 0218bff0ce..2169ded7d8 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/HelpBook.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/HelpBook.java
@@ -14,26 +14,26 @@ import org.eclipse.cdt.ui.ICHelpBook;
public class HelpBook implements ICHelpBook {
- private String title;
- private int type;
-
- public HelpBook (String title, String typeName) {
- this.title = title;
- if (typeName.equals("C")) //$NON-NLS-1$
- type = HELP_TYPE_C;
- else if (typeName.equals("C++")) //$NON-NLS-1$
- type = HELP_TYPE_CPP;
- else
- type = HELP_TYPE_ASM;
- }
- @Override
- public String getTitle () {
- return title;
- }
-
- @Override
- public int getCHelpType () {
- return type;
- }
+ private String title;
+ private int type;
+
+ public HelpBook (String title, String typeName) {
+ this.title = title;
+ if (typeName.equals("C")) //$NON-NLS-1$
+ type = HELP_TYPE_C;
+ else if (typeName.equals("C++")) //$NON-NLS-1$
+ type = HELP_TYPE_CPP;
+ else
+ type = HELP_TYPE_ASM;
+ }
+ @Override
+ public String getTitle () {
+ return title;
+ }
+
+ @Override
+ public int getCHelpType () {
+ return type;
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/LibHoverInfo.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/LibHoverInfo.java
index 097c0729a5..70724ffc47 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/LibHoverInfo.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/LibHoverInfo.java
@@ -16,9 +16,9 @@ import java.util.TreeMap;
public class LibHoverInfo implements Serializable {
- private static final long serialVersionUID = 1L;
- public HashMap<String, ClassInfo> classes = new HashMap<>();
- public HashMap<String, TypedefInfo> typedefs = new HashMap<>();
- public TreeMap<String, FunctionInfo> functions = new TreeMap<>();
+ private static final long serialVersionUID = 1L;
+ public HashMap<String, ClassInfo> classes = new HashMap<>();
+ public HashMap<String, TypedefInfo> typedefs = new HashMap<>();
+ public TreeMap<String, FunctionInfo> functions = new TreeMap<>();
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/LibhoverPlugin.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/LibhoverPlugin.java
index 8cdd691a4d..bfc1f0b5ec 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/LibhoverPlugin.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/LibhoverPlugin.java
@@ -27,73 +27,73 @@ import org.osgi.framework.BundleContext;
*/
public class LibhoverPlugin extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.cdt.libhover"; //$NON-NLS-1$
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.cdt.libhover"; //$NON-NLS-1$
- private static final String LOAD_JOB_TXT = "LibHover.LoadJob.txt"; //$NON-NLS-1$
-
- // The shared instance
- private static LibhoverPlugin plugin;
-
- static {
- plugin = new LibhoverPlugin();
- }
+ private static final String LOAD_JOB_TXT = "LibHover.LoadJob.txt"; //$NON-NLS-1$
- /**
- * The constructor
- */
- public LibhoverPlugin() {
- }
+ // The shared instance
+ private static LibhoverPlugin plugin;
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- ResourcesPlugin.getWorkspace().addSaveParticipant(PLUGIN_ID,
- new ISaveParticipant() {
- @Override
- public void saving(ISaveContext saveContext) {
- save(saveContext);
- }
- @Override
- public void rollback(ISaveContext saveContext) {}
- @Override
- public void prepareToSave(ISaveContext saveContext) {}
- @Override
- public void doneSaving(ISaveContext saveContext) {}
- });
- IPreferenceStore ps = getPreferenceStore();
- if (ps == null || !ps.getBoolean(PreferenceConstants.LAZY_LOAD)) {
- Job k = new LibHoverLoadJob(LibHoverMessages.getString(LOAD_JOB_TXT));
- k.schedule();
- }
- }
+ static {
+ plugin = new LibhoverPlugin();
+ }
- private void save(ISaveContext context) {
- LibHover.saveLibraries();
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
+ /**
+ * The constructor
+ */
+ public LibhoverPlugin() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ ResourcesPlugin.getWorkspace().addSaveParticipant(PLUGIN_ID,
+ new ISaveParticipant() {
+ @Override
+ public void saving(ISaveContext saveContext) {
+ save(saveContext);
+ }
+ @Override
+ public void rollback(ISaveContext saveContext) {}
+ @Override
+ public void prepareToSave(ISaveContext saveContext) {}
+ @Override
+ public void doneSaving(ISaveContext saveContext) {}
+ });
+ IPreferenceStore ps = getPreferenceStore();
+ if (ps == null || !ps.getBoolean(PreferenceConstants.LAZY_LOAD)) {
+ Job k = new LibHoverLoadJob(LibHoverMessages.getString(LOAD_JOB_TXT));
+ k.schedule();
+ }
+ }
+
+ private void save(ISaveContext context) {
+ LibHover.saveLibraries();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static LibhoverPlugin getDefault() {
+ return plugin;
+ }
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static LibhoverPlugin getDefault() {
- return plugin;
- }
-
} \ No newline at end of file
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/MemberInfo.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/MemberInfo.java
index 5b46a910db..8530c5e3cf 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/MemberInfo.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/MemberInfo.java
@@ -14,121 +14,121 @@ import java.io.Serializable;
import java.util.ArrayList;
public class MemberInfo implements Serializable {
- private static final long serialVersionUID = 1L;
- private String name;
- private String prototype;
- private String desc;
- private String returnType;
- private String[] paramTypes = new String[0];
- private ArrayList<MemberInfo> children = null;
+ private static final long serialVersionUID = 1L;
+ private String name;
+ private String prototype;
+ private String desc;
+ private String returnType;
+ private String[] paramTypes = new String[0];
+ private ArrayList<MemberInfo> children = null;
- /**
- * Constructor for member.
- *
- * @param name
- */
- public MemberInfo(String name) {
- this.name = name;
- }
+ /**
+ * Constructor for member.
+ *
+ * @param name
+ */
+ public MemberInfo(String name) {
+ this.name = name;
+ }
- /**
- * Get member name.
- *
- * @return member name
- */
- public String getName() {
- return name;
- }
+ /**
+ * Get member name.
+ *
+ * @return member name
+ */
+ public String getName() {
+ return name;
+ }
- /**
- * Get prototype for member.
- *
- * @return prototype string or null
- */
- public String getPrototype() {
- return prototype;
- }
+ /**
+ * Get prototype for member.
+ *
+ * @return prototype string or null
+ */
+ public String getPrototype() {
+ return prototype;
+ }
- /**
- * Set prototype string.
- *
- * @param prototype
- */
- public void setPrototype(String prototype) {
- this.prototype = prototype;
- }
+ /**
+ * Set prototype string.
+ *
+ * @param prototype
+ */
+ public void setPrototype(String prototype) {
+ this.prototype = prototype;
+ }
- /**
- * Get description for member.
- *
- * @return description string or null
- */
- public String getDescription() {
- return desc;
- }
+ /**
+ * Get description for member.
+ *
+ * @return description string or null
+ */
+ public String getDescription() {
+ return desc;
+ }
- /**
- * Set description string for member.
- *
- * @param desc
- */
- public void setDescription(String desc) {
- this.desc = desc;
- }
+ /**
+ * Set description string for member.
+ *
+ * @param desc
+ */
+ public void setDescription(String desc) {
+ this.desc = desc;
+ }
- /**
- * Get param types for member.
- *
- * @return return array of param types
- */
- public String[] getParamTypes() {
- return paramTypes;
- }
+ /**
+ * Get param types for member.
+ *
+ * @return return array of param types
+ */
+ public String[] getParamTypes() {
+ return paramTypes;
+ }
- /**
- * Set param types for member.
- *
- * @param paramTypes array of param types
- */
- public void setParamTypes(String[] paramTypes) {
- this.paramTypes = paramTypes;
- }
- /**
- * Get return type for member.
- *
- * @return return type as string or null
- */
- public String getReturnType() {
- return returnType;
- }
+ /**
+ * Set param types for member.
+ *
+ * @param paramTypes array of param types
+ */
+ public void setParamTypes(String[] paramTypes) {
+ this.paramTypes = paramTypes;
+ }
+ /**
+ * Get return type for member.
+ *
+ * @return return type as string or null
+ */
+ public String getReturnType() {
+ return returnType;
+ }
- /**
- * Set return type for member.
- *
- * @param returnType
- */
- public void setReturnType(String returnType) {
- this.returnType = returnType;
- }
+ /**
+ * Set return type for member.
+ *
+ * @param returnType
+ */
+ public void setReturnType(String returnType) {
+ this.returnType = returnType;
+ }
- /**
- * Add a member with the same name as a child of this member.
- *
- * @param info a member with same name as this member.
- */
- public void addChild(MemberInfo info) {
- if (children == null) {
- children = new ArrayList<>();
- }
- children.add(info);
- }
+ /**
+ * Add a member with the same name as a child of this member.
+ *
+ * @param info a member with same name as this member.
+ */
+ public void addChild(MemberInfo info) {
+ if (children == null) {
+ children = new ArrayList<>();
+ }
+ children.add(info);
+ }
- /**
- * Get the children members with same name as this member.
- *
- * @return an ArrayList of members with same name or null.
- */
- public ArrayList<MemberInfo> getChildren() {
- return children;
- }
+ /**
+ * Get the children members with same name as this member.
+ *
+ * @return an ArrayList of members with same name or null.
+ */
+ public ArrayList<MemberInfo> getChildren() {
+ return children;
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/TypedefInfo.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/TypedefInfo.java
index f71146f530..364b6f28ce 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/TypedefInfo.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/cdt/libhover/TypedefInfo.java
@@ -14,107 +14,107 @@ import java.io.Serializable;
import java.util.ArrayList;
public class TypedefInfo implements Serializable {
- private static final long serialVersionUID = 1L;
- private String[] templates = new String[0];
- private String typedefName;
- private String transformedType;
- private ArrayList<TypedefInfo> children = null;
- public TypedefInfo(String typedefName, String transformedType) {
- this.typedefName = typedefName;
- this.transformedType = transformedType;
- }
- public String getTypedefName() {
- return typedefName;
- }
- public void setTypedefName(String name) {
- typedefName = name;
- }
-
- private String[] getTemplateArgs(String str) {
- ArrayList<String> list = new ArrayList<>();
- int index = 0;
- int lastIndex = 0;
- int templateCounter = 0;
- while (index < str.length()) {
- char ch = str.charAt(index);
- if (ch == '<') {
- if (templateCounter == 0)
- lastIndex = index + 1;
- templateCounter++;
- } else if (ch == '>') {
- templateCounter--;
- } else if (ch == ',' && templateCounter == 1) {
- // FIXME: do we have to strip out all blanks here?
- list.add(str.substring(lastIndex, index).trim());
- lastIndex = index + 1;
- }
- ++index;
- }
- String[] args = new String[list.size()];
- return list.toArray(args);
- }
-
- public String getTransformedType(String className) {
- int index = className.indexOf('<');
- if (index > 0) {
- TypedefInfo e = this;
- // Search the children list in case the given class name
- // matches a specific template case.
- ArrayList<TypedefInfo> children = getChildren();
- for (int x = 0; x < children.size(); ++x) {
- TypedefInfo child = children.get(x);
- if (className.matches(child.getTypedefName())) {
- e = child;
- break;
- }
- }
- String[] templates = e.getTemplates();
- String transformedName = e.transformedType;
- // Check if there are any template arguments to replace. If not,
- // we can just return the transformed type we have.
- if (templates.length <= 0)
- return transformedName;
- String[] args = getTemplateArgs(className);
- String[] templateArgs = getTemplateArgs(e.getTypedefName());
- int j = 0;
- // For every argument that doesn't match up, it must be a template
- // parameter so we'll replace the template parameter name with the
- // supplied parameter. We have to query the template parameter list
- // for the names to replace because for partial specific templates
- // those names will have been replaced with regex sequences designed to
- // help us identify when the specific template has matched. For example,
- // <char, _Tp> will be stored as <char,[a-zA-Z0-9_]*> and if we have
- // <char,char> we will replace _Tp with char in the transformed type.
- for (int i = 0; i < args.length; ++i) {
- if (!args[i].equals(templateArgs[i])) {
- transformedName = transformedName.replaceAll(templates[j], args[i]);
- ++j;
- }
- }
- return transformedName;
- } else {
- // There is no template specified.
- return transformedType;
- }
- }
-
- public void addTypedef(TypedefInfo typedef) {
- if (children == null) {
- children = new ArrayList<>();
- }
- children.add(typedef);
- }
- public ArrayList<TypedefInfo> getChildren() {
- return children;
- }
- public void copyTemplates(String[] newTemplates) {
- templates = new String[newTemplates.length];
- for (int i = 0; i < templates.length; ++i) {
- templates[i] = newTemplates[i];
- }
- }
- public String[] getTemplates() {
- return templates;
- }
+ private static final long serialVersionUID = 1L;
+ private String[] templates = new String[0];
+ private String typedefName;
+ private String transformedType;
+ private ArrayList<TypedefInfo> children = null;
+ public TypedefInfo(String typedefName, String transformedType) {
+ this.typedefName = typedefName;
+ this.transformedType = transformedType;
+ }
+ public String getTypedefName() {
+ return typedefName;
+ }
+ public void setTypedefName(String name) {
+ typedefName = name;
+ }
+
+ private String[] getTemplateArgs(String str) {
+ ArrayList<String> list = new ArrayList<>();
+ int index = 0;
+ int lastIndex = 0;
+ int templateCounter = 0;
+ while (index < str.length()) {
+ char ch = str.charAt(index);
+ if (ch == '<') {
+ if (templateCounter == 0)
+ lastIndex = index + 1;
+ templateCounter++;
+ } else if (ch == '>') {
+ templateCounter--;
+ } else if (ch == ',' && templateCounter == 1) {
+ // FIXME: do we have to strip out all blanks here?
+ list.add(str.substring(lastIndex, index).trim());
+ lastIndex = index + 1;
+ }
+ ++index;
+ }
+ String[] args = new String[list.size()];
+ return list.toArray(args);
+ }
+
+ public String getTransformedType(String className) {
+ int index = className.indexOf('<');
+ if (index > 0) {
+ TypedefInfo e = this;
+ // Search the children list in case the given class name
+ // matches a specific template case.
+ ArrayList<TypedefInfo> children = getChildren();
+ for (int x = 0; x < children.size(); ++x) {
+ TypedefInfo child = children.get(x);
+ if (className.matches(child.getTypedefName())) {
+ e = child;
+ break;
+ }
+ }
+ String[] templates = e.getTemplates();
+ String transformedName = e.transformedType;
+ // Check if there are any template arguments to replace. If not,
+ // we can just return the transformed type we have.
+ if (templates.length <= 0)
+ return transformedName;
+ String[] args = getTemplateArgs(className);
+ String[] templateArgs = getTemplateArgs(e.getTypedefName());
+ int j = 0;
+ // For every argument that doesn't match up, it must be a template
+ // parameter so we'll replace the template parameter name with the
+ // supplied parameter. We have to query the template parameter list
+ // for the names to replace because for partial specific templates
+ // those names will have been replaced with regex sequences designed to
+ // help us identify when the specific template has matched. For example,
+ // <char, _Tp> will be stored as <char,[a-zA-Z0-9_]*> and if we have
+ // <char,char> we will replace _Tp with char in the transformed type.
+ for (int i = 0; i < args.length; ++i) {
+ if (!args[i].equals(templateArgs[i])) {
+ transformedName = transformedName.replaceAll(templates[j], args[i]);
+ ++j;
+ }
+ }
+ return transformedName;
+ } else {
+ // There is no template specified.
+ return transformedType;
+ }
+ }
+
+ public void addTypedef(TypedefInfo typedef) {
+ if (children == null) {
+ children = new ArrayList<>();
+ }
+ children.add(typedef);
+ }
+ public ArrayList<TypedefInfo> getChildren() {
+ return children;
+ }
+ public void copyTemplates(String[] newTemplates) {
+ templates = new String[newTemplates.length];
+ for (int i = 0; i < templates.length; ++i) {
+ templates[i] = newTemplates[i];
+ }
+ }
+ public String[] getTemplates() {
+ return templates;
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHover.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHover.java
index 1ea227773a..4329f326d6 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHover.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHover.java
@@ -83,21 +83,21 @@ import org.eclipse.linuxtools.internal.cdt.libhover.preferences.PreferenceConsta
public class LibHover implements ICHelpProvider {
- public final static String LIBHOVER_DOC_EXTENSION = LibhoverPlugin.PLUGIN_ID + ".library"; //$NON-NLS-1$
+ public final static String LIBHOVER_DOC_EXTENSION = LibhoverPlugin.PLUGIN_ID + ".library"; //$NON-NLS-1$
// see comment in initialize()
// private static String defaultSearchPath = null;
- private static ConcurrentHashMap<ICHelpBook, LibHoverLibrary> libraries = new ConcurrentHashMap<>();
+ private static ConcurrentHashMap<ICHelpBook, LibHoverLibrary> libraries = new ConcurrentHashMap<>();
static final String constructTypes[] = {
- "dtype", //$NON-NLS-1$
- "enum", //$NON-NLS-1$
- "function", //$NON-NLS-1$
- "groupsynopsis", //$NON-NLS-1$
- "struct", //$NON-NLS-1$
- "type", //$NON-NLS-1$
- "union" //$NON-NLS-1$
+ "dtype", //$NON-NLS-1$
+ "enum", //$NON-NLS-1$
+ "function", //$NON-NLS-1$
+ "groupsynopsis", //$NON-NLS-1$
+ "struct", //$NON-NLS-1$
+ "type", //$NON-NLS-1$
+ "union" //$NON-NLS-1$
};
static final int dtypeIndex = 0;
@@ -113,145 +113,145 @@ public class LibHover implements ICHelpProvider {
public static boolean docsFetched = false;
public static Collection<LibHoverLibrary> getLibraries() {
- return libraries.values();
+ return libraries.values();
}
public static void saveLibraries() {
- // If user preference is to cache libhover data, then save any un-saved
- // library hover data.
- IPreferenceStore ps = LibhoverPlugin.getDefault().getPreferenceStore();
- if (ps.getBoolean(PreferenceConstants.CACHE_EXT_LIBHOVER)) {
- IPath locationBase = LibhoverPlugin.getDefault().getStateLocation();
- for (Iterator<LibHoverLibrary> i = libraries.values().iterator(); i.hasNext();) {
- LibHoverLibrary l = i.next();
- try {
- // Now, output the LibHoverInfo for caching later
- IPath locationDir = locationBase;
- if (l.isCPP())
- locationDir = locationBase.append("CPP"); //$NON-NLS-1$
- else
- locationDir = locationBase.append("C"); //$NON-NLS-1$
- File lDir = new File(locationDir.toOSString());
- lDir.mkdir();
- IPath location = locationDir.append(getTransformedName(l.getName()) + ".libhover"); //$NON-NLS-1$
- File target = new File(location.toOSString());
- if (!target.exists()) {
- FileOutputStream f = new FileOutputStream(locationDir.append("tmpFile").toOSString()); //$NON-NLS-1$
- ObjectOutputStream out = new ObjectOutputStream(f);
- out.writeObject(l.getHoverInfo());
- out.close();
- File tmp = new File(locationDir.append("tmpFile").toOSString()); //$NON-NLS-1$
- tmp.renameTo(target);
- }
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- }
+ // If user preference is to cache libhover data, then save any un-saved
+ // library hover data.
+ IPreferenceStore ps = LibhoverPlugin.getDefault().getPreferenceStore();
+ if (ps.getBoolean(PreferenceConstants.CACHE_EXT_LIBHOVER)) {
+ IPath locationBase = LibhoverPlugin.getDefault().getStateLocation();
+ for (Iterator<LibHoverLibrary> i = libraries.values().iterator(); i.hasNext();) {
+ LibHoverLibrary l = i.next();
+ try {
+ // Now, output the LibHoverInfo for caching later
+ IPath locationDir = locationBase;
+ if (l.isCPP())
+ locationDir = locationBase.append("CPP"); //$NON-NLS-1$
+ else
+ locationDir = locationBase.append("C"); //$NON-NLS-1$
+ File lDir = new File(locationDir.toOSString());
+ lDir.mkdir();
+ IPath location = locationDir.append(getTransformedName(l.getName()) + ".libhover"); //$NON-NLS-1$
+ File target = new File(location.toOSString());
+ if (!target.exists()) {
+ FileOutputStream f = new FileOutputStream(locationDir.append("tmpFile").toOSString()); //$NON-NLS-1$
+ ObjectOutputStream out = new ObjectOutputStream(f);
+ out.writeObject(l.getHoverInfo());
+ out.close();
+ File tmp = new File(locationDir.append("tmpFile").toOSString()); //$NON-NLS-1$
+ tmp.renameTo(target);
+ }
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
}
- public static synchronized void getLibHoverDocs() {
- if (docsFetched)
- return;
- libraries.clear();
- helpBooks.clear();
- helpBooksMap.clear();
- // Check if caching of library info is enabled and if so, get any
- // cached library hover info.
- IPreferenceStore ps = LibhoverPlugin.getDefault().getPreferenceStore();
- if (ps.getBoolean(PreferenceConstants.CACHE_EXT_LIBHOVER)) {
- // Look for cached libhover files in the plugin state location
- IPath stateLocation = LibhoverPlugin.getDefault().getStateLocation();
- IFileSystem fs = EFS.getLocalFileSystem();
- IPath CLibraryLocation = stateLocation.append("C"); //$NON-NLS-1$
- IPath CPPLibraryLocation = stateLocation.append("CPP"); //$NON-NLS-1$
- IFileStore cDir = fs.getStore(CLibraryLocation);
- if (cDir.fetchInfo().exists())
- getCachedLibraries(cDir, "C"); //$NON-NLS-1$
- IFileStore cppDir = fs.getStore(CPPLibraryLocation);
- if (cppDir.fetchInfo().exists())
- getCachedLibraries(cppDir, "C++"); //$NON-NLS-1$
- }
- IExtensionRegistry x = RegistryFactory.getRegistry();
- IConfigurationElement[] ces = x.getConfigurationElementsFor(LIBHOVER_DOC_EXTENSION);
- for (int i = 0; i < ces.length; ++i) {
- IConfigurationElement ce = ces[i];
- if (ce.getName().equals("library")) { //$NON-NLS-1$
- // see comment in initialize()
- // Use the FileLocator class to open the magic hover doc file
- // in the plugin's jar.
- // Either open the html file or file system file depending
- // on what has been specified.
- String location = ce.getAttribute("location"); //$NON-NLS-1$
- String name = ce.getAttribute("name"); //$NON-NLS-1$
- String helpdocs = ce.getAttribute("docs"); //$NON-NLS-1$
- String type = ce.getAttribute("type"); //$NON-NLS-1$
- String nameSpace = ce.getContributor().getName();
- // If library not already cached, create it
- ICHelpBook book = helpBooksMap.get(name);
- if (book == null) {
- HelpBook h = new HelpBook(name, type);
- helpBooks.add(h);
- helpBooksMap.put(name, h);
- LibHoverLibrary l = new LibHoverLibrary(name, location, helpdocs, nameSpace,
- "C++".equals(type)); //$NON-NLS-1$
- libraries.put(h, l);
- } else {
- LibHoverLibrary l = libraries.get(book);
- if (l != null)
- l.setDocs(helpdocs);
- }
- docsFetched = true;
- }
- }
- }
-
- private static String getTransformedName(String name) {
- return name.replaceAll("\\s", "_"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- private static String getCleanName(String name) {
- return name.replaceAll("_", " "); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- private static void getCachedLibraries(IFileStore dir, String type) {
- try {
- boolean isCPP = type.equals("C++"); //$NON-NLS-1$
- IFileStore[] files = dir.childStores(EFS.NONE, null);
- for (int i = 0; i < files.length; ++i) {
- IFileStore file = files[i];
- String fileName = file.fetchInfo().getName();
- if (fileName.endsWith(".libhover")) { //$NON-NLS-1$
- File f = file.toLocalFile(EFS.NONE, null);
- if (f != null) {
- String name = getCleanName(fileName.substring(0,fileName.length()-9));
- HelpBook h = new HelpBook(name, type);
- helpBooks.add(h);
- helpBooksMap.put(name, h);
- String location = file.toURI().toString();
- LibHoverLibrary l = new LibHoverLibrary(name, location, null, null, isCPP);
- libraries.put(h, l);
- }
- }
- }
- } catch (CoreException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- @Override
- public void initialize() {
- getLibHoverDocs();
- }
-
- @Override
- public ICHelpBook[] getCHelpBooks () {
- ICHelpBook[] chelpbooks = new ICHelpBook[helpBooks.size()];
- return helpBooks.toArray(chelpbooks);
- }
-
- private static class FunctionSummary implements IFunctionSummary, Comparable<FunctionSummary> {
+ public static synchronized void getLibHoverDocs() {
+ if (docsFetched)
+ return;
+ libraries.clear();
+ helpBooks.clear();
+ helpBooksMap.clear();
+ // Check if caching of library info is enabled and if so, get any
+ // cached library hover info.
+ IPreferenceStore ps = LibhoverPlugin.getDefault().getPreferenceStore();
+ if (ps.getBoolean(PreferenceConstants.CACHE_EXT_LIBHOVER)) {
+ // Look for cached libhover files in the plugin state location
+ IPath stateLocation = LibhoverPlugin.getDefault().getStateLocation();
+ IFileSystem fs = EFS.getLocalFileSystem();
+ IPath CLibraryLocation = stateLocation.append("C"); //$NON-NLS-1$
+ IPath CPPLibraryLocation = stateLocation.append("CPP"); //$NON-NLS-1$
+ IFileStore cDir = fs.getStore(CLibraryLocation);
+ if (cDir.fetchInfo().exists())
+ getCachedLibraries(cDir, "C"); //$NON-NLS-1$
+ IFileStore cppDir = fs.getStore(CPPLibraryLocation);
+ if (cppDir.fetchInfo().exists())
+ getCachedLibraries(cppDir, "C++"); //$NON-NLS-1$
+ }
+ IExtensionRegistry x = RegistryFactory.getRegistry();
+ IConfigurationElement[] ces = x.getConfigurationElementsFor(LIBHOVER_DOC_EXTENSION);
+ for (int i = 0; i < ces.length; ++i) {
+ IConfigurationElement ce = ces[i];
+ if (ce.getName().equals("library")) { //$NON-NLS-1$
+ // see comment in initialize()
+ // Use the FileLocator class to open the magic hover doc file
+ // in the plugin's jar.
+ // Either open the html file or file system file depending
+ // on what has been specified.
+ String location = ce.getAttribute("location"); //$NON-NLS-1$
+ String name = ce.getAttribute("name"); //$NON-NLS-1$
+ String helpdocs = ce.getAttribute("docs"); //$NON-NLS-1$
+ String type = ce.getAttribute("type"); //$NON-NLS-1$
+ String nameSpace = ce.getContributor().getName();
+ // If library not already cached, create it
+ ICHelpBook book = helpBooksMap.get(name);
+ if (book == null) {
+ HelpBook h = new HelpBook(name, type);
+ helpBooks.add(h);
+ helpBooksMap.put(name, h);
+ LibHoverLibrary l = new LibHoverLibrary(name, location, helpdocs, nameSpace,
+ "C++".equals(type)); //$NON-NLS-1$
+ libraries.put(h, l);
+ } else {
+ LibHoverLibrary l = libraries.get(book);
+ if (l != null)
+ l.setDocs(helpdocs);
+ }
+ docsFetched = true;
+ }
+ }
+ }
+
+ private static String getTransformedName(String name) {
+ return name.replaceAll("\\s", "_"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ private static String getCleanName(String name) {
+ return name.replaceAll("_", " "); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ private static void getCachedLibraries(IFileStore dir, String type) {
+ try {
+ boolean isCPP = type.equals("C++"); //$NON-NLS-1$
+ IFileStore[] files = dir.childStores(EFS.NONE, null);
+ for (int i = 0; i < files.length; ++i) {
+ IFileStore file = files[i];
+ String fileName = file.fetchInfo().getName();
+ if (fileName.endsWith(".libhover")) { //$NON-NLS-1$
+ File f = file.toLocalFile(EFS.NONE, null);
+ if (f != null) {
+ String name = getCleanName(fileName.substring(0,fileName.length()-9));
+ HelpBook h = new HelpBook(name, type);
+ helpBooks.add(h);
+ helpBooksMap.put(name, h);
+ String location = file.toURI().toString();
+ LibHoverLibrary l = new LibHoverLibrary(name, location, null, null, isCPP);
+ libraries.put(h, l);
+ }
+ }
+ }
+ } catch (CoreException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void initialize() {
+ getLibHoverDocs();
+ }
+
+ @Override
+ public ICHelpBook[] getCHelpBooks () {
+ ICHelpBook[] chelpbooks = new ICHelpBook[helpBooks.size()];
+ return helpBooks.toArray(chelpbooks);
+ }
+
+ private static class FunctionSummary implements IFunctionSummary, Comparable<FunctionSummary> {
private String Name;
private String NameSpace;
@@ -261,104 +261,104 @@ public class LibHover implements ICHelpProvider {
private boolean prototypeHasBrackets;
private class RequiredInclude implements IRequiredInclude {
- private final String include;
+ private final String include;
- public RequiredInclude (String file) {
- include = file;
- }
+ public RequiredInclude (String file) {
+ include = file;
+ }
- @Override
- public String getIncludeName() {
- return include;
- }
+ @Override
+ public String getIncludeName() {
+ return include;
+ }
- @Override
- public boolean isStandard() {
- return true;
- }
+ @Override
+ public boolean isStandard() {
+ return true;
+ }
}
- @Override
- public int compareTo (FunctionSummary x) {
- FunctionSummary y = x;
- return getName().compareTo(y.getName());
- }
+ @Override
+ public int compareTo (FunctionSummary x) {
+ FunctionSummary y = x;
+ return getName().compareTo(y.getName());
+ }
private final ArrayList<RequiredInclude> Includes = new ArrayList<>();
private void setIncludeName (String iname) {
- RequiredInclude nri = new RequiredInclude(iname);
- Includes.add(nri);
+ RequiredInclude nri = new RequiredInclude(iname);
+ Includes.add(nri);
}
public class FunctionPrototypeSummary implements IFunctionPrototypeSummary {
@Override
- public String getName() { return Name; }
+ public String getName() { return Name; }
@Override
- public String getReturnType() { return ReturnType; }
+ public String getReturnType() { return ReturnType; }
@Override
- public String getArguments() { return Prototype; }
+ public String getArguments() { return Prototype; }
@Override
- public String getPrototypeString(boolean namefirst) {
+ public String getPrototypeString(boolean namefirst) {
if (true == namefirst) {
- if (prototypeHasBrackets())
- return Name + " " + Prototype + " " + ReturnType; //$NON-NLS-1$ //$NON-NLS-2$
+ if (prototypeHasBrackets())
+ return Name + " " + Prototype + " " + ReturnType; //$NON-NLS-1$ //$NON-NLS-2$
return Name + " (" + Prototype + ") " + ReturnType; //$NON-NLS-1$ //$NON-NLS-2$
}
else {
- if (prototypeHasBrackets())
- return ReturnType + " " + Name + " " + Prototype; //$NON-NLS-1$ //$NON-NLS-2$
+ if (prototypeHasBrackets())
+ return ReturnType + " " + Name + " " + Prototype; //$NON-NLS-1$ //$NON-NLS-2$
return ReturnType + " " + Name + " (" + Prototype + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
@Override
- public String getName() { return Name; }
+ public String getName() { return Name; }
@Override
- public String getNamespace() { return NameSpace; }
+ public String getNamespace() { return NameSpace; }
@Override
- public String getDescription() { return Summary; }
- public boolean prototypeHasBrackets() { return prototypeHasBrackets; }
- public void setPrototypeHasBrackets(boolean value) { prototypeHasBrackets = value; }
+ public String getDescription() { return Summary; }
+ public boolean prototypeHasBrackets() { return prototypeHasBrackets; }
+ public void setPrototypeHasBrackets(boolean value) { prototypeHasBrackets = value; }
@Override
- public IFunctionPrototypeSummary getPrototype() { return new FunctionPrototypeSummary(); }
+ public IFunctionPrototypeSummary getPrototype() { return new FunctionPrototypeSummary(); }
@Override
- public IRequiredInclude[] getIncludes() {
- IRequiredInclude[] includes = new IRequiredInclude[Includes.size()];
- for (int i = 0; i < Includes.size(); ++i) {
- includes[i] = Includes.get(i);
- }
- return includes;
+ public IRequiredInclude[] getIncludes() {
+ IRequiredInclude[] includes = new IRequiredInclude[Includes.size()];
+ for (int i = 0; i < Includes.size(); ++i) {
+ includes[i] = Includes.get(i);
+ }
+ return includes;
}
}
- private static class EnclosingASTNameJob extends SharedASTJob {
- private final int tlength;
- private final int toffset;
- private IASTName result = null;
- public EnclosingASTNameJob (ITranslationUnit t,
- int toffset, int tlength) {
- super("EnclosingASTNameJob", t); //$NON-NLS-1$
- this.toffset = toffset;
- this.tlength = tlength;
- }
- @Override
- public IStatus runOnAST(ILanguage lang, IASTTranslationUnit ast) {
- if (ast != null) {
- result = ast.getNodeSelector(null).findEnclosingName(toffset, tlength);
- }
- return Status.OK_STATUS;
- }
- public IASTName getASTName() {
- return result;
- }
- }
-
- @Override
- public IFunctionSummary getFunctionInfo(ICHelpInvocationContext context, ICHelpBook[] helpBooks, String name) {
+ private static class EnclosingASTNameJob extends SharedASTJob {
+ private final int tlength;
+ private final int toffset;
+ private IASTName result = null;
+ public EnclosingASTNameJob (ITranslationUnit t,
+ int toffset, int tlength) {
+ super("EnclosingASTNameJob", t); //$NON-NLS-1$
+ this.toffset = toffset;
+ this.tlength = tlength;
+ }
+ @Override
+ public IStatus runOnAST(ILanguage lang, IASTTranslationUnit ast) {
+ if (ast != null) {
+ result = ast.getNodeSelector(null).findEnclosingName(toffset, tlength);
+ }
+ return Status.OK_STATUS;
+ }
+ public IASTName getASTName() {
+ return result;
+ }
+ }
+
+ @Override
+ public IFunctionSummary getFunctionInfo(ICHelpInvocationContext context, ICHelpBook[] helpBooks, String name) {
IFunctionSummary f;
f = null;
@@ -368,374 +368,374 @@ public class LibHover implements ICHelpProvider {
ICPPFunctionType methodType = null;
if (t.isCXXLanguage()) {
- try {
- if (context instanceof IHoverHelpInvocationContext) {
- // We know the file offset of the member reference.
- IRegion region = ((IHoverHelpInvocationContext)context).getHoverRegion();
-
- // Now, let's find the declaration of the method. We need to do this because we want the specific
- // member prototype to go searching for. There could be many members called "x" which have different
- // documentation.
- final IASTName[] result= {null};
- EnclosingASTNameJob job = new EnclosingASTNameJob(t, region.getOffset(), region.getLength());
- job.schedule();
- try {
- job.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- if (job.getResult() == Status.OK_STATUS)
- result[0] = job.getASTName();
- if (result[0] != null) {
- final IBinding binding = result[0].getBinding();
- // Check to see we have a member function.
- if (binding instanceof ICPPFunction) {
- methodType = ((ICPPFunction)binding).getType();
- // We have a member function, find the class name.
- IBinding owner = ((ICPPFunction)binding).getOwner();
- if (owner instanceof ICPPClassType) {
- className = getClassName((ICPPClassType)owner);
- }
- }
- }
- }
- } catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ try {
+ if (context instanceof IHoverHelpInvocationContext) {
+ // We know the file offset of the member reference.
+ IRegion region = ((IHoverHelpInvocationContext)context).getHoverRegion();
+
+ // Now, let's find the declaration of the method. We need to do this because we want the specific
+ // member prototype to go searching for. There could be many members called "x" which have different
+ // documentation.
+ final IASTName[] result= {null};
+ EnclosingASTNameJob job = new EnclosingASTNameJob(t, region.getOffset(), region.getLength());
+ job.schedule();
+ try {
+ job.join();
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ if (job.getResult() == Status.OK_STATUS)
+ result[0] = job.getASTName();
+ if (result[0] != null) {
+ final IBinding binding = result[0].getBinding();
+ // Check to see we have a member function.
+ if (binding instanceof ICPPFunction) {
+ methodType = ((ICPPFunction)binding).getType();
+ // We have a member function, find the class name.
+ IBinding owner = ((ICPPFunction)binding).getOwner();
+ if (owner instanceof ICPPClassType) {
+ className = getClassName((ICPPClassType)owner);
+ }
+ }
+ }
+ }
+ } catch (IllegalArgumentException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
}
// Loop through all the documents we have and report first match.
for (int i = 0; i < helpBooks.length; ++i) {
- LibHoverLibrary l = libraries.get(helpBooks[i]);
- if (name != null) {
- if (className != null) {
- if (l.isCPP())
- f = getMemberSummary(l, className, name, methodType);
- } else {
- f = getFunctionSummary(l, name);
- }
- if (f != null)
- return f;
- }
+ LibHoverLibrary l = libraries.get(helpBooks[i]);
+ if (name != null) {
+ if (className != null) {
+ if (l.isCPP())
+ f = getMemberSummary(l, className, name, methodType);
+ } else {
+ f = getFunctionSummary(l, name);
+ }
+ if (f != null)
+ return f;
+ }
+ }
+
+ return null;
+ }
+
+ // Get the class name for a type, including any instance template parameters
+ // e.g. std::basic_string<char>
+ private String getClassName(ICPPClassType c) {
+ String className = null;
+ try {
+ String[] qualified = c.getQualifiedName();
+ className = qualified[0];
+ for (int k = 1; k < qualified.length; ++k) {
+ className += "::" + qualified[k]; //$NON-NLS-1$
+ }
+
+ // Check if we have an instance of a template class.
+ if (c instanceof ICPPTemplateInstance) {
+ ICPPTemplateInstance ti = (ICPPTemplateInstance)c;
+ // Get a map which tells us the values of the template
+ // arguments (e.g. _CharT maps to char in the instance).
+ ICPPTemplateParameterMap tiMap = ti.getTemplateParameterMap();
+ ICPPTemplateDefinition td = ti.getTemplateDefinition();
+ ICPPTemplateParameter[] templateArgs = td.getTemplateParameters();
+ className += "<"; //$NON-NLS-1$
+ String separator = ""; //$NON-NLS-1$
+ for (int x = 0; x < templateArgs.length; ++x) {
+ ICPPTemplateParameter tp = templateArgs[x];
+ ICPPTemplateArgument ta = tiMap.getArgument(tp);
+ IType type = null;
+ // The template may have a type specified or a value.
+ // In the case of a value, figure out its type and use
+ // that when we do a lookup.
+ if (ta.isTypeValue())
+ type = ta.getTypeValue();
+ else
+ type = ta.getTypeOfNonTypeValue();
+ if (tp.getTemplateNestingLevel() == 0) {
+ // if the parameter is a class type, use recursion to
+ // get its class name including template parameters
+ if (type instanceof ICPPClassType)
+ className += separator + getClassName((ICPPClassType)type);
+ else
+ className += separator + type.toString();
+ separator = ","; //$NON-NLS-1$
+ }
+ }
+ className += ">"; //$NON-NLS-1$
+ }
+ } catch(DOMException e) {
+ return null;
+ }
+ return className;
+ }
+
+ private IFunctionSummary getFunctionSummary(LibHoverLibrary l, String name) {
+ FunctionInfo x = l.getFunctionInfo(name);
+ if (x != null) {
+ FunctionSummary f = new FunctionSummary();
+ f.ReturnType = x.getReturnType();
+ f.Prototype = x.getPrototype();
+ f.Summary = x.getDescription();
+ f.Name = x.getName();
+ ArrayList<String> headers = x.getHeaders();
+ for (int i = 0; i < headers.size(); ++i)
+ f.setIncludeName(headers.get(i));
+ return f;
+ }
+ return null;
+ }
+
+ private IFunctionSummary getMemberSummary(LibHoverLibrary l, String className,
+ String memberName, ICPPFunctionType methodType) {
+
+ ArrayList<String> templateTypes = new ArrayList<>();
+ ClassInfo info = l.getClassInfo(className, templateTypes);
+ String[] args = new String[0];
+ @SuppressWarnings("unused")
+ IType returnType = null;
+ if (info == null)
+ return null;
+ if (methodType != null) {
+ try {
+ args = resolveArgs(info, methodType.getParameterTypes(), templateTypes);
+ returnType = methodType.getReturnType();
+ } catch (Exception e) {
+ return null;
+ }
}
+ MemberInfo member = info.getMember(memberName);
+ if (member != null) {
+ MemberInfo m = null;
+ if (!isParmMatch(member, args, templateTypes, info)) {
+ ArrayList<MemberInfo> members = member.getChildren();
+ for (int i = 0; i < members.size(); ++i) {
+ MemberInfo k = members.get(i);
+ if (isParmMatch(k, args, templateTypes, info)) {
+ m = k;
+ break;
+ }
+ }
+ } else {
+ m = member;
+ }
+ if (m != null) {
+ // FIXME: do some work to determine parameters and return type.
+ FunctionSummary f = new FunctionSummary();
+ f.ReturnType = m.getReturnType();
+ f.Prototype = m.getPrototype();
+ f.Summary = m.getDescription();
+ f.Name = className + "::" + memberName; //$NON-NLS-1$
+ String[] templateParms = info.getTemplateParms();
+ for (int i = 0; i < templateTypes.size(); ++i) {
+ f.ReturnType = f.ReturnType.replaceAll(templateParms[i], templateTypes.get(i));
+ f.Prototype = f.Prototype.replaceAll(templateParms[i], templateTypes.get(i));
+ f.Name = f.Name.replaceAll(templateParms[i], templateTypes.get(i));
+ }
+ if (f.ReturnType.indexOf('<') >= 0) {
+ f.ReturnType = f.ReturnType.replaceAll("<", "&lt;"); //$NON-NLS-1$ //$NON-NLS-2$
+ f.ReturnType = f.ReturnType.replaceAll(">", "&gt;"); //$NON-NLS-1$//$NON-NLS-2$
+ }
+ if (f.Prototype.indexOf('<') >= 0) {
+ f.Prototype = f.Prototype.replaceAll("<", "&lt;"); //$NON-NLS-1$ //$NON-NLS-2$
+ f.Prototype = f.Prototype.replaceAll(">", "&gt;"); //$NON-NLS-1$//$NON-NLS-2$
+ }
+ if (f.Name.indexOf('<') >= 0) {
+ f.Name = f.Name.replaceAll("<", "&lt;"); //$NON-NLS-1$//$NON-NLS-2$
+ f.Name = f.Name.replaceAll(">", "&gt;"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ f.setPrototypeHasBrackets(true);
+ f.setIncludeName(info.getInclude());
+ return f;
+ }
+ }
return null;
- }
-
- // Get the class name for a type, including any instance template parameters
- // e.g. std::basic_string<char>
- private String getClassName(ICPPClassType c) {
- String className = null;
- try {
- String[] qualified = c.getQualifiedName();
- className = qualified[0];
- for (int k = 1; k < qualified.length; ++k) {
- className += "::" + qualified[k]; //$NON-NLS-1$
- }
-
- // Check if we have an instance of a template class.
- if (c instanceof ICPPTemplateInstance) {
- ICPPTemplateInstance ti = (ICPPTemplateInstance)c;
- // Get a map which tells us the values of the template
- // arguments (e.g. _CharT maps to char in the instance).
- ICPPTemplateParameterMap tiMap = ti.getTemplateParameterMap();
- ICPPTemplateDefinition td = ti.getTemplateDefinition();
- ICPPTemplateParameter[] templateArgs = td.getTemplateParameters();
- className += "<"; //$NON-NLS-1$
- String separator = ""; //$NON-NLS-1$
- for (int x = 0; x < templateArgs.length; ++x) {
- ICPPTemplateParameter tp = templateArgs[x];
- ICPPTemplateArgument ta = tiMap.getArgument(tp);
- IType type = null;
- // The template may have a type specified or a value.
- // In the case of a value, figure out its type and use
- // that when we do a lookup.
- if (ta.isTypeValue())
- type = ta.getTypeValue();
- else
- type = ta.getTypeOfNonTypeValue();
- if (tp.getTemplateNestingLevel() == 0) {
- // if the parameter is a class type, use recursion to
- // get its class name including template parameters
- if (type instanceof ICPPClassType)
- className += separator + getClassName((ICPPClassType)type);
- else
- className += separator + type.toString();
- separator = ","; //$NON-NLS-1$
- }
- }
- className += ">"; //$NON-NLS-1$
- }
- } catch(DOMException e) {
- return null;
- }
- return className;
- }
-
- private IFunctionSummary getFunctionSummary(LibHoverLibrary l, String name) {
- FunctionInfo x = l.getFunctionInfo(name);
- if (x != null) {
- FunctionSummary f = new FunctionSummary();
- f.ReturnType = x.getReturnType();
- f.Prototype = x.getPrototype();
- f.Summary = x.getDescription();
- f.Name = x.getName();
- ArrayList<String> headers = x.getHeaders();
- for (int i = 0; i < headers.size(); ++i)
- f.setIncludeName(headers.get(i));
- return f;
- }
- return null;
- }
-
- private IFunctionSummary getMemberSummary(LibHoverLibrary l, String className,
- String memberName, ICPPFunctionType methodType) {
-
- ArrayList<String> templateTypes = new ArrayList<>();
- ClassInfo info = l.getClassInfo(className, templateTypes);
- String[] args = new String[0];
- @SuppressWarnings("unused")
- IType returnType = null;
- if (info == null)
- return null;
- if (methodType != null) {
- try {
- args = resolveArgs(info, methodType.getParameterTypes(), templateTypes);
- returnType = methodType.getReturnType();
- } catch (Exception e) {
- return null;
- }
- }
- MemberInfo member = info.getMember(memberName);
- if (member != null) {
- MemberInfo m = null;
- if (!isParmMatch(member, args, templateTypes, info)) {
- ArrayList<MemberInfo> members = member.getChildren();
- for (int i = 0; i < members.size(); ++i) {
- MemberInfo k = members.get(i);
- if (isParmMatch(k, args, templateTypes, info)) {
- m = k;
- break;
- }
- }
- } else {
- m = member;
- }
-
- if (m != null) {
- // FIXME: do some work to determine parameters and return type.
- FunctionSummary f = new FunctionSummary();
- f.ReturnType = m.getReturnType();
- f.Prototype = m.getPrototype();
- f.Summary = m.getDescription();
- f.Name = className + "::" + memberName; //$NON-NLS-1$
- String[] templateParms = info.getTemplateParms();
- for (int i = 0; i < templateTypes.size(); ++i) {
- f.ReturnType = f.ReturnType.replaceAll(templateParms[i], templateTypes.get(i));
- f.Prototype = f.Prototype.replaceAll(templateParms[i], templateTypes.get(i));
- f.Name = f.Name.replaceAll(templateParms[i], templateTypes.get(i));
- }
- if (f.ReturnType.indexOf('<') >= 0) {
- f.ReturnType = f.ReturnType.replaceAll("<", "&lt;"); //$NON-NLS-1$ //$NON-NLS-2$
- f.ReturnType = f.ReturnType.replaceAll(">", "&gt;"); //$NON-NLS-1$//$NON-NLS-2$
- }
- if (f.Prototype.indexOf('<') >= 0) {
- f.Prototype = f.Prototype.replaceAll("<", "&lt;"); //$NON-NLS-1$ //$NON-NLS-2$
- f.Prototype = f.Prototype.replaceAll(">", "&gt;"); //$NON-NLS-1$//$NON-NLS-2$
- }
- if (f.Name.indexOf('<') >= 0) {
- f.Name = f.Name.replaceAll("<", "&lt;"); //$NON-NLS-1$//$NON-NLS-2$
- f.Name = f.Name.replaceAll(">", "&gt;"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- f.setPrototypeHasBrackets(true);
- f.setIncludeName(info.getInclude());
- return f;
- }
- }
- return null;
- }
-
-
- private boolean isParmMatch(MemberInfo m, String[] args, ArrayList<String> templateTypes, ClassInfo info) {
- String[] memberParms = m.getParamTypes();
- String className = info.getClassName();
- int index = className.lastIndexOf("::"); //$NON-NLS-1$
- String unqualifiedName = className.substring(index+2);
- for (int i = 0; i < memberParms.length; ++i) {
- String[] templateParms = info.getTemplateParms();
- for (int j = 0; j < templateTypes.size(); ++j) {
- memberParms[i] = memberParms[i].replaceAll(templateParms[j], templateTypes.get(j));
- }
- // Look for the class being passed by reference...the doc prototype will not fill in
- // the template parms nor the qualifier so we do it here to make sure we match what
- // is coming back from the indexer which will be fully-qualified and have template
- // parameters specified.
- if (memberParms[i].contains(unqualifiedName) && !memberParms[i].contains(className)) {
- String classTemplate = ""; //$NON-NLS-1$
- if (templateTypes.size() > 0) {
- classTemplate = "<"; //$NON-NLS-1$
- String separator = ""; //$NON-NLS-1$
- for (int j = 0; j < templateTypes.size(); ++j) {
- classTemplate += separator + templateTypes.get(j);
- separator = ","; //$NON-NLS-1$
- }
- classTemplate += ">"; //$NON-NLS-1$
- }
- memberParms[i] = memberParms[i].replaceAll(unqualifiedName, className + classTemplate);
- }
- }
- return Arrays.equals(memberParms, args);
- }
-
- private String[] resolveArgs(ClassInfo info, IType[] parameterTypes, ArrayList<String> templateTypes) {
- String[] templateParms = info.getTemplateParms();
- String[] result = new String[parameterTypes.length];
- for (int i = 0; i < parameterTypes.length; ++i) {
- String param = parameterTypes[i].toString();
- param = param.replaceAll("\\{.*\\}", ""); //$NON-NLS-1$ //$NON-NLS-2$
- param = param.trim();
- int index = param.indexOf("#"); //$NON-NLS-1$
- while (index >= 0) {
- // We assume no class has more than 9 template parms.
- int digit = param.charAt(index + 1) - '0';
- // where possible, replace template parms with real values
- if (digit < templateTypes.size())
- param = param.replaceFirst(param.substring(index, index + 2), templateTypes.get(digit));
- else
- param = param.replaceFirst(param.substring(index, index + 2), templateParms[digit]);
- index = param.indexOf("#"); //$NON-NLS-1$
- }
- result[i] = param;
- }
- return result;
- }
-
- @Override
- public IFunctionSummary[] getMatchingFunctions(ICHelpInvocationContext context, ICHelpBook[] helpBooks, String prefix) {
- ArrayList<IFunctionSummary> fList = new ArrayList<>();
+ }
+
+
+ private boolean isParmMatch(MemberInfo m, String[] args, ArrayList<String> templateTypes, ClassInfo info) {
+ String[] memberParms = m.getParamTypes();
+ String className = info.getClassName();
+ int index = className.lastIndexOf("::"); //$NON-NLS-1$
+ String unqualifiedName = className.substring(index+2);
+ for (int i = 0; i < memberParms.length; ++i) {
+ String[] templateParms = info.getTemplateParms();
+ for (int j = 0; j < templateTypes.size(); ++j) {
+ memberParms[i] = memberParms[i].replaceAll(templateParms[j], templateTypes.get(j));
+ }
+ // Look for the class being passed by reference...the doc prototype will not fill in
+ // the template parms nor the qualifier so we do it here to make sure we match what
+ // is coming back from the indexer which will be fully-qualified and have template
+ // parameters specified.
+ if (memberParms[i].contains(unqualifiedName) && !memberParms[i].contains(className)) {
+ String classTemplate = ""; //$NON-NLS-1$
+ if (templateTypes.size() > 0) {
+ classTemplate = "<"; //$NON-NLS-1$
+ String separator = ""; //$NON-NLS-1$
+ for (int j = 0; j < templateTypes.size(); ++j) {
+ classTemplate += separator + templateTypes.get(j);
+ separator = ","; //$NON-NLS-1$
+ }
+ classTemplate += ">"; //$NON-NLS-1$
+ }
+ memberParms[i] = memberParms[i].replaceAll(unqualifiedName, className + classTemplate);
+ }
+ }
+ return Arrays.equals(memberParms, args);
+ }
+
+ private String[] resolveArgs(ClassInfo info, IType[] parameterTypes, ArrayList<String> templateTypes) {
+ String[] templateParms = info.getTemplateParms();
+ String[] result = new String[parameterTypes.length];
+ for (int i = 0; i < parameterTypes.length; ++i) {
+ String param = parameterTypes[i].toString();
+ param = param.replaceAll("\\{.*\\}", ""); //$NON-NLS-1$ //$NON-NLS-2$
+ param = param.trim();
+ int index = param.indexOf("#"); //$NON-NLS-1$
+ while (index >= 0) {
+ // We assume no class has more than 9 template parms.
+ int digit = param.charAt(index + 1) - '0';
+ // where possible, replace template parms with real values
+ if (digit < templateTypes.size())
+ param = param.replaceFirst(param.substring(index, index + 2), templateTypes.get(digit));
+ else
+ param = param.replaceFirst(param.substring(index, index + 2), templateParms[digit]);
+ index = param.indexOf("#"); //$NON-NLS-1$
+ }
+ result[i] = param;
+ }
+ return result;
+ }
+
+ @Override
+ public IFunctionSummary[] getMatchingFunctions(ICHelpInvocationContext context, ICHelpBook[] helpBooks, String prefix) {
+ ArrayList<IFunctionSummary> fList = new ArrayList<>();
ITranslationUnit t = context.getTranslationUnit();
boolean qualifiedCPP = false;
if (t.isCXXLanguage()) {
- try {
- if (context instanceof IContentAssistHelpInvocationContext) {
- // We know the file offset of the member reference.
- IASTCompletionNode node = ((IContentAssistHelpInvocationContext)context).getCompletionNode();
-
- IASTName[] names = node.getNames();
-
- for (IASTName name : names) {
- if (name.isQualified()) {
- qualifiedCPP = true;
- break;
- }
-
- }
-
- }
- } catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ try {
+ if (context instanceof IContentAssistHelpInvocationContext) {
+ // We know the file offset of the member reference.
+ IASTCompletionNode node = ((IContentAssistHelpInvocationContext)context).getCompletionNode();
+
+ IASTName[] names = node.getNames();
+
+ for (IASTName name : names) {
+ if (name.isQualified()) {
+ qualifiedCPP = true;
+ break;
+ }
+
+ }
+
+ }
+ } catch (IllegalArgumentException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
}
if (!qualifiedCPP) {
- for (int di = 0; di < helpBooks.length; ++di) {
- LibHoverLibrary l = libraries.get(helpBooks[di]);
- LibHoverInfo cppInfo = l.getHoverInfo();
- SortedMap<String, FunctionInfo> map = cppInfo.functions.tailMap(prefix);
- Set<Map.Entry<String, FunctionInfo>> c = map.entrySet();
- for (Iterator<Entry<String, FunctionInfo>> i = c.iterator(); i.hasNext();) {
- Map.Entry<String, FunctionInfo> e = i.next();
- FunctionInfo x = e.getValue();
- String name = x.getName();
- // Look for names that start with prefix, but ignore names that
- // start with "0" which is used to import text data that cannot
- // be omitted from the binary version of the document (e.g. invariant
- // sections of a GFDL licensed document). This data is given a
- // function name that starts with the character "0" which is not
- // valid for the start of a C/C++ function name. As such, it should
- // never be offered as a choice for an empty prefix.
- if (name.startsWith(prefix) && !name.startsWith("0")) { //$NON-NLS-1$
- FunctionSummary f = new FunctionSummary();
- f.ReturnType = x.getReturnType();
- f.Prototype = x.getPrototype();
- f.Summary = x.getDescription();
- f.Name = x.getName();
- ArrayList<String> headers = x.getHeaders();
- for (int i1 = 0; i1 < headers.size(); ++i1)
- f.setIncludeName(headers.get(i1));
- fList.add(f);
- }
- }
- }
+ for (int di = 0; di < helpBooks.length; ++di) {
+ LibHoverLibrary l = libraries.get(helpBooks[di]);
+ LibHoverInfo cppInfo = l.getHoverInfo();
+ SortedMap<String, FunctionInfo> map = cppInfo.functions.tailMap(prefix);
+ Set<Map.Entry<String, FunctionInfo>> c = map.entrySet();
+ for (Iterator<Entry<String, FunctionInfo>> i = c.iterator(); i.hasNext();) {
+ Map.Entry<String, FunctionInfo> e = i.next();
+ FunctionInfo x = e.getValue();
+ String name = x.getName();
+ // Look for names that start with prefix, but ignore names that
+ // start with "0" which is used to import text data that cannot
+ // be omitted from the binary version of the document (e.g. invariant
+ // sections of a GFDL licensed document). This data is given a
+ // function name that starts with the character "0" which is not
+ // valid for the start of a C/C++ function name. As such, it should
+ // never be offered as a choice for an empty prefix.
+ if (name.startsWith(prefix) && !name.startsWith("0")) { //$NON-NLS-1$
+ FunctionSummary f = new FunctionSummary();
+ f.ReturnType = x.getReturnType();
+ f.Prototype = x.getPrototype();
+ f.Summary = x.getDescription();
+ f.Name = x.getName();
+ ArrayList<String> headers = x.getHeaders();
+ for (int i1 = 0; i1 < headers.size(); ++i1)
+ f.setIncludeName(headers.get(i1));
+ fList.add(f);
+ }
+ }
+ }
+ }
+ IFunctionSummary[] summaries = new IFunctionSummary[fList.size()];
+ for (int k = 0; k < summaries.length; k++) {
+ summaries[k] = fList.get(k);
+ }
+ return summaries;
+ }
+
+ private static class HelpResource implements IHelpResource {
+ private final String href;
+ private final String label;
+ public HelpResource(String href, String label) {
+ this.href = href;
+ this.label = label;
+ }
+ @Override
+ public String getHref() {
+ return href;
+ }
+ @Override
+ public String getLabel() {
+ return label;
+ }
+ }
+
+ private static class HelpResourceDescriptor implements ICHelpResourceDescriptor {
+ private final ICHelpBook helpbook;
+
+ public HelpResourceDescriptor(ICHelpBook helpbook) {
+ this.helpbook = helpbook;
}
- IFunctionSummary[] summaries = new IFunctionSummary[fList.size()];
- for (int k = 0; k < summaries.length; k++) {
- summaries[k] = fList.get(k);
- }
- return summaries;
- }
-
- private static class HelpResource implements IHelpResource {
- private final String href;
- private final String label;
- public HelpResource(String href, String label) {
- this.href = href;
- this.label = label;
- }
- @Override
- public String getHref() {
- return href;
- }
- @Override
- public String getLabel() {
- return label;
- }
- }
-
- private static class HelpResourceDescriptor implements ICHelpResourceDescriptor {
- private final ICHelpBook helpbook;
-
- public HelpResourceDescriptor(ICHelpBook helpbook) {
- this.helpbook = helpbook;
- }
-
- @Override
- public ICHelpBook getCHelpBook() {
- return helpbook;
- }
-
- @Override
- public IHelpResource[] getHelpResources() {
- LibHoverLibrary l = libraries.get(helpbook);
- if (l != null) {
- IHelpResource[] hr = new IHelpResource[1];
- hr[0] = new HelpResource(l.getDocs(), l.getName());
- return hr;
- }
- return null;
- }
- }
-
- @Override
- public ICHelpResourceDescriptor[] getHelpResources(ICHelpInvocationContext context, ICHelpBook[] helpBooks, String name) {
- for (int i = 0; i < helpBooks.length; ++i) {
- IFunctionSummary fs = getFunctionInfo(context, new ICHelpBook[]{helpBooks[i]}, name);
- if (fs != null) {
- return new HelpResourceDescriptor[]{new HelpResourceDescriptor(helpBooks[i])};
- }
- }
- return null;
- }
+
+ @Override
+ public ICHelpBook getCHelpBook() {
+ return helpbook;
+ }
+
+ @Override
+ public IHelpResource[] getHelpResources() {
+ LibHoverLibrary l = libraries.get(helpbook);
+ if (l != null) {
+ IHelpResource[] hr = new IHelpResource[1];
+ hr[0] = new HelpResource(l.getDocs(), l.getName());
+ return hr;
+ }
+ return null;
+ }
+ }
+
+ @Override
+ public ICHelpResourceDescriptor[] getHelpResources(ICHelpInvocationContext context, ICHelpBook[] helpBooks, String name) {
+ for (int i = 0; i < helpBooks.length; ++i) {
+ IFunctionSummary fs = getFunctionInfo(context, new ICHelpBook[]{helpBooks[i]}, name);
+ if (fs != null) {
+ return new HelpResourceDescriptor[]{new HelpResourceDescriptor(helpBooks[i])};
+ }
+ }
+ return null;
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverLibrary.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverLibrary.java
index c7f2780d00..9cbfec653c 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverLibrary.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverLibrary.java
@@ -35,211 +35,211 @@ import org.eclipse.linuxtools.cdt.libhover.TypedefInfo;
import org.osgi.framework.Bundle;
public class LibHoverLibrary {
- private String name;
- private String location;
- private String docs;
- private String nameSpace;
- private boolean isCPP;
- private LibHoverInfo hoverInfo = new LibHoverInfo();
- private boolean haveReadHoverInfo = false;
-
- public LibHoverLibrary(String name, String location, String docs,
- String nameSpace, boolean isCPP) {
- this.name = name;
- this.location = location;
- this.docs = docs;
- this.isCPP = isCPP;
- this.nameSpace = nameSpace;
- }
-
- /**
- * Get the name of the library
- *
- * @return the name of the library
- */
- public String getName() {
- return name;
- }
-
- /**
- * Get the location of the library hover info (URL or file name)
- *
- * @return the URL or file name string for the library hover info location
- */
- public String getLocation() {
- return location;
- }
-
- /**
- * Get the browser help documentation URL for this library
- *
- * @return the name of the help documentation URL
- */
- public String getDocs() {
- return docs;
- }
-
- /**
- * Set the browser help documentation URL for this library
- *
- * @param docs The name of the help documentation URL
- */
- public void setDocs(String docs) {
- this.docs = docs;
- }
-
- /**
- * Get the name space of the library hover extension
- *
- * @return the name space of the library extension
- */
- public String getNameSpace() {
- return nameSpace;
- }
-
- /**
- * Is this library a C++ library?
- *
- * @return true if C++ library, false otherwise
- */
- public boolean isCPP() {
- return isCPP;
- }
-
- /**
- * Get the library hover info for this library
- *
- * @return the library hover info for this library
- */
- public synchronized LibHoverInfo getHoverInfo() {
- // We lazily get the hover info for this library since it is possible
- // the user will never access or ultimately need it if another library
- // supplies the information first.
- if (!haveReadHoverInfo) {
- URI acDoc;
- try {
- acDoc = new URI(location);
- IPath p = URIUtil.toPath(acDoc);
- InputStream docStream = null;
- if (p == null) {
- URL url = acDoc.toURL();
- URLConnection c = url.openConnection();
- c.setReadTimeout(5000); // pick a timeout value less than 15s (default)
- docStream = c.getInputStream();
- } else {
- try {
- // Try to open the file local to the plug-in declaring the
- // extension...or fall back to the libhover plug-in itself
- // if no name space for the plug-in is stored.
- Bundle bundle = LibhoverPlugin.getDefault().getBundle();
- String nameSpace = getNameSpace();
- if (nameSpace != null)
- bundle = Platform.getBundle(nameSpace);
- docStream = FileLocator.openStream(bundle, p, false);
- } catch (IOException e) {
- // File is not local to plug-in, try file system.
- docStream = new FileInputStream(p.toFile());
- }
- }
- ObjectInputStream input = new ObjectInputStream(docStream);
- hoverInfo = (LibHoverInfo)input.readObject();
- haveReadHoverInfo = true;
- input.close();
- docStream.close();
- } catch (URISyntaxException|MalformedURLException|ClassNotFoundException e) {
- e.printStackTrace();
- } catch (ConnectException|SocketTimeoutException e) {
- // Do nothing..time-out exception
- } catch (IOException e) {
- // Do nothing as empty devhelp causes this
- }
- }
- return hoverInfo;
- }
-
- /**
- * Set the library hover info.
- *
- * @param hoverInfo the library hover info to set
- */
- public synchronized void setHoverinfo(LibHoverInfo hoverInfo) {
- this.hoverInfo = hoverInfo;
- }
-
- /**
- * Fetch the class info for a given class.
- *
- * @param className the name of the class to fetch info for
- * @return ClassInfo or null if no class info can be found
- */
- public ClassInfo getClassInfo(String className, ArrayList<String> templateTypes) {
- String typedefName = className.replaceAll("<.*>", "<>"); //$NON-NLS-1$ //$NON-NLS-2$
- TypedefInfo typedef = getHoverInfo().typedefs.get(typedefName);
- if (typedef != null) {
- className = typedef.getTransformedType(className); // Reset class name to typedef transformation
- }
- int index = className.indexOf('<');
- // Check if it is a template reference.
- if (index != -1) {
- resolveTemplateTypes(className, templateTypes, index);
- // It is. We want to see if there are partial specific templates
- // and we choose the first match. If nothing matches our particular
- // case, we fall back on the initial generic template.
- ClassInfo info = getHoverInfo().classes.get(className.substring(0, index));
- if (info != null) {
- ArrayList<ClassInfo> children = info.getChildren();
- if (children != null && children.size() > 0) {
- for (int x = 0; x < children.size(); ++x) {
- ClassInfo child = children.get(x);
- if (className.matches(child.getClassName())) {
- info = child;
- break;
- }
- }
- }
- }
- return info;
- }
- // Otherwise no template, just fetch the class info directly.
- return getHoverInfo().classes.get(className);
- }
-
- private void resolveTemplateTypes(String className,
- ArrayList<String> templateTypes, int index) {
- int startIndex = index + 1;
- int i = startIndex;
- int count = 1;
- while (count > 0 && i < className.length()) {
- char x = className.charAt(i);
- switch (x) {
- case ('<'):
- ++count;
- break;
- case ('>'):
- --count;
- if (count == 0)
- templateTypes.add(className.substring(startIndex, i).trim());
- break;
- case (','): {
- if (count == 1) {
- templateTypes.add(className.substring(startIndex, i).trim());
- startIndex = i + 1;
- }
- }
- break;
- }
- ++i;
- }
- }
-
- /**
- * Fetch the function info for a given function.
- *
- * @param name of function to find info for
- * @return FunctionInfo or null if no function info exists
- */
- public FunctionInfo getFunctionInfo(String name) {
- return getHoverInfo().functions.get(name);
- }
+ private String name;
+ private String location;
+ private String docs;
+ private String nameSpace;
+ private boolean isCPP;
+ private LibHoverInfo hoverInfo = new LibHoverInfo();
+ private boolean haveReadHoverInfo = false;
+
+ public LibHoverLibrary(String name, String location, String docs,
+ String nameSpace, boolean isCPP) {
+ this.name = name;
+ this.location = location;
+ this.docs = docs;
+ this.isCPP = isCPP;
+ this.nameSpace = nameSpace;
+ }
+
+ /**
+ * Get the name of the library
+ *
+ * @return the name of the library
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Get the location of the library hover info (URL or file name)
+ *
+ * @return the URL or file name string for the library hover info location
+ */
+ public String getLocation() {
+ return location;
+ }
+
+ /**
+ * Get the browser help documentation URL for this library
+ *
+ * @return the name of the help documentation URL
+ */
+ public String getDocs() {
+ return docs;
+ }
+
+ /**
+ * Set the browser help documentation URL for this library
+ *
+ * @param docs The name of the help documentation URL
+ */
+ public void setDocs(String docs) {
+ this.docs = docs;
+ }
+
+ /**
+ * Get the name space of the library hover extension
+ *
+ * @return the name space of the library extension
+ */
+ public String getNameSpace() {
+ return nameSpace;
+ }
+
+ /**
+ * Is this library a C++ library?
+ *
+ * @return true if C++ library, false otherwise
+ */
+ public boolean isCPP() {
+ return isCPP;
+ }
+
+ /**
+ * Get the library hover info for this library
+ *
+ * @return the library hover info for this library
+ */
+ public synchronized LibHoverInfo getHoverInfo() {
+ // We lazily get the hover info for this library since it is possible
+ // the user will never access or ultimately need it if another library
+ // supplies the information first.
+ if (!haveReadHoverInfo) {
+ URI acDoc;
+ try {
+ acDoc = new URI(location);
+ IPath p = URIUtil.toPath(acDoc);
+ InputStream docStream = null;
+ if (p == null) {
+ URL url = acDoc.toURL();
+ URLConnection c = url.openConnection();
+ c.setReadTimeout(5000); // pick a timeout value less than 15s (default)
+ docStream = c.getInputStream();
+ } else {
+ try {
+ // Try to open the file local to the plug-in declaring the
+ // extension...or fall back to the libhover plug-in itself
+ // if no name space for the plug-in is stored.
+ Bundle bundle = LibhoverPlugin.getDefault().getBundle();
+ String nameSpace = getNameSpace();
+ if (nameSpace != null)
+ bundle = Platform.getBundle(nameSpace);
+ docStream = FileLocator.openStream(bundle, p, false);
+ } catch (IOException e) {
+ // File is not local to plug-in, try file system.
+ docStream = new FileInputStream(p.toFile());
+ }
+ }
+ ObjectInputStream input = new ObjectInputStream(docStream);
+ hoverInfo = (LibHoverInfo)input.readObject();
+ haveReadHoverInfo = true;
+ input.close();
+ docStream.close();
+ } catch (URISyntaxException|MalformedURLException|ClassNotFoundException e) {
+ e.printStackTrace();
+ } catch (ConnectException|SocketTimeoutException e) {
+ // Do nothing..time-out exception
+ } catch (IOException e) {
+ // Do nothing as empty devhelp causes this
+ }
+ }
+ return hoverInfo;
+ }
+
+ /**
+ * Set the library hover info.
+ *
+ * @param hoverInfo the library hover info to set
+ */
+ public synchronized void setHoverinfo(LibHoverInfo hoverInfo) {
+ this.hoverInfo = hoverInfo;
+ }
+
+ /**
+ * Fetch the class info for a given class.
+ *
+ * @param className the name of the class to fetch info for
+ * @return ClassInfo or null if no class info can be found
+ */
+ public ClassInfo getClassInfo(String className, ArrayList<String> templateTypes) {
+ String typedefName = className.replaceAll("<.*>", "<>"); //$NON-NLS-1$ //$NON-NLS-2$
+ TypedefInfo typedef = getHoverInfo().typedefs.get(typedefName);
+ if (typedef != null) {
+ className = typedef.getTransformedType(className); // Reset class name to typedef transformation
+ }
+ int index = className.indexOf('<');
+ // Check if it is a template reference.
+ if (index != -1) {
+ resolveTemplateTypes(className, templateTypes, index);
+ // It is. We want to see if there are partial specific templates
+ // and we choose the first match. If nothing matches our particular
+ // case, we fall back on the initial generic template.
+ ClassInfo info = getHoverInfo().classes.get(className.substring(0, index));
+ if (info != null) {
+ ArrayList<ClassInfo> children = info.getChildren();
+ if (children != null && children.size() > 0) {
+ for (int x = 0; x < children.size(); ++x) {
+ ClassInfo child = children.get(x);
+ if (className.matches(child.getClassName())) {
+ info = child;
+ break;
+ }
+ }
+ }
+ }
+ return info;
+ }
+ // Otherwise no template, just fetch the class info directly.
+ return getHoverInfo().classes.get(className);
+ }
+
+ private void resolveTemplateTypes(String className,
+ ArrayList<String> templateTypes, int index) {
+ int startIndex = index + 1;
+ int i = startIndex;
+ int count = 1;
+ while (count > 0 && i < className.length()) {
+ char x = className.charAt(i);
+ switch (x) {
+ case ('<'):
+ ++count;
+ break;
+ case ('>'):
+ --count;
+ if (count == 0)
+ templateTypes.add(className.substring(startIndex, i).trim());
+ break;
+ case (','): {
+ if (count == 1) {
+ templateTypes.add(className.substring(startIndex, i).trim());
+ startIndex = i + 1;
+ }
+ }
+ break;
+ }
+ ++i;
+ }
+ }
+
+ /**
+ * Fetch the function info for a given function.
+ *
+ * @param name of function to find info for
+ * @return FunctionInfo or null if no function info exists
+ */
+ public FunctionInfo getFunctionInfo(String name) {
+ return getHoverInfo().functions.get(name);
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverLoadJob.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverLoadJob.java
index 05754df6bb..71e461c0e1 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverLoadJob.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverLoadJob.java
@@ -20,25 +20,25 @@ import org.eclipse.core.runtime.jobs.Job;
public class LibHoverLoadJob extends Job {
- private static final String LOADING = "LibHover.Loading.msg"; //$NON-NLS-1$
- public LibHoverLoadJob(String title) {
- super(title);
- }
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- // Load all libhover docs now
- monitor.beginTask(LibHoverMessages.getString(LOADING),
- IProgressMonitor.UNKNOWN);
- monitor.worked(1);
- LibHover.getLibHoverDocs();
- Collection<LibHoverLibrary> c = LibHover.getLibraries();
- for (Iterator<LibHoverLibrary> i = c.iterator(); i.hasNext();) {
- LibHoverLibrary l = i.next();
- l.getHoverInfo();
- }
- monitor.done();
- return Status.OK_STATUS;
- }
+ private static final String LOADING = "LibHover.Loading.msg"; //$NON-NLS-1$
+ public LibHoverLoadJob(String title) {
+ super(title);
+ }
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ // Load all libhover docs now
+ monitor.beginTask(LibHoverMessages.getString(LOADING),
+ IProgressMonitor.UNKNOWN);
+ monitor.worked(1);
+ LibHover.getLibHoverDocs();
+ Collection<LibHoverLibrary> c = LibHover.getLibraries();
+ for (Iterator<LibHoverLibrary> i = c.iterator(); i.hasNext();) {
+ LibHoverLibrary l = i.next();
+ l.getHoverInfo();
+ }
+ monitor.done();
+ return Status.OK_STATUS;
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverMessages.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverMessages.java
index 74b2b412b5..a888f8222b 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverMessages.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/LibHoverMessages.java
@@ -21,41 +21,41 @@ import java.util.ResourceBundle;
*/
public class LibHoverMessages {
- /**
- *
- */
-
- private static final String RESOURCE_BUNDLE= LibHoverMessages.class.getName();
-
- private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);
-
- private LibHoverMessages() {
- }
-
- public static ResourceBundle getResourceBundle() {
- return fgResourceBundle;
- }
-
- public static String getString(String key) {
- try {
- return fgResourceBundle.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- } catch (NullPointerException e) {
- return '#' + key + '#';
- }
- }
-
- /**
- * Returns the formatted string from the resource bundle,
- * or 'key' if not found.
- *
- * @param key the message key
- * @param args an array of substituition strings
- * @return the resource bundle message
- */
- public static String getFormattedString(String key, String[] args) {
- return MessageFormat.format(getString(key), (Object[])args);
- }
+ /**
+ *
+ */
+
+ private static final String RESOURCE_BUNDLE= LibHoverMessages.class.getName();
+
+ private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);
+
+ private LibHoverMessages() {
+ }
+
+ public static ResourceBundle getResourceBundle() {
+ return fgResourceBundle;
+ }
+
+ public static String getString(String key) {
+ try {
+ return fgResourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ } catch (NullPointerException e) {
+ return '#' + key + '#';
+ }
+ }
+
+ /**
+ * Returns the formatted string from the resource bundle,
+ * or 'key' if not found.
+ *
+ * @param key the message key
+ * @param args an array of substituition strings
+ * @return the resource bundle message
+ */
+ public static String getFormattedString(String key, String[] args) {
+ return MessageFormat.format(getString(key), (Object[])args);
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/LibHoverPreferencePage.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/LibHoverPreferencePage.java
index b0488f5c3a..a27aa40185 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/LibHoverPreferencePage.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/LibHoverPreferencePage.java
@@ -19,10 +19,10 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* This class represents a preference page that
- * is contributed to the Preferences dialog. By
+ * is contributed to the Preferences dialog. By
* subclassing <samp>FieldEditorPreferencePage</samp>, we
* can use the field support built into JFace that allows
- * us to create a page that is small and knows how to
+ * us to create a page that is small and knows how to
* save, restore and apply itself.
* <p>
* This page is used to modify preferences only. They
@@ -32,43 +32,43 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
*/
public class LibHoverPreferencePage
- extends FieldEditorPreferencePage
- implements IWorkbenchPreferencePage {
-
- private final static String CACHE_EXT = "Libhover.CachePreference.msg"; //$NON-NLS-1$
- private final static String LOAD_ON_STARTUP = "Libhover.LoadOnStartup.msg"; //$NON-NLS-1$
+ extends FieldEditorPreferencePage
+ implements IWorkbenchPreferencePage {
- public LibHoverPreferencePage() {
- super(GRID);
- setPreferenceStore(LibhoverPlugin.getDefault().getPreferenceStore());
- }
-
- /**
- * Creates the field editors. Field editors are abstractions of
- * the common GUI blocks needed to manipulate various types
- * of preferences. Each field editor knows how to save and
- * restore itself.
- */
- @Override
- public void createFieldEditors() {
- addField(
- new BooleanFieldEditor(
- PreferenceConstants.CACHE_EXT_LIBHOVER,
- LibHoverMessages.getString(CACHE_EXT),
- getFieldEditorParent()));
- addField(
- new BooleanFieldEditor(
- PreferenceConstants.LAZY_LOAD,
- LibHoverMessages.getString(LOAD_ON_STARTUP),
- getFieldEditorParent()));
+ private final static String CACHE_EXT = "Libhover.CachePreference.msg"; //$NON-NLS-1$
+ private final static String LOAD_ON_STARTUP = "Libhover.LoadOnStartup.msg"; //$NON-NLS-1$
- }
+ public LibHoverPreferencePage() {
+ super(GRID);
+ setPreferenceStore(LibhoverPlugin.getDefault().getPreferenceStore());
+ }
+
+ /**
+ * Creates the field editors. Field editors are abstractions of
+ * the common GUI blocks needed to manipulate various types
+ * of preferences. Each field editor knows how to save and
+ * restore itself.
+ */
+ @Override
+ public void createFieldEditors() {
+ addField(
+ new BooleanFieldEditor(
+ PreferenceConstants.CACHE_EXT_LIBHOVER,
+ LibHoverMessages.getString(CACHE_EXT),
+ getFieldEditorParent()));
+ addField(
+ new BooleanFieldEditor(
+ PreferenceConstants.LAZY_LOAD,
+ LibHoverMessages.getString(LOAD_ON_STARTUP),
+ getFieldEditorParent()));
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
+ */
+ @Override
+ public void init(IWorkbench workbench) {
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- @Override
- public void init(IWorkbench workbench) {
- }
-
} \ No newline at end of file
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/PreferenceConstants.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/PreferenceConstants.java
index c700bc0415..435c59381d 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/PreferenceConstants.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/PreferenceConstants.java
@@ -15,7 +15,7 @@ package org.eclipse.linuxtools.internal.cdt.libhover.preferences;
*/
public class PreferenceConstants {
- public final static String CACHE_EXT_LIBHOVER = "org.eclipse.linuxtools.cdt.libhover.cacheExtLibhover"; //$NON-NLS-1$
- public final static String LAZY_LOAD = "org.eclipse.linuxtools.cdt.libhover.lazyLoad"; //$NON-NLS-1$
-
+ public final static String CACHE_EXT_LIBHOVER = "org.eclipse.linuxtools.cdt.libhover.cacheExtLibhover"; //$NON-NLS-1$
+ public final static String LAZY_LOAD = "org.eclipse.linuxtools.cdt.libhover.lazyLoad"; //$NON-NLS-1$
+
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/PreferenceInitializer.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/PreferenceInitializer.java
index 1c9ea57a40..c5344d12db 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/PreferenceInitializer.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/preferences/PreferenceInitializer.java
@@ -20,16 +20,16 @@ import org.eclipse.linuxtools.cdt.libhover.LibhoverPlugin;
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
- */
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = LibhoverPlugin.getDefault().getPreferenceStore();
- store.setDefault(PreferenceConstants.CACHE_EXT_LIBHOVER, true);
- store.setDefault(PreferenceConstants.LAZY_LOAD, false);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
+ */
+ @Override
+ public void initializeDefaultPreferences() {
+ IPreferenceStore store = LibhoverPlugin.getDefault().getPreferenceStore();
+ store.setDefault(PreferenceConstants.CACHE_EXT_LIBHOVER, true);
+ store.setDefault(PreferenceConstants.LAZY_LOAD, false);
+ }
}
diff --git a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/utils/BuildFunctionInfos.java b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/utils/BuildFunctionInfos.java
index 32a5008977..33245f66c9 100644
--- a/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/utils/BuildFunctionInfos.java
+++ b/libhover/org.eclipse.linuxtools.cdt.libhover/src/org/eclipse/linuxtools/internal/cdt/libhover/utils/BuildFunctionInfos.java
@@ -36,18 +36,18 @@ import org.xml.sax.SAXException;
public class BuildFunctionInfos {
- private Document document;
- private LibHoverInfo hoverInfo = new LibHoverInfo();
+ private Document document;
+ private LibHoverInfo hoverInfo = new LibHoverInfo();
- public BuildFunctionInfos(Document document) {
- this.document = document;
- }
+ public BuildFunctionInfos(Document document) {
+ this.document = document;
+ }
- public Document getDocument() {
- return document;
- }
+ public Document getDocument() {
+ return document;
+ }
- private FunctionInfo getFunctionInfoFromNode(String name, Node functionNode, Document document) {
+ private FunctionInfo getFunctionInfoFromNode(String name, Node functionNode, Document document) {
FunctionInfo f = new FunctionInfo(name);
NamedNodeMap functionNodeMap = functionNode.getAttributes();
Node functionNodeReturntypeNode = functionNodeMap.item(0);
@@ -59,11 +59,11 @@ public class BuildFunctionInfos {
String functionNodeRtValue = functionNodeReturntypeNode.getNodeValue();
f.setReturnType(functionNodeRtValue);
- } // returntype
+ } // returntype
NodeList kids = functionNode.getChildNodes();
for (int fnk = 0; fnk < kids.getLength(); fnk++) {
- Node kid = kids.item(fnk);
+ Node kid = kids.item(fnk);
String kidName = kid.getNodeName();
if (kidName.equals("prototype")) { //$NON-NLS-1$
@@ -84,7 +84,7 @@ public class BuildFunctionInfos {
}
}
f.setPrototype(prototype);
- } // prototype
+ } // prototype
else if (kidName.equals("headers")) { //$NON-NLS-1$
@@ -100,27 +100,27 @@ public class BuildFunctionInfos {
f.addHeader(headerNode.getNodeValue());
}
}
- } // headers
+ } // headers
else if (kidName.equals("groupsynopsis")) { //$NON-NLS-1$
- // group synopsis
-
- NamedNodeMap attr = kid.getAttributes();
- Node idnode = attr.getNamedItem("id"); //$NON-NLS-1$
- String id = idnode.getNodeValue();
- if (id != null) {
- Element elem2 = document.getElementById(id);
- if (null != elem2) {
- NodeList synopsisNode = elem2.getElementsByTagName("synopsis"); //$NON-NLS-1$
- if (null != synopsisNode && synopsisNode.getLength() > 0) {
- Node synopsis = synopsisNode.item(0);
- Node textNode = synopsis.getLastChild();
- f.setDescription(textNode.getNodeValue());
- }
- }
- }
+ // group synopsis
+
+ NamedNodeMap attr = kid.getAttributes();
+ Node idnode = attr.getNamedItem("id"); //$NON-NLS-1$
+ String id = idnode.getNodeValue();
+ if (id != null) {
+ Element elem2 = document.getElementById(id);
+ if (null != elem2) {
+ NodeList synopsisNode = elem2.getElementsByTagName("synopsis"); //$NON-NLS-1$
+ if (null != synopsisNode && synopsisNode.getLength() > 0) {
+ Node synopsis = synopsisNode.item(0);
+ Node textNode = synopsis.getLastChild();
+ f.setDescription(textNode.getNodeValue());
+ }
+ }
+ }
} else if (kidName.equals("synopsis")) { //$NON-NLS-1$
// synopsis
Node textNode = kid.getLastChild();
@@ -128,65 +128,65 @@ public class BuildFunctionInfos {
}
}
return f;
- }
-
- private void buildCPPInfo(String fileName) {
- Document document = getDocument();
- NodeList nl = document.getElementsByTagName("construct"); //$NON-NLS-1$
- for (int i = 0; i < nl.getLength(); ++i) {
- Node n = nl.item(i);
- NamedNodeMap m = n.getAttributes();
- Node id = m.getNamedItem("id"); //$NON-NLS-1$
- if (id != null && id.getNodeValue().startsWith("function-")) { //$NON-NLS-1$
- String name = id.getNodeValue().substring(9);
- NodeList nl2 = n.getChildNodes();
- for (int j = 0; j < nl2.getLength(); ++j) {
- Node n2 = nl2.item(j);
- if (n2.getNodeName().equals("function")) { //$NON-NLS-1$
- FunctionInfo f = getFunctionInfoFromNode(name, n2, document);
- hoverInfo.functions.put(name, f);
- }
- }
- }
- }
- try (FileOutputStream f = new FileOutputStream(fileName);
- ObjectOutputStream out = new ObjectOutputStream(f)){
- // Now, output the LibHoverInfo for caching later
- out.writeObject(hoverInfo);
- } catch(IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * @param args args[0] - URL or file name of xml document to parse
- * args[1] - file name to place resultant serialized LibHoverInfo
- */
- public static void main(String[] args) {
- URI acDoc;
- try {
- acDoc = new URI(args[0]);
- IPath p = URIUtil.toPath(acDoc);
- InputStream docStream = null;
- if (p == null) {
- URL url = acDoc.toURL();
- docStream = url.openStream();
- } else {
- docStream = new FileInputStream(p.toFile());
- }
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setValidating(false);
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document doc = builder.parse(docStream);
- if (doc != null) {
- BuildFunctionInfos d = new BuildFunctionInfos(doc);
- d.buildCPPInfo(args[1]);
- }
- System.out.println("Built " + args[1] + " from " + args[0]); //$NON-NLS-1$ //$NON-NLS-2$
- } catch (URISyntaxException|SAXException|ParserConfigurationException|IOException e) {
- e.printStackTrace();
- }
-
- }
+ }
+
+ private void buildCPPInfo(String fileName) {
+ Document document = getDocument();
+ NodeList nl = document.getElementsByTagName("construct"); //$NON-NLS-1$
+ for (int i = 0; i < nl.getLength(); ++i) {
+ Node n = nl.item(i);
+ NamedNodeMap m = n.getAttributes();
+ Node id = m.getNamedItem("id"); //$NON-NLS-1$
+ if (id != null && id.getNodeValue().startsWith("function-")) { //$NON-NLS-1$
+ String name = id.getNodeValue().substring(9);
+ NodeList nl2 = n.getChildNodes();
+ for (int j = 0; j < nl2.getLength(); ++j) {
+ Node n2 = nl2.item(j);
+ if (n2.getNodeName().equals("function")) { //$NON-NLS-1$
+ FunctionInfo f = getFunctionInfoFromNode(name, n2, document);
+ hoverInfo.functions.put(name, f);
+ }
+ }
+ }
+ }
+ try (FileOutputStream f = new FileOutputStream(fileName);
+ ObjectOutputStream out = new ObjectOutputStream(f)){
+ // Now, output the LibHoverInfo for caching later
+ out.writeObject(hoverInfo);
+ } catch(IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @param args args[0] - URL or file name of xml document to parse
+ * args[1] - file name to place resultant serialized LibHoverInfo
+ */
+ public static void main(String[] args) {
+ URI acDoc;
+ try {
+ acDoc = new URI(args[0]);
+ IPath p = URIUtil.toPath(acDoc);
+ InputStream docStream = null;
+ if (p == null) {
+ URL url = acDoc.toURL();
+ docStream = url.openStream();
+ } else {
+ docStream = new FileInputStream(p.toFile());
+ }
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setValidating(false);
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ Document doc = builder.parse(docStream);
+ if (doc != null) {
+ BuildFunctionInfos d = new BuildFunctionInfos(doc);
+ d.buildCPPInfo(args[1]);
+ }
+ System.out.println("Built " + args[1] + " from " + args[0]); //$NON-NLS-1$ //$NON-NLS-2$
+ } catch (URISyntaxException|SAXException|ParserConfigurationException|IOException e) {
+ e.printStackTrace();
+ }
+
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.ctf.core/src/org/eclipse/linuxtools/ctf/core/event/types/SequenceDeclaration.java b/lttng/org.eclipse.linuxtools.ctf.core/src/org/eclipse/linuxtools/ctf/core/event/types/SequenceDeclaration.java
index 082c70488a..66957087b4 100644
--- a/lttng/org.eclipse.linuxtools.ctf.core/src/org/eclipse/linuxtools/ctf/core/event/types/SequenceDeclaration.java
+++ b/lttng/org.eclipse.linuxtools.ctf.core/src/org/eclipse/linuxtools/ctf/core/event/types/SequenceDeclaration.java
@@ -16,7 +16,7 @@ import org.eclipse.linuxtools.ctf.core.trace.CTFReaderException;
/**
* A CTF sequence declaration.
- *
+ *
* An array where the size is fixed but declared in the trace, unlike array
* where it is declared with a literal
*
diff --git a/lttng/org.eclipse.linuxtools.gdbtrace.core/src/org/eclipse/linuxtools/internal/gdbtrace/core/trace/DsfGdbAdaptor.java b/lttng/org.eclipse.linuxtools.gdbtrace.core/src/org/eclipse/linuxtools/internal/gdbtrace/core/trace/DsfGdbAdaptor.java
index 4fb007f419..2d03a60ff6 100644
--- a/lttng/org.eclipse.linuxtools.gdbtrace.core/src/org/eclipse/linuxtools/internal/gdbtrace/core/trace/DsfGdbAdaptor.java
+++ b/lttng/org.eclipse.linuxtools.gdbtrace.core/src/org/eclipse/linuxtools/internal/gdbtrace/core/trace/DsfGdbAdaptor.java
@@ -221,7 +221,7 @@ public class DsfGdbAdaptor {
final ICommandControlService commandControl = tracker.getService(ICommandControlService.class);
if (traceControl != null && commandControl != null) {
ITraceTargetDMContext traceContext = (ITraceTargetDMContext) commandControl.getContext();
- traceControl.getCurrentTraceRecordContext(traceContext, queryRm);
+ traceControl.getCurrentTraceRecordContext(traceContext, queryRm);
} else {
queryRm.done();
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_invalid/invalid_view_multipledisplays.xml b/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_invalid/invalid_view_multipledisplays.xml
index bf820eaa0e..9ac7c7c755 100644
--- a/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_invalid/invalid_view_multipledisplays.xml
+++ b/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_invalid/invalid_view_multipledisplays.xml
@@ -8,28 +8,28 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
-* Geneviève Bastien - Initial API and implementation
+* Geneviève Bastien - Initial API and implementation
*************************************************************************** -->
<tmfxml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="xmlDefinition.xsd">
+ xsi:noNamespaceSchemaLocation="xmlDefinition.xsd">
- <stateSystemView id="org.eclipse.linuxtools.tmf.analysis.xml.ui.views.statesystem">
- <head>
- <analysis id="kernel.linux.sp" />
- <label value="Xml kernel View" />
- </head>
- <!-- StateValues -->
- <definedValue name="PROCESS_STATUS_UNKNOWN" value="0" color="#EEEEEE" />
- <definedValue name="PROCESS_STATUS_WAIT_BLOCKED" value="1" color="#CCCCCC" />
- <definedValue name="PROCESS_STATUS_RUN_USERMODE" value="2" color="#118811" />
- <definedValue name="PROCESS_STATUS_RUN_SYSCALL" value="3" color="#0000EE" />
- <definedValue name="PROCESS_STATUS_INTERRUPTED" value="4" color="#DDDD00" />
- <definedValue name="PROCESS_STATUS_WAIT_FOR_CPU" value="5" color="#AA0000" />
+ <stateSystemView id="org.eclipse.linuxtools.tmf.analysis.xml.ui.views.statesystem">
+ <head>
+ <analysis id="kernel.linux.sp" />
+ <label value="Xml kernel View" />
+ </head>
+ <!-- StateValues -->
+ <definedValue name="PROCESS_STATUS_UNKNOWN" value="0" color="#EEEEEE" />
+ <definedValue name="PROCESS_STATUS_WAIT_BLOCKED" value="1" color="#CCCCCC" />
+ <definedValue name="PROCESS_STATUS_RUN_USERMODE" value="2" color="#118811" />
+ <definedValue name="PROCESS_STATUS_RUN_SYSCALL" value="3" color="#0000EE" />
+ <definedValue name="PROCESS_STATUS_INTERRUPTED" value="4" color="#DDDD00" />
+ <definedValue name="PROCESS_STATUS_WAIT_FOR_CPU" value="5" color="#AA0000" />
- <!-- Control Flow View -->
- <entry path="CPUs/*">
- <display type="self" />
- <display type="constant" value="a" />
- </entry>
- </stateSystemView>
+ <!-- Control Flow View -->
+ <entry path="CPUs/*">
+ <display type="self" />
+ <display type="constant" value="a" />
+ </entry>
+ </stateSystemView>
</tmfxml> \ No newline at end of file
diff --git a/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_invalid/test_invalid.xml b/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_invalid/test_invalid.xml
index dcd5512c07..2d4bb70858 100644
--- a/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_invalid/test_invalid.xml
+++ b/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_invalid/test_invalid.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<tmfxml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="stateprovider.xsd">
+ xsi:noNamespaceSchemaLocation="stateprovider.xsd">
- <!-- This element does not belong to the schema -->
- <element id="fail"></element>
+ <!-- This element does not belong to the schema -->
+ <element id="fail"></element>
</tmfxml> \ No newline at end of file
diff --git a/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_valid.xml b/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_valid.xml
index c463896276..b59fd4583b 100644
--- a/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_valid.xml
+++ b/lttng/org.eclipse.linuxtools.tmf.analysis.xml.core.tests/test_xml_files/test_valid.xml
@@ -8,612 +8,612 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
-* Florian Wininger - Initial API and implementation
+* Florian Wininger - Initial API and implementation
*************************************************************************** -->
<tmfxml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="xmlDefinition.xsd">
+ xsi:noNamespaceSchemaLocation="xmlDefinition.xsd">
- <timeGraphView id="org.eclipse.linuxtools.tmf.analysis.xml.ui.views.statesystem">
- <head>
- <analysis id="kernel.linux.sp" />
- <label value="Xml Sample Kernel View" />
- </head>
- <!-- StateValues -->
- <definedValue name="PROCESS_STATUS_UNKNOWN" value="0" color="#EEEEEE" />
- <definedValue name="PROCESS_STATUS_WAIT_BLOCKED" value="1" color="#CCCCCC" />
- <definedValue name="PROCESS_STATUS_RUN_USERMODE" value="2" color="#118811" />
- <definedValue name="PROCESS_STATUS_RUN_SYSCALL" value="3" color="#0000EE" />
- <definedValue name="PROCESS_STATUS_INTERRUPTED" value="4" color="#DDDD00" />
- <definedValue name="PROCESS_STATUS_WAIT_FOR_CPU" value="5" color="#AA0000" />
+ <timeGraphView id="org.eclipse.linuxtools.tmf.analysis.xml.ui.views.statesystem">
+ <head>
+ <analysis id="kernel.linux.sp" />
+ <label value="Xml Sample Kernel View" />
+ </head>
+ <!-- StateValues -->
+ <definedValue name="PROCESS_STATUS_UNKNOWN" value="0" color="#EEEEEE" />
+ <definedValue name="PROCESS_STATUS_WAIT_BLOCKED" value="1" color="#CCCCCC" />
+ <definedValue name="PROCESS_STATUS_RUN_USERMODE" value="2" color="#118811" />
+ <definedValue name="PROCESS_STATUS_RUN_SYSCALL" value="3" color="#0000EE" />
+ <definedValue name="PROCESS_STATUS_INTERRUPTED" value="4" color="#DDDD00" />
+ <definedValue name="PROCESS_STATUS_WAIT_FOR_CPU" value="5" color="#AA0000" />
- <!-- Control Flow View -->
- <entry path="CPUs/*">
- <display type="constant" value="Status" />
- <parent type="constant" value="PPID" />
- <name type="constant" value="Exec_name" />
- </entry>
- <entry path="Threads">
- <display type="self" />
- <entry path="*">
- <display type="constant" value="Status" />
- <parent type="constant" value="PPID" />
- <name type="constant" value="Exec_name" />
- </entry>
- </entry>
- </timeGraphView>
+ <!-- Control Flow View -->
+ <entry path="CPUs/*">
+ <display type="constant" value="Status" />
+ <parent type="constant" value="PPID" />
+ <name type="constant" value="Exec_name" />
+ </entry>
+ <entry path="Threads">
+ <display type="self" />
+ <entry path="*">
+ <display type="constant" value="Status" />
+ <parent type="constant" value="PPID" />
+ <name type="constant" value="Exec_name" />
+ </entry>
+ </entry>
+ </timeGraphView>
- <stateProvider id="kernel.linux.sp" version="1">
- <head>
- <traceType id="org.eclipse.linuxtools.lttng2.kernel.tracetype" />
- <label value="Xml kernel State System" />
- </head>
- <!-- StateValues -->
- <definedValue name="CPU_STATUS_IDLE" value="0" />
- <definedValue name="CPU_STATUS_RUN_USERMODE" value="1" />
- <definedValue name="CPU_STATUS_RUN_SYSCALL" value="2" />
- <definedValue name="CPU_STATUS_IRQ" value="3" />
- <definedValue name="CPU_STATUS_SOFTIRQ" value="4" />
+ <stateProvider id="kernel.linux.sp" version="1">
+ <head>
+ <traceType id="org.eclipse.linuxtools.lttng2.kernel.tracetype" />
+ <label value="Xml kernel State System" />
+ </head>
+ <!-- StateValues -->
+ <definedValue name="CPU_STATUS_IDLE" value="0" />
+ <definedValue name="CPU_STATUS_RUN_USERMODE" value="1" />
+ <definedValue name="CPU_STATUS_RUN_SYSCALL" value="2" />
+ <definedValue name="CPU_STATUS_IRQ" value="3" />
+ <definedValue name="CPU_STATUS_SOFTIRQ" value="4" />
- <definedValue name="PROCESS_STATUS_UNKNOWN" value="0" />
- <definedValue name="PROCESS_STATUS_WAIT_BLOCKED" value="1" />
- <definedValue name="PROCESS_STATUS_RUN_USERMODE" value="2" />
- <definedValue name="PROCESS_STATUS_RUN_SYSCALL" value="3" />
- <definedValue name="PROCESS_STATUS_INTERRUPTED" value="4" />
- <definedValue name="PROCESS_STATUS_WAIT_FOR_CPU" value="5" />
+ <definedValue name="PROCESS_STATUS_UNKNOWN" value="0" />
+ <definedValue name="PROCESS_STATUS_WAIT_BLOCKED" value="1" />
+ <definedValue name="PROCESS_STATUS_RUN_USERMODE" value="2" />
+ <definedValue name="PROCESS_STATUS_RUN_SYSCALL" value="3" />
+ <definedValue name="PROCESS_STATUS_INTERRUPTED" value="4" />
+ <definedValue name="PROCESS_STATUS_WAIT_FOR_CPU" value="5" />
- <definedValue name="SOFT_IRQ_RAISED" value="-2" />
+ <definedValue name="SOFT_IRQ_RAISED" value="-2" />
- <!-- Shortcut Variables -->
- <location id="CurrentThread">
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="query">
- <stateAttribute type="constant" value="CPUs" />
- <stateAttribute type="eventField" value="cpu" />
- <stateAttribute type="constant" value="Current_thread" />
- </stateAttribute>
- </location>
- <location id="CurrentCPU">
- <stateAttribute type="constant" value="CPUs" />
- <stateAttribute type="eventField" value="cpu" />
- </location>
- <location id="CurrentIRQ">
- <stateAttribute type="constant" value="Resources"/>
- <stateAttribute type="constant" value="IRQs"/>
- <stateAttribute type="eventField" value="irq"/>
- </location>
- <location id="CurrentSoftIRQ">
- <stateAttribute type="constant" value="Resources" />
- <stateAttribute type="constant" value="Soft_IRQs" />
- <stateAttribute type="eventField" value="vec" />
- </location>
- <location id="newCurrentThread">
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="next_tid" />
- </location>
+ <!-- Shortcut Variables -->
+ <location id="CurrentThread">
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="query">
+ <stateAttribute type="constant" value="CPUs" />
+ <stateAttribute type="eventField" value="cpu" />
+ <stateAttribute type="constant" value="Current_thread" />
+ </stateAttribute>
+ </location>
+ <location id="CurrentCPU">
+ <stateAttribute type="constant" value="CPUs" />
+ <stateAttribute type="eventField" value="cpu" />
+ </location>
+ <location id="CurrentIRQ">
+ <stateAttribute type="constant" value="Resources"/>
+ <stateAttribute type="constant" value="IRQs"/>
+ <stateAttribute type="eventField" value="irq"/>
+ </location>
+ <location id="CurrentSoftIRQ">
+ <stateAttribute type="constant" value="Resources" />
+ <stateAttribute type="constant" value="Soft_IRQs" />
+ <stateAttribute type="eventField" value="vec" />
+ </location>
+ <location id="newCurrentThread">
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="next_tid" />
+ </location>
- <!-- case 1 : exit_syscall : Fields: int64 ret -->
- <eventHandler eventName="exit_syscall">
- <stateChange>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="null" />
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_RUN_USERMODE" />
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_RUN_USERMODE" />
- </stateChange>
- </eventHandler>
- <!-- case 2 : irq_handler_entry : Fields: int32 irq, string name -->
- <eventHandler eventName="irq_handler_entry">
- <stateChange>
- <stateAttribute type="location" value="CurrentIRQ" />
- <stateValue type="eventField" value="cpu" />
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_INTERRUPTED" />
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_IRQ" />
- </stateChange>
- </eventHandler>
- <!-- case 3 : irq_handler_exit : Fields: int32 irq, int32 ret -->
- <eventHandler eventName="irq_handler_exit">
- <stateChange>
- <stateAttribute type="location" value="CurrentIRQ" />
- <stateValue type="null" />
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_RUN_USERMODE" />
- </then>
- <else>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
- </else>
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_RUN_USERMODE" />
- </then>
- <else>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_RUN_SYSCALL" />
- </else>
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Current_thread" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_IDLE" />
- </then>
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Current_thread" />
- <stateValue type="int" value="0" />
- </condition>
- </if>
- <then>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_IDLE" />
- </then>
- </stateChange>
- </eventHandler>
- <!-- case 4 : softirq_entry : Fields: int32 vec -->
- <eventHandler eventName="softirq_entry">
- <stateChange>
- <stateAttribute type="location" value="CurrentSoftIRQ" />
- <stateValue type="eventField" value="cpu" />
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_INTERRUPTED" />
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_SOFTIRQ" />
- </stateChange>
- </eventHandler>
- <!-- case 5 : softirq_exit : Fields: int32 vec -->
- <eventHandler eventName="softirq_exit">
- <stateChange>
- <stateAttribute type="location" value="CurrentSoftIRQ" />
- <stateValue type="null" />
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_RUN_USERMODE" />
- </then>
- <else>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
- </else>
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_RUN_USERMODE" />
- </then>
- <else>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_RUN_SYSCALL" />
- </else>
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Current_thread" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_IDLE" />
- </then>
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Current_thread" />
- <stateValue type="int" value="0" />
- </condition>
- </if>
- <then>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_IDLE" />
- </then>
- </stateChange>
- </eventHandler>
- <!-- case 6 : softirq_raise : Fields: int32 vec -->
- <eventHandler eventName="softirq_raise">
- <stateChange>
- <stateAttribute type="location" value="CurrentSoftIRQ" />
- <stateValue type="int" value="$SOFT_IRQ_RAISED" />
- </stateChange>
- </eventHandler>
- <!-- case 7 : sched_switch : Fields: string prev_comm, int32 prev_tid,
- int32 prev_prio, int64 prev_state, string next_comm, int32 next_tid, int32
- next_prio -->
- <eventHandler eventName="sched_switch">
- <stateChange>
- <if>
- <condition>
- <field name="prev_state" />
- <stateValue type="long" value="0" />
- </condition>
- </if>
- <then>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="prev_tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_WAIT_FOR_CPU" />
- </then>
- <else>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="prev_tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_WAIT_BLOCKED" />
- </else>
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="location" value="newCurrentThread" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="location" value="newCurrentThread" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_RUN_USERMODE" />
- </then>
- <else>
- <stateAttribute type="location" value="newCurrentThread" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
- </else>
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="newCurrentThread" />
- <stateAttribute type="constant" value="Exec_name" />
- <stateValue type="eventField" value="next_comm" />
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Current_thread" />
- <stateValue type="eventField" value="next_tid" forcedType="int" />
- </stateChange>
- <stateChange>
- <if>
- <not>
- <condition>
- <field name="next_tid" />
- <stateValue type="long" value="0" />
- </condition>
- </not>
- </if>
- <then>
- <if>
- <condition>
- <stateAttribute type="location" value="newCurrentThread" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_RUN_USERMODE" />
- </then>
- <else>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_RUN_SYSCALL" />
- </else>
- </then>
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <field name="next_tid" />
- <stateValue type="long" value="0" />
- </condition>
- </if>
- <then>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_IDLE" />
- </then>
- </stateChange>
- </eventHandler>
- <!-- case 8 : sched_process_fork : Fields: string parent_comm, int32 parent_tid,
- string child_comm, int32 child_tid -->
- <eventHandler eventName="sched_process_fork">
- <stateChange>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="child_tid" />
- <stateAttribute type="constant" value="PPID" />
- <stateValue type="eventField" value="parent_tid" forcedType="int" />
- </stateChange>
- <stateChange>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="child_tid" />
- <stateAttribute type="constant" value="Exec_name" />
- <stateValue type="eventField" value="child_comm" />
- </stateChange>
- <stateChange>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="child_tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_WAIT_FOR_CPU" />
- </stateChange>
- <stateChange>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="child_tid" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="query">
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="parent_tid" />
- <stateAttribute type="constant" value="System_call" />
- </stateValue>
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="child_tid" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="child_tid" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="string" value="sys_clone" />
- </then>
- </stateChange>
- </eventHandler>
- <!-- case 10 : sched_process_free : Fields: string parent_comm, int32 parent_tid,
- string child_comm, int32 child_tid -->
- <eventHandler eventName="sched_process_free">
- <stateChange>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateValue type="delete" />
- </stateChange>
- </eventHandler>
- <!-- case 11 : lttng_statedump_process_state : Fields: int32 type, int32
- mode, int32 pid, int32 submode, int32 vpid, int32 ppid, int32 tid, string
- name, int32 status, int32 vtid -->
- <eventHandler eventName="lttng_statedump_process_state">
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="Exec_name" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="Exec_name" />
- <stateValue type="eventField" value="name" />
- </then>
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="PPID" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="PPID" />
- <stateValue type="eventField" value="ppid" forcedType="int" />
- </then>
- </stateChange>
- <stateChange>
- <if>
- <and>
- <condition>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="null" />
- </condition>
- <condition>
- <field name="status" />
- <stateValue type="long" value="2" />
- </condition>
- </and>
- </if>
- <then>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_WAIT_FOR_CPU" />
- </then>
- </stateChange>
- <stateChange>
- <if>
- <and>
- <condition>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="null" />
- </condition>
- <condition>
- <field name="status" />
- <stateValue type="long" value="5" />
- </condition>
- </and>
- </if>
- <then>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_WAIT_BLOCKED" />
- </then>
- </stateChange>
- <stateChange>
- <if>
- <condition>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="null" />
- </condition>
- </if>
- <then>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_UNKNOWN" />
- </then>
- </stateChange>
- </eventHandler>
- <!-- case 12 : sched_wakeup : case 13 : sched_wakeup_new : Fields (same
- fields for both types): string comm, int32 tid, int32 prio, int32 success,
- int32 target_cpu -->
- <eventHandler eventName="sched_wakeup*">
- <stateChange>
- <if>
- <and>
- <not>
- <condition>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_RUN_USERMODE" />
- </condition>
- </not>
- <not>
- <condition>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
- </condition>
- </not>
- </and>
- </if>
- <then>
- <stateAttribute type="constant" value="Threads" />
- <stateAttribute type="eventField" value="tid" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_WAIT_FOR_CPU" />
- </then>
- </stateChange>
- </eventHandler>
- <!-- delfault : syscall -->
- <eventHandler eventName="sys_*">
- <stateChange>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="eventName" />
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_RUN_SYSCALL" />
- </stateChange>
- </eventHandler>
- <!-- delfault : compat_syscall -->
- <eventHandler eventName="compat_sys_*">
- <stateChange>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="System_call" />
- <stateValue type="eventName" />
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="CurrentThread" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
- </stateChange>
- <stateChange>
- <stateAttribute type="location" value="CurrentCPU" />
- <stateAttribute type="constant" value="Status" />
- <stateValue type="int" value="$CPU_STATUS_RUN_SYSCALL" />
- </stateChange>
- </eventHandler>
- </stateProvider>
+ <!-- case 1 : exit_syscall : Fields: int64 ret -->
+ <eventHandler eventName="exit_syscall">
+ <stateChange>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="null" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_RUN_USERMODE" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_RUN_USERMODE" />
+ </stateChange>
+ </eventHandler>
+ <!-- case 2 : irq_handler_entry : Fields: int32 irq, string name -->
+ <eventHandler eventName="irq_handler_entry">
+ <stateChange>
+ <stateAttribute type="location" value="CurrentIRQ" />
+ <stateValue type="eventField" value="cpu" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_INTERRUPTED" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_IRQ" />
+ </stateChange>
+ </eventHandler>
+ <!-- case 3 : irq_handler_exit : Fields: int32 irq, int32 ret -->
+ <eventHandler eventName="irq_handler_exit">
+ <stateChange>
+ <stateAttribute type="location" value="CurrentIRQ" />
+ <stateValue type="null" />
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_RUN_USERMODE" />
+ </then>
+ <else>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
+ </else>
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_RUN_USERMODE" />
+ </then>
+ <else>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_RUN_SYSCALL" />
+ </else>
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Current_thread" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_IDLE" />
+ </then>
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Current_thread" />
+ <stateValue type="int" value="0" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_IDLE" />
+ </then>
+ </stateChange>
+ </eventHandler>
+ <!-- case 4 : softirq_entry : Fields: int32 vec -->
+ <eventHandler eventName="softirq_entry">
+ <stateChange>
+ <stateAttribute type="location" value="CurrentSoftIRQ" />
+ <stateValue type="eventField" value="cpu" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_INTERRUPTED" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_SOFTIRQ" />
+ </stateChange>
+ </eventHandler>
+ <!-- case 5 : softirq_exit : Fields: int32 vec -->
+ <eventHandler eventName="softirq_exit">
+ <stateChange>
+ <stateAttribute type="location" value="CurrentSoftIRQ" />
+ <stateValue type="null" />
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_RUN_USERMODE" />
+ </then>
+ <else>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
+ </else>
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_RUN_USERMODE" />
+ </then>
+ <else>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_RUN_SYSCALL" />
+ </else>
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Current_thread" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_IDLE" />
+ </then>
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Current_thread" />
+ <stateValue type="int" value="0" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_IDLE" />
+ </then>
+ </stateChange>
+ </eventHandler>
+ <!-- case 6 : softirq_raise : Fields: int32 vec -->
+ <eventHandler eventName="softirq_raise">
+ <stateChange>
+ <stateAttribute type="location" value="CurrentSoftIRQ" />
+ <stateValue type="int" value="$SOFT_IRQ_RAISED" />
+ </stateChange>
+ </eventHandler>
+ <!-- case 7 : sched_switch : Fields: string prev_comm, int32 prev_tid,
+ int32 prev_prio, int64 prev_state, string next_comm, int32 next_tid, int32
+ next_prio -->
+ <eventHandler eventName="sched_switch">
+ <stateChange>
+ <if>
+ <condition>
+ <field name="prev_state" />
+ <stateValue type="long" value="0" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="prev_tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_WAIT_FOR_CPU" />
+ </then>
+ <else>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="prev_tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_WAIT_BLOCKED" />
+ </else>
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="location" value="newCurrentThread" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="location" value="newCurrentThread" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_RUN_USERMODE" />
+ </then>
+ <else>
+ <stateAttribute type="location" value="newCurrentThread" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
+ </else>
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="newCurrentThread" />
+ <stateAttribute type="constant" value="Exec_name" />
+ <stateValue type="eventField" value="next_comm" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Current_thread" />
+ <stateValue type="eventField" value="next_tid" forcedType="int" />
+ </stateChange>
+ <stateChange>
+ <if>
+ <not>
+ <condition>
+ <field name="next_tid" />
+ <stateValue type="long" value="0" />
+ </condition>
+ </not>
+ </if>
+ <then>
+ <if>
+ <condition>
+ <stateAttribute type="location" value="newCurrentThread" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_RUN_USERMODE" />
+ </then>
+ <else>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_RUN_SYSCALL" />
+ </else>
+ </then>
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <field name="next_tid" />
+ <stateValue type="long" value="0" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_IDLE" />
+ </then>
+ </stateChange>
+ </eventHandler>
+ <!-- case 8 : sched_process_fork : Fields: string parent_comm, int32 parent_tid,
+ string child_comm, int32 child_tid -->
+ <eventHandler eventName="sched_process_fork">
+ <stateChange>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="child_tid" />
+ <stateAttribute type="constant" value="PPID" />
+ <stateValue type="eventField" value="parent_tid" forcedType="int" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="child_tid" />
+ <stateAttribute type="constant" value="Exec_name" />
+ <stateValue type="eventField" value="child_comm" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="child_tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_WAIT_FOR_CPU" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="child_tid" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="query">
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="parent_tid" />
+ <stateAttribute type="constant" value="System_call" />
+ </stateValue>
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="child_tid" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="child_tid" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="string" value="sys_clone" />
+ </then>
+ </stateChange>
+ </eventHandler>
+ <!-- case 10 : sched_process_free : Fields: string parent_comm, int32 parent_tid,
+ string child_comm, int32 child_tid -->
+ <eventHandler eventName="sched_process_free">
+ <stateChange>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateValue type="delete" />
+ </stateChange>
+ </eventHandler>
+ <!-- case 11 : lttng_statedump_process_state : Fields: int32 type, int32
+ mode, int32 pid, int32 submode, int32 vpid, int32 ppid, int32 tid, string
+ name, int32 status, int32 vtid -->
+ <eventHandler eventName="lttng_statedump_process_state">
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="Exec_name" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="Exec_name" />
+ <stateValue type="eventField" value="name" />
+ </then>
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="PPID" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="PPID" />
+ <stateValue type="eventField" value="ppid" forcedType="int" />
+ </then>
+ </stateChange>
+ <stateChange>
+ <if>
+ <and>
+ <condition>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="null" />
+ </condition>
+ <condition>
+ <field name="status" />
+ <stateValue type="long" value="2" />
+ </condition>
+ </and>
+ </if>
+ <then>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_WAIT_FOR_CPU" />
+ </then>
+ </stateChange>
+ <stateChange>
+ <if>
+ <and>
+ <condition>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="null" />
+ </condition>
+ <condition>
+ <field name="status" />
+ <stateValue type="long" value="5" />
+ </condition>
+ </and>
+ </if>
+ <then>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_WAIT_BLOCKED" />
+ </then>
+ </stateChange>
+ <stateChange>
+ <if>
+ <condition>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="null" />
+ </condition>
+ </if>
+ <then>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_UNKNOWN" />
+ </then>
+ </stateChange>
+ </eventHandler>
+ <!-- case 12 : sched_wakeup : case 13 : sched_wakeup_new : Fields (same
+ fields for both types): string comm, int32 tid, int32 prio, int32 success,
+ int32 target_cpu -->
+ <eventHandler eventName="sched_wakeup*">
+ <stateChange>
+ <if>
+ <and>
+ <not>
+ <condition>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_RUN_USERMODE" />
+ </condition>
+ </not>
+ <not>
+ <condition>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
+ </condition>
+ </not>
+ </and>
+ </if>
+ <then>
+ <stateAttribute type="constant" value="Threads" />
+ <stateAttribute type="eventField" value="tid" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_WAIT_FOR_CPU" />
+ </then>
+ </stateChange>
+ </eventHandler>
+ <!-- delfault : syscall -->
+ <eventHandler eventName="sys_*">
+ <stateChange>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="eventName" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_RUN_SYSCALL" />
+ </stateChange>
+ </eventHandler>
+ <!-- delfault : compat_syscall -->
+ <eventHandler eventName="compat_sys_*">
+ <stateChange>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="System_call" />
+ <stateValue type="eventName" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="CurrentThread" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$PROCESS_STATUS_RUN_SYSCALL" />
+ </stateChange>
+ <stateChange>
+ <stateAttribute type="location" value="CurrentCPU" />
+ <stateAttribute type="constant" value="Status" />
+ <stateValue type="int" value="$CPU_STATUS_RUN_SYSCALL" />
+ </stateChange>
+ </eventHandler>
+ </stateProvider>
</tmfxml> \ No newline at end of file
diff --git a/lttng/org.eclipse.linuxtools.tmf.analysis.xml.ui.tests/test_xml_files/test_builtin.xml b/lttng/org.eclipse.linuxtools.tmf.analysis.xml.ui.tests/test_xml_files/test_builtin.xml
index 205149380e..3e7a1e8715 100644
--- a/lttng/org.eclipse.linuxtools.tmf.analysis.xml.ui.tests/test_xml_files/test_builtin.xml
+++ b/lttng/org.eclipse.linuxtools.tmf.analysis.xml.ui.tests/test_xml_files/test_builtin.xml
@@ -8,21 +8,21 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
-* Geneviève Bastien - Initial API and implementation
+* Geneviève Bastien - Initial API and implementation
*************************************************************************** -->
<tmfxml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="xmldefinition.xsd">
+ xsi:noNamespaceSchemaLocation="xmldefinition.xsd">
- <stateProvider id="test.builtin.sp" version="1">
- <head>
- <label value="Test a builtin XML module file" />
- </head>
+ <stateProvider id="test.builtin.sp" version="1">
+ <head>
+ <label value="Test a builtin XML module file" />
+ </head>
- <eventHandler eventName="test">
- <stateChange>
- <stateAttribute type="constant" value="cpu" />
- <stateValue type="eventField" value="cpu" />
- </stateChange>
- </eventHandler>
- </stateProvider>
+ <eventHandler eventName="test">
+ <stateChange>
+ <stateAttribute type="constant" value="cpu" />
+ <stateValue type="eventField" value="cpu" />
+ </stateChange>
+ </eventHandler>
+ </stateProvider>
</tmfxml> \ No newline at end of file
diff --git a/lttng/org.eclipse.linuxtools.tmf.core.tests/src/org/eclipse/linuxtools/tmf/core/tests/TmfCoreTestPlugin.java b/lttng/org.eclipse.linuxtools.tmf.core.tests/src/org/eclipse/linuxtools/tmf/core/tests/TmfCoreTestPlugin.java
index b1b3710e42..4d6ec364fb 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core.tests/src/org/eclipse/linuxtools/tmf/core/tests/TmfCoreTestPlugin.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core.tests/src/org/eclipse/linuxtools/tmf/core/tests/TmfCoreTestPlugin.java
@@ -27,27 +27,27 @@ public class TmfCoreTestPlugin extends Plugin {
// Attributes
// ------------------------------------------------------------------------
- // The plug-in ID
- @SuppressWarnings("javadoc")
+ // The plug-in ID
+ @SuppressWarnings("javadoc")
public static final String PLUGIN_ID = "org.eclipse.linuxtools.tmf.tests";
- // The shared instance
- private static TmfCoreTestPlugin fPlugin;
+ // The shared instance
+ private static TmfCoreTestPlugin fPlugin;
// ------------------------------------------------------------------------
// Constructors
// ------------------------------------------------------------------------
- /**
- * The constructor
- */
- public TmfCoreTestPlugin() {
- setDefault(this);
- }
+ /**
+ * The constructor
+ */
+ public TmfCoreTestPlugin() {
+ setDefault(this);
+ }
- // ------------------------------------------------------------------------
+ // ------------------------------------------------------------------------
// Accessors
- // ------------------------------------------------------------------------
+ // ------------------------------------------------------------------------
/**
* @return the shared instance
@@ -56,29 +56,29 @@ public class TmfCoreTestPlugin extends Plugin {
return fPlugin;
}
- /**
- * @param plugin the shared instance
- */
- private static void setDefault(TmfCoreTestPlugin plugin) {
- fPlugin = plugin;
- }
+ /**
+ * @param plugin the shared instance
+ */
+ private static void setDefault(TmfCoreTestPlugin plugin) {
+ fPlugin = plugin;
+ }
- // ------------------------------------------------------------------------
+ // ------------------------------------------------------------------------
// Operations
- // ------------------------------------------------------------------------
+ // ------------------------------------------------------------------------
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- setDefault(this);
- TmfCoreTracer.init();
- }
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ setDefault(this);
+ TmfCoreTracer.init();
+ }
- @Override
- public void stop(BundleContext context) throws Exception {
- TmfCoreTracer.stop();
- setDefault(null);
- super.stop(context);
- }
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ TmfCoreTracer.stop();
+ setDefault(null);
+ super.stop(context);
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core.tests/src/org/eclipse/linuxtools/tmf/core/tests/component/TmfEventProviderTest.java b/lttng/org.eclipse.linuxtools.tmf.core.tests/src/org/eclipse/linuxtools/tmf/core/tests/component/TmfEventProviderTest.java
index 343fb88410..703888dfb4 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core.tests/src/org/eclipse/linuxtools/tmf/core/tests/component/TmfEventProviderTest.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core.tests/src/org/eclipse/linuxtools/tmf/core/tests/component/TmfEventProviderTest.java
@@ -223,13 +223,13 @@ public class TmfEventProviderTest {
request1.waitForStart();
request2.waitForStart();
-// // Verify that the requests are running
-// assertTrue("isRunning", request1.isRunning());
-// assertTrue("isRunning", request2.isRunning());
+// // Verify that the requests are running
+// assertTrue("isRunning", request1.isRunning());
+// assertTrue("isRunning", request2.isRunning());
request1.waitForCompletion();
-// // Check if request2 is still running
+// // Check if request2 is still running
// assertTrue("isRunning", request2.isRunning());
// Verify result (request1)
diff --git a/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/CreateTestFiles.java b/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/CreateTestFiles.java
index 2400dc5940..4ce1eb5db0 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/CreateTestFiles.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/CreateTestFiles.java
@@ -39,7 +39,7 @@ public class CreateTestFiles {
// ========================================================================
private static final String DIRECTORY = "testfiles";
- // private static final String FILE_NAMES[] = { "Test-10", "Test-1K", "Test-10K", "Test-100K" };
+ // private static final String FILE_NAMES[] = { "Test-10", "Test-1K", "Test-10K", "Test-100K" };
// private static final int FILE_SIZES[] = { 10 , 1000 , 10000 , 100000 };
private static final String FILE_NAMES[] = { "Test-10K" };
private static final int FILE_SIZES[] = { 10000 };
diff --git a/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/component/TmfClientStub.java b/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/component/TmfClientStub.java
index 6aac5a682f..d75fb51430 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/component/TmfClientStub.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/component/TmfClientStub.java
@@ -33,12 +33,12 @@ public class TmfClientStub extends TmfComponent {
public void findProvider() {
fProviders = TmfProviderManager.getProviders(TmfSyntheticEventStub.class, TmfSyntheticEventProviderStub.class);
- // TmfEventRequest<TmfEventStub> request;
+ // TmfEventRequest<TmfEventStub> request;
System.out.println(fProviders.length);
}
public void triggeRequest() {
- // TmfEventRequest<TmfEventStub> request;
+ // TmfEventRequest<TmfEventStub> request;
}
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/trace/TmfEventParserStub.java b/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/trace/TmfEventParserStub.java
index ccac578b56..86def21e4f 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/trace/TmfEventParserStub.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core.tests/stubs/org/eclipse/linuxtools/tmf/tests/stubs/trace/TmfEventParserStub.java
@@ -80,8 +80,8 @@ public class TmfEventParserStub implements ITmfEventParser {
return null;
}
- // String name = eventStream.getName();
- // name = name.substring(name.lastIndexOf('/') + 1);
+ // String name = eventStream.getName();
+ // name = name.substring(name.lastIndexOf('/') + 1);
// no need to use synchronized since it's already cover by the calling method
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/internal/tmf/core/trace/TmfExperimentCheckpoint.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/internal/tmf/core/trace/TmfExperimentCheckpoint.java
index e38f15c6f0..faa88d1e47 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/internal/tmf/core/trace/TmfExperimentCheckpoint.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/internal/tmf/core/trace/TmfExperimentCheckpoint.java
@@ -69,27 +69,27 @@ public class TmfExperimentCheckpoint implements Comparable<TmfExperimentCheckpoi
@Override
public int hashCode() {
- int result = 37;
- result = 17 * result + fTimestamp.hashCode();
- return result;
+ int result = 37;
+ result = 17 * result + fTimestamp.hashCode();
+ return result;
}
@Override
public boolean equals(final Object other) {
- if (!(other instanceof TmfExperimentCheckpoint)) {
- return false;
- }
- final TmfExperimentCheckpoint o = (TmfExperimentCheckpoint) other;
- return fTimestamp.equals(o.fTimestamp);
+ if (!(other instanceof TmfExperimentCheckpoint)) {
+ return false;
+ }
+ final TmfExperimentCheckpoint o = (TmfExperimentCheckpoint) other;
+ return fTimestamp.equals(o.fTimestamp);
}
// ------------------------------------------------------------------------
// Comparable
// ------------------------------------------------------------------------
- @Override
- public int compareTo(final TmfExperimentCheckpoint other) {
- return fTimestamp.compareTo(other.fTimestamp, false);
- }
+ @Override
+ public int compareTo(final TmfExperimentCheckpoint other) {
+ return fTimestamp.compareTo(other.fTimestamp, false);
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/exceptions/TmfTraceException.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/exceptions/TmfTraceException.java
index 708b128d15..90e5a8fc82 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/exceptions/TmfTraceException.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/exceptions/TmfTraceException.java
@@ -1,11 +1,11 @@
/*******************************************************************************
* Copyright (c) 2012 Ericsson
- *
+ *
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Francois Chouinard - Initial API and implementation
*******************************************************************************/
@@ -14,7 +14,7 @@ package org.eclipse.linuxtools.tmf.core.exceptions;
/**
* TMF trace related exception
- *
+ *
* @version 1.0
* @author Francois Chouinard
*/
@@ -27,7 +27,7 @@ public class TmfTraceException extends Exception {
/**
* Constructor
- *
+ *
* @param errMsg the error message
*/
public TmfTraceException(String errMsg) {
@@ -35,10 +35,10 @@ public class TmfTraceException extends Exception {
}
/**
- * Constructor
- *
+ * Constructor
+ *
* @param errMsg the error message
- * @param cause the error cause (<code>null</code> is permitted which means no cause is available)
+ * @param cause the error cause (<code>null</code> is permitted which means no cause is available)
*/
public TmfTraceException(String errMsg, Throwable cause) {
super(errMsg, cause);
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/ITmfFilterTreeNode.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/ITmfFilterTreeNode.java
index 40672e4eac..174f970a20 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/ITmfFilterTreeNode.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/ITmfFilterTreeNode.java
@@ -23,105 +23,105 @@ import org.eclipse.linuxtools.tmf.core.filter.ITmfFilter;
*/
public interface ITmfFilterTreeNode extends ITmfFilter {
- /**
- * <h4>Get the parent node of current node</h4>
- *
- * @return The parent node (null when the node has no parent).
- */
- public ITmfFilterTreeNode getParent();
-
- /**
- * <h4>Get the current node name</h4>
- *
- * @return The name of the current node.
- */
- public String getNodeName();
-
- /**
- * <h4>Tell if the node has children</h4>
- *
- * @return True if the node has children.
- */
- public boolean hasChildren();
-
- /**
- * <h4>Return the number of children</h4>
- *
- * @return The number of children.
- */
- public int getChildrenCount();
-
- /**
- * <h4>Get the array of children</h4>
- *
- * @return The array (possibly empty) of children nodes.
- */
- public ITmfFilterTreeNode[] getChildren();
-
- /**
- * <h4>Get the node by index</h4>
- *
- * @param index The index of node to return.
- * @return The desired node (null if the node is not exists).
- */
- public ITmfFilterTreeNode getChild(int index);
-
- /**
- * <h4>Remove the node from its parent</h4>
- *
- * <p>Shifts all nodes after the removed one to prevent having an empty spot.
- * See {@link #replaceChild(int, ITmfFilterTreeNode)} to replace a node.</p>
- *
- * @return The removed node.
- */
- public ITmfFilterTreeNode remove();
-
- /**
- * <h4>Remove the child from the current node</h4>
- *
- * <p>Shifts all nodes after the removed one to prevent having an empty spot.
- * See {@link #replaceChild(int, ITmfFilterTreeNode)} to replace a node.</p>
- *
- * @param node the parent node
- *
- * @return The removed node.
- */
- public ITmfFilterTreeNode removeChild(ITmfFilterTreeNode node);
-
- /**
- * <h4>Append a node to the current children</h4>
- *
- * @param node Node to append.
- * @return Index of added node (-1 if the node cannot be added).
- */
- public int addChild(ITmfFilterTreeNode node);
-
- /**
- * <h4>Replace a child node</h4>
- *
- * @param index Index of the node to replace.
- * @param node Node who will replace.
- * @return Node replaced.
- */
- public ITmfFilterTreeNode replaceChild(int index, ITmfFilterTreeNode node);
-
- /**
- * <h4>Sets the parent of current node</h4>
- *
- * @param parent The parent of current node.
- */
- public void setParent(ITmfFilterTreeNode parent);
-
- /**
- * <h4>Gets the list of valid children node names that could be added to the node</h4>
- *
- * @return The list of valid children node names.
- */
- public List<String> getValidChildren();
-
- /**
- * @return a clone of the node
- */
- public ITmfFilterTreeNode clone();
+ /**
+ * <h4>Get the parent node of current node</h4>
+ *
+ * @return The parent node (null when the node has no parent).
+ */
+ public ITmfFilterTreeNode getParent();
+
+ /**
+ * <h4>Get the current node name</h4>
+ *
+ * @return The name of the current node.
+ */
+ public String getNodeName();
+
+ /**
+ * <h4>Tell if the node has children</h4>
+ *
+ * @return True if the node has children.
+ */
+ public boolean hasChildren();
+
+ /**
+ * <h4>Return the number of children</h4>
+ *
+ * @return The number of children.
+ */
+ public int getChildrenCount();
+
+ /**
+ * <h4>Get the array of children</h4>
+ *
+ * @return The array (possibly empty) of children nodes.
+ */
+ public ITmfFilterTreeNode[] getChildren();
+
+ /**
+ * <h4>Get the node by index</h4>
+ *
+ * @param index The index of node to return.
+ * @return The desired node (null if the node is not exists).
+ */
+ public ITmfFilterTreeNode getChild(int index);
+
+ /**
+ * <h4>Remove the node from its parent</h4>
+ *
+ * <p>Shifts all nodes after the removed one to prevent having an empty spot.
+ * See {@link #replaceChild(int, ITmfFilterTreeNode)} to replace a node.</p>
+ *
+ * @return The removed node.
+ */
+ public ITmfFilterTreeNode remove();
+
+ /**
+ * <h4>Remove the child from the current node</h4>
+ *
+ * <p>Shifts all nodes after the removed one to prevent having an empty spot.
+ * See {@link #replaceChild(int, ITmfFilterTreeNode)} to replace a node.</p>
+ *
+ * @param node the parent node
+ *
+ * @return The removed node.
+ */
+ public ITmfFilterTreeNode removeChild(ITmfFilterTreeNode node);
+
+ /**
+ * <h4>Append a node to the current children</h4>
+ *
+ * @param node Node to append.
+ * @return Index of added node (-1 if the node cannot be added).
+ */
+ public int addChild(ITmfFilterTreeNode node);
+
+ /**
+ * <h4>Replace a child node</h4>
+ *
+ * @param index Index of the node to replace.
+ * @param node Node who will replace.
+ * @return Node replaced.
+ */
+ public ITmfFilterTreeNode replaceChild(int index, ITmfFilterTreeNode node);
+
+ /**
+ * <h4>Sets the parent of current node</h4>
+ *
+ * @param parent The parent of current node.
+ */
+ public void setParent(ITmfFilterTreeNode parent);
+
+ /**
+ * <h4>Gets the list of valid children node names that could be added to the node</h4>
+ *
+ * @return The list of valid children node names.
+ */
+ public List<String> getValidChildren();
+
+ /**
+ * @return a clone of the node
+ */
+ public ITmfFilterTreeNode clone();
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterAndNode.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterAndNode.java
index 8ad2d91cd3..2c054252dc 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterAndNode.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterAndNode.java
@@ -24,67 +24,67 @@ import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
@SuppressWarnings("javadoc")
public class TmfFilterAndNode extends TmfFilterTreeNode {
- public static final String NODE_NAME = "AND"; //$NON-NLS-1$
- public static final String NOT_ATTR = "not"; //$NON-NLS-1$
+ public static final String NODE_NAME = "AND"; //$NON-NLS-1$
+ public static final String NOT_ATTR = "not"; //$NON-NLS-1$
- private boolean fNot = false;
+ private boolean fNot = false;
- /**
- * @param parent the parent node
- */
- public TmfFilterAndNode(ITmfFilterTreeNode parent) {
- super(parent);
- }
+ /**
+ * @param parent the parent node
+ */
+ public TmfFilterAndNode(ITmfFilterTreeNode parent) {
+ super(parent);
+ }
- /**
- * @return the NOT state
- */
- public boolean isNot() {
- return fNot;
- }
+ /**
+ * @return the NOT state
+ */
+ public boolean isNot() {
+ return fNot;
+ }
- /**
- * @param not the NOT state
- */
- public void setNot(boolean not) {
- this.fNot = not;
- }
+ /**
+ * @param not the NOT state
+ */
+ public void setNot(boolean not) {
+ this.fNot = not;
+ }
- @Override
- public String getNodeName() {
- return NODE_NAME;
- }
+ @Override
+ public String getNodeName() {
+ return NODE_NAME;
+ }
- @Override
- public boolean matches(ITmfEvent event) {
- for (ITmfFilterTreeNode node : getChildren()) {
- if (! node.matches(event)) {
- return false ^ fNot;
- }
- }
- return true ^ fNot;
- }
+ @Override
+ public boolean matches(ITmfEvent event) {
+ for (ITmfFilterTreeNode node : getChildren()) {
+ if (! node.matches(event)) {
+ return false ^ fNot;
+ }
+ }
+ return true ^ fNot;
+ }
- @Override
- public String toString() {
- StringBuffer buf = new StringBuffer();
- if (fNot) {
- buf.append("not "); //$NON-NLS-1$
- }
- if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) {
- buf.append("( "); //$NON-NLS-1$
- }
- for (int i = 0; i < getChildrenCount(); i++) {
- ITmfFilterTreeNode node = getChildren()[i];
- buf.append(node.toString());
- if (i < getChildrenCount() - 1) {
- buf.append(" and "); //$NON-NLS-1$
- }
- }
- if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) {
- buf.append(" )"); //$NON-NLS-1$
- }
- return buf.toString();
- }
+ @Override
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ if (fNot) {
+ buf.append("not "); //$NON-NLS-1$
+ }
+ if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) {
+ buf.append("( "); //$NON-NLS-1$
+ }
+ for (int i = 0; i < getChildrenCount(); i++) {
+ ITmfFilterTreeNode node = getChildren()[i];
+ buf.append(node.toString());
+ if (i < getChildrenCount() - 1) {
+ buf.append(" and "); //$NON-NLS-1$
+ }
+ }
+ if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) {
+ buf.append(" )"); //$NON-NLS-1$
+ }
+ return buf.toString();
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java
index 48d033baf8..a452753ab4 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java
@@ -31,130 +31,130 @@ import org.eclipse.linuxtools.tmf.core.timestamp.TmfTimestamp;
public class TmfFilterCompareNode extends TmfFilterTreeNode {
public static final String NODE_NAME = "COMPARE"; //$NON-NLS-1$
- public static final String NOT_ATTR = "not"; //$NON-NLS-1$
- public static final String FIELD_ATTR = "field"; //$NON-NLS-1$
- public static final String RESULT_ATTR = "result"; //$NON-NLS-1$
- public static final String TYPE_ATTR = "type"; //$NON-NLS-1$
- public static final String VALUE_ATTR = "value"; //$NON-NLS-1$
-
- /**
- * Supported comparison types
- */
- public static enum Type {
- NUM,
- ALPHA,
- TIMESTAMP
- }
-
- private boolean fNot = false;
- private String fField;
- private int fResult;
- private Type fType = Type.NUM;
- private String fValue;
- private Number fValueNumber;
- private TmfTimestamp fValueTimestamp;
-
- /**
- * @param parent the parent node
- */
- public TmfFilterCompareNode(ITmfFilterTreeNode parent) {
- super(parent);
- }
-
- /**
- * @return the NOT state
- */
- public boolean isNot() {
- return fNot;
- }
+ public static final String NOT_ATTR = "not"; //$NON-NLS-1$
+ public static final String FIELD_ATTR = "field"; //$NON-NLS-1$
+ public static final String RESULT_ATTR = "result"; //$NON-NLS-1$
+ public static final String TYPE_ATTR = "type"; //$NON-NLS-1$
+ public static final String VALUE_ATTR = "value"; //$NON-NLS-1$
+
+ /**
+ * Supported comparison types
+ */
+ public static enum Type {
+ NUM,
+ ALPHA,
+ TIMESTAMP
+ }
+
+ private boolean fNot = false;
+ private String fField;
+ private int fResult;
+ private Type fType = Type.NUM;
+ private String fValue;
+ private Number fValueNumber;
+ private TmfTimestamp fValueTimestamp;
+
+ /**
+ * @param parent the parent node
+ */
+ public TmfFilterCompareNode(ITmfFilterTreeNode parent) {
+ super(parent);
+ }
+
+ /**
+ * @return the NOT state
+ */
+ public boolean isNot() {
+ return fNot;
+ }
/**
* @param not the NOT state
*/
- public void setNot(boolean not) {
- this.fNot = not;
- }
-
- /**
- * @return the field name
- */
- public String getField() {
- return fField;
- }
-
- /**
- * @param field the field name
- */
- public void setField(String field) {
- this.fField = field;
- }
-
- /**
- * @return the compare result
- */
- public int getResult() {
- return fResult;
- }
-
- /**
- * @param result the compare result
- */
- public void setResult(int result) {
- this.fResult = result;
- }
-
- /**
- * @return the comparison type
- */
- public Type getType() {
- return fType;
- }
-
- /**
- * @param type the comparison type
- */
- public void setType(Type type) {
- this.fType = type;
- setValue(fValue);
- }
-
- /**
- * @return the comparison value
- */
- public String getValue() {
- return fValue;
- }
-
- /**
- * @param value the comparison value
- */
- public void setValue(String value) {
- this.fValue = value;
- fValueNumber = null;
- fValueTimestamp = null;
- if (value == null) {
- return;
- }
- if (fType == Type.NUM) {
- try {
- fValueNumber = NumberFormat.getInstance().parse(value).doubleValue();
- } catch (ParseException e) {
- }
- } else if (fType == Type.TIMESTAMP) {
- try {
- fValueTimestamp = new TmfTimestamp((long) (1E9 * NumberFormat.getInstance().parse(value.toString()).doubleValue()));
- } catch (ParseException e) {
- }
- }
- }
-
- @Override
- public String getNodeName() {
- return NODE_NAME;
- }
-
- @Override
- public boolean matches(ITmfEvent event) {
+ public void setNot(boolean not) {
+ this.fNot = not;
+ }
+
+ /**
+ * @return the field name
+ */
+ public String getField() {
+ return fField;
+ }
+
+ /**
+ * @param field the field name
+ */
+ public void setField(String field) {
+ this.fField = field;
+ }
+
+ /**
+ * @return the compare result
+ */
+ public int getResult() {
+ return fResult;
+ }
+
+ /**
+ * @param result the compare result
+ */
+ public void setResult(int result) {
+ this.fResult = result;
+ }
+
+ /**
+ * @return the comparison type
+ */
+ public Type getType() {
+ return fType;
+ }
+
+ /**
+ * @param type the comparison type
+ */
+ public void setType(Type type) {
+ this.fType = type;
+ setValue(fValue);
+ }
+
+ /**
+ * @return the comparison value
+ */
+ public String getValue() {
+ return fValue;
+ }
+
+ /**
+ * @param value the comparison value
+ */
+ public void setValue(String value) {
+ this.fValue = value;
+ fValueNumber = null;
+ fValueTimestamp = null;
+ if (value == null) {
+ return;
+ }
+ if (fType == Type.NUM) {
+ try {
+ fValueNumber = NumberFormat.getInstance().parse(value).doubleValue();
+ } catch (ParseException e) {
+ }
+ } else if (fType == Type.TIMESTAMP) {
+ try {
+ fValueTimestamp = new TmfTimestamp((long) (1E9 * NumberFormat.getInstance().parse(value.toString()).doubleValue()));
+ } catch (ParseException e) {
+ }
+ }
+ }
+
+ @Override
+ public String getNodeName() {
+ return NODE_NAME;
+ }
+
+ @Override
+ public boolean matches(ITmfEvent event) {
Object value = getFieldValue(event, fField);
if (value == null) {
return false ^ fNot;
@@ -195,26 +195,26 @@ public class TmfFilterCompareNode extends TmfFilterTreeNode {
}
}
return false ^ fNot;
- }
-
- @Override
- public List<String> getValidChildren() {
- return new ArrayList<>(0);
- }
-
- @Override
- public String toString() {
- String result = (fResult == 0 ? "= " : fResult < 0 ? "< " : "> "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- String open = (fType == Type.NUM ? "" : fType == Type.ALPHA ? "\"" : "["); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- String close = (fType == Type.NUM ? "" : fType == Type.ALPHA ? "\"" : "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- return fField + (fNot ? " not " : " ") + result + open + fValue + close; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Override
- public ITmfFilterTreeNode clone() {
- TmfFilterCompareNode clone = (TmfFilterCompareNode) super.clone();
- clone.fField = fField;
- clone.setValue(fValue);
- return clone;
- }
+ }
+
+ @Override
+ public List<String> getValidChildren() {
+ return new ArrayList<>(0);
+ }
+
+ @Override
+ public String toString() {
+ String result = (fResult == 0 ? "= " : fResult < 0 ? "< " : "> "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ String open = (fType == Type.NUM ? "" : fType == Type.ALPHA ? "\"" : "["); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ String close = (fType == Type.NUM ? "" : fType == Type.ALPHA ? "\"" : "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ return fField + (fNot ? " not " : " ") + result + open + fValue + close; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Override
+ public ITmfFilterTreeNode clone() {
+ TmfFilterCompareNode clone = (TmfFilterCompareNode) super.clone();
+ clone.fField = fField;
+ clone.setValue(fValue);
+ return clone;
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterContainsNode.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterContainsNode.java
index d02aa99563..ee91c7d0ef 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterContainsNode.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterContainsNode.java
@@ -26,91 +26,91 @@ import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
@SuppressWarnings("javadoc")
public class TmfFilterContainsNode extends TmfFilterTreeNode {
- public static final String NODE_NAME = "CONTAINS"; //$NON-NLS-1$
+ public static final String NODE_NAME = "CONTAINS"; //$NON-NLS-1$
public static final String NOT_ATTR = "not"; //$NON-NLS-1$
- public static final String FIELD_ATTR = "field"; //$NON-NLS-1$
- public static final String VALUE_ATTR = "value"; //$NON-NLS-1$
- public static final String IGNORECASE_ATTR = "ignorecase"; //$NON-NLS-1$
-
- private boolean fNot = false;
- private String fField;
- private String fValue;
- private String fValueUpperCase;
- private boolean fIgnoreCase = false;
-
- /**
- * @param parent the parent node
- */
- public TmfFilterContainsNode(ITmfFilterTreeNode parent) {
- super(parent);
- }
-
- /**
- * @return the NOT state
- */
- public boolean isNot() {
- return fNot;
- }
-
- /**
- * @param not the NOT state
- */
- public void setNot(boolean not) {
- this.fNot = not;
- }
-
- /**
- * @return the field name
- */
- public String getField() {
- return fField;
- }
-
- /**
- * @param field the field name
- */
- public void setField(String field) {
- this.fField = field;
- }
-
- /**
- * @return the contains value
- */
- public String getValue() {
- return fValue;
- }
-
- /**
- * @param value the contains value
- */
- public void setValue(String value) {
- this.fValue = value;
- if (value != null) {
- fValueUpperCase = value.toUpperCase();
- }
- }
-
- /**
- * @return the ignoreCase state
- */
- public boolean isIgnoreCase() {
- return fIgnoreCase;
- }
-
- /**
- * @param ignoreCase the ignoreCase state
- */
- public void setIgnoreCase(boolean ignoreCase) {
- this.fIgnoreCase = ignoreCase;
- }
-
- @Override
- public String getNodeName() {
- return NODE_NAME;
- }
-
- @Override
- public boolean matches(ITmfEvent event) {
+ public static final String FIELD_ATTR = "field"; //$NON-NLS-1$
+ public static final String VALUE_ATTR = "value"; //$NON-NLS-1$
+ public static final String IGNORECASE_ATTR = "ignorecase"; //$NON-NLS-1$
+
+ private boolean fNot = false;
+ private String fField;
+ private String fValue;
+ private String fValueUpperCase;
+ private boolean fIgnoreCase = false;
+
+ /**
+ * @param parent the parent node
+ */
+ public TmfFilterContainsNode(ITmfFilterTreeNode parent) {
+ super(parent);
+ }
+
+ /**
+ * @return the NOT state
+ */
+ public boolean isNot() {
+ return fNot;
+ }
+
+ /**
+ * @param not the NOT state
+ */
+ public void setNot(boolean not) {
+ this.fNot = not;
+ }
+
+ /**
+ * @return the field name
+ */
+ public String getField() {
+ return fField;
+ }
+
+ /**
+ * @param field the field name
+ */
+ public void setField(String field) {
+ this.fField = field;
+ }
+
+ /**
+ * @return the contains value
+ */
+ public String getValue() {
+ return fValue;
+ }
+
+ /**
+ * @param value the contains value
+ */
+ public void setValue(String value) {
+ this.fValue = value;
+ if (value != null) {
+ fValueUpperCase = value.toUpperCase();
+ }
+ }
+
+ /**
+ * @return the ignoreCase state
+ */
+ public boolean isIgnoreCase() {
+ return fIgnoreCase;
+ }
+
+ /**
+ * @param ignoreCase the ignoreCase state
+ */
+ public void setIgnoreCase(boolean ignoreCase) {
+ this.fIgnoreCase = ignoreCase;
+ }
+
+ @Override
+ public String getNodeName() {
+ return NODE_NAME;
+ }
+
+ @Override
+ public boolean matches(ITmfEvent event) {
Object value = getFieldValue(event, fField);
if (value == null) {
return false ^ fNot;
@@ -120,23 +120,23 @@ public class TmfFilterContainsNode extends TmfFilterTreeNode {
return valueString.toUpperCase().contains(fValueUpperCase) ^ fNot;
}
return valueString.contains(fValue) ^ fNot;
- }
-
- @Override
- public List<String> getValidChildren() {
- return new ArrayList<>(0);
- }
-
- @Override
- public String toString() {
- return fField + (fNot ? " not" : "") + " contains \"" + fValue + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Override
- public ITmfFilterTreeNode clone() {
- TmfFilterContainsNode clone = (TmfFilterContainsNode) super.clone();
- clone.fField = fField;
- clone.setValue(fValue);
- return clone;
- }
+ }
+
+ @Override
+ public List<String> getValidChildren() {
+ return new ArrayList<>(0);
+ }
+
+ @Override
+ public String toString() {
+ return fField + (fNot ? " not" : "") + " contains \"" + fValue + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Override
+ public ITmfFilterTreeNode clone() {
+ TmfFilterContainsNode clone = (TmfFilterContainsNode) super.clone();
+ clone.fField = fField;
+ clone.setValue(fValue);
+ return clone;
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEqualsNode.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEqualsNode.java
index 472fd953eb..d7183765c5 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEqualsNode.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEqualsNode.java
@@ -28,86 +28,86 @@ import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
public class TmfFilterEqualsNode extends TmfFilterTreeNode {
public static final String NODE_NAME = "EQUALS"; //$NON-NLS-1$
- public static final String NOT_ATTR = "not"; //$NON-NLS-1$
- public static final String FIELD_ATTR = "field"; //$NON-NLS-1$
- public static final String VALUE_ATTR = "value"; //$NON-NLS-1$
- public static final String IGNORECASE_ATTR = "ignorecase"; //$NON-NLS-1$
-
- private boolean fNot = false;
- private String fField;
- private String fValue;
- private boolean fIgnoreCase = false;
-
- /**
- * @param parent the aprent node
- */
- public TmfFilterEqualsNode(ITmfFilterTreeNode parent) {
- super(parent);
- }
-
- /**
- * @return the NOT state
- */
- public boolean isNot() {
- return fNot;
- }
-
- /**
- * @param not the NOT state
- */
- public void setNot(boolean not) {
- this.fNot = not;
- }
+ public static final String NOT_ATTR = "not"; //$NON-NLS-1$
+ public static final String FIELD_ATTR = "field"; //$NON-NLS-1$
+ public static final String VALUE_ATTR = "value"; //$NON-NLS-1$
+ public static final String IGNORECASE_ATTR = "ignorecase"; //$NON-NLS-1$
+
+ private boolean fNot = false;
+ private String fField;
+ private String fValue;
+ private boolean fIgnoreCase = false;
+
+ /**
+ * @param parent the aprent node
+ */
+ public TmfFilterEqualsNode(ITmfFilterTreeNode parent) {
+ super(parent);
+ }
+
+ /**
+ * @return the NOT state
+ */
+ public boolean isNot() {
+ return fNot;
+ }
+
+ /**
+ * @param not the NOT state
+ */
+ public void setNot(boolean not) {
+ this.fNot = not;
+ }
/**
* @return the field name
*/
- public String getField() {
- return fField;
- }
-
- /**
- * @param field the field name
- */
- public void setField(String field) {
- this.fField = field;
- }
-
- /**
- * @return the equals value
- */
- public String getValue() {
- return fValue;
- }
-
- /**
- * @param value the equals value
- */
- public void setValue(String value) {
- this.fValue = value;
- }
-
- /**
- * @return the ignoreCase state
- */
- public boolean isIgnoreCase() {
- return fIgnoreCase;
- }
-
- /**
- * @param ignoreCase the ignoreCase state
- */
- public void setIgnoreCase(boolean ignoreCase) {
- this.fIgnoreCase = ignoreCase;
- }
-
- @Override
- public String getNodeName() {
- return NODE_NAME;
- }
-
- @Override
- public boolean matches(ITmfEvent event) {
+ public String getField() {
+ return fField;
+ }
+
+ /**
+ * @param field the field name
+ */
+ public void setField(String field) {
+ this.fField = field;
+ }
+
+ /**
+ * @return the equals value
+ */
+ public String getValue() {
+ return fValue;
+ }
+
+ /**
+ * @param value the equals value
+ */
+ public void setValue(String value) {
+ this.fValue = value;
+ }
+
+ /**
+ * @return the ignoreCase state
+ */
+ public boolean isIgnoreCase() {
+ return fIgnoreCase;
+ }
+
+ /**
+ * @param ignoreCase the ignoreCase state
+ */
+ public void setIgnoreCase(boolean ignoreCase) {
+ this.fIgnoreCase = ignoreCase;
+ }
+
+ @Override
+ public String getNodeName() {
+ return NODE_NAME;
+ }
+
+ @Override
+ public boolean matches(ITmfEvent event) {
Object value = getFieldValue(event, fField);
if (value == null) {
return false ^ fNot;
@@ -120,23 +120,23 @@ public class TmfFilterEqualsNode extends TmfFilterTreeNode {
return valueString.equalsIgnoreCase(fValue) ^ fNot;
}
return valueString.equals(fValue) ^ fNot;
- }
-
- @Override
- public List<String> getValidChildren() {
- return new ArrayList<>(0);
- }
-
- @Override
- public String toString() {
- return fField + (fNot ? " not" : "") + " equals \"" + fValue + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Override
- public ITmfFilterTreeNode clone() {
- TmfFilterEqualsNode clone = (TmfFilterEqualsNode) super.clone();
- clone.fField = fField;
- clone.fValue = fValue;
- return clone;
- }
+ }
+
+ @Override
+ public List<String> getValidChildren() {
+ return new ArrayList<>(0);
+ }
+
+ @Override
+ public String toString() {
+ return fField + (fNot ? " not" : "") + " equals \"" + fValue + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Override
+ public ITmfFilterTreeNode clone() {
+ TmfFilterEqualsNode clone = (TmfFilterEqualsNode) super.clone();
+ clone.fField = fField;
+ clone.fValue = fValue;
+ return clone;
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEventTypeNode.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEventTypeNode.java
index 4da5bd32c3..28f7ef9f4c 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEventTypeNode.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterEventTypeNode.java
@@ -27,51 +27,51 @@ import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
public class TmfFilterEventTypeNode extends TmfFilterTreeNode {
public static final String NODE_NAME = "EVENTTYPE"; //$NON-NLS-1$
- public static final String TYPE_ATTR = "type"; //$NON-NLS-1$
- public static final String NAME_ATTR = "name"; //$NON-NLS-1$
+ public static final String TYPE_ATTR = "type"; //$NON-NLS-1$
+ public static final String NAME_ATTR = "name"; //$NON-NLS-1$
- private String fType;
- private String fName;
+ private String fType;
+ private String fName;
- /**
- * @param parent the parent node
- */
- public TmfFilterEventTypeNode(ITmfFilterTreeNode parent) {
- super(parent);
- }
+ /**
+ * @param parent the parent node
+ */
+ public TmfFilterEventTypeNode(ITmfFilterTreeNode parent) {
+ super(parent);
+ }
- @Override
- public String getNodeName() {
- return NODE_NAME;
- }
+ @Override
+ public String getNodeName() {
+ return NODE_NAME;
+ }
- /**
- * @return the event type
- */
- public String getEventType() {
- return fType;
- }
+ /**
+ * @return the event type
+ */
+ public String getEventType() {
+ return fType;
+ }
- /**
- * @param type the event type
- */
- public void setEventType(String type) {
- this.fType = type;
- }
+ /**
+ * @param type the event type
+ */
+ public void setEventType(String type) {
+ this.fType = type;
+ }
- /**
- * @return TBD
- */
- public String getName() {
- return fName;
- }
+ /**
+ * @return TBD
+ */
+ public String getName() {
+ return fName;
+ }
- /**
- * @param name TBD
- */
- public void setName(String name) {
- this.fName = name;
- }
+ /**
+ * @param name TBD
+ */
+ public void setName(String name) {
+ this.fName = name;
+ }
@Override
public boolean matches(ITmfEvent event) {
@@ -100,34 +100,34 @@ public class TmfFilterEventTypeNode extends TmfFilterTreeNode {
return false;
}
- @Override
- public List<String> getValidChildren() {
- if (getChildrenCount() == 0) {
- return super.getValidChildren();
- }
+ @Override
+ public List<String> getValidChildren() {
+ if (getChildrenCount() == 0) {
+ return super.getValidChildren();
+ }
return new ArrayList<>(0); // only one child allowed
- }
+ }
- @Override
- public String toString() {
- StringBuffer buf = new StringBuffer();
- buf.append("EventType is " + fName); //$NON-NLS-1$
- if (getChildrenCount() > 0) {
- buf.append(" and "); //$NON-NLS-1$
- }
- if (getChildrenCount() > 1) {
- buf.append("( "); //$NON-NLS-1$
- }
- for (int i = 0; i < getChildrenCount(); i++) {
- ITmfFilterTreeNode node = getChildren()[i];
- buf.append(node.toString());
- if (i < getChildrenCount() - 1) {
- buf.append(" and "); //$NON-NLS-1$
- }
- }
- if (getChildrenCount() > 1) {
- buf.append(" )"); //$NON-NLS-1$
- }
- return buf.toString();
- }
+ @Override
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("EventType is " + fName); //$NON-NLS-1$
+ if (getChildrenCount() > 0) {
+ buf.append(" and "); //$NON-NLS-1$
+ }
+ if (getChildrenCount() > 1) {
+ buf.append("( "); //$NON-NLS-1$
+ }
+ for (int i = 0; i < getChildrenCount(); i++) {
+ ITmfFilterTreeNode node = getChildren()[i];
+ buf.append(node.toString());
+ if (i < getChildrenCount() - 1) {
+ buf.append(" and "); //$NON-NLS-1$
+ }
+ }
+ if (getChildrenCount() > 1) {
+ buf.append(" )"); //$NON-NLS-1$
+ }
+ return buf.toString();
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterNode.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterNode.java
index 77cecb0766..fa20c0dd1a 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterNode.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterNode.java
@@ -27,81 +27,81 @@ import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
public class TmfFilterNode extends TmfFilterTreeNode {
public static final String NODE_NAME = "FILTER"; //$NON-NLS-1$
- public static final String NAME_ATTR = "name"; //$NON-NLS-1$
+ public static final String NAME_ATTR = "name"; //$NON-NLS-1$
- String fFilterName;
+ String fFilterName;
- /**
- * @param filterName the filter name
- */
- public TmfFilterNode(String filterName) {
- super(null);
- fFilterName = filterName;
- }
+ /**
+ * @param filterName the filter name
+ */
+ public TmfFilterNode(String filterName) {
+ super(null);
+ fFilterName = filterName;
+ }
- /**
- * @param parent the parent node
+ /**
+ * @param parent the parent node
* @param filterName the filter name
- */
- public TmfFilterNode(ITmfFilterTreeNode parent, String filterName) {
- super(parent);
- fFilterName = filterName;
- }
+ */
+ public TmfFilterNode(ITmfFilterTreeNode parent, String filterName) {
+ super(parent);
+ fFilterName = filterName;
+ }
- /**
- * @return the filer name
- */
- public String getFilterName() {
- return fFilterName;
- }
+ /**
+ * @return the filer name
+ */
+ public String getFilterName() {
+ return fFilterName;
+ }
- /**
- * @param filterName the filer name
- */
- public void setFilterName(String filterName) {
- fFilterName = filterName;
- }
+ /**
+ * @param filterName the filer name
+ */
+ public void setFilterName(String filterName) {
+ fFilterName = filterName;
+ }
- @Override
- public String getNodeName() {
- return NODE_NAME;
- }
+ @Override
+ public String getNodeName() {
+ return NODE_NAME;
+ }
- @Override
- public boolean matches(ITmfEvent event) {
- // There should be at most one child
- for (ITmfFilterTreeNode node : getChildren()) {
- if (node.matches(event)) {
- return true;
- }
- }
- return false;
- }
+ @Override
+ public boolean matches(ITmfEvent event) {
+ // There should be at most one child
+ for (ITmfFilterTreeNode node : getChildren()) {
+ if (node.matches(event)) {
+ return true;
+ }
+ }
+ return false;
+ }
- @Override
- public List<String> getValidChildren() {
- if (getChildrenCount() == 0) {
- return super.getValidChildren();
- }
+ @Override
+ public List<String> getValidChildren() {
+ if (getChildrenCount() == 0) {
+ return super.getValidChildren();
+ }
return new ArrayList<>(0); // only one child allowed
- }
+ }
- @Override
- public String toString() {
- StringBuffer buf = new StringBuffer();
- if (getChildrenCount() > 1) {
- buf.append("( "); //$NON-NLS-1$
- }
- for (int i = 0; i < getChildrenCount(); i++) {
- ITmfFilterTreeNode node = getChildren()[i];
- buf.append(node.toString());
- if (i < (getChildrenCount() - 1)) {
- buf.append(" and "); //$NON-NLS-1$
- }
- }
- if (getChildrenCount() > 1) {
- buf.append(" )"); //$NON-NLS-1$
- }
- return buf.toString();
- }
+ @Override
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ if (getChildrenCount() > 1) {
+ buf.append("( "); //$NON-NLS-1$
+ }
+ for (int i = 0; i < getChildrenCount(); i++) {
+ ITmfFilterTreeNode node = getChildren()[i];
+ buf.append(node.toString());
+ if (i < (getChildrenCount() - 1)) {
+ buf.append(" and "); //$NON-NLS-1$
+ }
+ }
+ if (getChildrenCount() > 1) {
+ buf.append(" )"); //$NON-NLS-1$
+ }
+ return buf.toString();
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterOrNode.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterOrNode.java
index 8479f38c1b..30bbcdfba1 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterOrNode.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterOrNode.java
@@ -24,65 +24,65 @@ import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
public class TmfFilterOrNode extends TmfFilterTreeNode {
public static final String NODE_NAME = "OR"; //$NON-NLS-1$
- public static final String NOT_ATTR = "not"; //$NON-NLS-1$
+ public static final String NOT_ATTR = "not"; //$NON-NLS-1$
- private boolean fNot = false;
+ private boolean fNot = false;
- /**
- * @param parent the parent node
- */
- public TmfFilterOrNode(ITmfFilterTreeNode parent) {
- super(parent);
- }
+ /**
+ * @param parent the parent node
+ */
+ public TmfFilterOrNode(ITmfFilterTreeNode parent) {
+ super(parent);
+ }
- @Override
- public String getNodeName() {
- return NODE_NAME;
- }
+ @Override
+ public String getNodeName() {
+ return NODE_NAME;
+ }
- /**
- * @return the NOT state
- */
- public boolean isNot() {
- return fNot;
- }
+ /**
+ * @return the NOT state
+ */
+ public boolean isNot() {
+ return fNot;
+ }
- /**
- * @param not the NOT state
- */
- public void setNot(boolean not) {
- this.fNot = not;
- }
+ /**
+ * @param not the NOT state
+ */
+ public void setNot(boolean not) {
+ this.fNot = not;
+ }
- @Override
- public boolean matches(ITmfEvent event) {
- for (ITmfFilterTreeNode node : getChildren()) {
- if (node.matches(event)) {
- return true ^ fNot;
- }
- }
- return false & fNot;
- }
+ @Override
+ public boolean matches(ITmfEvent event) {
+ for (ITmfFilterTreeNode node : getChildren()) {
+ if (node.matches(event)) {
+ return true ^ fNot;
+ }
+ }
+ return false & fNot;
+ }
- @Override
- public String toString() {
- StringBuffer buf = new StringBuffer();
- if (fNot) {
- buf.append("not "); //$NON-NLS-1$
- }
- if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) {
- buf.append("( "); //$NON-NLS-1$
- }
- for (int i = 0; i < getChildrenCount(); i++) {
- ITmfFilterTreeNode node = getChildren()[i];
- buf.append(node.toString());
- if (i < getChildrenCount() - 1) {
- buf.append(" or "); //$NON-NLS-1$
- }
- }
- if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) {
- buf.append(" )"); //$NON-NLS-1$
- }
- return buf.toString();
- }
+ @Override
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ if (fNot) {
+ buf.append("not "); //$NON-NLS-1$
+ }
+ if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) {
+ buf.append("( "); //$NON-NLS-1$
+ }
+ for (int i = 0; i < getChildrenCount(); i++) {
+ ITmfFilterTreeNode node = getChildren()[i];
+ buf.append(node.toString());
+ if (i < getChildrenCount() - 1) {
+ buf.append(" or "); //$NON-NLS-1$
+ }
+ }
+ if (getParent() != null && !(getParent() instanceof TmfFilterRootNode) && !(getParent() instanceof TmfFilterNode)) {
+ buf.append(" )"); //$NON-NLS-1$
+ }
+ return buf.toString();
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterRootNode.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterRootNode.java
index bf610bcbc9..9c754604d8 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterRootNode.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterRootNode.java
@@ -25,38 +25,38 @@ import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
*/
public class TmfFilterRootNode extends TmfFilterTreeNode {
- @SuppressWarnings("javadoc")
+ @SuppressWarnings("javadoc")
public static final String NODE_NAME = "ROOT"; //$NON-NLS-1$
- private static final String[] VALID_CHILDREN = {
- TmfFilterNode.NODE_NAME
- };
-
- /**
- * Default constructor
- */
- public TmfFilterRootNode() {
- super(null);
- }
-
- @Override
- public String getNodeName() {
- return NODE_NAME;
- }
-
- @Override
- public boolean matches(ITmfEvent event) {
- for (ITmfFilterTreeNode node : getChildren()) {
- if (! node.matches(event)) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public List<String> getValidChildren() {
- return Arrays.asList(VALID_CHILDREN);
- }
+ private static final String[] VALID_CHILDREN = {
+ TmfFilterNode.NODE_NAME
+ };
+
+ /**
+ * Default constructor
+ */
+ public TmfFilterRootNode() {
+ super(null);
+ }
+
+ @Override
+ public String getNodeName() {
+ return NODE_NAME;
+ }
+
+ @Override
+ public boolean matches(ITmfEvent event) {
+ for (ITmfFilterTreeNode node : getChildren()) {
+ if (! node.matches(event)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public List<String> getValidChildren() {
+ return Arrays.asList(VALID_CHILDREN);
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterContentHandler.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterContentHandler.java
index cff55a609d..87f9576fb3 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterContentHandler.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterContentHandler.java
@@ -41,139 +41,139 @@ import org.xml.sax.helpers.DefaultHandler;
*/
public class TmfFilterContentHandler extends DefaultHandler {
- private ITmfFilterTreeNode fRoot = null;
- private Stack<ITmfFilterTreeNode> fFilterTreeStack = null;
-
- /**
- * The default constructor
- */
- public TmfFilterContentHandler() {
- super();
- fFilterTreeStack = new Stack<>();
- }
-
- /**
- * Getter of tree
- *
- * @return The builded tree
- */
- public ITmfFilterTreeNode getTree() {
- return fRoot;
- }
-
-
- @Override
- public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
- ITmfFilterTreeNode node = null;
-
- if (localName.equalsIgnoreCase(TmfFilterRootNode.NODE_NAME)) {
-
- node = new TmfFilterRootNode();
-
- } else if (localName.equals(TmfFilterNode.NODE_NAME)) {
-
- node = new TmfFilterNode(atts.getValue(TmfFilterNode.NAME_ATTR));
-
- } else if (localName.equals(TmfFilterEventTypeNode.NODE_NAME)) {
-
- node = new TmfFilterEventTypeNode(null);
- ((TmfFilterEventTypeNode) node).setEventType(atts.getValue(TmfFilterEventTypeNode.TYPE_ATTR));
- ((TmfFilterEventTypeNode) node).setName(atts.getValue(TmfFilterEventTypeNode.NAME_ATTR));
-
- } else if (localName.equals(TmfFilterAndNode.NODE_NAME)) {
-
- node = new TmfFilterAndNode(null);
- String value = atts.getValue(TmfFilterAndNode.NOT_ATTR);
- if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
- ((TmfFilterAndNode) node).setNot(true);
- }
-
- } else if (localName.equals(TmfFilterOrNode.NODE_NAME)) {
-
- node = new TmfFilterOrNode(null);
- String value = atts.getValue(TmfFilterOrNode.NOT_ATTR);
- if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
- ((TmfFilterOrNode) node).setNot(true);
- }
-
- } else if (localName.equals(TmfFilterContainsNode.NODE_NAME)) {
-
- node = new TmfFilterContainsNode(null);
- String value = atts.getValue(TmfFilterContainsNode.NOT_ATTR);
- if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
- ((TmfFilterContainsNode) node).setNot(true);
- }
- ((TmfFilterContainsNode) node).setField(atts.getValue(TmfFilterContainsNode.FIELD_ATTR));
- ((TmfFilterContainsNode) node).setValue(atts.getValue(TmfFilterContainsNode.VALUE_ATTR));
- value = atts.getValue(TmfFilterContainsNode.IGNORECASE_ATTR);
- if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
- ((TmfFilterContainsNode) node).setIgnoreCase(true);
- }
-
- } else if (localName.equals(TmfFilterEqualsNode.NODE_NAME)) {
-
- node = new TmfFilterEqualsNode(null);
- String value = atts.getValue(TmfFilterEqualsNode.NOT_ATTR);
- if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
- ((TmfFilterEqualsNode) node).setNot(true);
- }
- ((TmfFilterEqualsNode) node).setField(atts.getValue(TmfFilterEqualsNode.FIELD_ATTR));
- ((TmfFilterEqualsNode) node).setValue(atts.getValue(TmfFilterEqualsNode.VALUE_ATTR));
- value = atts.getValue(TmfFilterEqualsNode.IGNORECASE_ATTR);
- if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
- ((TmfFilterEqualsNode) node).setIgnoreCase(true);
- }
-
- } else if (localName.equals(TmfFilterMatchesNode.NODE_NAME)) {
-
- node = new TmfFilterMatchesNode(null);
- String value = atts.getValue(TmfFilterMatchesNode.NOT_ATTR);
- if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
- ((TmfFilterMatchesNode) node).setNot(true);
- }
- ((TmfFilterMatchesNode) node).setField(atts.getValue(TmfFilterMatchesNode.FIELD_ATTR));
- ((TmfFilterMatchesNode) node).setRegex(atts.getValue(TmfFilterMatchesNode.REGEX_ATTR));
-
- } else if (localName.equals(TmfFilterCompareNode.NODE_NAME)) {
-
- node = new TmfFilterCompareNode(null);
- String value = atts.getValue(TmfFilterCompareNode.NOT_ATTR);
- if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
- ((TmfFilterCompareNode) node).setNot(true);
- }
- ((TmfFilterCompareNode) node).setField(atts.getValue(TmfFilterCompareNode.FIELD_ATTR));
- value = atts.getValue(TmfFilterCompareNode.TYPE_ATTR);
- if (value != null) {
- ((TmfFilterCompareNode) node).setType(Type.valueOf(value));
- }
- value = atts.getValue(TmfFilterCompareNode.RESULT_ATTR);
- if (value != null) {
- if (value.equals(Integer.toString(-1))) {
- ((TmfFilterCompareNode) node).setResult(-1);
- } else if (value.equals(Integer.toString(1))) {
- ((TmfFilterCompareNode) node).setResult(1);
- } else {
- ((TmfFilterCompareNode) node).setResult(0);
- }
- }
- ((TmfFilterCompareNode) node).setValue(atts.getValue(TmfFilterCompareNode.VALUE_ATTR));
-
- }
-
- fFilterTreeStack.push(node);
- }
-
- @Override
- public void endElement(String uri, String localName, String qName) throws SAXException {
- ITmfFilterTreeNode node = fFilterTreeStack.pop();
-
- if (fFilterTreeStack.isEmpty()) {
- fRoot = node;
- } else if (fFilterTreeStack.lastElement() instanceof TmfFilterTreeNode &&
- node instanceof TmfFilterTreeNode) {
- fFilterTreeStack.lastElement().addChild(node);
- }
-
- }
+ private ITmfFilterTreeNode fRoot = null;
+ private Stack<ITmfFilterTreeNode> fFilterTreeStack = null;
+
+ /**
+ * The default constructor
+ */
+ public TmfFilterContentHandler() {
+ super();
+ fFilterTreeStack = new Stack<>();
+ }
+
+ /**
+ * Getter of tree
+ *
+ * @return The builded tree
+ */
+ public ITmfFilterTreeNode getTree() {
+ return fRoot;
+ }
+
+
+ @Override
+ public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
+ ITmfFilterTreeNode node = null;
+
+ if (localName.equalsIgnoreCase(TmfFilterRootNode.NODE_NAME)) {
+
+ node = new TmfFilterRootNode();
+
+ } else if (localName.equals(TmfFilterNode.NODE_NAME)) {
+
+ node = new TmfFilterNode(atts.getValue(TmfFilterNode.NAME_ATTR));
+
+ } else if (localName.equals(TmfFilterEventTypeNode.NODE_NAME)) {
+
+ node = new TmfFilterEventTypeNode(null);
+ ((TmfFilterEventTypeNode) node).setEventType(atts.getValue(TmfFilterEventTypeNode.TYPE_ATTR));
+ ((TmfFilterEventTypeNode) node).setName(atts.getValue(TmfFilterEventTypeNode.NAME_ATTR));
+
+ } else if (localName.equals(TmfFilterAndNode.NODE_NAME)) {
+
+ node = new TmfFilterAndNode(null);
+ String value = atts.getValue(TmfFilterAndNode.NOT_ATTR);
+ if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
+ ((TmfFilterAndNode) node).setNot(true);
+ }
+
+ } else if (localName.equals(TmfFilterOrNode.NODE_NAME)) {
+
+ node = new TmfFilterOrNode(null);
+ String value = atts.getValue(TmfFilterOrNode.NOT_ATTR);
+ if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
+ ((TmfFilterOrNode) node).setNot(true);
+ }
+
+ } else if (localName.equals(TmfFilterContainsNode.NODE_NAME)) {
+
+ node = new TmfFilterContainsNode(null);
+ String value = atts.getValue(TmfFilterContainsNode.NOT_ATTR);
+ if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
+ ((TmfFilterContainsNode) node).setNot(true);
+ }
+ ((TmfFilterContainsNode) node).setField(atts.getValue(TmfFilterContainsNode.FIELD_ATTR));
+ ((TmfFilterContainsNode) node).setValue(atts.getValue(TmfFilterContainsNode.VALUE_ATTR));
+ value = atts.getValue(TmfFilterContainsNode.IGNORECASE_ATTR);
+ if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
+ ((TmfFilterContainsNode) node).setIgnoreCase(true);
+ }
+
+ } else if (localName.equals(TmfFilterEqualsNode.NODE_NAME)) {
+
+ node = new TmfFilterEqualsNode(null);
+ String value = atts.getValue(TmfFilterEqualsNode.NOT_ATTR);
+ if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
+ ((TmfFilterEqualsNode) node).setNot(true);
+ }
+ ((TmfFilterEqualsNode) node).setField(atts.getValue(TmfFilterEqualsNode.FIELD_ATTR));
+ ((TmfFilterEqualsNode) node).setValue(atts.getValue(TmfFilterEqualsNode.VALUE_ATTR));
+ value = atts.getValue(TmfFilterEqualsNode.IGNORECASE_ATTR);
+ if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
+ ((TmfFilterEqualsNode) node).setIgnoreCase(true);
+ }
+
+ } else if (localName.equals(TmfFilterMatchesNode.NODE_NAME)) {
+
+ node = new TmfFilterMatchesNode(null);
+ String value = atts.getValue(TmfFilterMatchesNode.NOT_ATTR);
+ if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
+ ((TmfFilterMatchesNode) node).setNot(true);
+ }
+ ((TmfFilterMatchesNode) node).setField(atts.getValue(TmfFilterMatchesNode.FIELD_ATTR));
+ ((TmfFilterMatchesNode) node).setRegex(atts.getValue(TmfFilterMatchesNode.REGEX_ATTR));
+
+ } else if (localName.equals(TmfFilterCompareNode.NODE_NAME)) {
+
+ node = new TmfFilterCompareNode(null);
+ String value = atts.getValue(TmfFilterCompareNode.NOT_ATTR);
+ if (value != null && value.equalsIgnoreCase(Boolean.TRUE.toString())) {
+ ((TmfFilterCompareNode) node).setNot(true);
+ }
+ ((TmfFilterCompareNode) node).setField(atts.getValue(TmfFilterCompareNode.FIELD_ATTR));
+ value = atts.getValue(TmfFilterCompareNode.TYPE_ATTR);
+ if (value != null) {
+ ((TmfFilterCompareNode) node).setType(Type.valueOf(value));
+ }
+ value = atts.getValue(TmfFilterCompareNode.RESULT_ATTR);
+ if (value != null) {
+ if (value.equals(Integer.toString(-1))) {
+ ((TmfFilterCompareNode) node).setResult(-1);
+ } else if (value.equals(Integer.toString(1))) {
+ ((TmfFilterCompareNode) node).setResult(1);
+ } else {
+ ((TmfFilterCompareNode) node).setResult(0);
+ }
+ }
+ ((TmfFilterCompareNode) node).setValue(atts.getValue(TmfFilterCompareNode.VALUE_ATTR));
+
+ }
+
+ fFilterTreeStack.push(node);
+ }
+
+ @Override
+ public void endElement(String uri, String localName, String qName) throws SAXException {
+ ITmfFilterTreeNode node = fFilterTreeStack.pop();
+
+ if (fFilterTreeStack.isEmpty()) {
+ fRoot = node;
+ } else if (fFilterTreeStack.lastElement() instanceof TmfFilterTreeNode &&
+ node instanceof TmfFilterTreeNode) {
+ fFilterTreeStack.lastElement().addChild(node);
+ }
+
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLWriter.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLWriter.java
index 2f104c0a23..e642733e8e 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLWriter.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/xml/TmfFilterXMLWriter.java
@@ -45,118 +45,118 @@ import org.w3c.dom.Element;
*/
public class TmfFilterXMLWriter {
- private Document document = null;
+ private Document document = null;
- /**
- * The XMLParser constructor
- *
+ /**
+ * The XMLParser constructor
+ *
* @param root The tree root
- * @throws ParserConfigurationException if a DocumentBuilder
+ * @throws ParserConfigurationException if a DocumentBuilder
* cannot be created which satisfies the configuration requested.
- */
- public TmfFilterXMLWriter(final ITmfFilterTreeNode root) throws ParserConfigurationException {
- DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
- document = documentBuilder.newDocument();
-
- Element rootElement = document.createElement(root.getNodeName());
- document.appendChild(rootElement);
-
- for (ITmfFilterTreeNode node : root.getChildren()) {
- buildXMLTree(document, node, rootElement);
- }
- }
-
- /**
- * The Tree to XML parser
- *
- * @param document The XML document
- * @param treenode The node to write
- * @param parentElement The XML element of the parent
- */
- public static void buildXMLTree(final Document document, final ITmfFilterTreeNode treenode, Element parentElement) {
- Element element = document.createElement(treenode.getNodeName());
-
- if (treenode instanceof TmfFilterNode) {
-
- TmfFilterNode node = (TmfFilterNode) treenode;
- element.setAttribute(TmfFilterNode.NAME_ATTR, node.getFilterName());
-
- } else if (treenode instanceof TmfFilterEventTypeNode) {
-
- TmfFilterEventTypeNode node = (TmfFilterEventTypeNode) treenode;
- element.setAttribute(TmfFilterEventTypeNode.TYPE_ATTR, node.getEventType());
- element.setAttribute(TmfFilterEventTypeNode.NAME_ATTR, node.getName());
-
- } else if (treenode instanceof TmfFilterAndNode) {
-
- TmfFilterAndNode node = (TmfFilterAndNode) treenode;
- element.setAttribute(TmfFilterAndNode.NOT_ATTR, Boolean.toString(node.isNot()));
-
- } else if (treenode instanceof TmfFilterOrNode) {
-
- TmfFilterOrNode node = (TmfFilterOrNode) treenode;
- element.setAttribute(TmfFilterOrNode.NOT_ATTR, Boolean.toString(node.isNot()));
-
- } else if (treenode instanceof TmfFilterContainsNode) {
-
- TmfFilterContainsNode node = (TmfFilterContainsNode) treenode;
- element.setAttribute(TmfFilterContainsNode.NOT_ATTR, Boolean.toString(node.isNot()));
- element.setAttribute(TmfFilterContainsNode.FIELD_ATTR, node.getField());
- element.setAttribute(TmfFilterContainsNode.VALUE_ATTR, node.getValue());
- element.setAttribute(TmfFilterContainsNode.IGNORECASE_ATTR, Boolean.toString(node.isIgnoreCase()));
-
- } else if (treenode instanceof TmfFilterEqualsNode) {
-
- TmfFilterEqualsNode node = (TmfFilterEqualsNode) treenode;
- element.setAttribute(TmfFilterEqualsNode.NOT_ATTR, Boolean.toString(node.isNot()));
- element.setAttribute(TmfFilterEqualsNode.FIELD_ATTR, node.getField());
- element.setAttribute(TmfFilterEqualsNode.VALUE_ATTR, node.getValue());
- element.setAttribute(TmfFilterEqualsNode.IGNORECASE_ATTR, Boolean.toString(node.isIgnoreCase()));
-
- } else if (treenode instanceof TmfFilterMatchesNode) {
-
- TmfFilterMatchesNode node = (TmfFilterMatchesNode) treenode;
- element.setAttribute(TmfFilterMatchesNode.NOT_ATTR, Boolean.toString(node.isNot()));
- element.setAttribute(TmfFilterMatchesNode.FIELD_ATTR, node.getField());
- element.setAttribute(TmfFilterMatchesNode.REGEX_ATTR, node.getRegex());
-
- } else if (treenode instanceof TmfFilterCompareNode) {
-
- TmfFilterCompareNode node = (TmfFilterCompareNode) treenode;
- element.setAttribute(TmfFilterCompareNode.NOT_ATTR, Boolean.toString(node.isNot()));
- element.setAttribute(TmfFilterCompareNode.FIELD_ATTR, node.getField());
- element.setAttribute(TmfFilterCompareNode.RESULT_ATTR, Integer.toString(node.getResult()));
- element.setAttribute(TmfFilterCompareNode.TYPE_ATTR, node.getType().toString());
- element.setAttribute(TmfFilterCompareNode.VALUE_ATTR, node.getValue());
-
- }
-
- parentElement.appendChild(element);
-
- for (int i = 0; i < treenode.getChildrenCount(); i++) {
- buildXMLTree(document, treenode.getChild(i), element);
- }
- }
-
- /**
- * Save the tree
- *
- * @param uri The new Filter XML path
- */
- public void saveTree(final String uri) {
- TransformerFactory transformerFactory = TransformerFactory.newInstance();
-
- try {
- Transformer transformer = transformerFactory.newTransformer();
- DOMSource source = new DOMSource(document);
- StreamResult result = new StreamResult(new File(uri));
- transformer.transform(source, result);
- } catch (TransformerConfigurationException e) {
- e.printStackTrace();
- } catch (TransformerException e) {
- e.printStackTrace();
- }
- }
+ */
+ public TmfFilterXMLWriter(final ITmfFilterTreeNode root) throws ParserConfigurationException {
+ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
+ document = documentBuilder.newDocument();
+
+ Element rootElement = document.createElement(root.getNodeName());
+ document.appendChild(rootElement);
+
+ for (ITmfFilterTreeNode node : root.getChildren()) {
+ buildXMLTree(document, node, rootElement);
+ }
+ }
+
+ /**
+ * The Tree to XML parser
+ *
+ * @param document The XML document
+ * @param treenode The node to write
+ * @param parentElement The XML element of the parent
+ */
+ public static void buildXMLTree(final Document document, final ITmfFilterTreeNode treenode, Element parentElement) {
+ Element element = document.createElement(treenode.getNodeName());
+
+ if (treenode instanceof TmfFilterNode) {
+
+ TmfFilterNode node = (TmfFilterNode) treenode;
+ element.setAttribute(TmfFilterNode.NAME_ATTR, node.getFilterName());
+
+ } else if (treenode instanceof TmfFilterEventTypeNode) {
+
+ TmfFilterEventTypeNode node = (TmfFilterEventTypeNode) treenode;
+ element.setAttribute(TmfFilterEventTypeNode.TYPE_ATTR, node.getEventType());
+ element.setAttribute(TmfFilterEventTypeNode.NAME_ATTR, node.getName());
+
+ } else if (treenode instanceof TmfFilterAndNode) {
+
+ TmfFilterAndNode node = (TmfFilterAndNode) treenode;
+ element.setAttribute(TmfFilterAndNode.NOT_ATTR, Boolean.toString(node.isNot()));
+
+ } else if (treenode instanceof TmfFilterOrNode) {
+
+ TmfFilterOrNode node = (TmfFilterOrNode) treenode;
+ element.setAttribute(TmfFilterOrNode.NOT_ATTR, Boolean.toString(node.isNot()));
+
+ } else if (treenode instanceof TmfFilterContainsNode) {
+
+ TmfFilterContainsNode node = (TmfFilterContainsNode) treenode;
+ element.setAttribute(TmfFilterContainsNode.NOT_ATTR, Boolean.toString(node.isNot()));
+ element.setAttribute(TmfFilterContainsNode.FIELD_ATTR, node.getField());
+ element.setAttribute(TmfFilterContainsNode.VALUE_ATTR, node.getValue());
+ element.setAttribute(TmfFilterContainsNode.IGNORECASE_ATTR, Boolean.toString(node.isIgnoreCase()));
+
+ } else if (treenode instanceof TmfFilterEqualsNode) {
+
+ TmfFilterEqualsNode node = (TmfFilterEqualsNode) treenode;
+ element.setAttribute(TmfFilterEqualsNode.NOT_ATTR, Boolean.toString(node.isNot()));
+ element.setAttribute(TmfFilterEqualsNode.FIELD_ATTR, node.getField());
+ element.setAttribute(TmfFilterEqualsNode.VALUE_ATTR, node.getValue());
+ element.setAttribute(TmfFilterEqualsNode.IGNORECASE_ATTR, Boolean.toString(node.isIgnoreCase()));
+
+ } else if (treenode instanceof TmfFilterMatchesNode) {
+
+ TmfFilterMatchesNode node = (TmfFilterMatchesNode) treenode;
+ element.setAttribute(TmfFilterMatchesNode.NOT_ATTR, Boolean.toString(node.isNot()));
+ element.setAttribute(TmfFilterMatchesNode.FIELD_ATTR, node.getField());
+ element.setAttribute(TmfFilterMatchesNode.REGEX_ATTR, node.getRegex());
+
+ } else if (treenode instanceof TmfFilterCompareNode) {
+
+ TmfFilterCompareNode node = (TmfFilterCompareNode) treenode;
+ element.setAttribute(TmfFilterCompareNode.NOT_ATTR, Boolean.toString(node.isNot()));
+ element.setAttribute(TmfFilterCompareNode.FIELD_ATTR, node.getField());
+ element.setAttribute(TmfFilterCompareNode.RESULT_ATTR, Integer.toString(node.getResult()));
+ element.setAttribute(TmfFilterCompareNode.TYPE_ATTR, node.getType().toString());
+ element.setAttribute(TmfFilterCompareNode.VALUE_ATTR, node.getValue());
+
+ }
+
+ parentElement.appendChild(element);
+
+ for (int i = 0; i < treenode.getChildrenCount(); i++) {
+ buildXMLTree(document, treenode.getChild(i), element);
+ }
+ }
+
+ /**
+ * Save the tree
+ *
+ * @param uri The new Filter XML path
+ */
+ public void saveTree(final String uri) {
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+
+ try {
+ Transformer transformer = transformerFactory.newTransformer();
+ DOMSource source = new DOMSource(document);
+ StreamResult result = new StreamResult(new File(uri));
+ transformer.transform(source, result);
+ } catch (TransformerConfigurationException e) {
+ e.printStackTrace();
+ } catch (TransformerException e) {
+ e.printStackTrace();
+ }
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/parsers/custom/CustomTxtEvent.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/parsers/custom/CustomTxtEvent.java
index 5ac13a73d9..b8d11f2927 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/parsers/custom/CustomTxtEvent.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/parsers/custom/CustomTxtEvent.java
@@ -89,9 +89,9 @@ public class CustomTxtEvent extends CustomEvent {
* The regex matcher to use
*/
public void processGroups(InputLine input, Matcher matcher) {
- if (input.columns == null) {
- return;
- }
+ if (input.columns == null) {
+ return;
+ }
for (int i = 0; i < input.columns.size(); i++) {
InputData column = input.columns.get(i);
if (i < matcher.groupCount() && matcher.group(i + 1) != null) {
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/parsers/custom/CustomXmlEventType.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/parsers/custom/CustomXmlEventType.java
index 097d7bbd51..3757b62283 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/parsers/custom/CustomXmlEventType.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/parsers/custom/CustomXmlEventType.java
@@ -26,8 +26,8 @@ public class CustomXmlEventType extends CustomEventType {
* @param definition
* Trace definition
*/
- public CustomXmlEventType(CustomXmlTraceDefinition definition) {
- super(definition);
- }
+ public CustomXmlEventType(CustomXmlTraceDefinition definition) {
+ super(definition);
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfEndSynchSignal.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfEndSynchSignal.java
index c36acfb72a..f4a0f4203b 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfEndSynchSignal.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfEndSynchSignal.java
@@ -26,8 +26,8 @@ public class TmfEndSynchSignal extends TmfSignal {
* @param synchId
* The ID assigned to this signal
*/
- public TmfEndSynchSignal(int synchId) {
- super(null, synchId);
- }
+ public TmfEndSynchSignal(int synchId) {
+ super(null, synchId);
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfSignalHandler.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfSignalHandler.java
index a63caee86e..caff3db90a 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfSignalHandler.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfSignalHandler.java
@@ -1,11 +1,11 @@
/*******************************************************************************
* Copyright (c) 2009, 2012 Ericsson
- *
+ *
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Francois Chouinard - Initial API and implementation
*******************************************************************************/
@@ -19,7 +19,7 @@ import java.lang.annotation.Target;
/**
* Marker for TMF signal handlers.
- *
+ *
* @version 1.0
* @author Francois Chouinard
*/
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfSignalTracer.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfSignalTracer.java
index 54f1cea0d1..66106920c6 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfSignalTracer.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/signal/TmfSignalTracer.java
@@ -20,20 +20,20 @@ package org.eclipse.linuxtools.tmf.core.signal;
*/
public class TmfSignalTracer {
- static TmfSignalTracer fInstance;
+ static TmfSignalTracer fInstance;
/**
* @return The single instance of the signal tracer object
*/
- static public TmfSignalTracer getInstance() {
- if (fInstance == null) {
- fInstance = new TmfSignalTracer();
- }
- return fInstance;
- }
+ static public TmfSignalTracer getInstance() {
+ if (fInstance == null) {
+ fInstance = new TmfSignalTracer();
+ }
+ return fInstance;
+ }
- private TmfSignalTracer() {
- }
+ private TmfSignalTracer() {
+ }
/**
* Handler for all TMF signal types
@@ -41,8 +41,8 @@ public class TmfSignalTracer {
* @param signal
* Incoming signal
*/
- @TmfSignalHandler
- public void traceSignal(TmfSignal signal) {
- System.out.println(signal.getSource().toString() + ": " + signal.toString()); //$NON-NLS-1$
- }
+ @TmfSignalHandler
+ public void traceSignal(TmfSignal signal) {
+ System.out.println(signal.getSource().toString() + ": " + signal.toString()); //$NON-NLS-1$
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/timestamp/TmfTimestamp.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/timestamp/TmfTimestamp.java
index e3a4ecca73..95648c55cc 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/timestamp/TmfTimestamp.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/timestamp/TmfTimestamp.java
@@ -8,7 +8,7 @@
*
* Contributors:
* Francois Chouinard - Initial API and implementation
- * Thomas Gatterweh - Updated scaling / synchronization
+ * Thomas Gatterweh - Updated scaling / synchronization
* Francois Chouinard - Refactoring to align with TMF Event Model 1.0
* Francois Chouinard - Implement augmented interface
* Geneviève Bastien - Added copy constructor with new value
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/trace/ITmfEventParser.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/trace/ITmfEventParser.java
index f8752876c2..d855f8b267 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/trace/ITmfEventParser.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/trace/ITmfEventParser.java
@@ -26,13 +26,13 @@ import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
*/
public interface ITmfEventParser {
- /**
- * Parses the trace event referenced by the context.
- * The context should *not* be altered.
- *
- * @param context the trace context
- * @return a parsed event (null if none)
- */
- ITmfEvent parseEvent(ITmfContext context);
+ /**
+ * Parses the trace event referenced by the context.
+ * The context should *not* be altered.
+ *
+ * @param context the trace context
+ * @return a parsed event (null if none)
+ */
+ ITmfEvent parseEvent(ITmfContext context);
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.help/build.xml b/lttng/org.eclipse.linuxtools.tmf.help/build.xml
index d9b88c0e07..6499418f96 100644
--- a/lttng/org.eclipse.linuxtools.tmf.help/build.xml
+++ b/lttng/org.eclipse.linuxtools.tmf.help/build.xml
@@ -41,9 +41,9 @@
</target>
<target name="test" description="Verify that all of the HTML files are well-formed XML">
- <!--
+ <!--
Don't bother with DTD validation: we only care if the files are well-formed.
- We therefore provide an empty DTD
+ We therefore provide an empty DTD
-->
<xmlvalidate lenient="true">
<fileset dir="doc">
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui.tests/plugin.xml b/lttng/org.eclipse.linuxtools.tmf.ui.tests/plugin.xml
index 9723b92d0b..c0015384b4 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui.tests/plugin.xml
+++ b/lttng/org.eclipse.linuxtools.tmf.ui.tests/plugin.xml
@@ -1,15 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
- <extension
+ <extension
point="org.eclipse.ui.views">
- <category id="org.eclipse.linuxtools.tmf.ui.stubs" name="TMF UI Stubs">
- </category>
- <view category="org.eclipse.linuxtools.tmf.ui.stubs"
- class="org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.views.TsfTraceAnalysisView"
- id="org.eclipse.linuxtools.tmf.ui.widgets.timeAnalysis.test.stub.views.TmfTaTimeAnalysis"
- name="Time Graph View" restorable="true">
- </view>
+ <category id="org.eclipse.linuxtools.tmf.ui.stubs" name="TMF UI Stubs">
+ </category>
+ <view category="org.eclipse.linuxtools.tmf.ui.stubs"
+ class="org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.views.TsfTraceAnalysisView"
+ id="org.eclipse.linuxtools.tmf.ui.widgets.timeAnalysis.test.stub.views.TmfTaTimeAnalysis"
+ name="Time Graph View" restorable="true">
+ </view>
<view
category="org.eclipse.linuxtools.tmf.ui.stubs"
class="org.eclipse.linuxtools.tmf.ui.views.uml2sd.SDView"
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui.tests/src/org/eclipse/linuxtools/tmf/ui/tests/views/uml2sd/loader/TmfUml2SDSyncLoaderFindTest.java b/lttng/org.eclipse.linuxtools.tmf.ui.tests/src/org/eclipse/linuxtools/tmf/ui/tests/views/uml2sd/loader/TmfUml2SDSyncLoaderFindTest.java
index 42cc643feb..d6f338cbcb 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui.tests/src/org/eclipse/linuxtools/tmf/ui/tests/views/uml2sd/loader/TmfUml2SDSyncLoaderFindTest.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui.tests/src/org/eclipse/linuxtools/tmf/ui/tests/views/uml2sd/loader/TmfUml2SDSyncLoaderFindTest.java
@@ -160,7 +160,7 @@ public class TmfUml2SDSyncLoaderFindTest {
fFacility.getLoader().find(criteria);
// Wait for the selection to finish - needed due to new platform behavior in Juno
- fFacility.delay(IUml2SDTestConstants.GUI_REFESH_DELAY);
+ fFacility.delay(IUml2SDTestConstants.GUI_REFESH_DELAY);
assertTrue("find", fTmfComponent.isSignalReceived());
assertFalse("find", fTmfComponent.isSignalError());
assertFalse("find", fTmfComponent.isCurrentTimeError());
@@ -195,7 +195,7 @@ public class TmfUml2SDSyncLoaderFindTest {
fFacility.getLoader().find(criteria);
// Wait for the selection to finish - needed due to new platform behavior in Juno
- fFacility.delay(IUml2SDTestConstants.GUI_REFESH_DELAY);
+ fFacility.delay(IUml2SDTestConstants.GUI_REFESH_DELAY);
assertTrue("find", fTmfComponent.isSignalReceived());
assertFalse("find", fTmfComponent.isSignalError());
assertFalse("find", fTmfComponent.isCurrentTimeError());
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui.tests/src/org/eclipse/linuxtools/tmf/ui/tests/views/uml2sd/loader/TmfUml2SDSyncLoaderSignalTest.java b/lttng/org.eclipse.linuxtools.tmf.ui.tests/src/org/eclipse/linuxtools/tmf/ui/tests/views/uml2sd/loader/TmfUml2SDSyncLoaderSignalTest.java
index c7910d7cc0..111780f1b1 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui.tests/src/org/eclipse/linuxtools/tmf/ui/tests/views/uml2sd/loader/TmfUml2SDSyncLoaderSignalTest.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui.tests/src/org/eclipse/linuxtools/tmf/ui/tests/views/uml2sd/loader/TmfUml2SDSyncLoaderSignalTest.java
@@ -121,7 +121,7 @@ public class TmfUml2SDSyncLoaderSignalTest {
fFacility.getSdView().getSDWidget().moveTo(node); // selects the given node
// Wait for the selection to finish - needed due to new platform behavior in Juno
- fFacility.delay(IUml2SDTestConstants.GUI_REFESH_DELAY);
+ fFacility.delay(IUml2SDTestConstants.GUI_REFESH_DELAY);
assertTrue("TmfTimeSynchSignal", fTmfComponent.isSignalReceived());
assertFalse("TmfTimeSynchSignal", fTmfComponent.isSignalError());
assertFalse("TmfTimeSynchSignal", fTmfComponent.isCurrentTimeError());
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/adaption/TsfImplProvider.java b/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/adaption/TsfImplProvider.java
index 1184e1c1db..9e4170049d 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/adaption/TsfImplProvider.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/adaption/TsfImplProvider.java
@@ -23,32 +23,32 @@ import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.test.stub.model.EventImpl
*/
public class TsfImplProvider extends TimeGraphPresentationProvider {
- // ========================================================================
- // Methods
- // ========================================================================
- @Override
- public int getStateTableIndex(ITimeEvent event) {
- return 0;
- }
+ // ========================================================================
+ // Methods
+ // ========================================================================
+ @Override
+ public int getStateTableIndex(ITimeEvent event) {
+ return 0;
+ }
- @Override
- public Map<String, String> getEventHoverToolTipInfo(ITimeEvent revent) {
- Map<String, String> toolTipEventMsgs = new HashMap<>();
- if (revent instanceof EventImpl) {
- toolTipEventMsgs.put("Test Tip1", "Test Value tip1");
- toolTipEventMsgs.put("Test Tip2", "Test Value tip2");
- }
+ @Override
+ public Map<String, String> getEventHoverToolTipInfo(ITimeEvent revent) {
+ Map<String, String> toolTipEventMsgs = new HashMap<>();
+ if (revent instanceof EventImpl) {
+ toolTipEventMsgs.put("Test Tip1", "Test Value tip1");
+ toolTipEventMsgs.put("Test Tip2", "Test Value tip2");
+ }
- return toolTipEventMsgs;
- }
+ return toolTipEventMsgs;
+ }
- @Override
- public String getEventName(ITimeEvent event) {
- String name = "Unknown";
- if (event instanceof EventImpl) {
- EventImpl devent = (EventImpl) event;
- name = devent.getType().toString();
- }
- return name;
- }
+ @Override
+ public String getEventName(ITimeEvent event) {
+ String name = "Unknown";
+ if (event instanceof EventImpl) {
+ EventImpl devent = (EventImpl) event;
+ name = devent.getType().toString();
+ }
+ return name;
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/EventImpl.java b/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/EventImpl.java
index cac59d4964..c8ed3d411d 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/EventImpl.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/EventImpl.java
@@ -19,67 +19,67 @@ import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry;
*/
@SuppressWarnings("javadoc")
public class EventImpl implements ITimeEvent {
- // ========================================================================
- // Data
- // ========================================================================
- public static enum Type {ERROR, WARNING, TIMEADJUSTMENT, ALARM, EVENT, INFORMATION, UNKNOWN, INFO1, INFO2, INFO3, INFO4, INFO5, INFO6, INFO7, INFO8, INFO9}
+ // ========================================================================
+ // Data
+ // ========================================================================
+ public static enum Type {ERROR, WARNING, TIMEADJUSTMENT, ALARM, EVENT, INFORMATION, UNKNOWN, INFO1, INFO2, INFO3, INFO4, INFO5, INFO6, INFO7, INFO8, INFO9}
- private long time = 0;
- private ITimeGraphEntry trace = null;
- private Type myType = Type.UNKNOWN;
- private long duration;
+ private long time = 0;
+ private ITimeGraphEntry trace = null;
+ private Type myType = Type.UNKNOWN;
+ private long duration;
- // ========================================================================
- // Constructor
- // ========================================================================
- public EventImpl(long time, ITimeGraphEntry trace, Type type) {
- this.time = time;
- this.trace = trace;
- this.myType = type;
- }
+ // ========================================================================
+ // Constructor
+ // ========================================================================
+ public EventImpl(long time, ITimeGraphEntry trace, Type type) {
+ this.time = time;
+ this.trace = trace;
+ this.myType = type;
+ }
- // ========================================================================
- // Methods
- // ========================================================================
- public Type getType() {
- return myType;
- }
+ // ========================================================================
+ // Methods
+ // ========================================================================
+ public Type getType() {
+ return myType;
+ }
- public void setType(Type myType) {
- this.myType = myType;
- }
+ public void setType(Type myType) {
+ this.myType = myType;
+ }
- public void setTime(long time) {
- this.time = time;
- }
+ public void setTime(long time) {
+ this.time = time;
+ }
- public void setTrace(ITimeGraphEntry trace) {
- this.trace = trace;
- }
+ public void setTrace(ITimeGraphEntry trace) {
+ this.trace = trace;
+ }
- @Override
- public long getTime() {
- return time;
- }
+ @Override
+ public long getTime() {
+ return time;
+ }
- @Override
- public ITimeGraphEntry getEntry() {
- return trace;
- }
+ @Override
+ public ITimeGraphEntry getEntry() {
+ return trace;
+ }
- /**
- * @param duration the duration to set
- */
- public void setDuration(long duration) {
- this.duration = duration;
- }
+ /**
+ * @param duration the duration to set
+ */
+ public void setDuration(long duration) {
+ this.duration = duration;
+ }
- /**
- * @return the duration
- */
- @Override
- public long getDuration() {
- return duration;
- }
+ /**
+ * @return the duration
+ */
+ @Override
+ public long getDuration() {
+ return duration;
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceModelImplFactory.java b/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceModelImplFactory.java
index 7b98ed5e6b..bd875921b0 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceModelImplFactory.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui.tests/widgetStubs/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/test/stub/model/TraceModelImplFactory.java
@@ -16,91 +16,91 @@ import java.util.Date;
@SuppressWarnings("javadoc")
public class TraceModelImplFactory {
- // ========================================================================
- // Data
- // ========================================================================
- private int count = 0;
- private final TraceStrings[] traceNames;
- private static final long msTons = 1000000;
- private final Long timeRef = new Date().getTime() * msTons;
-
- // ========================================================================
- // Constructor
- // ========================================================================
- public TraceModelImplFactory() {
- traceNames = new TraceStrings[17];
- loadTraceNameStrings();
- }
-
- // ========================================================================
- // Methods
- // ========================================================================
- public TraceImpl[] createTraces() {
- TraceImpl trace;
- TraceImpl[] traceArr = new TraceImpl[17];
- for (int i = 0; i < traceArr.length; i++) {
- trace = new TraceImpl(traceNames[i].name, timeRef, timeRef + 40,
- traceNames[i].classNmme);
- count = i;
- createEvents(trace);
- traceArr[i] = trace;
- }
- return traceArr;
- }
-
- /**
- * 5000 Events per Trace.
- * @param number
- * @return
- */
- public TraceImpl[] createLargeTraces(int number) {
- TraceImpl trace;
- TraceImpl[] traceArr = new TraceImpl[number];
- for (int i = 0; i < traceArr.length; i++) {
- int counter = i%17;
- long sTime = i * (long) 1E6;
- trace = new TraceImpl(traceNames[counter].name, sTime , sTime + 20000,
- traceNames[counter].classNmme);
- create5000Events(trace);
- traceArr[i] = trace;
- }
- return traceArr;
- }
-
- private static void create5000Events(TraceImpl trace) {
- EventImpl event;
- Long eventTime;
- int numEvents = 5000;
- long sTime = trace.getStartTime();
- long eTime = trace.getEndTime();
- long duration = (eTime - sTime)/numEvents;
- for (int i = 0; i < numEvents; i++) {
- eventTime = sTime + (i * duration);
- // eventTime = timeRef + (5 * (count % 4) + (5 * (int) (i/2) ));
- // System.out.println("Trace: " + trace.getName() + " EventTime: "
- // + eventTime);
-// duration = i * msTons + (long) ((i % 4));
-
- event = new EventImpl(eventTime, trace, getEventType(i%16));
- event.setDuration(duration);
- trace.addTraceEvent(event);
- }
- }
-
- private void createEvents(TraceImpl trace) {
- EventImpl event;
- Long eventTime;
- int numEvents = 17;
- long duration = 0;
- for (int i = 0; i < numEvents; i++) {
- eventTime = timeRef + msTons * i + (5 * msTons * count) + (5 * i);
- duration = msTons + i * msTons + ((i % 4));
-// duration = i + (long) ((i % 4));
- event = new EventImpl(eventTime, trace, getEventType(i));
- event.setDuration(duration);
- trace.addTraceEvent(event);
- }
- }
+ // ========================================================================
+ // Data
+ // ========================================================================
+ private int count = 0;
+ private final TraceStrings[] traceNames;
+ private static final long msTons = 1000000;
+ private final Long timeRef = new Date().getTime() * msTons;
+
+ // ========================================================================
+ // Constructor
+ // ========================================================================
+ public TraceModelImplFactory() {
+ traceNames = new TraceStrings[17];
+ loadTraceNameStrings();
+ }
+
+ // ========================================================================
+ // Methods
+ // ========================================================================
+ public TraceImpl[] createTraces() {
+ TraceImpl trace;
+ TraceImpl[] traceArr = new TraceImpl[17];
+ for (int i = 0; i < traceArr.length; i++) {
+ trace = new TraceImpl(traceNames[i].name, timeRef, timeRef + 40,
+ traceNames[i].classNmme);
+ count = i;
+ createEvents(trace);
+ traceArr[i] = trace;
+ }
+ return traceArr;
+ }
+
+ /**
+ * 5000 Events per Trace.
+ * @param number
+ * @return
+ */
+ public TraceImpl[] createLargeTraces(int number) {
+ TraceImpl trace;
+ TraceImpl[] traceArr = new TraceImpl[number];
+ for (int i = 0; i < traceArr.length; i++) {
+ int counter = i%17;
+ long sTime = i * (long) 1E6;
+ trace = new TraceImpl(traceNames[counter].name, sTime , sTime + 20000,
+ traceNames[counter].classNmme);
+ create5000Events(trace);
+ traceArr[i] = trace;
+ }
+ return traceArr;
+ }
+
+ private static void create5000Events(TraceImpl trace) {
+ EventImpl event;
+ Long eventTime;
+ int numEvents = 5000;
+ long sTime = trace.getStartTime();
+ long eTime = trace.getEndTime();
+ long duration = (eTime - sTime)/numEvents;
+ for (int i = 0; i < numEvents; i++) {
+ eventTime = sTime + (i * duration);
+ // eventTime = timeRef + (5 * (count % 4) + (5 * (int) (i/2) ));
+ // System.out.println("Trace: " + trace.getName() + " EventTime: "
+ // + eventTime);
+// duration = i * msTons + (long) ((i % 4));
+
+ event = new EventImpl(eventTime, trace, getEventType(i%16));
+ event.setDuration(duration);
+ trace.addTraceEvent(event);
+ }
+ }
+
+ private void createEvents(TraceImpl trace) {
+ EventImpl event;
+ Long eventTime;
+ int numEvents = 17;
+ long duration = 0;
+ for (int i = 0; i < numEvents; i++) {
+ eventTime = timeRef + msTons * i + (5 * msTons * count) + (5 * i);
+ duration = msTons + i * msTons + ((i % 4));
+// duration = i + (long) ((i % 4));
+ event = new EventImpl(eventTime, trace, getEventType(i));
+ event.setDuration(duration);
+ trace.addTraceEvent(event);
+ }
+ }
private static EventImpl.Type getEventType(int val) {
if (EventImpl.Type.ALARM.ordinal() == val) {
@@ -151,82 +151,82 @@ public class TraceModelImplFactory {
return EventImpl.Type.UNKNOWN;
}
- private void loadTraceNameStrings() {
- traceNames[0] = new TraceStrings();
- traceNames[0].name = "TE Log - TATA BSC11";
- traceNames[0].classNmme = "All Boards";
+ private void loadTraceNameStrings() {
+ traceNames[0] = new TraceStrings();
+ traceNames[0].name = "TE Log - TATA BSC11";
+ traceNames[0].classNmme = "All Boards";
- traceNames[1] = new TraceStrings();
- traceNames[1].name = "System Log";
- traceNames[1].classNmme = "BSC11";
+ traceNames[1] = new TraceStrings();
+ traceNames[1].name = "System Log";
+ traceNames[1].classNmme = "BSC11";
- traceNames[2] = new TraceStrings();
- traceNames[2].name = "Alarm Log";
- traceNames[2].classNmme = "BSC11";
+ traceNames[2] = new TraceStrings();
+ traceNames[2].name = "Alarm Log";
+ traceNames[2].classNmme = "BSC11";
- traceNames[3] = new TraceStrings();
- traceNames[3].name = "Events Log";
- traceNames[3].classNmme = "BSC 11";
+ traceNames[3] = new TraceStrings();
+ traceNames[3].name = "Events Log";
+ traceNames[3].classNmme = "BSC 11";
- traceNames[4] = new TraceStrings();
- traceNames[4].name = "CPU Load";
- traceNames[4].classNmme = "All Boards";
+ traceNames[4] = new TraceStrings();
+ traceNames[4].name = "CPU Load";
+ traceNames[4].classNmme = "All Boards";
- traceNames[5] = new TraceStrings();
- traceNames[5].name = "Performance Log";
- traceNames[5].classNmme = "BSC11";
+ traceNames[5] = new TraceStrings();
+ traceNames[5].name = "Performance Log";
+ traceNames[5].classNmme = "BSC11";
- traceNames[6] = new TraceStrings();
- traceNames[6].name = "TE Log - TATA BSC14";
- traceNames[6].classNmme = "Board 24";
+ traceNames[6] = new TraceStrings();
+ traceNames[6].name = "TE Log - TATA BSC14";
+ traceNames[6].classNmme = "Board 24";
- traceNames[7] = new TraceStrings();
- traceNames[7].name = "TE Log - TATA BSC14";
- traceNames[7].classNmme = "Board 23";
+ traceNames[7] = new TraceStrings();
+ traceNames[7].name = "TE Log - TATA BSC14";
+ traceNames[7].classNmme = "Board 23";
- traceNames[8] = new TraceStrings();
- traceNames[8].name = "TE Log - TATA BSC14";
- traceNames[8].classNmme = "Board 11";
+ traceNames[8] = new TraceStrings();
+ traceNames[8].name = "TE Log - TATA BSC14";
+ traceNames[8].classNmme = "Board 11";
- traceNames[9] = new TraceStrings();
- traceNames[9].name = "TE Log - TATA BSC14";
- traceNames[9].classNmme = "Board 14, SPO";
+ traceNames[9] = new TraceStrings();
+ traceNames[9].name = "TE Log - TATA BSC14";
+ traceNames[9].classNmme = "Board 14, SPO";
- traceNames[10] = new TraceStrings();
- traceNames[10].name = "INFO 1";
- traceNames[10].classNmme = "All Boards";
+ traceNames[10] = new TraceStrings();
+ traceNames[10].name = "INFO 1";
+ traceNames[10].classNmme = "All Boards";
- traceNames[11] = new TraceStrings();
- traceNames[11].name = "INFO2";
- traceNames[11].classNmme = "BSC11";
+ traceNames[11] = new TraceStrings();
+ traceNames[11].name = "INFO2";
+ traceNames[11].classNmme = "BSC11";
- traceNames[12] = new TraceStrings();
- traceNames[12].name = "INFO3";
- traceNames[12].classNmme = "Board 24";
+ traceNames[12] = new TraceStrings();
+ traceNames[12].name = "INFO3";
+ traceNames[12].classNmme = "Board 24";
- traceNames[13] = new TraceStrings();
- traceNames[13].name = "MISC1";
- traceNames[13].classNmme = "Board 23";
+ traceNames[13] = new TraceStrings();
+ traceNames[13].name = "MISC1";
+ traceNames[13].classNmme = "Board 23";
- traceNames[14] = new TraceStrings();
- traceNames[14].name = "MISC2";
- traceNames[14].classNmme = "Board 11";
+ traceNames[14] = new TraceStrings();
+ traceNames[14].name = "MISC2";
+ traceNames[14].classNmme = "Board 11";
- traceNames[15] = new TraceStrings();
- traceNames[15].name = "MISC3";
- traceNames[15].classNmme = "Board 23";
+ traceNames[15] = new TraceStrings();
+ traceNames[15].name = "MISC3";
+ traceNames[15].classNmme = "Board 23";
- traceNames[16] = new TraceStrings();
- traceNames[16].name = "MISC4";
- traceNames[16].classNmme = "Board 11";
+ traceNames[16] = new TraceStrings();
+ traceNames[16].name = "MISC4";
+ traceNames[16].classNmme = "Board 11";
- }
+ }
- // ========================================================================
- // Inner Class
- // ========================================================================
- private static class TraceStrings {
- public String name = "";
- public String classNmme = name + " class";
- }
+ // ========================================================================
+ // Inner Class
+ // ========================================================================
+ private static class TraceStrings {
+ public String name = "";
+ public String classNmme = name + " class";
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/plugin.xml b/lttng/org.eclipse.linuxtools.tmf.ui/plugin.xml
index 8974ab40f9..66c15d9d9f 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/plugin.xml
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/plugin.xml
@@ -44,7 +44,7 @@
id="org.eclipse.linuxtools.tmf.ui.views.colors"
name="%colors.view.name"
restorable="true">
- </view>
+ </view>
<view
allowMultiple="false"
category="org.eclipse.linuxtools.tmf.ui.views.category"
@@ -126,7 +126,7 @@
project="true">
<description>
%project.new.wizard.description
-
+
</description>
</wizard>
<wizard
@@ -1049,7 +1049,7 @@
</command>
<category
description="%commands.uml2sd.category.name"
- id="org.eclipse.linuxtools.tmf.ui.views.uml2sd.category"
+ id="org.eclipse.linuxtools.tmf.ui.views.uml2sd.category"
name="%commands.uml2sd.category.name">
</category>
<command
@@ -1069,7 +1069,7 @@
description="%commands.uml2sd.showstart.description"
id="org.eclipse.linuxtools.tmf.ui.views.uml2sd.handlers.ShowNodeStart"
name="%commands.uml2sd.showstart">
- </command>
+ </command>
<command
categoryId="org.eclipse.linuxtools.tmf.ui.views.uml2sd.category"
description="%commands.uml2sd.scrollup.description"
@@ -1534,25 +1534,25 @@
contextId="org.eclipse.linuxtools.tmf.ui.view.uml2sd.context"
commandId="org.eclipse.linuxtools.tmf.ui.views.uml2sd.handlers.GoToMessage"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration">
- </key>
+ </key>
<key
sequence="SHIFT+ALT+END"
contextId="org.eclipse.linuxtools.tmf.ui.view.uml2sd.context"
commandId="org.eclipse.linuxtools.tmf.ui.views.uml2sd.handlers.ShowNodeEnd"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration">
- </key>
+ </key>
<key
sequence="SHIFT+ALT+HOME"
contextId="org.eclipse.linuxtools.tmf.ui.view.uml2sd.context"
commandId="org.eclipse.linuxtools.tmf.ui.views.uml2sd.handlers.ShowNodeStart"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration">
- </key>
+ </key>
<key
sequence="SHIFT+ALT+ARROW_UP"
contextId="org.eclipse.linuxtools.tmf.ui.view.uml2sd.context"
commandId="org.eclipse.linuxtools.tmf.ui.views.uml2sd.handlers.MoveSDUp"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration">
- </key>
+ </key>
<key
sequence="SHIFT+ALT+ARROW_DOWN"
contextId="org.eclipse.linuxtools.tmf.ui.view.uml2sd.context"
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/commands/ManageCustomParsersCommandHandler.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/commands/ManageCustomParsersCommandHandler.java
index e81a193ab4..1f73c8a002 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/commands/ManageCustomParsersCommandHandler.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/commands/ManageCustomParsersCommandHandler.java
@@ -26,7 +26,7 @@ import org.eclipse.swt.widgets.Display;
public class ManageCustomParsersCommandHandler extends AbstractHandler {
@Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
+ public Object execute(ExecutionEvent event) throws ExecutionException {
ManageCustomParsersDialog dialog = new ManageCustomParsersDialog(Display.getDefault().getActiveShell());
dialog.open();
return null;
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RefreshHandler.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RefreshHandler.java
index d8e2fbabf1..c947be07c3 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RefreshHandler.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RefreshHandler.java
@@ -42,9 +42,9 @@ public class RefreshHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
- // Check if we are closing down
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window == null) {
+ // Check if we are closing down
+ IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ if (window == null) {
return null;
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RenameExperimentHandler.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RenameExperimentHandler.java
index 854f99c3f3..de96794c14 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RenameExperimentHandler.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RenameExperimentHandler.java
@@ -32,9 +32,9 @@ import org.eclipse.ui.PlatformUI;
*/
public class RenameExperimentHandler extends AbstractHandler {
- private TmfExperimentElement fExperiment = null;
+ private TmfExperimentElement fExperiment = null;
- // ------------------------------------------------------------------------
+ // ------------------------------------------------------------------------
// isEnabled
// ------------------------------------------------------------------------
@@ -65,7 +65,7 @@ public class RenameExperimentHandler extends AbstractHandler {
TreeSelection sel = (TreeSelection) selection;
Object element = sel.getFirstElement();
if (element instanceof TmfExperimentElement) {
- fExperiment = (TmfExperimentElement) element;
+ fExperiment = (TmfExperimentElement) element;
}
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RenameTraceHandler.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RenameTraceHandler.java
index 6a611a1ac1..d5d77821f1 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RenameTraceHandler.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/RenameTraceHandler.java
@@ -53,9 +53,9 @@ import org.eclipse.ui.actions.WorkspaceModifyOperation;
*/
public class RenameTraceHandler extends AbstractHandler {
- private TmfTraceElement fTrace = null;
+ private TmfTraceElement fTrace = null;
- // ------------------------------------------------------------------------
+ // ------------------------------------------------------------------------
// isEnabled
// ------------------------------------------------------------------------
@@ -84,10 +84,10 @@ public class RenameTraceHandler extends AbstractHandler {
fTrace = null;
if (selection instanceof TreeSelection) {
TreeSelection sel = (TreeSelection) selection;
- // There should be only one item selected as per the plugin.xml
+ // There should be only one item selected as per the plugin.xml
Object element = sel.getFirstElement();
if (element instanceof TmfTraceElement) {
- fTrace = (TmfTraceElement) element;
+ fTrace = (TmfTraceElement) element;
}
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/SelectTracesHandler.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/SelectTracesHandler.java
index 637a30a691..c46b5a85ae 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/SelectTracesHandler.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/internal/tmf/ui/project/handlers/SelectTracesHandler.java
@@ -67,10 +67,10 @@ public class SelectTracesHandler extends AbstractHandler {
fExperiment = null;
if (selection instanceof TreeSelection) {
TreeSelection sel = (TreeSelection) selection;
- // There should be only one item selected as per the plugin.xml
+ // There should be only one item selected as per the plugin.xml
Object element = sel.getFirstElement();
if (element instanceof TmfExperimentElement) {
- fExperiment = (TmfExperimentElement) element;
+ fExperiment = (TmfExperimentElement) element;
}
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditor.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditor.java
index 8ad3694128..359a771925 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditor.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfEditor.java
@@ -52,12 +52,12 @@ public abstract class TmfEditor extends EditorPart implements ITmfComponent {
// ------------------------------------------------------------------------
@Override
- public String getName() {
+ public String getName() {
return fName;
}
@Override
- public void broadcast(TmfSignal signal) {
+ public void broadcast(TmfSignal signal) {
TmfSignalManager.dispatchSignal(signal);
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfMultiPageEditorPart.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfMultiPageEditorPart.java
index 56cca1c90e..1b9fbd91db 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfMultiPageEditorPart.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/editors/TmfMultiPageEditorPart.java
@@ -51,12 +51,12 @@ public abstract class TmfMultiPageEditorPart extends MultiPageEditorPart impleme
// ------------------------------------------------------------------------
@Override
- public String getName() {
+ public String getName() {
return fName;
}
@Override
- public void broadcast(TmfSignal signal) {
+ public void broadcast(TmfSignal signal) {
TmfSignalManager.dispatchSignal(signal);
}
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSetting.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSetting.java
index 176d10779d..2aa85bcd71 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSetting.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSetting.java
@@ -31,17 +31,17 @@ import org.eclipse.ui.themes.ColorUtil;
*/
public class ColorSetting {
- private RGB fForegroundRGB;
- private RGB fBackgroundRGB;
- private RGB fTickColorRGB;
- private Color fForegroundColor;
- private Color fBackgroundColor;
- private Color fDimmedForegroundColor;
- private Color fDimmedBackgroundColor;
- private Color fTickColor;
- private ITmfFilterTreeNode fFilter;
-
- /**
+ private RGB fForegroundRGB;
+ private RGB fBackgroundRGB;
+ private RGB fTickColorRGB;
+ private Color fForegroundColor;
+ private Color fBackgroundColor;
+ private Color fDimmedForegroundColor;
+ private Color fDimmedBackgroundColor;
+ private Color fTickColor;
+ private ITmfFilterTreeNode fFilter;
+
+ /**
* Constructor
*
* You must dispose the color setting when it is no longer required.
@@ -55,160 +55,160 @@ public class ColorSetting {
* @param filter
* The filter tree node
*/
- public ColorSetting(RGB foreground, RGB background, RGB tickColorRGB, ITmfFilterTreeNode filter) {
- fForegroundRGB = foreground;
- fBackgroundRGB = background;
- fTickColorRGB = tickColorRGB;
- fFilter = filter;
- Display display = Display.getDefault();
- fForegroundColor = new Color(display, fForegroundRGB);
- fBackgroundColor = new Color(display, fBackgroundRGB);
- fDimmedForegroundColor = new Color(display, ColorUtil.blend(
- fForegroundRGB, fBackgroundRGB));
- fDimmedBackgroundColor = new Color(display, ColorUtil.blend(
- fBackgroundRGB, display.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB()));
- fTickColor = new Color(display, fTickColorRGB);
- }
-
- /**
- * Dispose the color setting resources
- */
- public void dispose() {
- fForegroundColor.dispose();
- fBackgroundColor.dispose();
- fDimmedForegroundColor.dispose();
- fDimmedBackgroundColor.dispose();
- fTickColor.dispose();
- }
-
- /**
- * Returns foreground RGB value.
- *
- * @return the foreground RGB
- */
- public RGB getForegroundRGB() {
- return fForegroundRGB;
- }
-
- /**
- * Sets the foreground RGB value
- *
- * @param foreground the foreground to set
- */
- public void setForegroundRGB(RGB foreground) {
- fForegroundRGB = foreground;
- fForegroundColor.dispose();
- fDimmedForegroundColor.dispose();
- Display display = Display.getDefault();
- fForegroundColor = new Color(display, fForegroundRGB);
- fDimmedForegroundColor = new Color(display, ColorUtil.blend(
- fForegroundRGB, fBackgroundRGB));
- }
-
- /**
- * Returns the background RGB value.
- *
- * @return the background RGB
- */
- public RGB getBackgroundRGB() {
- return fBackgroundRGB;
- }
-
- /**
- * Sets the background RGB value.
- *
- * @param background the background to set
- */
- public void setBackgroundRGB(RGB background) {
- fBackgroundRGB = background;
- fBackgroundColor.dispose();
- fDimmedBackgroundColor.dispose();
- Display display = Display.getDefault();
- fBackgroundColor = new Color(display, fBackgroundRGB);
- fDimmedBackgroundColor = new Color(display, ColorUtil.blend(
- fBackgroundRGB, display.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB()));
- }
-
- /**
- * Returns the RGB of the tick color
- *
- * @return the RGB of the tick color
- */
- public RGB getTickColorRGB() {
- return fTickColorRGB;
- }
-
- /**
- * Sets the RGB of the tick color
- *
- * @param tickColorRGB the tick color TGB
- */
- public void setTickColorRGB(RGB tickColorRGB) {
- fTickColorRGB = tickColorRGB;
- fTickColor.dispose();
+ public ColorSetting(RGB foreground, RGB background, RGB tickColorRGB, ITmfFilterTreeNode filter) {
+ fForegroundRGB = foreground;
+ fBackgroundRGB = background;
+ fTickColorRGB = tickColorRGB;
+ fFilter = filter;
+ Display display = Display.getDefault();
+ fForegroundColor = new Color(display, fForegroundRGB);
+ fBackgroundColor = new Color(display, fBackgroundRGB);
+ fDimmedForegroundColor = new Color(display, ColorUtil.blend(
+ fForegroundRGB, fBackgroundRGB));
+ fDimmedBackgroundColor = new Color(display, ColorUtil.blend(
+ fBackgroundRGB, display.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB()));
+ fTickColor = new Color(display, fTickColorRGB);
+ }
+
+ /**
+ * Dispose the color setting resources
+ */
+ public void dispose() {
+ fForegroundColor.dispose();
+ fBackgroundColor.dispose();
+ fDimmedForegroundColor.dispose();
+ fDimmedBackgroundColor.dispose();
+ fTickColor.dispose();
+ }
+
+ /**
+ * Returns foreground RGB value.
+ *
+ * @return the foreground RGB
+ */
+ public RGB getForegroundRGB() {
+ return fForegroundRGB;
+ }
+
+ /**
+ * Sets the foreground RGB value
+ *
+ * @param foreground the foreground to set
+ */
+ public void setForegroundRGB(RGB foreground) {
+ fForegroundRGB = foreground;
+ fForegroundColor.dispose();
+ fDimmedForegroundColor.dispose();
+ Display display = Display.getDefault();
+ fForegroundColor = new Color(display, fForegroundRGB);
+ fDimmedForegroundColor = new Color(display, ColorUtil.blend(
+ fForegroundRGB, fBackgroundRGB));
+ }
+
+ /**
+ * Returns the background RGB value.
+ *
+ * @return the background RGB
+ */
+ public RGB getBackgroundRGB() {
+ return fBackgroundRGB;
+ }
+
+ /**
+ * Sets the background RGB value.
+ *
+ * @param background the background to set
+ */
+ public void setBackgroundRGB(RGB background) {
+ fBackgroundRGB = background;
+ fBackgroundColor.dispose();
+ fDimmedBackgroundColor.dispose();
+ Display display = Display.getDefault();
+ fBackgroundColor = new Color(display, fBackgroundRGB);
+ fDimmedBackgroundColor = new Color(display, ColorUtil.blend(
+ fBackgroundRGB, display.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB()));
+ }
+
+ /**
+ * Returns the RGB of the tick color
+ *
+ * @return the RGB of the tick color
+ */
+ public RGB getTickColorRGB() {
+ return fTickColorRGB;
+ }
+
+ /**
+ * Sets the RGB of the tick color
+ *
+ * @param tickColorRGB the tick color TGB
+ */
+ public void setTickColorRGB(RGB tickColorRGB) {
+ fTickColorRGB = tickColorRGB;
+ fTickColor.dispose();
Display display = Display.getDefault();
fTickColor = new Color(display, fTickColorRGB);
- }
-
- /**
- * Returns the filter implementation.
- * @return the filter
- */
- public ITmfFilterTreeNode getFilter() {
- return fFilter;
- }
-
- /**
- * Sets the filter implementation.
- *
- * @param filter the filter to set
- */
- public void setFilter(ITmfFilterTreeNode filter) {
- fFilter = filter;
- }
-
- /**
- * Returns the foreground color.
- *
- * @return the foreground color
- */
- public Color getForegroundColor() {
- return fForegroundColor;
- }
-
- /**
- * Returns the background color.
- *
- * @return the background color
- */
- public Color getBackgroundColor() {
- return fBackgroundColor;
- }
-
- /**
- * Returns the dimmed foreground color.
- *
- * @return the dimmed foreground color
- */
- public Color getDimmedForegroundColor() {
- return fDimmedForegroundColor;
- }
-
- /**
- * Returns the dimmed background color.
- *
- * @return the dimmed background color
- */
- public Color getDimmedBackgroundColor() {
- return fDimmedBackgroundColor;
- }
-
- /**
- * Returns the tick color.
- *
- * @return the tick color
- */
- public Color getTickColor() {
+ }
+
+ /**
+ * Returns the filter implementation.
+ * @return the filter
+ */
+ public ITmfFilterTreeNode getFilter() {
+ return fFilter;
+ }
+
+ /**
+ * Sets the filter implementation.
+ *
+ * @param filter the filter to set
+ */
+ public void setFilter(ITmfFilterTreeNode filter) {
+ fFilter = filter;
+ }
+
+ /**
+ * Returns the foreground color.
+ *
+ * @return the foreground color
+ */
+ public Color getForegroundColor() {
+ return fForegroundColor;
+ }
+
+ /**
+ * Returns the background color.
+ *
+ * @return the background color
+ */
+ public Color getBackgroundColor() {
+ return fBackgroundColor;
+ }
+
+ /**
+ * Returns the dimmed foreground color.
+ *
+ * @return the dimmed foreground color
+ */
+ public Color getDimmedForegroundColor() {
+ return fDimmedForegroundColor;
+ }
+
+ /**
+ * Returns the dimmed background color.
+ *
+ * @return the dimmed background color
+ */
+ public Color getDimmedBackgroundColor() {
+ return fDimmedBackgroundColor;
+ }
+
+ /**
+ * Returns the tick color.
+ *
+ * @return the tick color
+ */
+ public Color getTickColor() {
return fTickColor;
}
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsManager.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsManager.java
index ed53ed427f..16a68e9805 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsManager.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/colors/ColorSettingsManager.java
@@ -32,51 +32,51 @@ import org.eclipse.swt.widgets.Display;
public class ColorSettingsManager {
// The color settings file name
- private static final String COLOR_SETTINGS_FILE_NAME = "color_settings.xml"; //$NON-NLS-1$
+ private static final String COLOR_SETTINGS_FILE_NAME = "color_settings.xml"; //$NON-NLS-1$
- // The path for the color settings file
- private static final String COLOR_SETTINGS_PATH_NAME =
+ // The path for the color settings file
+ private static final String COLOR_SETTINGS_PATH_NAME =
Activator.getDefault().getStateLocation().addTrailingSeparator().append(COLOR_SETTINGS_FILE_NAME).toString();
- // The default color setting
- private static final ColorSetting DEFAULT_COLOR_SETTING = new ColorSetting(
- Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(),
- Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(),
- Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(),
- null);
-
- /**
- * Special value for priority if unknown.
- */
- public static final int PRIORITY_NONE = Integer.MAX_VALUE;
-
- // The stored color settings
- private static ColorSetting[] fColorSettings = ColorSettingsXML.load(COLOR_SETTINGS_PATH_NAME);
-
- // The listener list
- private static List<IColorSettingsListener> fListeners = new ArrayList<>();
-
- /**
- * Returns an array of color settings.
- *
- * @return an array of color settings.
- */
- public static ColorSetting[] getColorSettings() {
- return (fColorSettings != null) ? Arrays.copyOf(fColorSettings, fColorSettings.length) : null;
- }
-
- /**
- * Sets the array of color settings.
- *
- * @param colorSettings A array of color settings to set
- */
- public static void setColorSettings(ColorSetting[] colorSettings) {
- fColorSettings = (colorSettings != null) ? Arrays.copyOf(colorSettings, colorSettings.length) : null;
- ColorSettingsXML.save(COLOR_SETTINGS_PATH_NAME, fColorSettings);
- fireColorSettingsChanged();
- }
-
- /**
+ // The default color setting
+ private static final ColorSetting DEFAULT_COLOR_SETTING = new ColorSetting(
+ Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(),
+ Display.getDefault().getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(),
+ Display.getDefault().getSystemColor(SWT.COLOR_LIST_FOREGROUND).getRGB(),
+ null);
+
+ /**
+ * Special value for priority if unknown.
+ */
+ public static final int PRIORITY_NONE = Integer.MAX_VALUE;
+
+ // The stored color settings
+ private static ColorSetting[] fColorSettings = ColorSettingsXML.load(COLOR_SETTINGS_PATH_NAME);
+
+ // The listener list
+ private static List<IColorSettingsListener> fListeners = new ArrayList<>();
+
+ /**
+ * Returns an array of color settings.
+ *
+ * @return an array of color settings.
+ */
+ public static ColorSetting[] getColorSettings() {
+ return (fColorSettings != null) ? Arrays.copyOf(fColorSettings, fColorSettings.length) : null;
+ }
+
+ /**
+ * Sets the array of color settings.
+ *
+ * @param colorSettings A array of color settings to set
+ */
+ public static void setColorSettings(ColorSetting[] colorSettings) {
+ fColorSettings = (colorSettings != null) ? Arrays.copyOf(colorSettings, colorSettings.length) : null;
+ ColorSettingsXML.save(COLOR_SETTINGS_PATH_NAME, fColorSettings);
+ fireColorSettingsChanged();
+ }
+
+ /**
* Gets the color settings that matches the filter for given event.
*
* @param event
@@ -85,69 +85,69 @@ public class ColorSettingsManager {
* @return color settings defined for filter if found else default color
* settings
*/
- public static ColorSetting getColorSetting(ITmfEvent event) {
+ public static ColorSetting getColorSetting(ITmfEvent event) {
for (int i = 0; i < fColorSettings.length; i++) {
- ColorSetting colorSetting = fColorSettings[i];
- if (colorSetting.getFilter() != null && colorSetting.getFilter().matches(event)) {
- return colorSetting;
- }
+ ColorSetting colorSetting = fColorSettings[i];
+ if (colorSetting.getFilter() != null && colorSetting.getFilter().matches(event)) {
+ return colorSetting;
+ }
}
return DEFAULT_COLOR_SETTING;
- }
-
- /**
- * Gets the color settings priority for the given event.
- *
- * @param event A event the event to check
- * @return the priority defined for the filter else PRIORITY_NONE
- */
- public static int getColorSettingPriority(ITmfEvent event) {
+ }
+
+ /**
+ * Gets the color settings priority for the given event.
+ *
+ * @param event A event the event to check
+ * @return the priority defined for the filter else PRIORITY_NONE
+ */
+ public static int getColorSettingPriority(ITmfEvent event) {
for (int i = 0; i < fColorSettings.length; i++) {
- ColorSetting colorSetting = fColorSettings[i];
- if (colorSetting.getFilter() != null && colorSetting.getFilter().matches(event)) {
- return i;
- }
+ ColorSetting colorSetting = fColorSettings[i];
+ if (colorSetting.getFilter() != null && colorSetting.getFilter().matches(event)) {
+ return i;
+ }
}
return PRIORITY_NONE;
- }
-
- /**
- * Returns the color settings based the priority.
- *
- * @param priority A priority (index) of color settings
- * @return the color settings defined for the priority else default color settings
- */
- public static ColorSetting getColorSetting(int priority) {
- if (priority < fColorSettings.length) {
- return fColorSettings[priority];
- }
- return DEFAULT_COLOR_SETTING;
- }
-
- /**
- * Adds a color settings listener.
- *
- * @param listener A listener to add.
- */
- public static void addColorSettingsListener(IColorSettingsListener listener) {
- if (! fListeners.contains(listener)) {
- fListeners.add(listener);
- }
- }
-
- /**
- * Removes a color settings listener.
- *
- * @param listener A listener to remove.
- */
- public static void removeColorSettingsListener(IColorSettingsListener listener) {
- fListeners.remove(listener);
- }
-
- // Notify listeners
- private static void fireColorSettingsChanged() {
- for (IColorSettingsListener listener : fListeners) {
- listener.colorSettingsChanged(fColorSettings);
- }
- }
+ }
+
+ /**
+ * Returns the color settings based the priority.
+ *
+ * @param priority A priority (index) of color settings
+ * @return the color settings defined for the priority else default color settings
+ */
+ public static ColorSetting getColorSetting(int priority) {
+ if (priority < fColorSettings.length) {
+ return fColorSettings[priority];
+ }
+ return DEFAULT_COLOR_SETTING;
+ }
+
+ /**
+ * Adds a color settings listener.
+ *
+ * @param listener A listener to add.
+ */
+ public static void addColorSettingsListener(IColorSettingsListener listener) {
+ if (! fListeners.contains(listener)) {
+ fListeners.add(listener);
+ }
+ }
+
+ /**
+ * Removes a color settings listener.
+ *
+ * @param listener A listener to remove.
+ */
+ public static void removeColorSettingsListener(IColorSettingsListener listener) {
+ fListeners.remove(listener);
+ }
+
+ // Notify listeners
+ private static void fireColorSettingsChanged() {
+ for (IColorSettingsListener listener : fListeners) {
+ listener.colorSettingsChanged(fColorSettings);
+ }
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterManager.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterManager.java
index ac3671b525..db6b551de8 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterManager.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/filter/FilterManager.java
@@ -32,14 +32,14 @@ import org.xml.sax.SAXException;
*/
public class FilterManager {
- private static final String SAVED_FILTERS_FILE_NAME = "saved_filters.xml"; //$NON-NLS-1$
- private static final String SAVED_FILTERS_PATH_NAME =
+ private static final String SAVED_FILTERS_FILE_NAME = "saved_filters.xml"; //$NON-NLS-1$
+ private static final String SAVED_FILTERS_PATH_NAME =
Activator.getDefault().getStateLocation().addTrailingSeparator().append(SAVED_FILTERS_FILE_NAME).toString();
private static ITmfFilterTreeNode fRoot = new TmfFilterRootNode();
static {
- try {
- fRoot = new TmfFilterXMLParser(SAVED_FILTERS_PATH_NAME).getTree();
+ try {
+ fRoot = new TmfFilterXMLParser(SAVED_FILTERS_PATH_NAME).getTree();
} catch (FileNotFoundException e) {
} catch (SAXException e) {
Activator.getDefault().logError("Error parsing saved filter xml file: " + SAVED_FILTERS_PATH_NAME, e); //$NON-NLS-1$
@@ -54,7 +54,7 @@ public class FilterManager {
* @return The array of filters
*/
public static ITmfFilterTreeNode[] getSavedFilters() {
- return fRoot.clone().getChildren();
+ return fRoot.clone().getChildren();
}
/**
@@ -64,13 +64,13 @@ public class FilterManager {
* The filters to save
*/
public static void setSavedFilters(ITmfFilterTreeNode[] filters) {
- fRoot = new TmfFilterRootNode();
- for (ITmfFilterTreeNode filter : filters) {
- fRoot.addChild(filter.clone());
- }
- try {
- TmfFilterXMLWriter writerXML = new TmfFilterXMLWriter(fRoot);
- writerXML.saveTree(SAVED_FILTERS_PATH_NAME);
+ fRoot = new TmfFilterRootNode();
+ for (ITmfFilterTreeNode filter : filters) {
+ fRoot.addChild(filter.clone());
+ }
+ try {
+ TmfFilterXMLWriter writerXML = new TmfFilterXMLWriter(fRoot);
+ writerXML.saveTree(SAVED_FILTERS_PATH_NAME);
} catch (ParserConfigurationException e) {
Activator.getDefault().logError("Error saving filter xml file: " + SAVED_FILTERS_PATH_NAME, e); //$NON-NLS-1$
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisEntry.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisEntry.java
index 2275389f13..f2309ac626 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisEntry.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartAnalysisEntry.java
@@ -198,7 +198,7 @@ public class TimeChartAnalysisEntry implements ITimeGraphEntry {
if (event.getItemizedEntry() == null) {
event.merge((TimeChartEvent) timeEvent);
} else {
- event.mergeDecorations((TimeChartEvent) timeEvent);
+ event.mergeDecorations((TimeChartEvent) timeEvent);
event.getItemizedEntry().addTraceEvent(timeEvent);
}
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartDecorationProvider.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartDecorationProvider.java
index 7978eaabcf..7eaeb22b17 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartDecorationProvider.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartDecorationProvider.java
@@ -31,7 +31,7 @@ import org.eclipse.linuxtools.tmf.core.filter.ITmfFilter;
*/
public class TimeChartDecorationProvider {
- private final IFile fBookmarksFile;
+ private final IFile fBookmarksFile;
private final Set<Long> fBookmarksSet = new HashSet<>();
private ITmfFilter fFilterFilter;
private ITmfFilter fSearchFilter;
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartEvent.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartEvent.java
index 7520ec932a..9f12d2f9d8 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartEvent.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/timechart/TimeChartEvent.java
@@ -70,7 +70,7 @@ public class TimeChartEvent implements ITimeEvent {
fIsSearchMatch = decorationProvider.isSearchMatch(event);
}
- @Override
+ @Override
public ITimeGraphEntry getEntry() {
return fParentEntry;
}
@@ -119,7 +119,7 @@ public class TimeChartEvent implements ITimeEvent {
* The other event
*/
public void merge(TimeChartEvent event) {
- mergeDecorations(event);
+ mergeDecorations(event);
if (fTime == event.getTime() && fDuration == event.getDuration()) {
return;
}
@@ -131,7 +131,7 @@ public class TimeChartEvent implements ITimeEvent {
fNbEvents += event.fNbEvents;
fItemizedEntry = null;
synchronized (fRankRangeList) {
- fRankRangeList.merge(event.getRankRangeList());
+ fRankRangeList.merge(event.getRankRangeList());
}
}
@@ -145,8 +145,8 @@ public class TimeChartEvent implements ITimeEvent {
public void mergeDecorations(TimeChartEvent event) {
fColorSettingPriority = Math.min(fColorSettingPriority, event.getColorSettingPriority());
fIsBookmark |= event.fIsBookmark;
- fIsVisible |= event.fIsVisible;
- fIsSearchMatch |= event.fIsSearchMatch;
+ fIsVisible |= event.fIsVisible;
+ fIsSearchMatch |= event.fIsSearchMatch;
}
/**
@@ -165,7 +165,7 @@ public class TimeChartEvent implements ITimeEvent {
* @return The priority
*/
public int getColorSettingPriority() {
- return fColorSettingPriority;
+ return fColorSettingPriority;
}
/**
@@ -175,7 +175,7 @@ public class TimeChartEvent implements ITimeEvent {
* The priority to set
*/
public void setColorSettingPriority(int priority) {
- fColorSettingPriority = priority;
+ fColorSettingPriority = priority;
}
/**
@@ -184,7 +184,7 @@ public class TimeChartEvent implements ITimeEvent {
* @return Y/N
*/
public boolean isBookmarked() {
- return fIsBookmark;
+ return fIsBookmark;
}
/**
@@ -194,7 +194,7 @@ public class TimeChartEvent implements ITimeEvent {
* Should time time event become a bookmark, or not
*/
public void setIsBookmarked(boolean isBookmarked) {
- fIsBookmark = isBookmarked;
+ fIsBookmark = isBookmarked;
}
/**
@@ -203,7 +203,7 @@ public class TimeChartEvent implements ITimeEvent {
* @return If the event is visible
*/
public boolean isVisible() {
- return fIsVisible;
+ return fIsVisible;
}
/**
@@ -212,7 +212,7 @@ public class TimeChartEvent implements ITimeEvent {
* @param isVisible The new status
*/
public void setIsVisible(boolean isVisible) {
- fIsVisible = isVisible;
+ fIsVisible = isVisible;
}
/**
@@ -221,7 +221,7 @@ public class TimeChartEvent implements ITimeEvent {
* @return If it matches, Y/N
*/
public boolean isSearchMatch() {
- return fIsSearchMatch;
+ return fIsSearchMatch;
}
/**
@@ -231,7 +231,7 @@ public class TimeChartEvent implements ITimeEvent {
* The new matching status
*/
public void setIsSearchMatch(boolean isSearchMatch) {
- fIsSearchMatch = isSearchMatch;
+ fIsSearchMatch = isSearchMatch;
}
/**
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/core/LifelineCategories.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/core/LifelineCategories.java
index f0be1c24a7..7fd02a0625 100755
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/core/LifelineCategories.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/core/LifelineCategories.java
@@ -31,51 +31,51 @@ public class LifelineCategories {
// ------------------------------------------------------------------------
/**
- * The category name
- */
- private String fName = null;
- /**
- * The category image
- */
- private IImage fCategoryImage = null;
+ * The category name
+ */
+ private String fName = null;
+ /**
+ * The category image
+ */
+ private IImage fCategoryImage = null;
// ------------------------------------------------------------------------
// Methods
// ------------------------------------------------------------------------
- /**
- * Returns the category name.
- *
- * @return the category name
- */
- public String getName() {
- return fName;
- }
+ /**
+ * Returns the category name.
+ *
+ * @return the category name
+ */
+ public String getName() {
+ return fName;
+ }
- /**
- * Sets the category name.
- *
- * @param string the name
- */
- public void setName(String string) {
- fName = string;
- }
+ /**
+ * Sets the category name.
+ *
+ * @param string the name
+ */
+ public void setName(String string) {
+ fName = string;
+ }
- /**
- * Returns the category icon.
- *
- * @return the category icon
- */
- public IImage getImage() {
- return fCategoryImage;
- }
+ /**
+ * Returns the category icon.
+ *
+ * @return the category icon
+ */
+ public IImage getImage() {
+ return fCategoryImage;
+ }
- /**
- * Sets the category icon.
- *
- * @param image the icon
- */
- public void setImage(IImage image) {
- fCategoryImage = image;
- }
+ /**
+ * Sets the category icon.
+ *
+ * @param image the icon
+ */
+ public void setImage(IImage image) {
+ fCategoryImage = image;
+ }
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/dialogs/FilterListDialog.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/dialogs/FilterListDialog.java
index 6a1f4128bd..a5963e140b 100755
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/dialogs/FilterListDialog.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/dialogs/FilterListDialog.java
@@ -134,8 +134,8 @@ public class FilterListDialog extends Dialog {
}
/**
- * Handles table selection count.
- */
+ * Handles table selection count.
+ */
protected void handleTableSelectionCount() {
int count = fTable.getSelectionCount();
fEdit.setEnabled(count == 1);
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/dialogs/TabContents.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/dialogs/TabContents.java
index 98e5bf4efb..eb453783ee 100755
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/dialogs/TabContents.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/dialogs/TabContents.java
@@ -234,8 +234,8 @@ public class TabContents extends Composite {
}
/**
- * Updates parent OK button based on input data.
- */
+ * Updates parent OK button based on input data.
+ */
public void updateOkButton() {
if (fParentOkButton == null) {
return;
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/loader/TmfUml2SDSyncLoader.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/loader/TmfUml2SDSyncLoader.java
index c862498839..9ab09ac8b7 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/loader/TmfUml2SDSyncLoader.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/views/uml2sd/loader/TmfUml2SDSyncLoader.java
@@ -998,45 +998,45 @@ public class TmfUml2SDSyncLoader extends TmfComponent implements IUml2SDLoader,
protected void moveToMessageInPage() {
fLock.lock();
try {
- if (!fView.getSDWidget().isDisposed()) {
- // Check for GUI thread
- if(Display.getCurrent() != null) {
- // Already in GUI thread - execute directly
- TmfSyncMessage prevMessage = null;
- TmfSyncMessage syncMessage = null;
- boolean isExactTime = false;
- for (int i = 0; i < fFrame.syncMessageCount(); i++) {
- if (fFrame.getSyncMessage(i) instanceof TmfSyncMessage) {
- syncMessage = (TmfSyncMessage) fFrame.getSyncMessage(i);
- if (syncMessage.getStartTime().compareTo(fCurrentTime, false) == 0) {
- isExactTime = true;
- break;
- } else if ((syncMessage.getStartTime().compareTo(fCurrentTime, false) > 0) && (prevMessage != null)) {
- syncMessage = prevMessage;
- break;
- }
- prevMessage = syncMessage;
- }
- }
- if (fIsSelect && isExactTime) {
- fView.getSDWidget().moveTo(syncMessage);
- }
- else {
- fView.getSDWidget().ensureVisible(syncMessage);
- fView.getSDWidget().clearSelection();
- fView.getSDWidget().redraw();
- }
- }
- else {
- // Not in GUI thread - queue action in GUI thread.
- fView.getSDWidget().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- moveToMessageInPage();
- }
- });
- }
- }
+ if (!fView.getSDWidget().isDisposed()) {
+ // Check for GUI thread
+ if(Display.getCurrent() != null) {
+ // Already in GUI thread - execute directly
+ TmfSyncMessage prevMessage = null;
+ TmfSyncMessage syncMessage = null;
+ boolean isExactTime = false;
+ for (int i = 0; i < fFrame.syncMessageCount(); i++) {
+ if (fFrame.getSyncMessage(i) instanceof TmfSyncMessage) {
+ syncMessage = (TmfSyncMessage) fFrame.getSyncMessage(i);
+ if (syncMessage.getStartTime().compareTo(fCurrentTime, false) == 0) {
+ isExactTime = true;
+ break;
+ } else if ((syncMessage.getStartTime().compareTo(fCurrentTime, false) > 0) && (prevMessage != null)) {
+ syncMessage = prevMessage;
+ break;
+ }
+ prevMessage = syncMessage;
+ }
+ }
+ if (fIsSelect && isExactTime) {
+ fView.getSDWidget().moveTo(syncMessage);
+ }
+ else {
+ fView.getSDWidget().ensureVisible(syncMessage);
+ fView.getSDWidget().clearSelection();
+ fView.getSDWidget().redraw();
+ }
+ }
+ else {
+ // Not in GUI thread - queue action in GUI thread.
+ fView.getSDWidget().getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ moveToMessageInPage();
+ }
+ });
+ }
+ }
}
finally {
fLock.unlock();
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/rawviewer/TmfRawEventViewer.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/rawviewer/TmfRawEventViewer.java
index f4a8602445..9845fa09b7 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/rawviewer/TmfRawEventViewer.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/rawviewer/TmfRawEventViewer.java
@@ -78,97 +78,97 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
private Composite fTextArea;
private StyledText fStyledText;
private Font fFixedFont;
- private Slider fSlider;
-
- private final List<LineData> fLines = new ArrayList<>();
- private boolean fActualRanks = false;
- private int fTopLineIndex;
- private int fLastTopLineIndex;
- private final CaretPosition[] fStoredCaretPosition = new CaretPosition[]
- { new CaretPosition(0, 0), new CaretPosition(0,0)};
- private int fNumVisibleLines;
+ private Slider fSlider;
+
+ private final List<LineData> fLines = new ArrayList<>();
+ private boolean fActualRanks = false;
+ private int fTopLineIndex;
+ private int fLastTopLineIndex;
+ private final CaretPosition[] fStoredCaretPosition = new CaretPosition[]
+ { new CaretPosition(0, 0), new CaretPosition(0,0)};
+ private int fNumVisibleLines;
private ITmfLocation fSelectedLocation = null;
private long fHighlightedRank = Long.MIN_VALUE;
private int fCursorYCoordinate = -1;
private int fHoldSelection = 0;
- private static class LineData {
- long rank;
- ITmfLocation location;
- String string;
- public LineData(long rank, ITmfLocation location, String string) {
- this.rank = rank;
- this.location = location;
+ private static class LineData {
+ long rank;
+ ITmfLocation location;
+ String string;
+ public LineData(long rank, ITmfLocation location, String string) {
+ this.rank = rank;
+ this.location = location;
if (string.length() == 0) {
this.string = " "; // workaround for setLineBackground has no effect on empty line //$NON-NLS-1$
} else {
this.string = string;
}
- }
+ }
@Override
public String toString() {
return rank + " [" + location + "]: " + string; //$NON-NLS-1$ //$NON-NLS-2$
}
- }
-
- private static class CaretPosition {
- int time;
- int caretOffset;
- public CaretPosition(int time, int caretOffset) {
- this.time = time;
- this.caretOffset = caretOffset;
- }
- }
-
- // ------------------------------------------------------------------------
- // Constructor
- // ------------------------------------------------------------------------
-
- /**
- * Constructor
- * @param parent The parent composite
- * @param style The style bits
- */
- public TmfRawEventViewer(Composite parent, int style) {
- super(parent, style & (~SWT.H_SCROLL) & (~SWT.V_SCROLL));
-
- // Set the layout
- GridLayout gridLayout = new GridLayout();
- gridLayout.numColumns = 2;
- gridLayout.horizontalSpacing = 0;
- gridLayout.verticalSpacing = 0;
+ }
+
+ private static class CaretPosition {
+ int time;
+ int caretOffset;
+ public CaretPosition(int time, int caretOffset) {
+ this.time = time;
+ this.caretOffset = caretOffset;
+ }
+ }
+
+ // ------------------------------------------------------------------------
+ // Constructor
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor
+ * @param parent The parent composite
+ * @param style The style bits
+ */
+ public TmfRawEventViewer(Composite parent, int style) {
+ super(parent, style & (~SWT.H_SCROLL) & (~SWT.V_SCROLL));
+
+ // Set the layout
+ GridLayout gridLayout = new GridLayout();
+ gridLayout.numColumns = 2;
+ gridLayout.horizontalSpacing = 0;
+ gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
- setLayout(gridLayout);
+ setLayout(gridLayout);
- // Create the controls
- createTextArea(style & SWT.H_SCROLL);
- createSlider(style & SWT.V_SCROLL);
+ // Create the controls
+ createTextArea(style & SWT.H_SCROLL);
+ createSlider(style & SWT.V_SCROLL);
- // Prevent the slider from being traversed
- setTabList(new Control[] { fScrolledComposite });
- }
+ // Prevent the slider from being traversed
+ setTabList(new Control[] { fScrolledComposite });
+ }
@Override
- public void dispose() {
+ public void dispose() {
if (fFixedFont != null) {
fFixedFont.dispose();
fFixedFont = null;
}
- super.dispose();
- }
+ super.dispose();
+ }
- // ------------------------------------------------------------------------
- // Text area handling
- // ------------------------------------------------------------------------
+ // ------------------------------------------------------------------------
+ // Text area handling
+ // ------------------------------------------------------------------------
/**
- * Create the text area and add listeners
- */
- private void createTextArea(int style) {
- fScrolledComposite = new ScrolledComposite(this, style);
- fScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- fTextArea = new Composite(fScrolledComposite, SWT.NONE);
+ * Create the text area and add listeners
+ */
+ private void createTextArea(int style) {
+ fScrolledComposite = new ScrolledComposite(this, style);
+ fScrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ fTextArea = new Composite(fScrolledComposite, SWT.NONE);
fTextArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
fScrolledComposite.setContent(fTextArea);
fScrolledComposite.setExpandHorizontal(true);
@@ -205,38 +205,38 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
fTextArea.setBackground(fStyledText.getBackground());
fTextArea.addMouseListener(new MouseAdapter() {
- @Override
+ @Override
public void mouseDown(MouseEvent e) {
- fTextArea.setFocus();
+ fTextArea.setFocus();
}});
- }
+ }
- // ------------------------------------------------------------------------
- // Slider handling
- // ------------------------------------------------------------------------
+ // ------------------------------------------------------------------------
+ // Slider handling
+ // ------------------------------------------------------------------------
- private void createSlider(int style) {
- fSlider = new Slider(this, SWT.VERTICAL);
+ private void createSlider(int style) {
+ fSlider = new Slider(this, SWT.VERTICAL);
fSlider.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true));
fSlider.setValues(0, 0, SLIDER_MAX, SLIDER_MAX, 1, 1);
- fSlider.addSelectionListener(this);
+ fSlider.addSelectionListener(this);
if ((style & SWT.V_SCROLL) == 0) {
fSlider.setVisible(false);
}
- }
+ }
- // ------------------------------------------------------------------------
- // Controls interactions
- // ------------------------------------------------------------------------
+ // ------------------------------------------------------------------------
+ // Controls interactions
+ // ------------------------------------------------------------------------
- @Override
- public boolean setFocus() {
- boolean isVisible = isVisible();
- if (isVisible) {
- fTextArea.setFocus();
- }
- return isVisible;
- }
+ @Override
+ public boolean setFocus() {
+ boolean isVisible = isVisible();
+ if (isVisible) {
+ fTextArea.setFocus();
+ }
+ return isVisible;
+ }
@Override
public void setMenu(Menu menu) {
@@ -248,48 +248,48 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
* @param trace The trace to set
*/
public void setTrace(ITmfTrace trace) {
- fTrace = trace;
- fTopLineIndex = 0;
- fLines.clear();
- refreshEventCount();
- }
+ fTrace = trace;
+ fTopLineIndex = 0;
+ fLines.clear();
+ refreshEventCount();
+ }
/**
* Refreshes the event count, updates the slider thumb and loads display
*/
- public void refreshEventCount() {
- if (fTrace != null) {
- if (fTrace.getNbEvents() > 0) {
- fSlider.setThumb((int) Math.max(SLIDER_MAX / fTrace.getNbEvents(), 1));
- } else {
- fSlider.setThumb(SLIDER_MAX);
- }
-
- if (!isVisible()) {
+ public void refreshEventCount() {
+ if (fTrace != null) {
+ if (fTrace.getNbEvents() > 0) {
+ fSlider.setThumb((int) Math.max(SLIDER_MAX / fTrace.getNbEvents(), 1));
+ } else {
+ fSlider.setThumb(SLIDER_MAX);
+ }
+
+ if (!isVisible()) {
return;
}
- if (fLines.size() == 0) {
- setTopRank(0);
- } else if (fLines.size() < fNumVisibleLines) {
- fBottomContext = null;
- loadLineData();
- fillTextArea();
- //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents())));
- fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location)));
- }
+ if (fLines.size() == 0) {
+ setTopRank(0);
+ } else if (fLines.size() < fNumVisibleLines) {
+ fBottomContext = null;
+ loadLineData();
+ fillTextArea();
+ //fSlider.setSelection((int) (SLIDER_MAX * ((double) fLines.get(fTopLineIndex).rank / fTrace.getNbEvents())));
+ fSlider.setSelection((int) (SLIDER_MAX * fTrace.getLocationRatio(fLines.get(fTopLineIndex).location)));
+ }
} else {
fBottomContext = null;
fillTextArea();
fSlider.setThumb(SLIDER_MAX);
fSlider.setSelection(0);
- }
- }
+ }
+ }
- /**
- * Selects the event of given rank and makes it visible.
- * @param rank The rank of event
- */
+ /**
+ * Selects the event of given rank and makes it visible.
+ * @param rank The rank of event
+ */
public void selectAndReveal(long rank) {
if (fTrace == null || !isVisible()) {
return;
@@ -379,7 +379,7 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
refreshTextArea();
}
- private void loadLineData() {
+ private void loadLineData() {
if (fTopLineIndex < 0) {
//if (fLines.size() > 0 && fLines.get(0).rank > 0) {
//long endRank = fLines.get(0).rank;
@@ -401,7 +401,7 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
//}
//}
if (fLines.size() > 0 && fTrace.getLocationRatio(fLines.get(0).location) > 0) {
- double lastRatio = fTrace.getLocationRatio(fLines.get(fLines.size() - 1).location);
+ double lastRatio = fTrace.getLocationRatio(fLines.get(fLines.size() - 1).location);
double firstRatio = fTrace.getLocationRatio(fLines.get(0).location);
double delta;
boolean singleEvent = false;
@@ -423,7 +423,7 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
location = context.getLocation();
ITmfEvent event = fTrace.getNext(context);
if (event == null) {
- break;
+ break;
}
if (event.getContent() != null && event.getContent().getValue() != null) {
String[] lines = event.getContent().getValue().toString().split("\r?\n"); //$NON-NLS-1$
@@ -450,7 +450,7 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
break;
}
if (singleEvent) {
- delta = Math.min(delta * 10, 0.1);
+ delta = Math.min(delta * 10, 0.1);
}
}
}
@@ -459,19 +459,19 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
}
}
- while (fLines.size() - fTopLineIndex < fNumVisibleLines) {
- if (fBottomContext == null) {
- if (fLines.size() == 0) {
- fBottomContext = fTrace.seekEvent(0);
- } else {
+ while (fLines.size() - fTopLineIndex < fNumVisibleLines) {
+ if (fBottomContext == null) {
+ if (fLines.size() == 0) {
+ fBottomContext = fTrace.seekEvent(0);
+ } else {
//fBottomContext = fTrace.seekEvent(fLines.get(fLines.size() - 1).rank + 1);
- fBottomContext = fTrace.seekEvent(fLines.get(fLines.size() - 1).location);
- fTrace.getNext(fBottomContext);
- }
- if (fBottomContext == null) {
- break;
- }
- }
+ fBottomContext = fTrace.seekEvent(fLines.get(fLines.size() - 1).location);
+ fTrace.getNext(fBottomContext);
+ }
+ if (fBottomContext == null) {
+ break;
+ }
+ }
long rank = fBottomContext.getRank();
ITmfLocation location = fBottomContext.getLocation() != null ? fBottomContext.getLocation() : null;
ITmfEvent event = fTrace.getNext(fBottomContext);
@@ -482,7 +482,7 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
for (String line : event.getContent().getValue().toString().split("\r?\n")) { //$NON-NLS-1$
int crPos;
if ((crPos = line.indexOf('\r')) != -1) {
- line = line.substring(0, crPos);
+ line = line.substring(0, crPos);
}
LineData lineData = new LineData(rank, location, line);
fLines.add(lineData);
@@ -491,32 +491,32 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
LineData lineData = new LineData(rank, location, ""); //$NON-NLS-1$
fLines.add(lineData);
}
- }
- fTopLineIndex = Math.max(0, Math.min(fTopLineIndex, fLines.size() - 1));
-
- if (fLines.size() > MAX_LINE_DATA_SIZE) {
- if (fTopLineIndex < MAX_LINE_DATA_SIZE / 2) {
- long rank = fLines.get(MAX_LINE_DATA_SIZE - 1).rank;
- for (int i = MAX_LINE_DATA_SIZE; i < fLines.size(); i++) {
- if (fLines.get(i).rank > rank) {
- fLines.subList(i, fLines.size()).clear();
- fBottomContext = null;
- break;
- }
- }
- } else {
- long rank = fLines.get(fLines.size() - MAX_LINE_DATA_SIZE).rank;
- for (int i = fLines.size() - MAX_LINE_DATA_SIZE - 1; i >= 0; i--) {
+ }
+ fTopLineIndex = Math.max(0, Math.min(fTopLineIndex, fLines.size() - 1));
+
+ if (fLines.size() > MAX_LINE_DATA_SIZE) {
+ if (fTopLineIndex < MAX_LINE_DATA_SIZE / 2) {
+ long rank = fLines.get(MAX_LINE_DATA_SIZE - 1).rank;
+ for (int i = MAX_LINE_DATA_SIZE; i < fLines.size(); i++) {
+ if (fLines.get(i).rank > rank) {
+ fLines.subList(i, fLines.size()).clear();
+ fBottomContext = null;
+ break;
+ }
+ }
+ } else {
+ long rank = fLines.get(fLines.size() - MAX_LINE_DATA_SIZE).rank;
+ for (int i = fLines.size() - MAX_LINE_DATA_SIZE - 1; i >= 0; i--) {
if (fLines.get(i).rank < rank) {
fLines.subList(0, i + 1).clear();
fTopLineIndex -= (i + 1);
fLastTopLineIndex -= (i + 1);
break;
}
- }
- }
- }
- }
+ }
+ }
+ }
+ }
private void refreshTextArea() {
fStyledText.setText(""); //$NON-NLS-1$
@@ -547,60 +547,60 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
}
int endLine = Math.min(fNumVisibleLines, fLines.size());
if (endLine < fStyledText.getLineCount()) {
- int endOffset = fStyledText.getOffsetAtLine(endLine) - 1;
- if (endOffset > fStyledText.getCharCount()) {
+ int endOffset = fStyledText.getOffsetAtLine(endLine) - 1;
+ if (endOffset > fStyledText.getCharCount()) {
fHoldSelection++;
- fStyledText.replaceTextRange(endOffset, fStyledText.getCharCount() - endOffset, ""); //$NON-NLS-1$
+ fStyledText.replaceTextRange(endOffset, fStyledText.getCharCount() - endOffset, ""); //$NON-NLS-1$
fHoldSelection--;
- }
+ }
}
fTextArea.layout();
fScrolledComposite.setMinSize(fTextArea.computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
- private void updateTextArea() {
- if (fTopLineIndex < fLastTopLineIndex) {
- StringBuffer insertedText = new StringBuffer();
- for (int i = fTopLineIndex; i < fLastTopLineIndex; i++) {
- insertedText.append(fLines.get(i).string + "\n"); //$NON-NLS-1$
- }
- fStyledText.replaceTextRange(0, 0, insertedText.toString());
+ private void updateTextArea() {
+ if (fTopLineIndex < fLastTopLineIndex) {
+ StringBuffer insertedText = new StringBuffer();
+ for (int i = fTopLineIndex; i < fLastTopLineIndex; i++) {
+ insertedText.append(fLines.get(i).string + "\n"); //$NON-NLS-1$
+ }
+ fStyledText.replaceTextRange(0, 0, insertedText.toString());
for (int i = 0; i < fLastTopLineIndex - fTopLineIndex; i++) {
LineData lineData = fLines.get(fTopLineIndex + i);
setLineBackground(i, lineData);
}
- fLastTopLineIndex = fTopLineIndex;
- } else if (fTopLineIndex > fLastTopLineIndex) {
- int length = 0;
- for (int i = 0; i < fTopLineIndex - fLastTopLineIndex && i < fNumVisibleLines; i++) {
- length += fLines.get(i + fLastTopLineIndex).string.length();
- if (i < fStyledText.getLineCount()) {
+ fLastTopLineIndex = fTopLineIndex;
+ } else if (fTopLineIndex > fLastTopLineIndex) {
+ int length = 0;
+ for (int i = 0; i < fTopLineIndex - fLastTopLineIndex && i < fNumVisibleLines; i++) {
+ length += fLines.get(i + fLastTopLineIndex).string.length();
+ if (i < fStyledText.getLineCount()) {
length += 1;
}
- }
- fStyledText.replaceTextRange(0, length, ""); //$NON-NLS-1$
+ }
+ fStyledText.replaceTextRange(0, length, ""); //$NON-NLS-1$
fLastTopLineIndex = fTopLineIndex;
fillTextArea();
- }
+ }
int endLine = Math.min(fNumVisibleLines, fLines.size());
if (endLine < fStyledText.getLineCount()) {
- int endOffset = fStyledText.getOffsetAtLine(endLine) - 1;
- if (endOffset > fStyledText.getCharCount()) {
- fStyledText.replaceTextRange(endOffset, fStyledText.getCharCount() - endOffset, ""); //$NON-NLS-1$
- }
+ int endOffset = fStyledText.getOffsetAtLine(endLine) - 1;
+ if (endOffset > fStyledText.getCharCount()) {
+ fStyledText.replaceTextRange(endOffset, fStyledText.getCharCount() - endOffset, ""); //$NON-NLS-1$
+ }
}
- fTextArea.layout();
- fScrolledComposite.setMinSize(fTextArea.computeSize(SWT.DEFAULT, SWT.DEFAULT));
- }
+ fTextArea.layout();
+ fScrolledComposite.setMinSize(fTextArea.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+ }
- private void refreshLineBackgrounds() {
+ private void refreshLineBackgrounds() {
for (int i = 0; (i < fStyledText.getLineCount()) && (i < fNumVisibleLines) && (i < fLines.size() - fTopLineIndex); i++) {
LineData lineData = fLines.get(fTopLineIndex + i);
setLineBackground(i, lineData);
}
- }
+ }
- private void setLineBackground(int index, LineData lineData) {
+ private void setLineBackground(int index, LineData lineData) {
if (lineData.location.equals(fSelectedLocation)) {
fStyledText.setLineBackground(index, 1, COLOR_BACKGROUND_SELECTED);
} else if (lineData.rank == fHighlightedRank) {
@@ -610,25 +610,25 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
} else {
fStyledText.setLineBackground(index, 1, COLOR_BACKGROUND_ODD);
}
- }
-
- private void storeCaretPosition(int time, int caretOffset) {
- if (fStoredCaretPosition[0].time == time) {
- fStoredCaretPosition[0].caretOffset = caretOffset;
- } else {
- fStoredCaretPosition[1] = fStoredCaretPosition[0];
- fStoredCaretPosition[0] = new CaretPosition(time, caretOffset);
- }
- }
-
- private int getPreviousCaretOffset(int time) {
- if (fStoredCaretPosition[0].time == time) {
- return fStoredCaretPosition[1].caretOffset;
- }
+ }
+
+ private void storeCaretPosition(int time, int caretOffset) {
+ if (fStoredCaretPosition[0].time == time) {
+ fStoredCaretPosition[0].caretOffset = caretOffset;
+ } else {
+ fStoredCaretPosition[1] = fStoredCaretPosition[0];
+ fStoredCaretPosition[0] = new CaretPosition(time, caretOffset);
+ }
+ }
+
+ private int getPreviousCaretOffset(int time) {
+ if (fStoredCaretPosition[0].time == time) {
+ return fStoredCaretPosition[1].caretOffset;
+ }
return fStoredCaretPosition[0].caretOffset;
- }
+ }
- private void updateHighlightedRank() {
+ private void updateHighlightedRank() {
if (fCursorYCoordinate < 0 || fCursorYCoordinate > fStyledText.getSize().y) {
if (fHighlightedRank != Long.MIN_VALUE) {
fHighlightedRank = Long.MIN_VALUE;
@@ -650,7 +650,7 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
refreshLineBackgrounds();
}
}
- }
+ }
// ------------------------------------------------------------------------
// ControlListener (ScrolledComposite)
@@ -681,7 +681,7 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
@Override
public void widgetSelected(SelectionEvent e) {
- fTextArea.setFocus();
+ fTextArea.setFocus();
if (fLines.size() == 0) {
return;
}
@@ -693,11 +693,11 @@ public class TmfRawEventViewer extends Composite implements ControlListener, Sel
case SWT.NONE: {
//long rank = (long) (fTrace.getNbEvents() * ((double) fSlider.getSelection() / SLIDER_MAX));
//setTopRank(rank);
- if (fSlider.getSelection() == 0 || fSlider.getThumb() == SLIDER_MAX) {
+ if (fSlider.getSelection() == 0 || fSlider.getThumb() == SLIDER_MAX) {
fLines.clear();
setTopPosition(0.0);
break;
- }
+ }
double ratio = (double) fSlider.getSelection() / (SLIDER_MAX - fSlider.getThumb());
double delta = Math.pow(10, -15);
fLines.clear();
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/IDoubleClickListener.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/IDoubleClickListener.java
index afa994b23e..a11152dd31 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/IDoubleClickListener.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/IDoubleClickListener.java
@@ -19,12 +19,12 @@ import org.eclipse.swt.widgets.TableItem;
*/
public interface IDoubleClickListener {
- /**
- * Handle a double click event
- * @param table the table that was double clicked
- * @param item the item that was double clicked in the table
- * @param column the column that was double clicked in the item in the table.
- */
- void handleDoubleClick(TmfVirtualTable table, TableItem item, int column);
+ /**
+ * Handle a double click event
+ * @param table the table that was double clicked
+ * @param item the item that was double clicked in the table
+ * @param column the column that was double clicked in the item in the table.
+ */
+ void handleDoubleClick(TmfVirtualTable table, TableItem item, int column);
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/TmfVirtualTable.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/TmfVirtualTable.java
index c73c07ffe1..0940ac13d6 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/TmfVirtualTable.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/TmfVirtualTable.java
@@ -700,7 +700,7 @@ public class TmfVirtualTable extends Composite {
/**
* Method setItemCount
* @param nbItems int the number of items in the table
- *
+ *
*/
public void setItemCount(int nbItems) {
final int nb = Math.max(0, nbItems);
@@ -1069,7 +1069,7 @@ public class TmfVirtualTable extends Composite {
/**
* @return the tooltipProvider
- */
+ */
public TooltipProvider getTooltipProvider() {
return tooltipProvider;
}
@@ -1083,7 +1083,7 @@ public class TmfVirtualTable extends Composite {
/**
* @return the doubleClickListener
- */
+ */
public IDoubleClickListener getDoubleClickListener() {
return doubleClickListener;
}
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/TooltipProvider.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/TooltipProvider.java
index 2f451f60d7..5ccfc9be81 100644
--- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/TooltipProvider.java
+++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/virtualtable/TooltipProvider.java
@@ -18,12 +18,12 @@ package org.eclipse.linuxtools.tmf.ui.widgets.virtualtable;
*/
public interface TooltipProvider {
- /**
- * get a Tooltip for a given column in a table row. (a cell if you will)
- * @param column the column
- * @param data the object being selected. (quite often a "TableItem")
- * @return the string of text to display in the tooltip.
- */
- String getTooltip(int column, Object data);
+ /**
+ * get a Tooltip for a given column in a table row. (a cell if you will)
+ * @param column the column
+ * @param data the object being selected. (quite often a "TableItem")
+ * @return the string of text to display in the tooltip.
+ */
+ String getTooltip(int column, Object data);
}
diff --git a/lttng/org.eclipse.linuxtools.tmf/pom.xml b/lttng/org.eclipse.linuxtools.tmf/pom.xml
index 1183753660..e6737f5e66 100644
--- a/lttng/org.eclipse.linuxtools.tmf/pom.xml
+++ b/lttng/org.eclipse.linuxtools.tmf/pom.xml
@@ -24,7 +24,7 @@
<name>Linux Tools TMF (Tracing and Monitoring Framework) Feature</name>
<groupId>org.eclipse.linuxtools.tmf</groupId>
-
+
<build>
<plugins>
<plugin>
diff --git a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/Activator.java b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/Activator.java
index 509771dcc1..33e6b5f67e 100644
--- a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/Activator.java
+++ b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/Activator.java
@@ -18,45 +18,45 @@ import org.osgi.framework.BundleContext;
*/
public class Activator extends AbstractUIPlugin {
- /** The plug-in ID */
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.man"; //$NON-NLS-1$
-
- // The shared instance
- private static Activator plugin;
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
- * )
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
- * )
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
+ /** The plug-in ID */
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.man"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
+ * )
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
}
diff --git a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/parser/ManDocument.java b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/parser/ManDocument.java
index 98f3102543..73253fc202 100644
--- a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/parser/ManDocument.java
+++ b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/parser/ManDocument.java
@@ -21,50 +21,50 @@ import org.eclipse.jface.text.Document;
// TODO consider bold and underline symbols to handle ranges.
public class ManDocument extends Document {
- private static final String BOLD = "\b"; //$NON-NLS-1$
- private List<Integer> boldSymbols = new ArrayList<>();
- private List<Integer> underlineSymbols = new ArrayList<>();
+ private static final String BOLD = "\b"; //$NON-NLS-1$
+ private List<Integer> boldSymbols = new ArrayList<>();
+ private List<Integer> underlineSymbols = new ArrayList<>();
- /**
- * Creates an IDocument for the given man page and taking care for marking
- * bold and underline symbols.
- *
- * @param manPage
- * The man page to create document for.
- */
- public ManDocument(String manPage) {
- StringBuilder sb = new ManParser().getRawManPage(manPage);
- while (sb.indexOf(BOLD) != -1) {
- int index = sb.indexOf(BOLD);
- if (sb.charAt(index - 1) == '_') {
- sb.replace(index - 1, index + 2,
- sb.substring(index + 1, index + 2));
- underlineSymbols.add(index - 1);
- } else {
- sb.replace(index - 1, index + 1,
- sb.substring(index - 1, index - 1));
- boldSymbols.add(index - 1);
- }
- }
- set(sb.toString());
+ /**
+ * Creates an IDocument for the given man page and taking care for marking
+ * bold and underline symbols.
+ *
+ * @param manPage
+ * The man page to create document for.
+ */
+ public ManDocument(String manPage) {
+ StringBuilder sb = new ManParser().getRawManPage(manPage);
+ while (sb.indexOf(BOLD) != -1) {
+ int index = sb.indexOf(BOLD);
+ if (sb.charAt(index - 1) == '_') {
+ sb.replace(index - 1, index + 2,
+ sb.substring(index + 1, index + 2));
+ underlineSymbols.add(index - 1);
+ } else {
+ sb.replace(index - 1, index + 1,
+ sb.substring(index - 1, index - 1));
+ boldSymbols.add(index - 1);
+ }
+ }
+ set(sb.toString());
- }
+ }
- /**
- * Returns the indexes of bold symbols.
- *
- * @return List of bold symbols.
- */
- public List<Integer> getBoldSymbols() {
- return boldSymbols;
- }
+ /**
+ * Returns the indexes of bold symbols.
+ *
+ * @return List of bold symbols.
+ */
+ public List<Integer> getBoldSymbols() {
+ return boldSymbols;
+ }
- /**
- * Returns the indexes of underline symbols.
- *
- * @return List of underline symbols.
- */
- public List<Integer> getUnderlinedSymbols() {
- return underlineSymbols;
- }
+ /**
+ * Returns the indexes of underline symbols.
+ *
+ * @return List of underline symbols.
+ */
+ public List<Integer> getUnderlinedSymbols() {
+ return underlineSymbols;
+ }
}
diff --git a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/parser/ManParser.java b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/parser/ManParser.java
index ff5fde659a..fbd5d8b08b 100644
--- a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/parser/ManParser.java
+++ b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/parser/ManParser.java
@@ -22,45 +22,45 @@ import org.eclipse.linuxtools.internal.man.preferences.PreferenceConstants;
/**
* Parser for the man executable output.
- *
+ *
*/
public class ManParser {
- /**
- * Returns the raw representation of the man executable for a given man page
- * i.e. `man ls`.
- *
- * @param manPage
- * The man page to fetch.
- * @return Raw output of the man command.
- */
- public StringBuilder getRawManPage(String manPage) {
- String manExecutable = Activator.getDefault().getPreferenceStore()
- .getString(PreferenceConstants.P_PATH);
- ProcessBuilder builder = new ProcessBuilder(manExecutable, manPage);
- builder.redirectErrorStream(true);
- Process process;
- StringBuilder sb = new StringBuilder();
- try {
- process = builder.start();
- if (!(System.getProperty("os.name").toLowerCase() //$NON-NLS-1$
- .indexOf("windows") == 0)) { //$NON-NLS-1$
- process.waitFor();
- }
+ /**
+ * Returns the raw representation of the man executable for a given man page
+ * i.e. `man ls`.
+ *
+ * @param manPage
+ * The man page to fetch.
+ * @return Raw output of the man command.
+ */
+ public StringBuilder getRawManPage(String manPage) {
+ String manExecutable = Activator.getDefault().getPreferenceStore()
+ .getString(PreferenceConstants.P_PATH);
+ ProcessBuilder builder = new ProcessBuilder(manExecutable, manPage);
+ builder.redirectErrorStream(true);
+ Process process;
+ StringBuilder sb = new StringBuilder();
+ try {
+ process = builder.start();
+ if (!(System.getProperty("os.name").toLowerCase() //$NON-NLS-1$
+ .indexOf("windows") == 0)) { //$NON-NLS-1$
+ process.waitFor();
+ }
- String line = null;
- try (InputStream manContent = process.getInputStream();
- BufferedReader reader = new BufferedReader(
- new InputStreamReader(manContent))) {
- while ((line = reader.readLine()) != null) {
- sb.append(line + "\n"); //$NON-NLS-1$
- }
- }
- } catch (IOException | InterruptedException e1) {
- Status status = new Status(IStatus.ERROR, e1.getMessage(),
- Activator.PLUGIN_ID);
- Activator.getDefault().getLog().log(status);
- }
- return sb;
- }
+ String line = null;
+ try (InputStream manContent = process.getInputStream();
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(manContent))) {
+ while ((line = reader.readLine()) != null) {
+ sb.append(line + "\n"); //$NON-NLS-1$
+ }
+ }
+ } catch (IOException | InterruptedException e1) {
+ Status status = new Status(IStatus.ERROR, e1.getMessage(),
+ Activator.PLUGIN_ID);
+ Activator.getDefault().getLog().log(status);
+ }
+ return sb;
+ }
}
diff --git a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/ManPathPage.java b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/ManPathPage.java
index fecb8c94ed..f49a11e48f 100644
--- a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/ManPathPage.java
+++ b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/ManPathPage.java
@@ -21,37 +21,37 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
*/
public class ManPathPage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
+ IWorkbenchPreferencePage {
- /**
- * Preference page for setting the man path.
- */
- public ManPathPage() {
- super(GRID);
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- setDescription(Messages.ManPathPage_0);
- }
+ /**
+ * Preference page for setting the man path.
+ */
+ public ManPathPage() {
+ super(GRID);
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ setDescription(Messages.ManPathPage_0);
+ }
- /**
- * Creates the field editors. Field editors are abstractions of the common
- * GUI blocks needed to manipulate various types of preferences. Each field
- * editor knows how to save and restore itself.
- */
- @Override
- public void createFieldEditors() {
- addField(new FileFieldEditor(PreferenceConstants.P_PATH,
- Messages.ManPathPage_1, getFieldEditorParent()));
- }
+ /**
+ * Creates the field editors. Field editors are abstractions of the common
+ * GUI blocks needed to manipulate various types of preferences. Each field
+ * editor knows how to save and restore itself.
+ */
+ @Override
+ public void createFieldEditors() {
+ addField(new FileFieldEditor(PreferenceConstants.P_PATH,
+ Messages.ManPathPage_1, getFieldEditorParent()));
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- @Override
- public void init(IWorkbench workbench) {
- // nothing to do
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
+ */
+ @Override
+ public void init(IWorkbench workbench) {
+ // nothing to do
+ }
} \ No newline at end of file
diff --git a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/Messages.java b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/Messages.java
index 7d757fd84e..2e82c542b3 100644
--- a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/Messages.java
+++ b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/Messages.java
@@ -14,23 +14,23 @@ import org.eclipse.osgi.util.NLS;
/**
* Message constants.
- *
+ *
*/
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.man.preferences.messages"; //$NON-NLS-1$
- /**
- * Preference page title.
- */
- public static String ManPathPage_0;
- /**
- * Preference page label.
- */
- public static String ManPathPage_1;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.man.preferences.messages"; //$NON-NLS-1$
+ /**
+ * Preference page title.
+ */
+ public static String ManPathPage_0;
+ /**
+ * Preference page label.
+ */
+ public static String ManPathPage_1;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/PreferenceConstants.java b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/PreferenceConstants.java
index 12cbcdbc37..2f2a1dcd18 100644
--- a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/PreferenceConstants.java
+++ b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/PreferenceConstants.java
@@ -15,9 +15,9 @@ package org.eclipse.linuxtools.internal.man.preferences;
*/
public class PreferenceConstants {
- /**
- * Path preference constant.
- */
- public static final String P_PATH = "pathPreference"; //$NON-NLS-1$
+ /**
+ * Path preference constant.
+ */
+ public static final String P_PATH = "pathPreference"; //$NON-NLS-1$
}
diff --git a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/PreferenceInitializer.java b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/PreferenceInitializer.java
index 92075141c2..ddaf08d97d 100644
--- a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/PreferenceInitializer.java
+++ b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/preferences/PreferenceInitializer.java
@@ -19,16 +19,16 @@ import org.eclipse.linuxtools.internal.man.Activator;
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
- /*
- * (non-Javadoc)
- *
- * @seeorg.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#
- * initializeDefaultPreferences()
- */
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = Activator.getDefault().getPreferenceStore();
- store.setDefault(PreferenceConstants.P_PATH, "/usr/bin/man"); //$NON-NLS-1$
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @seeorg.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#
+ * initializeDefaultPreferences()
+ */
+ @Override
+ public void initializeDefaultPreferences() {
+ IPreferenceStore store = Activator.getDefault().getPreferenceStore();
+ store.setDefault(PreferenceConstants.P_PATH, "/usr/bin/man"); //$NON-NLS-1$
+ }
}
diff --git a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/views/ManTextViewer.java b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/views/ManTextViewer.java
index 9480fb8fcd..208fbef6fc 100644
--- a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/views/ManTextViewer.java
+++ b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/internal/man/views/ManTextViewer.java
@@ -19,42 +19,42 @@ import org.eclipse.swt.widgets.Composite;
/**
* Text viewer for a man page.
- *
+ *
*/
public class ManTextViewer extends SourceViewer {
- /**
- * Creates a resizable text viewer.
- *
- * @param parent
- */
- public ManTextViewer(Composite parent) {
- super(parent, null, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- // setEditable(false);
- }
+ /**
+ * Creates a resizable text viewer.
+ *
+ * @param parent
+ */
+ public ManTextViewer(Composite parent) {
+ super(parent, null, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
+ // setEditable(false);
+ }
- /**
- * Sets the document to display.
- *
- * @param document
- * The document to display.
- */
- public void setDocument(ManDocument document) {
- super.setDocument(document);
- TextPresentation style = new TextPresentation();
- for (int underlineSymbol : document.getUnderlinedSymbols()) {
- StyleRange styleRange = new StyleRange(underlineSymbol, 1, null,
- null, SWT.NORMAL);
- styleRange.underline = true;
- style.addStyleRange(styleRange);
- }
- for (int boldSymbol : document.getBoldSymbols()) {
- style.mergeStyleRange(new StyleRange(boldSymbol, 1, null, null,
- SWT.BOLD));
- }
- getTextWidget().setBackground(
- getControl().getDisplay().getSystemColor(SWT.COLOR_GRAY));
- changeTextPresentation(style, true);
- }
+ /**
+ * Sets the document to display.
+ *
+ * @param document
+ * The document to display.
+ */
+ public void setDocument(ManDocument document) {
+ super.setDocument(document);
+ TextPresentation style = new TextPresentation();
+ for (int underlineSymbol : document.getUnderlinedSymbols()) {
+ StyleRange styleRange = new StyleRange(underlineSymbol, 1, null,
+ null, SWT.NORMAL);
+ styleRange.underline = true;
+ style.addStyleRange(styleRange);
+ }
+ for (int boldSymbol : document.getBoldSymbols()) {
+ style.mergeStyleRange(new StyleRange(boldSymbol, 1, null, null,
+ SWT.BOLD));
+ }
+ getTextWidget().setBackground(
+ getControl().getDisplay().getSystemColor(SWT.COLOR_GRAY));
+ changeTextPresentation(style, true);
+ }
}
diff --git a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/man/parser/ManPage.java b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/man/parser/ManPage.java
index bf39c54d3f..aeb0f98361 100644
--- a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/man/parser/ManPage.java
+++ b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/man/parser/ManPage.java
@@ -18,123 +18,123 @@ import org.eclipse.linuxtools.internal.man.parser.ManParser;
*/
public class ManPage {
- private StringBuilder rawContent;
- private StringBuilder strippedTextPage;
+ private StringBuilder rawContent;
+ private StringBuilder strippedTextPage;
- /**
- * Creates the man page which includes retrieving the raw content and
- * changing format symbols to html.
- *
- * @param manPage
- * The man page.
- */
- public ManPage(String manPage) {
- parse(new ManParser().getRawManPage(manPage));
- }
+ /**
+ * Creates the man page which includes retrieving the raw content and
+ * changing format symbols to html.
+ *
+ * @param manPage
+ * The man page.
+ */
+ public ManPage(String manPage) {
+ parse(new ManParser().getRawManPage(manPage));
+ }
- // TODO make bold and underline be ranges instead of separate symbols.
- private void parse(StringBuilder rawManPage) {
- StringBuilder sb = new StringBuilder();
- sb.append(rawManPage);
+ // TODO make bold and underline be ranges instead of separate symbols.
+ private void parse(StringBuilder rawManPage) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(rawManPage);
- while (sb.indexOf("_\b") != -1) { //$NON-NLS-1$
- int index = sb.indexOf("_\b"); //$NON-NLS-1$
- sb.replace(index, index + 3,
- "<u>" + sb.substring(index + 2, index + 3) + "</u>"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- while (sb.indexOf("\b") != -1) { //$NON-NLS-1$
- int index = sb.indexOf("\b"); //$NON-NLS-1$
- sb.replace(index - 1, index + 2,
- "<b>" + sb.substring(index - 1, index) + "</b>"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- rawContent = sb;
- }
+ while (sb.indexOf("_\b") != -1) { //$NON-NLS-1$
+ int index = sb.indexOf("_\b"); //$NON-NLS-1$
+ sb.replace(index, index + 3,
+ "<u>" + sb.substring(index + 2, index + 3) + "</u>"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ while (sb.indexOf("\b") != -1) { //$NON-NLS-1$
+ int index = sb.indexOf("\b"); //$NON-NLS-1$
+ sb.replace(index - 1, index + 2,
+ "<b>" + sb.substring(index - 1, index) + "</b>"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ rawContent = sb;
+ }
- /**
- * Returns html representation of the man page. The whole man page is kept
- * in one giant &lt;pre&gt; block with bold and underline symbols.
- *
- * @return The whole html man page.
- */
- public StringBuilder getHtmlPage() {
- StringBuilder sb = new StringBuilder();
- sb.append("<pre>").append(rawContent).append("</pre>"); //$NON-NLS-1$ //$NON-NLS-2$
- return sb;
- }
+ /**
+ * Returns html representation of the man page. The whole man page is kept
+ * in one giant &lt;pre&gt; block with bold and underline symbols.
+ *
+ * @return The whole html man page.
+ */
+ public StringBuilder getHtmlPage() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("<pre>").append(rawContent).append("</pre>"); //$NON-NLS-1$ //$NON-NLS-2$
+ return sb;
+ }
- /**
- * Returns stripped representation of the man page. Stripped parts are:
- * <ul>
- * <li>Header - all the parts before <b>NAME</b></li>
- * <li>Footer - all the parts from <b>AUTHOR</b> till the end</li>
- * </ul>
- *
- * @return The stripped html content of the man page.
- */
- public StringBuilder getStrippedHtmlPage() {
- StringBuilder sb = getStrippedPage();
- sb.insert(0, "<pre>"); //$NON-NLS-1$
- sb.append("</pre>"); //$NON-NLS-1$
- return sb;
- }
+ /**
+ * Returns stripped representation of the man page. Stripped parts are:
+ * <ul>
+ * <li>Header - all the parts before <b>NAME</b></li>
+ * <li>Footer - all the parts from <b>AUTHOR</b> till the end</li>
+ * </ul>
+ *
+ * @return The stripped html content of the man page.
+ */
+ public StringBuilder getStrippedHtmlPage() {
+ StringBuilder sb = getStrippedPage();
+ sb.insert(0, "<pre>"); //$NON-NLS-1$
+ sb.append("</pre>"); //$NON-NLS-1$
+ return sb;
+ }
- /**
- * Returns stripped representation of the man page in the format it was
- * received from executing man. Stripped parts are:
- * <ul>
- * <li>Header - all the parts before <b>NAME</b></li>
- * <li>Footer - all the parts from <b>AUTHOR</b> till the end</li>
- * </ul>
- *
- * @return The stripped plain text content of the man page.
- * @since 1.1
- */
- public StringBuilder getStrippedPage() {
- StringBuilder sb = new StringBuilder();
- sb.append(rawContent);
- // The raw content may or may not be HTML
- if (sb.indexOf("<b>N</b>") != -1) { //$NON-NLS-1$
- sb.delete(0, sb.indexOf("<b>N</b>")); //$NON-NLS-1$
- } else if (sb.indexOf("NAME") != -1) { //$NON-NLS-1$
- sb.delete(0, sb.indexOf("NAME")); //$NON-NLS-1$
- }
+ /**
+ * Returns stripped representation of the man page in the format it was
+ * received from executing man. Stripped parts are:
+ * <ul>
+ * <li>Header - all the parts before <b>NAME</b></li>
+ * <li>Footer - all the parts from <b>AUTHOR</b> till the end</li>
+ * </ul>
+ *
+ * @return The stripped plain text content of the man page.
+ * @since 1.1
+ */
+ public StringBuilder getStrippedPage() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(rawContent);
+ // The raw content may or may not be HTML
+ if (sb.indexOf("<b>N</b>") != -1) { //$NON-NLS-1$
+ sb.delete(0, sb.indexOf("<b>N</b>")); //$NON-NLS-1$
+ } else if (sb.indexOf("NAME") != -1) { //$NON-NLS-1$
+ sb.delete(0, sb.indexOf("NAME")); //$NON-NLS-1$
+ }
- if (sb.indexOf("<b>A</b><b>U</b><b>T</b><b>H</b><b>O</b><b>R</b>") != -1) { //$NON-NLS-1$
- sb.delete(
- sb.indexOf("<b>A</b><b>U</b><b>T</b><b>H</b><b>O</b><b>R</b>"), //$NON-NLS-1$
- sb.length());
- } else if (sb.indexOf("AUTHOR") != -1) { //$NON-NLS-1$
- sb.delete(sb.indexOf("AUTHOR"), //$NON-NLS-1$
- sb.length());
- }
+ if (sb.indexOf("<b>A</b><b>U</b><b>T</b><b>H</b><b>O</b><b>R</b>") != -1) { //$NON-NLS-1$
+ sb.delete(
+ sb.indexOf("<b>A</b><b>U</b><b>T</b><b>H</b><b>O</b><b>R</b>"), //$NON-NLS-1$
+ sb.length());
+ } else if (sb.indexOf("AUTHOR") != -1) { //$NON-NLS-1$
+ sb.delete(sb.indexOf("AUTHOR"), //$NON-NLS-1$
+ sb.length());
+ }
- return sb;
- }
+ return sb;
+ }
- /**
- * Removes all HTML markings are returns a text only version.
- *
- * @return a text only version of the manpage
- * @since 1.1
- */
- public StringBuilder getStrippedTextPage() {
- if (this.strippedTextPage == null) {
- this.strippedTextPage = getStrippedPage();
- int index = strippedTextPage.indexOf("<b>"); //$NON-NLS-1$
- while (index != -1) {
- strippedTextPage.replace(index, index + 3, ""); //$NON-NLS-1$
- strippedTextPage.replace(index + 1, index + 5, ""); //$NON-NLS-1$
- index = strippedTextPage.indexOf("<b>"); //$NON-NLS-1$
- }
+ /**
+ * Removes all HTML markings are returns a text only version.
+ *
+ * @return a text only version of the manpage
+ * @since 1.1
+ */
+ public StringBuilder getStrippedTextPage() {
+ if (this.strippedTextPage == null) {
+ this.strippedTextPage = getStrippedPage();
+ int index = strippedTextPage.indexOf("<b>"); //$NON-NLS-1$
+ while (index != -1) {
+ strippedTextPage.replace(index, index + 3, ""); //$NON-NLS-1$
+ strippedTextPage.replace(index + 1, index + 5, ""); //$NON-NLS-1$
+ index = strippedTextPage.indexOf("<b>"); //$NON-NLS-1$
+ }
- index = strippedTextPage.indexOf("<u>"); //$NON-NLS-1$
- while (index != -1) {
- strippedTextPage.replace(index, index + 3, ""); //$NON-NLS-1$
- strippedTextPage.replace(index + 1, index + 5, ""); //$NON-NLS-1$
- index = strippedTextPage.indexOf("<u>"); //$NON-NLS-1$
- }
- }
+ index = strippedTextPage.indexOf("<u>"); //$NON-NLS-1$
+ while (index != -1) {
+ strippedTextPage.replace(index, index + 3, ""); //$NON-NLS-1$
+ strippedTextPage.replace(index + 1, index + 5, ""); //$NON-NLS-1$
+ index = strippedTextPage.indexOf("<u>"); //$NON-NLS-1$
+ }
+ }
- return strippedTextPage;
- }
+ return strippedTextPage;
+ }
}
diff --git a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/man/views/ManView.java b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/man/views/ManView.java
index 51c85d386c..8e80c3167b 100644
--- a/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/man/views/ManView.java
+++ b/man/org.eclipse.linuxtools.man.core/src/org/eclipse/linuxtools/man/views/ManView.java
@@ -22,43 +22,43 @@ import org.eclipse.ui.part.ViewPart;
public class ManView extends ViewPart {
- /**
- * The ID of the view as specified by the extension.
- */
- public static final String ID = "org.eclipse.linuxtools.man.views.ManView"; //$NON-NLS-1$
+ /**
+ * The ID of the view as specified by the extension.
+ */
+ public static final String ID = "org.eclipse.linuxtools.man.views.ManView"; //$NON-NLS-1$
- private ManTextViewer viewer;
+ private ManTextViewer viewer;
- /**
- * This is a callback that will allow us to create the viewer and initialize
- * it.
- */
- @Override
- public void createPartControl(Composite parent) {
- viewer = new ManTextViewer(parent);
- // Create the help context id for the viewer's control
- PlatformUI
- .getWorkbench()
- .getHelpSystem()
- .setHelp(viewer.getControl(),
- "org.eclipse.linuxtools.man.viewer"); //$NON-NLS-1$
- }
+ /**
+ * This is a callback that will allow us to create the viewer and initialize
+ * it.
+ */
+ @Override
+ public void createPartControl(Composite parent) {
+ viewer = new ManTextViewer(parent);
+ // Create the help context id for the viewer's control
+ PlatformUI
+ .getWorkbench()
+ .getHelpSystem()
+ .setHelp(viewer.getControl(),
+ "org.eclipse.linuxtools.man.viewer"); //$NON-NLS-1$
+ }
- /**
- * Sets the man page to dispaly
- *
- * @param manPageName
- * The name of the man page to display.
- */
- public void setManPageName(String manPageName) {
- viewer.setDocument(new ManDocument(manPageName));
- }
+ /**
+ * Sets the man page to dispaly
+ *
+ * @param manPageName
+ * The name of the man page to display.
+ */
+ public void setManPageName(String manPageName) {
+ viewer.setDocument(new ManDocument(manPageName));
+ }
- /**
- * Passing the focus request to the viewer's control.
- */
- @Override
- public void setFocus() {
- viewer.getControl().setFocus();
- }
+ /**
+ * Passing the focus request to the viewer's control.
+ */
+ @Override
+ public void setFocus() {
+ viewer.getControl().setFocus();
+ }
} \ No newline at end of file
diff --git a/oprofile/org.eclipse.linuxtools.oprofile.remote-feature/pom.xml b/oprofile/org.eclipse.linuxtools.oprofile.remote-feature/pom.xml
index ae032f2580..76f382aabb 100644
--- a/oprofile/org.eclipse.linuxtools.oprofile.remote-feature/pom.xml
+++ b/oprofile/org.eclipse.linuxtools.oprofile.remote-feature/pom.xml
@@ -22,7 +22,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools Remote OProfile Integration Feature</name>
-
+
<build>
<plugins>
<plugin>
diff --git a/perf/org.eclipse.linuxtools.perf.doc/build-helper.xml b/perf/org.eclipse.linuxtools.perf.doc/build-helper.xml
index c9733f888d..da12bdcb29 100644
--- a/perf/org.eclipse.linuxtools.perf.doc/build-helper.xml
+++ b/perf/org.eclipse.linuxtools.perf.doc/build-helper.xml
@@ -1,60 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="org.eclipse.linuxtools.perf.doc" default="all">
- <description>
+ <description>
Generate Eclipse help content for the Linux Tools Perf user guide
</description>
- <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
+ <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
- <path id="wikitext.tasks.classpath">
- <!-- Replace dir with the dir you have wikitext installed into.-->
- <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
- <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
- </fileset>
- </path>
+ <path id="wikitext.tasks.classpath">
+ <!-- Replace dir with the dir you have wikitext installed into.-->
+ <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
+ <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
+ </fileset>
+ </path>
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
- <target name="all" description="Generate Eclipse help content for the Linux Tools Perf user guide">
- <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="Perf User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
+ <target name="all" description="Generate Eclipse help content for the Linux Tools Perf user guide">
+ <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="Perf User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
- <path name="Linux_Tools_Project/PERF/User_Guide" title="Perf User Guide" generateToc="false" />
- <stylesheet url="book.css" />
- <pageAppendum>
+ <path name="Linux_Tools_Project/PERF/User_Guide" title="Perf User Guide" generateToc="false" />
+ <stylesheet url="book.css" />
+ <pageAppendum>
= Updating This Document =
-This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
+This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
http://wiki.eclipse.org/Linux_Tools_Project/PERF/User_Guide .
</pageAppendum>
- </mediawiki-to-eclipse-help>
- <antcall target="test" />
- </target>
+ </mediawiki-to-eclipse-help>
+ <antcall target="test" />
+ </target>
- <target name="test" description="verify that all of the HTML files are well-formed XML">
- <echo level="info">
+ <target name="test" description="verify that all of the HTML files are well-formed XML">
+ <echo level="info">
Validating help content XML and HTML files: The Eclipse help system expects well-formed XML
-
+
If validation fails it is because either:
-
+
* the userguide source code is poorly formed, or
* the WikiText MediaWiki parser has a bug
-
+
Problems with userguide source are usually caused by improper use of HTML markup in the MediaWiki source,
or inadvertently starting a line with a space character (in MediaWiki this starts a preformatted block)
- </echo>
-
- <!--
- Don't bother with DTD validation: we only care if the files are well-formed.
- We therefore provide an empty DTD
- -->
- <echo file="tmp/__empty.dtd" message="" />
- <xmlvalidate lenient="true">
- <fileset dir="Linux_Tools_Project">
- <include name="**/*.html" />
- </fileset>
- <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
- </xmlvalidate>
- <delete dir="tmp" />
- </target>
+ </echo>
+
+ <!--
+ Don't bother with DTD validation: we only care if the files are well-formed.
+ We therefore provide an empty DTD
+ -->
+ <echo file="tmp/__empty.dtd" message="" />
+ <xmlvalidate lenient="true">
+ <fileset dir="Linux_Tools_Project">
+ <include name="**/*.html" />
+ </fileset>
+ <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
+ </xmlvalidate>
+ <delete dir="tmp" />
+ </target>
</project>
diff --git a/perf/org.eclipse.linuxtools.perf.doc/toc-doc.xml b/perf/org.eclipse.linuxtools.perf.doc/toc-doc.xml
index b6e8863295..b5f85e84ac 100644
--- a/perf/org.eclipse.linuxtools.perf.doc/toc-doc.xml
+++ b/perf/org.eclipse.linuxtools.perf.doc/toc-doc.xml
@@ -1,5 +1,5 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/PERF/User_Guide/User-Guide.html" label="Perf User Guide">
-<link toc="toc.xml" />
+<link toc="toc.xml" />
<topic href="doc/notices.html" label="Legal"> </topic>
</toc>
diff --git a/perf/org.eclipse.linuxtools.perf.doc/toc.xml b/perf/org.eclipse.linuxtools.perf.doc/toc.xml
index cac066fc87..1e15987627 100644
--- a/perf/org.eclipse.linuxtools.perf.doc/toc.xml
+++ b/perf/org.eclipse.linuxtools.perf.doc/toc.xml
@@ -1,29 +1,29 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/PERF/User_Guide/User-Guide.html" label="Perf User Guide">
- <topic href="Linux_Tools_Project/PERF/User_Guide/User-Guide.html" label="Perf User Guide">
- <topic href="Linux_Tools_Project/PERF/User_Guide/User-Guide.html" label="Overview"></topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Installing.html" label="Installing"></topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Launching-a-Profile.html" label="Launching a Profile">
- <topic href="Linux_Tools_Project/PERF/User_Guide/Launching-a-Profile.html#One-click_launch" label="One-click launch"></topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Launching-a-Profile.html#Launching_a_Customized_Profile" label="Launching a Customized Profile"></topic>
- </topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Profiling-Configuration.html" label="Profiling Configuration">
- <topic href="Linux_Tools_Project/PERF/User_Guide/Profiling-Configuration.html#Remote_Profiling" label="Remote Profiling"></topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Profiling-Configuration.html#Perf_Options_tab" label="Perf Options tab"></topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Profiling-Configuration.html#Perf_Events_tab" label="Perf Events tab"></topic>
- </topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Perf-Views.html" label="Perf Views">
- <topic href="Linux_Tools_Project/PERF/User_Guide/Perf-Views.html#Perf_Tree_View" label="Perf Tree View"></topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Perf-Views.html#Source_Disassembly_View" label="Source Disassembly View"></topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Perf-Views.html#Stat_View" label="Stat View"></topic>
- </topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Sessions.html" label="Sessions">
- <topic href="Linux_Tools_Project/PERF/User_Guide/Sessions.html#Saving_a_Session" label="Saving a Session"></topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Sessions.html#Comparing_Sessions" label="Comparing Sessions">
- <topic href="Linux_Tools_Project/PERF/User_Guide/Sessions.html#Manual_Comparison" label="Manual Comparison"></topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Sessions.html#Automatic_comparison" label="Automatic comparison"></topic>
- </topic>
- </topic>
- <topic href="Linux_Tools_Project/PERF/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
- </topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/User-Guide.html" label="Perf User Guide">
+ <topic href="Linux_Tools_Project/PERF/User_Guide/User-Guide.html" label="Overview"></topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Installing.html" label="Installing"></topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Launching-a-Profile.html" label="Launching a Profile">
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Launching-a-Profile.html#One-click_launch" label="One-click launch"></topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Launching-a-Profile.html#Launching_a_Customized_Profile" label="Launching a Customized Profile"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Profiling-Configuration.html" label="Profiling Configuration">
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Profiling-Configuration.html#Remote_Profiling" label="Remote Profiling"></topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Profiling-Configuration.html#Perf_Options_tab" label="Perf Options tab"></topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Profiling-Configuration.html#Perf_Events_tab" label="Perf Events tab"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Perf-Views.html" label="Perf Views">
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Perf-Views.html#Perf_Tree_View" label="Perf Tree View"></topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Perf-Views.html#Source_Disassembly_View" label="Source Disassembly View"></topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Perf-Views.html#Stat_View" label="Stat View"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Sessions.html" label="Sessions">
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Sessions.html#Saving_a_Session" label="Saving a Session"></topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Sessions.html#Comparing_Sessions" label="Comparing Sessions">
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Sessions.html#Manual_Comparison" label="Manual Comparison"></topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Sessions.html#Automatic_comparison" label="Automatic comparison"></topic>
+ </topic>
+ </topic>
+ <topic href="Linux_Tools_Project/PERF/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
+ </topic>
</toc> \ No newline at end of file
diff --git a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AbstractSWTBotTest.java b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AbstractSWTBotTest.java
index aeb0266d48..0b1a3d438c 100644
--- a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AbstractSWTBotTest.java
+++ b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AbstractSWTBotTest.java
@@ -53,253 +53,253 @@ import org.osgi.framework.FrameworkUtil;
*/
@RunWith(SWTBotJunit4ClassRunner.class)
public abstract class AbstractSWTBotTest extends AbstractTest {
- private static final String PROJ_NAME = "fibTest";
- private static SWTBotView projectExplorer;
-
- private static class NodeAvailableAndSelect extends DefaultCondition {
-
- private SWTBotTree tree;
- private String parent;
- private String node;
-
- /**
- * Wait for a tree node (with a known parent) to become visible, and select it
- * when it does. Note that this wait condition should only be used after having
- * made an attempt to reveal the node.
- * @param tree The SWTBotTree that contains the node to select.
- * @param parent The text of the parent node that contains the node to select.
- * @param node The text of the node to select.
- */
- NodeAvailableAndSelect(SWTBotTree tree, String parent, String node){
- this.tree = tree;
- this.node = node;
- this.parent = parent;
- }
-
- @Override
- public boolean test() {
- try {
- SWTBotTreeItem parentNode = tree.getTreeItem(parent);
- parentNode.getNode(node).select();
- return true;
- } catch (WidgetNotFoundException e) {
- return false;
- }
- }
-
- @Override
- public String getFailureMessage() {
- return "Timed out waiting for " + node; //$NON-NLS-1$
- }
- }
-
- @BeforeClass
- public static void setUpWorkbench() throws Exception {
- SWTWorkbenchBot bot = new SWTWorkbenchBot();
- try {
- bot.viewByTitle("Welcome").close();
- // hide Subclipse Usage stats popup if present/installed
- bot.shell("Subclipse Usage").activate();
- bot.button("Cancel").click();
- } catch (WidgetNotFoundException e) {
- // ignore
- }
-
- // Set C/C++ perspective.
- bot.perspectiveByLabel("C/C++").activate();
- bot.sleep(500);
- for (SWTBotShell sh : bot.shells()) {
- if (sh.getText().startsWith("C/C++")) {
- sh.activate();
- bot.sleep(500);
- break;
- }
- }
-
- // Turn off automatic building by default to avoid timing issues
- SWTBotMenu windowsMenu = bot.menu("Window");
- windowsMenu.menu("Preferences").click();
- SWTBotShell shell = bot.shell("Preferences");
- shell.activate();
- bot.text().setText("Workspace");
- bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "General", "Workspace"));
- SWTBotCheckBox buildAuto = bot.checkBox("Build automatically");
- if (buildAuto != null && buildAuto.isChecked()) {
- buildAuto.click();
- }
- bot.sleep(1000);
- bot.button("Apply").click();
- bot.button("OK").click();
- bot.waitUntil(shellCloses(shell));
-
- projectExplorer = bot.viewByTitle("Project Explorer");
- }
-
- @AfterClass
- public static void resetExplorerState() {
- exitProjectFolder(new SWTWorkbenchBot());
- }
-
- @Test
- public void runPerfViewTest() throws Exception {
- SWTWorkbenchBot bot = new SWTWorkbenchBot();
-
- /*
- * - Method returns when the build is complete -
- * AbstractTest#createProjectAndBuild builds a single executable binary
- * under "Binaries".
- */
- proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), PROJ_NAME);
- try {
- runPerfViewTestActions(bot);
- } catch (Exception e) {
- throw e;
- } finally {
- deleteProject(proj);
- }
- }
-
- private void runPerfViewTestActions(SWTWorkbenchBot bot) throws Exception {
- projectExplorer.bot().tree().select(PROJ_NAME);
- final Shell shellWidget = bot.activeShell().widget;
-
- // Open profiling configurations dialog
- UIThreadRunnable.asyncExec(new VoidResult() {
- @Override
- public void run() {
- DebugUITools.openLaunchConfigurationDialogOnGroup(shellWidget,
- (StructuredSelection) PlatformUI.getWorkbench().getWorkbenchWindows()[0].
- getSelectionService().getSelection(), "org.eclipse.debug.ui.launchGroup.profilee");
- }
- });
- bot.shell("Profiling Tools Configurations").activate();
-
- // Create new Perf configuration
- SWTBotTree profilingConfigs = bot.tree();
- SWTBotTree perfNode = profilingConfigs.select("Profile with Perf");
- perfNode.contextMenu("New").click();
-
- // Activate options tab
- bot.cTabItem("Perf Options").activate();
-
- setPerfOptions(bot);
-
- bot.button("Apply").click();
-
- if (PerfCore.checkPerfInPath(null)) {
- bot.button("Profile").click();
-
- } else {
- bot.button("Close").click();
- openStubView();
- }
-
- testPerfView();
- }
-
- /**
- * Compare The selected items in PROJ_NAME with each other
- * @param The name of a tree item to select
- * @param The name of a second tree item to select
- */
- public void compareWithEachOther (String first, String second) {
- SWTWorkbenchBot bot = new SWTWorkbenchBot();
- enterProjectFolder(bot);
-
- // Refresh and Select
- SWTBotTree treeBot = projectExplorer.bot().tree();
- treeBot.contextMenu("Refresh").click();
- treeBot.select(new String [] {first, second});
-
- // Workaround for context menu on multiple selections
- click(ContextMenuHelper.contextMenu(treeBot, "Compare With", "Each Other"));
- exitProjectFolder(bot);
- }
-
- /**
- * Enter the project folder so as to avoid expanding trees later
- */
- private static SWTBotView enterProjectFolder(SWTWorkbenchBot bot) {
- projectExplorer.bot().tree().select(PROJ_NAME).
- contextMenu("Go Into").click();
- bot.waitUntil(waitForWidget(WidgetMatcherFactory.withText(
- PROJ_NAME), projectExplorer.getWidget()));
- return projectExplorer;
- }
-
- /**
- * Exit from the project tree.
- */
- private static void exitProjectFolder(SWTWorkbenchBot bot) {
- try {
- SWTBotToolbarButton forwardButton = projectExplorer.toolbarPushButton("Forward");
- projectExplorer.toolbarPushButton("Back to Workspace").click();
- bot.waitUntil(widgetIsEnabled(forwardButton));
- } catch (WidgetNotFoundException e) {
- // Already exited from project folder
- }
- }
-
- /**
- * Click specfied menu item.
- *
- * @param menuItem
- * menu item to click
- */
- public static void click(final MenuItem menuItem) {
- final Event event = new Event();
- event.time = (int) System.currentTimeMillis();
- event.widget = menuItem;
- event.display = menuItem.getDisplay();
- event.type = SWT.Selection;
-
- UIThreadRunnable.asyncExec(menuItem.getDisplay(), new VoidResult() {
- @Override
- public void run() {
- menuItem.notifyListeners(SWT.Selection, event);
- }
- });
- }
-
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return null;
- }
-
- @Override
- protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- }
-
- /**
- * Set Perf launch options.
- *
- * @param bot SWTWorkbenchBot bot focused in Perf options tab.
- */
- protected abstract void setPerfOptions(SWTWorkbenchBot bot);
-
- /**
- * Open view with fake data. To be used when perf is not installed.
- */
- protected abstract void openStubView();
-
- /**
- * Test perf view.
- */
- protected abstract void testPerfView();
-
- /**
- * Stub data for use in case the Perf tool is not installed.
- */
- protected static class StubPerfData implements IPerfData {
- @Override
- public String getPerfData() {
- return "stub_perf_data";
- }
-
- @Override
- public String getTitle() {
- return "stub_perf_title";
- }
-
- }
+ private static final String PROJ_NAME = "fibTest";
+ private static SWTBotView projectExplorer;
+
+ private static class NodeAvailableAndSelect extends DefaultCondition {
+
+ private SWTBotTree tree;
+ private String parent;
+ private String node;
+
+ /**
+ * Wait for a tree node (with a known parent) to become visible, and select it
+ * when it does. Note that this wait condition should only be used after having
+ * made an attempt to reveal the node.
+ * @param tree The SWTBotTree that contains the node to select.
+ * @param parent The text of the parent node that contains the node to select.
+ * @param node The text of the node to select.
+ */
+ NodeAvailableAndSelect(SWTBotTree tree, String parent, String node){
+ this.tree = tree;
+ this.node = node;
+ this.parent = parent;
+ }
+
+ @Override
+ public boolean test() {
+ try {
+ SWTBotTreeItem parentNode = tree.getTreeItem(parent);
+ parentNode.getNode(node).select();
+ return true;
+ } catch (WidgetNotFoundException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return "Timed out waiting for " + node; //$NON-NLS-1$
+ }
+ }
+
+ @BeforeClass
+ public static void setUpWorkbench() throws Exception {
+ SWTWorkbenchBot bot = new SWTWorkbenchBot();
+ try {
+ bot.viewByTitle("Welcome").close();
+ // hide Subclipse Usage stats popup if present/installed
+ bot.shell("Subclipse Usage").activate();
+ bot.button("Cancel").click();
+ } catch (WidgetNotFoundException e) {
+ // ignore
+ }
+
+ // Set C/C++ perspective.
+ bot.perspectiveByLabel("C/C++").activate();
+ bot.sleep(500);
+ for (SWTBotShell sh : bot.shells()) {
+ if (sh.getText().startsWith("C/C++")) {
+ sh.activate();
+ bot.sleep(500);
+ break;
+ }
+ }
+
+ // Turn off automatic building by default to avoid timing issues
+ SWTBotMenu windowsMenu = bot.menu("Window");
+ windowsMenu.menu("Preferences").click();
+ SWTBotShell shell = bot.shell("Preferences");
+ shell.activate();
+ bot.text().setText("Workspace");
+ bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "General", "Workspace"));
+ SWTBotCheckBox buildAuto = bot.checkBox("Build automatically");
+ if (buildAuto != null && buildAuto.isChecked()) {
+ buildAuto.click();
+ }
+ bot.sleep(1000);
+ bot.button("Apply").click();
+ bot.button("OK").click();
+ bot.waitUntil(shellCloses(shell));
+
+ projectExplorer = bot.viewByTitle("Project Explorer");
+ }
+
+ @AfterClass
+ public static void resetExplorerState() {
+ exitProjectFolder(new SWTWorkbenchBot());
+ }
+
+ @Test
+ public void runPerfViewTest() throws Exception {
+ SWTWorkbenchBot bot = new SWTWorkbenchBot();
+
+ /*
+ * - Method returns when the build is complete -
+ * AbstractTest#createProjectAndBuild builds a single executable binary
+ * under "Binaries".
+ */
+ proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), PROJ_NAME);
+ try {
+ runPerfViewTestActions(bot);
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ deleteProject(proj);
+ }
+ }
+
+ private void runPerfViewTestActions(SWTWorkbenchBot bot) throws Exception {
+ projectExplorer.bot().tree().select(PROJ_NAME);
+ final Shell shellWidget = bot.activeShell().widget;
+
+ // Open profiling configurations dialog
+ UIThreadRunnable.asyncExec(new VoidResult() {
+ @Override
+ public void run() {
+ DebugUITools.openLaunchConfigurationDialogOnGroup(shellWidget,
+ (StructuredSelection) PlatformUI.getWorkbench().getWorkbenchWindows()[0].
+ getSelectionService().getSelection(), "org.eclipse.debug.ui.launchGroup.profilee");
+ }
+ });
+ bot.shell("Profiling Tools Configurations").activate();
+
+ // Create new Perf configuration
+ SWTBotTree profilingConfigs = bot.tree();
+ SWTBotTree perfNode = profilingConfigs.select("Profile with Perf");
+ perfNode.contextMenu("New").click();
+
+ // Activate options tab
+ bot.cTabItem("Perf Options").activate();
+
+ setPerfOptions(bot);
+
+ bot.button("Apply").click();
+
+ if (PerfCore.checkPerfInPath(null)) {
+ bot.button("Profile").click();
+
+ } else {
+ bot.button("Close").click();
+ openStubView();
+ }
+
+ testPerfView();
+ }
+
+ /**
+ * Compare The selected items in PROJ_NAME with each other
+ * @param The name of a tree item to select
+ * @param The name of a second tree item to select
+ */
+ public void compareWithEachOther (String first, String second) {
+ SWTWorkbenchBot bot = new SWTWorkbenchBot();
+ enterProjectFolder(bot);
+
+ // Refresh and Select
+ SWTBotTree treeBot = projectExplorer.bot().tree();
+ treeBot.contextMenu("Refresh").click();
+ treeBot.select(new String [] {first, second});
+
+ // Workaround for context menu on multiple selections
+ click(ContextMenuHelper.contextMenu(treeBot, "Compare With", "Each Other"));
+ exitProjectFolder(bot);
+ }
+
+ /**
+ * Enter the project folder so as to avoid expanding trees later
+ */
+ private static SWTBotView enterProjectFolder(SWTWorkbenchBot bot) {
+ projectExplorer.bot().tree().select(PROJ_NAME).
+ contextMenu("Go Into").click();
+ bot.waitUntil(waitForWidget(WidgetMatcherFactory.withText(
+ PROJ_NAME), projectExplorer.getWidget()));
+ return projectExplorer;
+ }
+
+ /**
+ * Exit from the project tree.
+ */
+ private static void exitProjectFolder(SWTWorkbenchBot bot) {
+ try {
+ SWTBotToolbarButton forwardButton = projectExplorer.toolbarPushButton("Forward");
+ projectExplorer.toolbarPushButton("Back to Workspace").click();
+ bot.waitUntil(widgetIsEnabled(forwardButton));
+ } catch (WidgetNotFoundException e) {
+ // Already exited from project folder
+ }
+ }
+
+ /**
+ * Click specfied menu item.
+ *
+ * @param menuItem
+ * menu item to click
+ */
+ public static void click(final MenuItem menuItem) {
+ final Event event = new Event();
+ event.time = (int) System.currentTimeMillis();
+ event.widget = menuItem;
+ event.display = menuItem.getDisplay();
+ event.type = SWT.Selection;
+
+ UIThreadRunnable.asyncExec(menuItem.getDisplay(), new VoidResult() {
+ @Override
+ public void run() {
+ menuItem.notifyListeners(SWT.Selection, event);
+ }
+ });
+ }
+
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return null;
+ }
+
+ @Override
+ protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ }
+
+ /**
+ * Set Perf launch options.
+ *
+ * @param bot SWTWorkbenchBot bot focused in Perf options tab.
+ */
+ protected abstract void setPerfOptions(SWTWorkbenchBot bot);
+
+ /**
+ * Open view with fake data. To be used when perf is not installed.
+ */
+ protected abstract void openStubView();
+
+ /**
+ * Test perf view.
+ */
+ protected abstract void testPerfView();
+
+ /**
+ * Stub data for use in case the Perf tool is not installed.
+ */
+ protected static class StubPerfData implements IPerfData {
+ @Override
+ public String getPerfData() {
+ return "stub_perf_data";
+ }
+
+ @Override
+ public String getTitle() {
+ return "stub_perf_title";
+ }
+
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AbstractStyledTextViewTest.java b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AbstractStyledTextViewTest.java
index 1f1e766009..5752f67e40 100644
--- a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AbstractStyledTextViewTest.java
+++ b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AbstractStyledTextViewTest.java
@@ -26,29 +26,29 @@ import org.hamcrest.Matcher;
*/
public abstract class AbstractStyledTextViewTest extends AbstractSWTBotTest {
- @Override
- protected void testPerfView() {
- SWTWorkbenchBot bot = new SWTWorkbenchBot();
-
- Matcher<IViewReference> withPartName = withPartName(getViewId());
- SWTBotView view = bot.view(withPartName);
- assertNotNull(view);
-
- view.setFocus();
- SWTBotStyledText text = bot.styledText();
- assertNotNull(text);
- assertEquals(getExpectedText(), text.getText());
- }
-
- /**
- * Get unique test view identifier.
- * @return String unique identifier of view part to test.
- */
- protected abstract String getViewId();
-
- /**
- * Get exptected text of <code>StyledText</code> widget contained in this view.
- * @return String expected text of view.
- */
- protected abstract String getExpectedText();
+ @Override
+ protected void testPerfView() {
+ SWTWorkbenchBot bot = new SWTWorkbenchBot();
+
+ Matcher<IViewReference> withPartName = withPartName(getViewId());
+ SWTBotView view = bot.view(withPartName);
+ assertNotNull(view);
+
+ view.setFocus();
+ SWTBotStyledText text = bot.styledText();
+ assertNotNull(text);
+ assertEquals(getExpectedText(), text.getText());
+ }
+
+ /**
+ * Get unique test view identifier.
+ * @return String unique identifier of view part to test.
+ */
+ protected abstract String getViewId();
+
+ /**
+ * Get exptected text of <code>StyledText</code> widget contained in this view.
+ * @return String expected text of view.
+ */
+ protected abstract String getExpectedText();
}
diff --git a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AllPerfTests.java b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AllPerfTests.java
index b7e97d0caf..4220f2a37f 100644
--- a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AllPerfTests.java
+++ b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/AllPerfTests.java
@@ -15,9 +15,9 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
- StatViewTest.class,
- SourceDisassemblyViewTest.class,
- StatComparisonViewTest.class,
- ReportComparisonViewTest.class})
+ StatViewTest.class,
+ SourceDisassemblyViewTest.class,
+ StatComparisonViewTest.class,
+ ReportComparisonViewTest.class})
public class AllPerfTests {
}
diff --git a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/ReportComparisonViewTest.java b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/ReportComparisonViewTest.java
index 2a8f586871..98b00e49d8 100644
--- a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/ReportComparisonViewTest.java
+++ b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/ReportComparisonViewTest.java
@@ -20,20 +20,20 @@ import org.eclipse.swtbot.swt.finder.widgets.SWTBotCheckBox;
*/
public class ReportComparisonViewTest extends AbstractSWTBotTest {
- @Override
- protected void setPerfOptions(SWTWorkbenchBot bot) {
- SWTBotCheckBox chkBox = bot.checkBox("Show Source Disassembly View");
- assertNotNull(chkBox);
- chkBox.select();
- }
+ @Override
+ protected void setPerfOptions(SWTWorkbenchBot bot) {
+ SWTBotCheckBox chkBox = bot.checkBox("Show Source Disassembly View");
+ assertNotNull(chkBox);
+ chkBox.select();
+ }
- @Override
- protected void openStubView() {
- }
+ @Override
+ protected void openStubView() {
+ }
- @Override
- protected void testPerfView() {
- compareWithEachOther("perf_old.data", "perf_new.data");
- }
+ @Override
+ protected void testPerfView() {
+ compareWithEachOther("perf_old.data", "perf_new.data");
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/SourceDisassemblyViewTest.java b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/SourceDisassemblyViewTest.java
index a2f7978e6e..2a503ee3c7 100644
--- a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/SourceDisassemblyViewTest.java
+++ b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/SourceDisassemblyViewTest.java
@@ -22,29 +22,29 @@ import org.eclipse.swtbot.swt.finder.widgets.SWTBotCheckBox;
*/
public class SourceDisassemblyViewTest extends AbstractStyledTextViewTest {
- @Override
- protected void setPerfOptions(SWTWorkbenchBot bot) {
- SWTBotCheckBox chkBox = bot.checkBox("Show Source Disassembly View");
- assertNotNull(chkBox);
- chkBox.select();
- }
-
- @Override
- protected void openStubView() {
- PerfPlugin.getDefault().setSourceDisassemblyData(new StubPerfData());
- SourceDisassemblyView.refreshView();
-
- }
-
- @Override
- protected String getViewId() {
- // supply secondary id
- return "Perf Source Disassembly";
-
- }
-
- @Override
- protected String getExpectedText() {
- return PerfPlugin.getDefault().getSourceDisassemblyData().getPerfData();
- }
+ @Override
+ protected void setPerfOptions(SWTWorkbenchBot bot) {
+ SWTBotCheckBox chkBox = bot.checkBox("Show Source Disassembly View");
+ assertNotNull(chkBox);
+ chkBox.select();
+ }
+
+ @Override
+ protected void openStubView() {
+ PerfPlugin.getDefault().setSourceDisassemblyData(new StubPerfData());
+ SourceDisassemblyView.refreshView();
+
+ }
+
+ @Override
+ protected String getViewId() {
+ // supply secondary id
+ return "Perf Source Disassembly";
+
+ }
+
+ @Override
+ protected String getExpectedText() {
+ return PerfPlugin.getDefault().getSourceDisassemblyData().getPerfData();
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/StatComparisonViewTest.java b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/StatComparisonViewTest.java
index 245980837f..bb0d078dd1 100644
--- a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/StatComparisonViewTest.java
+++ b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/StatComparisonViewTest.java
@@ -21,24 +21,24 @@ import org.eclipse.swtbot.swt.finder.widgets.SWTBotSpinner;
*/
public class StatComparisonViewTest extends AbstractSWTBotTest {
- @Override
- protected void setPerfOptions(SWTWorkbenchBot bot) {
- SWTBotCheckBox chkBox = bot.checkBox("Show Stat View");
- assertNotNull(chkBox);
- chkBox.select();
-
- SWTBotSpinner spinner = bot.spinner();
- assertNotNull(spinner);
- spinner.setSelection(3);
- }
-
- @Override
- protected void testPerfView() {
- compareWithEachOther("perf_old.stat", "perf_new.stat");
- }
-
- @Override
- protected void openStubView() {
- }
+ @Override
+ protected void setPerfOptions(SWTWorkbenchBot bot) {
+ SWTBotCheckBox chkBox = bot.checkBox("Show Stat View");
+ assertNotNull(chkBox);
+ chkBox.select();
+
+ SWTBotSpinner spinner = bot.spinner();
+ assertNotNull(spinner);
+ spinner.setSelection(3);
+ }
+
+ @Override
+ protected void testPerfView() {
+ compareWithEachOther("perf_old.stat", "perf_new.stat");
+ }
+
+ @Override
+ protected void openStubView() {
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/StatViewTest.java b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/StatViewTest.java
index d221c1779c..a51d2d6c83 100644
--- a/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/StatViewTest.java
+++ b/perf/org.eclipse.linuxtools.perf.swtbot.tests/src/org/eclipse/linuxtools/internal/perf/swtbot/tests/StatViewTest.java
@@ -22,33 +22,33 @@ import org.eclipse.swtbot.swt.finder.widgets.SWTBotSpinner;
* SWTBot test for StatView.
*/
public class StatViewTest extends AbstractStyledTextViewTest {
- private static final int STAT_RUNS = 3;
-
- @Override
- protected void setPerfOptions(SWTWorkbenchBot bot) {
- SWTBotCheckBox chkBox = bot.checkBox("Show Stat View");
- assertNotNull(chkBox);
- chkBox.select();
-
- SWTBotSpinner spinner = bot.spinner();
- assertNotNull(spinner);
- spinner.setSelection(STAT_RUNS);
-
- }
-
- @Override
- protected void openStubView() {
- PerfPlugin.getDefault().setStatData(new StubPerfData());
- StatView.refreshView();
- }
-
- @Override
- protected String getViewId() {
- return "Perf Statistics";
- }
-
- @Override
- protected String getExpectedText() {
- return PerfPlugin.getDefault().getStatData().getPerfData();
- }
+ private static final int STAT_RUNS = 3;
+
+ @Override
+ protected void setPerfOptions(SWTWorkbenchBot bot) {
+ SWTBotCheckBox chkBox = bot.checkBox("Show Stat View");
+ assertNotNull(chkBox);
+ chkBox.select();
+
+ SWTBotSpinner spinner = bot.spinner();
+ assertNotNull(spinner);
+ spinner.setSelection(STAT_RUNS);
+
+ }
+
+ @Override
+ protected void openStubView() {
+ PerfPlugin.getDefault().setStatData(new StubPerfData());
+ StatView.refreshView();
+ }
+
+ @Override
+ protected String getViewId() {
+ return "Perf Statistics";
+ }
+
+ @Override
+ protected String getExpectedText() {
+ return PerfPlugin.getDefault().getStatData().getPerfData();
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/AllPerfTests.java b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/AllPerfTests.java
index 41307f107c..1bc73a7721 100644
--- a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/AllPerfTests.java
+++ b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/AllPerfTests.java
@@ -15,8 +15,8 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
- LaunchTabsTest.class,ModelTest.class,DataManipulatorTest.class,SaveSessionTest.class,
- StatsComparisonTest.class,LaunchTest.class, LaunchRemoteTest.class, FindActionTest.class
+ LaunchTabsTest.class,ModelTest.class,DataManipulatorTest.class,SaveSessionTest.class,
+ StatsComparisonTest.class,LaunchTest.class, LaunchRemoteTest.class, FindActionTest.class
})
public class AllPerfTests {
diff --git a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/DataManipulatorTest.java b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/DataManipulatorTest.java
index a97464bb85..b5fed58d4d 100644
--- a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/DataManipulatorTest.java
+++ b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/DataManipulatorTest.java
@@ -28,148 +28,148 @@ import org.junit.Test;
public class DataManipulatorTest {
- private static final String output = "output"; //$NON-NLS-1$
-
- @Test
- public void testEchoSourceDisassemblyData() {
- final IPath path = new Path("/a/b/c/"); //$NON-NLS-1$
-
- StubSourceDisassemblyData sdData = new StubSourceDisassemblyData(
- "disassembly data", path); //$NON-NLS-1$
- sdData.parse();
-
- String expected = "perf annotate -i " + path.toOSString() + "perf.data"; //$NON-NLS-1$
-
- assertEquals(expected, sdData.getPerfData().trim());
- }
- @Test
- public void testEchoStatData() {
- final String binary = "a/b/c.out";
- final String[] args = new String[] { "arg1", "arg2", "arg3" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- final int runCount = 3;
-
- StubStatData sData = new StubStatData(
- "stat data", binary, args, runCount, null); //$NON-NLS-1$
- sData.parse();
-
- String expected = "perf stat -r " + runCount + " -o " + output + " " + binary; //$NON-NLS-1$ //$NON-NLS-2$
- for (String i:args) {
- expected += " " + i; //$NON-NLS-1$
- }
-
- assertEquals(expected, sData.getPerfData().trim());
- }
- @Test
- public void testEchoStatDataEvents() {
- final String binary = "a/b/c.out";
- final String[] args = new String[] { "arg1", "arg2", "arg3" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- final String[] events = new String[] { "event1", "event2", "event3" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- final int runCount = 3;
-
- StubStatData sData = new StubStatData(
- "stat data", binary, args, runCount, events); //$NON-NLS-1$
- sData.parse();
-
- String expected = "perf stat -r " + runCount; //$NON-NLS-1$
- for(String event : events){
- expected += " -e " + event; //$NON-NLS-1$
- }
-
- expected = expected + " -o " + output + " " + binary; //$NON-NLS-1$
- for (String i : args) {
- expected += " " + i; //$NON-NLS-1$
- }
-
- assertEquals(expected, sData.getPerfData().trim());
- }
-
- @Test
- public void testEchoReportDiffData() {
- IPath oldData = Path.fromOSString("perf.old.data"); //$NON-NLS-1$
- IPath newData = Path.fromOSString("perf.data"); //$NON-NLS-1$
- StubReportDiffData diffData = new StubReportDiffData("title", //$NON-NLS-1$
- oldData, newData);
- diffData.parse();
-
- String expected = "perf diff " + oldData.toOSString() //$NON-NLS-1$
- + " " + newData.toOSString(); //$NON-NLS-1$
-
- assertEquals(expected, diffData.getPerfData().trim());
- }
-
- @Test
- public void testPerfStatDataOpenHandler() throws IOException {
+ private static final String output = "output"; //$NON-NLS-1$
+
+ @Test
+ public void testEchoSourceDisassemblyData() {
+ final IPath path = new Path("/a/b/c/"); //$NON-NLS-1$
+
+ StubSourceDisassemblyData sdData = new StubSourceDisassemblyData(
+ "disassembly data", path); //$NON-NLS-1$
+ sdData.parse();
+
+ String expected = "perf annotate -i " + path.toOSString() + "perf.data"; //$NON-NLS-1$
+
+ assertEquals(expected, sdData.getPerfData().trim());
+ }
+ @Test
+ public void testEchoStatData() {
+ final String binary = "a/b/c.out";
+ final String[] args = new String[] { "arg1", "arg2", "arg3" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ final int runCount = 3;
+
+ StubStatData sData = new StubStatData(
+ "stat data", binary, args, runCount, null); //$NON-NLS-1$
+ sData.parse();
+
+ String expected = "perf stat -r " + runCount + " -o " + output + " " + binary; //$NON-NLS-1$ //$NON-NLS-2$
+ for (String i:args) {
+ expected += " " + i; //$NON-NLS-1$
+ }
+
+ assertEquals(expected, sData.getPerfData().trim());
+ }
+ @Test
+ public void testEchoStatDataEvents() {
+ final String binary = "a/b/c.out";
+ final String[] args = new String[] { "arg1", "arg2", "arg3" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ final String[] events = new String[] { "event1", "event2", "event3" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ final int runCount = 3;
+
+ StubStatData sData = new StubStatData(
+ "stat data", binary, args, runCount, events); //$NON-NLS-1$
+ sData.parse();
+
+ String expected = "perf stat -r " + runCount; //$NON-NLS-1$
+ for(String event : events){
+ expected += " -e " + event; //$NON-NLS-1$
+ }
+
+ expected = expected + " -o " + output + " " + binary; //$NON-NLS-1$
+ for (String i : args) {
+ expected += " " + i; //$NON-NLS-1$
+ }
+
+ assertEquals(expected, sData.getPerfData().trim());
+ }
+
+ @Test
+ public void testEchoReportDiffData() {
+ IPath oldData = Path.fromOSString("perf.old.data"); //$NON-NLS-1$
+ IPath newData = Path.fromOSString("perf.data"); //$NON-NLS-1$
+ StubReportDiffData diffData = new StubReportDiffData("title", //$NON-NLS-1$
+ oldData, newData);
+ diffData.parse();
+
+ String expected = "perf diff " + oldData.toOSString() //$NON-NLS-1$
+ + " " + newData.toOSString(); //$NON-NLS-1$
+
+ assertEquals(expected, diffData.getPerfData().trim());
+ }
+
+ @Test
+ public void testPerfStatDataOpenHandler() throws IOException {
String resourceDirPath = "/resources/stat-data/perf_simple.stat"; //$NON-NLS-1$
String path = FileLocator.toFileURL(
this.getClass().getResource(resourceDirPath)).getPath();
PerfStatDataOpenHandler handler = new PerfStatDataOpenHandler();
handler.open(new Path(path));
- }
-
- /**
- * Used for testing SourceDisassemblyData
- */
- private static class StubSourceDisassemblyData extends SourceDisassemblyData {
-
- public StubSourceDisassemblyData(String title, IPath workingDir) {
- super(title, workingDir);
- }
-
- @Override
- public String[] getCommand(String workingDir) {
- List<String> ret = new ArrayList<>();
- // return the same command with 'echo' prepended
- ret.add("echo"); //$NON-NLS-1$
- ret.addAll(Arrays.asList(super.getCommand(workingDir)));
- return ret.toArray(new String[ret.size()]);
- }
- }
-
- /**
- * Used for testing StatData
- */
- private static class StubStatData extends StatData {
-
- public StubStatData(String title, String cmd, String[] args,
- int runCount, String[] events) {
- super(title, Path.fromOSString(""), cmd, args, runCount, events);
- }
-
- @Override
- public String[] getCommand(String command, String[] args, String file) {
- // return the same command with 'echo' prepended
- List<String> ret = new ArrayList<>();
- ret.add("echo"); //$NON-NLS-1$
- ret.addAll(Arrays.asList(super.getCommand(command, args, file)));
- return ret.toArray(new String[ret.size()]);
- }
-
- @Override
- public void parse() {
- String[] cmd = getCommand(getProgram(), getArguments(), output); //$NON-NLS-1$
- // echo will print to standard out
- performCommand(cmd, 1);
- }
- }
-
- /**
- * Used for testing ReportComparisonData
- */
- private static class StubReportDiffData extends ReportComparisonData{
-
- public StubReportDiffData(String title, IPath oldFile, IPath newFile) {
- super(title, oldFile, newFile, null);
- }
-
- @Override
- protected String[] getCommand() {
- // return the same command with 'echo' prepended
- List<String> ret = new ArrayList<>();
- ret.add("echo"); //$NON-NLS-1$
- ret.addAll(Arrays.asList(super.getCommand()));
- return ret.toArray(new String[ret.size()]);
- }
-
- }
+ }
+
+ /**
+ * Used for testing SourceDisassemblyData
+ */
+ private static class StubSourceDisassemblyData extends SourceDisassemblyData {
+
+ public StubSourceDisassemblyData(String title, IPath workingDir) {
+ super(title, workingDir);
+ }
+
+ @Override
+ public String[] getCommand(String workingDir) {
+ List<String> ret = new ArrayList<>();
+ // return the same command with 'echo' prepended
+ ret.add("echo"); //$NON-NLS-1$
+ ret.addAll(Arrays.asList(super.getCommand(workingDir)));
+ return ret.toArray(new String[ret.size()]);
+ }
+ }
+
+ /**
+ * Used for testing StatData
+ */
+ private static class StubStatData extends StatData {
+
+ public StubStatData(String title, String cmd, String[] args,
+ int runCount, String[] events) {
+ super(title, Path.fromOSString(""), cmd, args, runCount, events);
+ }
+
+ @Override
+ public String[] getCommand(String command, String[] args, String file) {
+ // return the same command with 'echo' prepended
+ List<String> ret = new ArrayList<>();
+ ret.add("echo"); //$NON-NLS-1$
+ ret.addAll(Arrays.asList(super.getCommand(command, args, file)));
+ return ret.toArray(new String[ret.size()]);
+ }
+
+ @Override
+ public void parse() {
+ String[] cmd = getCommand(getProgram(), getArguments(), output); //$NON-NLS-1$
+ // echo will print to standard out
+ performCommand(cmd, 1);
+ }
+ }
+
+ /**
+ * Used for testing ReportComparisonData
+ */
+ private static class StubReportDiffData extends ReportComparisonData{
+
+ public StubReportDiffData(String title, IPath oldFile, IPath newFile) {
+ super(title, oldFile, newFile, null);
+ }
+
+ @Override
+ protected String[] getCommand() {
+ // return the same command with 'echo' prepended
+ List<String> ret = new ArrayList<>();
+ ret.add("echo"); //$NON-NLS-1$
+ ret.addAll(Arrays.asList(super.getCommand()));
+ return ret.toArray(new String[ret.size()]);
+ }
+
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/FindActionTest.java b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/FindActionTest.java
index d00f9c8d83..e8d6f4731a 100644
--- a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/FindActionTest.java
+++ b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/FindActionTest.java
@@ -21,85 +21,85 @@ import org.junit.Test;
* Tests for perf source disassembly find text dialog.
*/
public class FindActionTest {
- private static final String SAMPLE_STRS[] = new String[] { "sample", "styled", "text", " ", "tyled", "ample" };
+ private static final String SAMPLE_STRS[] = new String[] { "sample", "styled", "text", " ", "tyled", "ample" };
- @Test
- public void testFindAction() {
- for (String strFind : SAMPLE_STRS) {
- int[] offsets = new int[] { 0, strFind.length()/2, strFind.length()};
- for (int offset : offsets) {
- testForwardSearch(offset , strFind);
- testBackwardSearch(offset , strFind);
- }
- }
- }
+ @Test
+ public void testFindAction() {
+ for (String strFind : SAMPLE_STRS) {
+ int[] offsets = new int[] { 0, strFind.length()/2, strFind.length()};
+ for (int offset : offsets) {
+ testForwardSearch(offset , strFind);
+ testBackwardSearch(offset , strFind);
+ }
+ }
+ }
- /**
- * Test forward search functionality.
- * @param offset offset at which searching starts
- * @param findStr the string to find
- */
- private void testForwardSearch(int offset, String findStr) {
- StubSourceDisassemblyView stubView = new StubSourceDisassemblyView();
- String searchStr = stubView.getContent();
- int[] indices = new int[]{
- /*
- * SourceDisassemblyView#findAndSelect parameters:
- * - widgetOffset, findstring, searchforward, casesensitive, wholeword
- */
- stubView.findAndSelect(offset, findStr, true, true, false),
- stubView.findAndSelect(offset, findStr, true, false, false)
- };
+ /**
+ * Test forward search functionality.
+ * @param offset offset at which searching starts
+ * @param findStr the string to find
+ */
+ private void testForwardSearch(int offset, String findStr) {
+ StubSourceDisassemblyView stubView = new StubSourceDisassemblyView();
+ String searchStr = stubView.getContent();
+ int[] indices = new int[]{
+ /*
+ * SourceDisassemblyView#findAndSelect parameters:
+ * - widgetOffset, findstring, searchforward, casesensitive, wholeword
+ */
+ stubView.findAndSelect(offset, findStr, true, true, false),
+ stubView.findAndSelect(offset, findStr, true, false, false)
+ };
- int expected = -1;
- for(int actual : indices){
- expected = searchStr.indexOf(findStr, offset);
- assertEquals("Failed on the following case:"
- + " offset= " + offset
- + " substring= " + findStr,
- expected, actual);
- }
- }
+ int expected = -1;
+ for(int actual : indices){
+ expected = searchStr.indexOf(findStr, offset);
+ assertEquals("Failed on the following case:"
+ + " offset= " + offset
+ + " substring= " + findStr,
+ expected, actual);
+ }
+ }
- /**
- * Test backward search functionality.
- * @param offset offset at which searching starts
- * @param findStr the string to find
- */
- private void testBackwardSearch(int offset, String findStr) {
+ /**
+ * Test backward search functionality.
+ * @param offset offset at which searching starts
+ * @param findStr the string to find
+ */
+ private void testBackwardSearch(int offset, String findStr) {
- StubSourceDisassemblyView stubView = new StubSourceDisassemblyView();
- String searchStr = stubView.getContent().substring(0, offset);
- int[] indices = new int[]{
- /*
- * SourceDisassemblyView#findAndSelect parameters:
- * - widgetOffset, findString, searchForward, caseSensitive, wholeWord
- */
- stubView.findAndSelect(offset, findStr, false, true, false),
- stubView.findAndSelect(offset, findStr, false, false, false)
- };
+ StubSourceDisassemblyView stubView = new StubSourceDisassemblyView();
+ String searchStr = stubView.getContent().substring(0, offset);
+ int[] indices = new int[]{
+ /*
+ * SourceDisassemblyView#findAndSelect parameters:
+ * - widgetOffset, findString, searchForward, caseSensitive, wholeWord
+ */
+ stubView.findAndSelect(offset, findStr, false, true, false),
+ stubView.findAndSelect(offset, findStr, false, false, false)
+ };
- int expected = -1;
- for(int actual : indices){
- expected = searchStr.lastIndexOf(findStr, offset - 1);
- assertEquals("Failed on the following case:"
- + " offset= " + offset
- + " substring= " + findStr,
- expected, actual);
- }
- }
+ int expected = -1;
+ for(int actual : indices){
+ expected = searchStr.lastIndexOf(findStr, offset - 1);
+ assertEquals("Failed on the following case:"
+ + " offset= " + offset
+ + " substring= " + findStr,
+ expected, actual);
+ }
+ }
- /**
- * Stub source disassemlby view part.
- */
- private static class StubSourceDisassemblyView extends
- SourceDisassemblyView {
- public StubSourceDisassemblyView() {
- Shell parent = new Shell();
- StyledText txt = new StyledText(parent, SWT.DEFAULT);
- txt.setText("sample styled text");
- txt.setEditable(false);
- setStyledText(txt);
- }
- }
+ /**
+ * Stub source disassemlby view part.
+ */
+ private static class StubSourceDisassemblyView extends
+ SourceDisassemblyView {
+ public StubSourceDisassemblyView() {
+ Shell parent = new Shell();
+ StyledText txt = new StyledText(parent, SWT.DEFAULT);
+ txt.setText("sample styled text");
+ txt.setEditable(false);
+ setStyledText(txt);
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchRemoteTest.java b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchRemoteTest.java
index 1dbdf3fd4f..727b378951 100644
--- a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchRemoteTest.java
+++ b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchRemoteTest.java
@@ -34,70 +34,70 @@ import org.osgi.framework.FrameworkUtil;
public class LaunchRemoteTest extends AbstractRemoteTest {
- private ILaunchConfiguration config;
- private PerfLaunchConfigDelegate delegate;
- private ILaunch launch;
- private ILaunchConfigurationWorkingCopy wc;
- private IProject project;
+ private ILaunchConfiguration config;
+ private PerfLaunchConfigDelegate delegate;
+ private ILaunch launch;
+ private ILaunchConfigurationWorkingCopy wc;
+ private IProject project;
- private final String CONNECTION_NAME = "localhost"; //$NON-NLS-1$
- private final String CONNECTION_DIR = "/tmp/eclipse-perf-ext_project_test/"; //$NON-NLS-1$
- private final String EXTERNAL_PROJECT_PATH = "remotetools://"+ CONNECTION_NAME + CONNECTION_DIR; //$NON-NLS-1$
- private final String PROJECT_NAME = "fibTest"; //$NON-NLS-1$
- private final String SOURCE_FILE = "fib.cpp"; //$NON-NLS-1$
+ private final String CONNECTION_NAME = "localhost"; //$NON-NLS-1$
+ private final String CONNECTION_DIR = "/tmp/eclipse-perf-ext_project_test/"; //$NON-NLS-1$
+ private final String EXTERNAL_PROJECT_PATH = "remotetools://"+ CONNECTION_NAME + CONNECTION_DIR; //$NON-NLS-1$
+ private final String PROJECT_NAME = "fibTest"; //$NON-NLS-1$
+ private final String SOURCE_FILE = "fib.cpp"; //$NON-NLS-1$
- @Before
- public void setUp() throws Exception {
- if ((!(AbstractRemoteTest.USERNAME.isEmpty()))) {
- project = createRemoteExternalProjectAndBuild(FrameworkUtil.getBundle(this.getClass()),
- PROJECT_NAME, EXTERNAL_PROJECT_PATH, SOURCE_FILE);
+ @Before
+ public void setUp() throws Exception {
+ if ((!(AbstractRemoteTest.USERNAME.isEmpty()))) {
+ project = createRemoteExternalProjectAndBuild(FrameworkUtil.getBundle(this.getClass()),
+ PROJECT_NAME, EXTERNAL_PROJECT_PATH, SOURCE_FILE);
- config = createConfiguration(project);
- delegate = new PerfLaunchConfigDelegate();
- launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
- wc = config.getWorkingCopy();
- setProfileAttributes(wc);
- }
- }
+ config = createConfiguration(project);
+ delegate = new PerfLaunchConfigDelegate();
+ launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
+ wc = config.getWorkingCopy();
+ setProfileAttributes(wc);
+ }
+ }
- @After
- public void tearDown() {
- if (!(AbstractRemoteTest.USERNAME.isEmpty())) {
- deleteResource(CONNECTION_DIR);
- }
- }
+ @After
+ public void tearDown() {
+ if (!(AbstractRemoteTest.USERNAME.isEmpty())) {
+ deleteResource(CONNECTION_DIR);
+ }
+ }
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(PerfPlugin.LAUNCHCONF_ID);
- }
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(PerfPlugin.LAUNCHCONF_ID);
+ }
- @Override
- protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- PerfEventsTab eventsTab = new PerfEventsTab();
- PerfOptionsTab optionsTab = new PerfOptionsTab();
- wc.setAttribute(PerfPlugin.ATTR_SourceLineNumbers, false);
- eventsTab.setDefaults(wc);
- optionsTab.setDefaults(wc);
- }
+ @Override
+ protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ PerfEventsTab eventsTab = new PerfEventsTab();
+ PerfOptionsTab optionsTab = new PerfOptionsTab();
+ wc.setAttribute(PerfPlugin.ATTR_SourceLineNumbers, false);
+ eventsTab.setDefaults(wc);
+ optionsTab.setDefaults(wc);
+ }
- @Test
- public void testDefaultRun() throws CoreException {
- if (!(AbstractRemoteTest.USERNAME.isEmpty())) {
- delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
- }
- }
+ @Test
+ public void testDefaultRun() throws CoreException {
+ if (!(AbstractRemoteTest.USERNAME.isEmpty())) {
+ delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
+ }
+ }
- @Test
- public void testClockEventRun() throws CoreException {
- if (!(AbstractRemoteTest.USERNAME.isEmpty())) {
- ArrayList<String> list = new ArrayList<>();
- list.addAll(Arrays.asList(new String[] { "cpu-clock", "task-clock",
- "cycles" }));
- wc.setAttribute(PerfPlugin.ATTR_DefaultEvent, false);
- wc.setAttribute(PerfPlugin.ATTR_SelectedEvents, list);
- delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
- }
- }
+ @Test
+ public void testClockEventRun() throws CoreException {
+ if (!(AbstractRemoteTest.USERNAME.isEmpty())) {
+ ArrayList<String> list = new ArrayList<>();
+ list.addAll(Arrays.asList(new String[] { "cpu-clock", "task-clock",
+ "cycles" }));
+ wc.setAttribute(PerfPlugin.ATTR_DefaultEvent, false);
+ wc.setAttribute(PerfPlugin.ATTR_SelectedEvents, list);
+ delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchTabsTest.java b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchTabsTest.java
index a218aae6c4..b945cb2cad 100644
--- a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchTabsTest.java
+++ b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchTabsTest.java
@@ -38,202 +38,202 @@ import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.Version;
public class LaunchTabsTest extends AbstractTest {
- private ILaunchConfiguration config;
- private Shell testShell;
-
- @Before
- public void setUp() throws Exception {
- proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), "fibTest"); //$NON-NLS-1$
- config = createConfiguration(proj.getProject());
- testShell = new Shell(Display.getDefault());
- testShell.setLayout(new GridLayout());
- }
-
- @After
- public void tearDown() throws Exception {
- testShell.dispose();
- deleteProject(proj);
- }
-
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(PerfPlugin.LAUNCHCONF_ID);
- }
-
- @Override
- protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- PerfEventsTab eventsTab = new PerfEventsTab();
- PerfOptionsTab optionsTab = new PerfOptionsTab();
- eventsTab.setDefaults(wc);
- optionsTab.setDefaults(wc);
- }
-
-
- //getter functions for otherwise unaccessible member variables
- private static class TestOptionsTab extends PerfOptionsTab {
- protected Text getTxtKernelLocation() { return txtKernelLocation; }
- protected Button getChkRecordRealtime() { return chkRecordRealtime; }
- protected Button getChkRecordVerbose() { return chkRecordVerbose; }
- protected Button getChkSourceLineNumbers() { return chkSourceLineNumbers; }
- protected Button getChkKernelSourceLineNumbers() { return chkKernelSourceLineNumbers; }
- protected Button getChkMultiplexEvents() { return chkMultiplexEvents; }
- protected Button getChkModuleSymbols() { return chkModuleSymbols; }
- protected Button getChkHideUnresolvedSymbols() { return chkHideUnresolvedSymbols; }
- }
- @Test
- public void testOptionsTab() throws CoreException {
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- TestOptionsTab tab = new TestOptionsTab();
- tab.createControl(new Shell());
- assertNotNull(tab.getImage());
- assertNotNull(tab.getName());
-
- //default config
- tab.setDefaults(wc);
- tab.initializeFrom(config);
- assertTrue(tab.isValid(config));
-
- Button rrCheck = tab.getChkRecordRealtime();
- rrCheck.setSelection(true);
- rrCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(true, config.getAttribute(PerfPlugin.ATTR_Record_Realtime, false));
- rrCheck.setSelection(false);
- rrCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(false, config.getAttribute(PerfPlugin.ATTR_Record_Realtime, true));
-
- Button rvCheck = tab.getChkRecordVerbose();
- rvCheck.setSelection(true);
- rvCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(true, config.getAttribute(PerfPlugin.ATTR_Record_Verbose, false));
- rvCheck.setSelection(false);
- rvCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(false, config.getAttribute(PerfPlugin.ATTR_Record_Verbose, true));
-
- Button slcCheck = tab.getChkSourceLineNumbers();
- slcCheck.setSelection(true);
- slcCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(true, config.getAttribute(PerfPlugin.ATTR_SourceLineNumbers, false));
- slcCheck.setSelection(false);
- slcCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(false, config.getAttribute(PerfPlugin.ATTR_SourceLineNumbers, true));
-
- Button kslcCheck = tab.getChkKernelSourceLineNumbers();
- kslcCheck.setSelection(true);
- kslcCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(true, config.getAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, false));
- kslcCheck.setSelection(false);
- kslcCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(false, config.getAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, true));
-
- Version version = PerfCore.getPerfVersion(config);
- Button meCheck = tab.getChkMultiplexEvents();
- if (meCheck.isEnabled()) {
- assertTrue (version != null && new Version(2, 6, 35).compareTo(version) > 0);
-
- meCheck.setSelection(true);
- meCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(true, config.getAttribute(PerfPlugin.ATTR_Multiplex, false));
- meCheck.setSelection(false);
- meCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(false, config.getAttribute(PerfPlugin.ATTR_Multiplex, true));
- } else {
- assertTrue (version == null || new Version(2, 6, 35).compareTo(version) < 0);
- }
-
- Button msCheck = tab.getChkModuleSymbols();
- msCheck.setSelection(true);
- msCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(true, config.getAttribute(PerfPlugin.ATTR_ModuleSymbols, false));
- msCheck.setSelection(false);
- msCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(false, config.getAttribute(PerfPlugin.ATTR_ModuleSymbols, true));
-
- Button husCheck = tab.getChkHideUnresolvedSymbols();
- husCheck.setSelection(true);
- husCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(true, config.getAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, false));
- husCheck.setSelection(false);
- husCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertEquals(false, config.getAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, true));
-
- rrCheck.setSelection(true);
- rrCheck.notifyListeners(SWT.Selection, null);
- rvCheck.setSelection(true);
- rvCheck.notifyListeners(SWT.Selection, null);
- slcCheck.setSelection(true);
- slcCheck.notifyListeners(SWT.Selection, null);
- kslcCheck.setSelection(true);
- kslcCheck.notifyListeners(SWT.Selection, null);
- meCheck.setSelection(true);
- meCheck.notifyListeners(SWT.Selection, null);
- msCheck.setSelection(true);
- msCheck.notifyListeners(SWT.Selection, null);
- husCheck.setSelection(true);
- husCheck.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- tab.initializeFrom(config);
- assertTrue(rrCheck.getSelection());
- assertTrue(rvCheck.getSelection());
- assertTrue(slcCheck.getSelection());
- assertTrue(kslcCheck.getSelection());
- assertTrue(meCheck.getSelection());
- assertTrue(msCheck.getSelection());
- assertTrue(husCheck.getSelection());
-
- Text klocText = tab.getTxtKernelLocation();
- klocText.setText("doesntexist"); //$NON-NLS-1$
- klocText.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertFalse(tab.isValid(config));
-
- klocText.setText(""); //$NON-NLS-1$
- klocText.notifyListeners(SWT.Selection, null);
- performApply(tab, wc);
- assertTrue(tab.isValid(config));
- }
-
- //getter functions for otherwise unaccessible member variables
- private static class TestEventsTab extends PerfEventsTab {
- public Button get_chkDefaultEvent() { return chkDefaultEvent; }
- }
-
- @Test
- public void testEventsTab() throws CoreException {
- TestEventsTab tab = new TestEventsTab();
- tab.createControl(new Shell());
- assertNotNull(tab.getImage());
- assertNotNull(tab.getName());
-
- //default config
- tab.setDefaults(config.getWorkingCopy());
- tab.initializeFrom(config);
- assertTrue(tab.isValid(config));
-
- assertTrue(tab.get_chkDefaultEvent().getSelection());
-
- tab.get_chkDefaultEvent().notifyListeners(SWT.Selection, null);
- tab.get_chkDefaultEvent().setSelection(false);
- tab.get_chkDefaultEvent().notifyListeners(SWT.Selection, null);
- assertFalse(tab.get_chkDefaultEvent().getSelection());
- }
-
- public void performApply (ILaunchConfigurationTab tab, ILaunchConfigurationWorkingCopy wc) throws CoreException {
- tab.performApply(wc);
- wc.doSave();
- }
+ private ILaunchConfiguration config;
+ private Shell testShell;
+
+ @Before
+ public void setUp() throws Exception {
+ proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), "fibTest"); //$NON-NLS-1$
+ config = createConfiguration(proj.getProject());
+ testShell = new Shell(Display.getDefault());
+ testShell.setLayout(new GridLayout());
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ testShell.dispose();
+ deleteProject(proj);
+ }
+
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(PerfPlugin.LAUNCHCONF_ID);
+ }
+
+ @Override
+ protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ PerfEventsTab eventsTab = new PerfEventsTab();
+ PerfOptionsTab optionsTab = new PerfOptionsTab();
+ eventsTab.setDefaults(wc);
+ optionsTab.setDefaults(wc);
+ }
+
+
+ //getter functions for otherwise unaccessible member variables
+ private static class TestOptionsTab extends PerfOptionsTab {
+ protected Text getTxtKernelLocation() { return txtKernelLocation; }
+ protected Button getChkRecordRealtime() { return chkRecordRealtime; }
+ protected Button getChkRecordVerbose() { return chkRecordVerbose; }
+ protected Button getChkSourceLineNumbers() { return chkSourceLineNumbers; }
+ protected Button getChkKernelSourceLineNumbers() { return chkKernelSourceLineNumbers; }
+ protected Button getChkMultiplexEvents() { return chkMultiplexEvents; }
+ protected Button getChkModuleSymbols() { return chkModuleSymbols; }
+ protected Button getChkHideUnresolvedSymbols() { return chkHideUnresolvedSymbols; }
+ }
+ @Test
+ public void testOptionsTab() throws CoreException {
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ TestOptionsTab tab = new TestOptionsTab();
+ tab.createControl(new Shell());
+ assertNotNull(tab.getImage());
+ assertNotNull(tab.getName());
+
+ //default config
+ tab.setDefaults(wc);
+ tab.initializeFrom(config);
+ assertTrue(tab.isValid(config));
+
+ Button rrCheck = tab.getChkRecordRealtime();
+ rrCheck.setSelection(true);
+ rrCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(true, config.getAttribute(PerfPlugin.ATTR_Record_Realtime, false));
+ rrCheck.setSelection(false);
+ rrCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(false, config.getAttribute(PerfPlugin.ATTR_Record_Realtime, true));
+
+ Button rvCheck = tab.getChkRecordVerbose();
+ rvCheck.setSelection(true);
+ rvCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(true, config.getAttribute(PerfPlugin.ATTR_Record_Verbose, false));
+ rvCheck.setSelection(false);
+ rvCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(false, config.getAttribute(PerfPlugin.ATTR_Record_Verbose, true));
+
+ Button slcCheck = tab.getChkSourceLineNumbers();
+ slcCheck.setSelection(true);
+ slcCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(true, config.getAttribute(PerfPlugin.ATTR_SourceLineNumbers, false));
+ slcCheck.setSelection(false);
+ slcCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(false, config.getAttribute(PerfPlugin.ATTR_SourceLineNumbers, true));
+
+ Button kslcCheck = tab.getChkKernelSourceLineNumbers();
+ kslcCheck.setSelection(true);
+ kslcCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(true, config.getAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, false));
+ kslcCheck.setSelection(false);
+ kslcCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(false, config.getAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, true));
+
+ Version version = PerfCore.getPerfVersion(config);
+ Button meCheck = tab.getChkMultiplexEvents();
+ if (meCheck.isEnabled()) {
+ assertTrue (version != null && new Version(2, 6, 35).compareTo(version) > 0);
+
+ meCheck.setSelection(true);
+ meCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(true, config.getAttribute(PerfPlugin.ATTR_Multiplex, false));
+ meCheck.setSelection(false);
+ meCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(false, config.getAttribute(PerfPlugin.ATTR_Multiplex, true));
+ } else {
+ assertTrue (version == null || new Version(2, 6, 35).compareTo(version) < 0);
+ }
+
+ Button msCheck = tab.getChkModuleSymbols();
+ msCheck.setSelection(true);
+ msCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(true, config.getAttribute(PerfPlugin.ATTR_ModuleSymbols, false));
+ msCheck.setSelection(false);
+ msCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(false, config.getAttribute(PerfPlugin.ATTR_ModuleSymbols, true));
+
+ Button husCheck = tab.getChkHideUnresolvedSymbols();
+ husCheck.setSelection(true);
+ husCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(true, config.getAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, false));
+ husCheck.setSelection(false);
+ husCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertEquals(false, config.getAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, true));
+
+ rrCheck.setSelection(true);
+ rrCheck.notifyListeners(SWT.Selection, null);
+ rvCheck.setSelection(true);
+ rvCheck.notifyListeners(SWT.Selection, null);
+ slcCheck.setSelection(true);
+ slcCheck.notifyListeners(SWT.Selection, null);
+ kslcCheck.setSelection(true);
+ kslcCheck.notifyListeners(SWT.Selection, null);
+ meCheck.setSelection(true);
+ meCheck.notifyListeners(SWT.Selection, null);
+ msCheck.setSelection(true);
+ msCheck.notifyListeners(SWT.Selection, null);
+ husCheck.setSelection(true);
+ husCheck.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ tab.initializeFrom(config);
+ assertTrue(rrCheck.getSelection());
+ assertTrue(rvCheck.getSelection());
+ assertTrue(slcCheck.getSelection());
+ assertTrue(kslcCheck.getSelection());
+ assertTrue(meCheck.getSelection());
+ assertTrue(msCheck.getSelection());
+ assertTrue(husCheck.getSelection());
+
+ Text klocText = tab.getTxtKernelLocation();
+ klocText.setText("doesntexist"); //$NON-NLS-1$
+ klocText.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertFalse(tab.isValid(config));
+
+ klocText.setText(""); //$NON-NLS-1$
+ klocText.notifyListeners(SWT.Selection, null);
+ performApply(tab, wc);
+ assertTrue(tab.isValid(config));
+ }
+
+ //getter functions for otherwise unaccessible member variables
+ private static class TestEventsTab extends PerfEventsTab {
+ public Button get_chkDefaultEvent() { return chkDefaultEvent; }
+ }
+
+ @Test
+ public void testEventsTab() throws CoreException {
+ TestEventsTab tab = new TestEventsTab();
+ tab.createControl(new Shell());
+ assertNotNull(tab.getImage());
+ assertNotNull(tab.getName());
+
+ //default config
+ tab.setDefaults(config.getWorkingCopy());
+ tab.initializeFrom(config);
+ assertTrue(tab.isValid(config));
+
+ assertTrue(tab.get_chkDefaultEvent().getSelection());
+
+ tab.get_chkDefaultEvent().notifyListeners(SWT.Selection, null);
+ tab.get_chkDefaultEvent().setSelection(false);
+ tab.get_chkDefaultEvent().notifyListeners(SWT.Selection, null);
+ assertFalse(tab.get_chkDefaultEvent().getSelection());
+ }
+
+ public void performApply (ILaunchConfigurationTab tab, ILaunchConfigurationWorkingCopy wc) throws CoreException {
+ tab.performApply(wc);
+ wc.doSave();
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchTest.java b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchTest.java
index fe75308820..2ea8ed2325 100644
--- a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchTest.java
+++ b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/LaunchTest.java
@@ -33,60 +33,60 @@ import org.osgi.framework.FrameworkUtil;
public class LaunchTest extends AbstractTest {
- protected ILaunchConfiguration config;
- protected PerfLaunchConfigDelegate delegate;
- protected ILaunch launch;
- protected ILaunchConfigurationWorkingCopy wc;
+ protected ILaunchConfiguration config;
+ protected PerfLaunchConfigDelegate delegate;
+ protected ILaunch launch;
+ protected ILaunchConfigurationWorkingCopy wc;
- @Before
- public void setUp() throws Exception {
- proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), "fibTest"); //$NON-NLS-1$
- config = createConfiguration(proj.getProject());
+ @Before
+ public void setUp() throws Exception {
+ proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), "fibTest"); //$NON-NLS-1$
+ config = createConfiguration(proj.getProject());
- delegate = new PerfLaunchConfigDelegate();
- launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
- wc = config.getWorkingCopy();
- setProfileAttributes(wc);
- }
+ delegate = new PerfLaunchConfigDelegate();
+ launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
+ wc = config.getWorkingCopy();
+ setProfileAttributes(wc);
+ }
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- wc.delete();
- }
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ wc.delete();
+ }
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(PerfPlugin.LAUNCHCONF_ID);
- }
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(PerfPlugin.LAUNCHCONF_ID);
+ }
- @Override
- protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- PerfEventsTab eventsTab = new PerfEventsTab();
- PerfOptionsTab optionsTab = new PerfOptionsTab();
- wc.setAttribute(PerfPlugin.ATTR_SourceLineNumbers, false);
- wc.setAttribute(PerfPlugin.ATTR_ShowSourceDisassembly, true);
- eventsTab.setDefaults(wc);
- optionsTab.setDefaults(wc);
- }
+ @Override
+ protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ PerfEventsTab eventsTab = new PerfEventsTab();
+ PerfOptionsTab optionsTab = new PerfOptionsTab();
+ wc.setAttribute(PerfPlugin.ATTR_SourceLineNumbers, false);
+ wc.setAttribute(PerfPlugin.ATTR_ShowSourceDisassembly, true);
+ eventsTab.setDefaults(wc);
+ optionsTab.setDefaults(wc);
+ }
- @Test
- public void testDefaultRun() throws CoreException {
- if (PerfCore.checkPerfInPath(null)) {
- delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
- }
- }
+ @Test
+ public void testDefaultRun() throws CoreException {
+ if (PerfCore.checkPerfInPath(null)) {
+ delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
+ }
+ }
- @Test
- public void testClockEventRun() throws CoreException {
- if (PerfCore.checkPerfInPath(null)) {
- ArrayList<String> list = new ArrayList<>();
- list.addAll(Arrays.asList(new String[] { "cpu-clock", "task-clock",
- "cycles" }));
- wc.setAttribute(PerfPlugin.ATTR_DefaultEvent, false);
- wc.setAttribute(PerfPlugin.ATTR_SelectedEvents, list);
- delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
- }
- }
+ @Test
+ public void testClockEventRun() throws CoreException {
+ if (PerfCore.checkPerfInPath(null)) {
+ ArrayList<String> list = new ArrayList<>();
+ list.addAll(Arrays.asList(new String[] { "cpu-clock", "task-clock",
+ "cycles" }));
+ wc.setAttribute(PerfPlugin.ATTR_DefaultEvent, false);
+ wc.setAttribute(PerfPlugin.ATTR_SelectedEvents, list);
+ delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/ModelTest.java b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/ModelTest.java
index babc39f092..8e4c691339 100644
--- a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/ModelTest.java
+++ b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/ModelTest.java
@@ -57,438 +57,438 @@ import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.Version;
public class ModelTest extends AbstractTest {
- private ILaunchConfiguration config;
- private Stack<Class<?>> stack;
-
- @Before
- public void setUp() throws Exception {
- proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), "fibTest"); //$NON-NLS-1$
- config = createConfiguration(proj.getProject());
-
- Class<?>[] klassList = new Class<?>[] { PMSymbol.class, PMFile.class,
- PMDso.class, PMCommand.class, PMEvent.class };
- stack = new Stack<>();
- stack.addAll(Arrays.asList(klassList));
- }
-
- @After
- public void tearDown() throws Exception {
- deleteProject(proj);
- }
-
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(PerfPlugin.LAUNCHCONF_ID);
- }
-
- @Override
- protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- PerfEventsTab eventsTab = new PerfEventsTab();
- PerfOptionsTab optionsTab = new PerfOptionsTab();
- wc.setAttribute(PerfPlugin.ATTR_SourceLineNumbers, false);
- eventsTab.setDefaults(wc);
- optionsTab.setDefaults(wc);
- }
- @Test
- public void testModelDefaultGenericStructure() {
- TreeParent invisibleRoot = buildModel(
- "resources/defaultevent-data/perf.data",
- "resources/defaultevent-data/perf.data.txt",
- "resources/defaultevent-data/perf.data.err.log");
-
- checkChildrenStructure(invisibleRoot, stack);
- }
- @Test
- public void testModelMultiEventGenericStructure() {
- TreeParent invisibleRoot = buildModel(
- "resources/multievent-data/perf.data",
- "resources/multievent-data/perf.data.txt",
- "resources/multievent-data/perf.data.err.log");
-
- checkChildrenStructure(invisibleRoot, stack);
- }
- @Test
- public void testPercentages() {
- TreeParent invisibleRoot = buildModel(
- "resources/defaultevent-data/perf.data",
- "resources/defaultevent-data/perf.data.txt",
- "resources/defaultevent-data/perf.data.err.log");
-
- checkChildrenPercentages(invisibleRoot, invisibleRoot.getPercent());
- }
- @Test
- public void testDoubleClickAction () {
- TreeParent invisibleRoot = buildModel(
- "resources/defaultevent-data/perf.data",
- "resources/defaultevent-data/perf.data.txt",
- "resources/defaultevent-data/perf.data.err.log");
-
- PerfPlugin.getDefault().setModelRoot(invisibleRoot);
- // update the model root for the view
- PerfCore.refreshView("resources/defaultevent-data/perf.data");
-
- // number of parents excluding invisibleRoot
- int numOfParents = getNumberOfParents(invisibleRoot) - 1;
-
- // create a double click action to act on the tree viewer
- try {
- PerfProfileView view = (PerfProfileView) PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage()
- .showView(PerfPlugin.VIEW_ID);
- TreeViewer tv = view.getTreeViewer();
- PerfDoubleClickAction dblClick = new PerfDoubleClickAction(tv);
-
- // double click every element
- doubleClickAllChildren(invisibleRoot, tv, dblClick);
-
- // If all elements are expanded, this is the number of elements
- // in our model that have children.
- assertEquals(numOfParents, tv.getExpandedElements().length);
- } catch (PartInitException e) {
- fail("Failed to open the Profiling View.");
- }
- }
- @Test
- public void testParserMultiEvent() {
- TreeParent invisibleRoot = buildModel(
- "resources/multievent-data/perf.data",
- "resources/multievent-data/perf.data.txt",
- "resources/multievent-data/perf.data.err.log");
-
- assertEquals(invisibleRoot.getChildren().length, 5);
-
- String cur = null;
-
- for (TreeParent event : invisibleRoot.getChildren()) {
-
- cur = event.getName();
-
- // Assert specific properties extracted by the parser.
- if ("cpu-clock".equals(cur)) {
- assertTrue(event.hasChildren());
- assertEquals(event.getChildren().length, 1);
-
- TreeParent cmd = event.getChildren()[0];
- assertEquals(cmd.getChildren().length, 1);
-
- String[] cmdLabels = { "hellotest" };
- checkCommadLabels(cmdLabels, cmd);
- } else if ("task-clock".equals(cur)) {
- assertTrue(event.hasChildren());
- assertEquals(event.getChildren().length, 1);
-
- TreeParent cmd = event.getChildren()[0];
- assertEquals(cmd.getChildren().length, 1);
-
- String[] cmdLabels = { "hellotest" };
- checkCommadLabels(cmdLabels, cmd);
- } else if ("page-faults".equals(cur)) {
- assertTrue(event.hasChildren());
- assertEquals(event.getChildren().length, 1);
-
- TreeParent cmd = event.getChildren()[0];
- assertEquals(cmd.getChildren().length, 3);
-
- String[] cmdLabels = { "ld-2.14.90.so", "[kernel.kallsyms]",
- "libc-2.14.90.so" };
- checkCommadLabels(cmdLabels, cmd);
- } else if ("minor-faults".equals(cur)) {
- assertTrue(event.hasChildren());
- assertEquals(event.getChildren().length, 1);
-
- TreeParent cmd = event.getChildren()[0];
- assertEquals(cmd.getChildren().length, 3);
-
- String[] cmdLabels = { "ld-2.14.90.so", "[kernel.kallsyms]",
- "libc-2.14.90.so" };
- checkCommadLabels(cmdLabels, cmd);
- } else if ("major-faults".equals(cur)) {
- assertFalse(event.hasChildren());
- }
-
- }
- }
- @Test
- public void testParserDefaultEvent() {
- TreeParent invisibleRoot = buildModel(
- "resources/defaultevent-data/perf.data",
- "resources/defaultevent-data/perf.data.txt",
- "resources/defaultevent-data/perf.data.err.log");
-
- // Assert specific properties extracted by the parser.
- assertEquals(invisibleRoot.getChildren().length, 1);
-
- TreeParent event = invisibleRoot.getChildren()[0];
- assertEquals(event.getName(), "cycles");
- assertTrue(event.hasChildren());
- assertEquals(event.getChildren().length, 1);
-
- TreeParent cmd = event.getChildren()[0];
- assertTrue(cmd.hasChildren());
- assertEquals(cmd.getChildren().length, 4);
-
- String[] cmdLabels = { "hellotest", "[kernel.kallsyms]",
- "ld-2.14.90.so", "perf" };
- checkCommadLabels(cmdLabels, cmd);
- }
- @Test
- public void testParseEventList() throws FileNotFoundException {
- BufferedReader input = new BufferedReader(new FileReader("resources/simple-perf-event-list"));
-
- Map<String, List<String>> eventList = PerfCore.parseEventList(input);
- for(String key : eventList.keySet()){
- if ("Raw hardware event descriptor".equals(key)) {
- assertTrue(eventList.get(key).contains("rNNN"));
- assertTrue(eventList.get(key).contains("cpu/t1=v1"));
- } else if ("Hardware breakpoint".equals(key)) {
- assertTrue(eventList.get(key).contains("mem:<addr>"));
- } else if ("Software event".equals(key)) {
- assertTrue(eventList.get(key).contains("cpu-clock"));
- assertTrue(eventList.get(key).contains("task-clock"));
- } else if ("Hardware cache event".equals(key)) {
- assertTrue(eventList.get(key).contains("L1-dcache-loads"));
- assertTrue(eventList.get(key).contains("L1-dcache-load-misses"));
- } else if ("Tracepoint event".equals(key)) {
- assertTrue(eventList.get(key).contains("mac80211:drv_return_void"));
- assertTrue(eventList.get(key).contains("mac80211:drv_return_int"));
- } else if ("Hardware event".equals(key)) {
- assertTrue(eventList.get(key).contains("cpu-cycles"));
- assertTrue(eventList.get(key).contains("stalled-cycles-frontend"));
- }
- }
- }
- @Test
- public void testParseAnnotation() throws FileNotFoundException {
- BufferedReader input = new BufferedReader(new FileReader(
- "resources/perf-annotation-data"));
-
- // Set up arguments for the annotation parser.
- IPath workingDir = Path.fromOSString("/working/directory/");
- PMCommand cmd = new PMCommand("testCommand");
- PMDso dso = new PMDso("testDso", false);
- PMFile tmpFile = new PMFile(PerfPlugin.STRINGS_UnfiledSymbols);
- PMSymbol sym = new PMSymbol("testSym", 0, 0);
-
- // Set children and respective parents.
- cmd.addChild(dso);
- dso.addChild(tmpFile);
- tmpFile.addChild(sym);
-
- dso.setParent(cmd);
- tmpFile.setParent(dso);
- sym.setParent(tmpFile);
-
- PerfCore.parseAnnotation(null, input, workingDir, dso, sym);
-
- // Expected results data.
- String expectedDsoPath = "/working/directory/fibonacci";
- String expectedFilePath = "/home/user/workspace/fibonacci/Debug/../src/fibonacci.cpp";
-
- assertTrue(expectedDsoPath.equals(dso.getPath()));
- assertEquals(dso.getChildren().length, 2);
-
- for (TreeParent dsoChild : dso.getChildren()) {
- String filePath = ((PMFile) dsoChild).getPath();
-
- if (PerfPlugin.STRINGS_UnfiledSymbols.equals(filePath)) {
- assertFalse(dsoChild.hasChildren());
- } else {
- assertTrue(expectedFilePath.equals(filePath));
- assertTrue(dsoChild.hasChildren());
- assertEquals(dsoChild.getChildren().length, 1);
-
- TreeParent curSym = dsoChild.getChildren()[0];
- assertTrue(curSym.hasChildren());
- assertEquals(curSym.getChildren().length, 5);
-
- float percentCount = 0;
- for (TreeParent symChild : curSym.getChildren()) {
- percentCount += symChild.getPercent();
- }
-
- assertEquals(Math.ceil(percentCount), 100.0, 0.0);
-
- }
- }
- }
-
- @Test
- public void testAnnotateString() throws CoreException {
- ILaunchConfigurationWorkingCopy tempConfig = config.copy("test-config");
- tempConfig
- .setAttribute(PerfPlugin.ATTR_Kernel_Location, "/boot/kernel");
- tempConfig.setAttribute(PerfPlugin.ATTR_ModuleSymbols, true);
-
- String[] annotateString = PerfCore.getAnnotateString(tempConfig, "dso",
- "symbol", "resources/defaultevent-data/perf.data", false);
-
- String[] expectedString = new String[] { PerfPlugin.PERF_COMMAND,
- "annotate", "-d", "dso", "-s", "symbol", "-l", "-P",
- "--vmlinux", "/boot/kernel", "-m", "-i",
- "resources/defaultevent-data/perf.data" };
-
- assertArrayEquals(expectedString, annotateString);
- }
-
- @Test
- public void testRecordString() throws CoreException {
- ILaunchConfigurationWorkingCopy tempConfig = config.copy("test-config");
- tempConfig.setAttribute(PerfPlugin.ATTR_Record_Realtime, true);
- tempConfig.setAttribute(PerfPlugin.ATTR_Record_Realtime_Priority, 2);
- tempConfig.setAttribute(PerfPlugin.ATTR_Record_Verbose, true);
- tempConfig.setAttribute(PerfPlugin.ATTR_Multiplex, true);
-
- ArrayList<String> selectedEvents = new ArrayList<>();
- selectedEvents.add("cpu-cycles");
- selectedEvents.add("cache-misses");
- selectedEvents.add("cpu-clock");
- tempConfig.setAttribute(PerfPlugin.ATTR_SelectedEvents, selectedEvents);
-
- tempConfig.setAttribute(PerfPlugin.ATTR_DefaultEvent, false);
-
- String[] recordString = PerfCore.getRecordString(tempConfig, new Version(0, 0, 0));
- assertNotNull(recordString);
-
- String[] expectedString = { PerfPlugin.PERF_COMMAND, "record", "-f",
- "-r", "2", "-v", "-M", "-e", "cpu-cycles", "-e", "cache-misses",
- "-e", "cpu-clock" };
- assertArrayEquals(expectedString, recordString);
- }
-
- @Test
- public void testReportString() throws CoreException {
- ILaunchConfigurationWorkingCopy tempConfig = null;
- tempConfig = config.copy("test-config");
- tempConfig
- .setAttribute(PerfPlugin.ATTR_Kernel_Location, "/boot/kernel");
- tempConfig.setAttribute(PerfPlugin.ATTR_ModuleSymbols, true);
-
- String[] reportString = PerfCore.getReportString(tempConfig,
- "resources/defaultevent-data/perf.data");
- assertNotNull(reportString);
-
- String[] expectedString = { PerfPlugin.PERF_COMMAND, "report",
- "--sort", "comm,dso,sym", "-n", "-t", "" + (char) 1,
- "--vmlinux", "/boot/kernel", "-m", "-i",
- "resources/defaultevent-data/perf.data" };
- assertArrayEquals(expectedString, reportString);
- }
-
- /**
- * @param root some element that will serve as the root
- * @param sum the expected sum of the percentages of this root's
- * immediate children
- */
- private void checkChildrenPercentages (TreeParent root, float sum) {
- float actualSum = 0;
- // If a root has no children we're done
- if (root.getChildren().length != 0) {
- for (TreeParent child : root.getChildren()) {
- actualSum += child.getPercent();
- checkChildrenPercentages(child, child.getPercent());
- }
- // some top-level elements have an undefined percentage but
- // their children have defined percentages
- // eg. the invisible root, and PMCommand
- if (actualSum != 100 && sum != -1){
- assertTrue(actualSum/sum <= 1.0 && actualSum/sum >= 0.99);
- }
- }
- }
-
- /**
- * @param root some element that will serve as the root
- * @param stack a stack of classes
- */
- private void checkChildrenStructure (TreeParent root, Stack<Class<?>> stack){
- if (!stack.isEmpty()){
- // children of root must be instances of the top class on the stack
- Class<?> klass = stack.pop();
- for (TreeParent tp : root.getChildren()){
- // tp.getClass() instanceof klass
- assertTrue(klass.isAssignableFrom(tp.getClass()));
- // each sibling needs its own stack
- Stack<Class<?>> newStack = new Stack<>();
- newStack.addAll(Arrays.asList(stack.toArray(new Class<?> [] {})));
- checkChildrenStructure(tp, newStack);
- }
- }
- }
-
- /**
- * Performs a Perf double-click action on every element in the
- * TreeViewer model.
- *
- * @param root some element that will serve as the root
- * @param tv a TreeViewer containing elements from the Perf model
- * @param dblClick the double-click action to perform on every
- * element of the TreeViewer.
- */
- private void doubleClickAllChildren(TreeParent root, TreeViewer tv,
- PerfDoubleClickAction dblClick) {
-
- for (TreeParent child : root.getChildren()) {
- // see PerfDoubleClickAction for IStructuredSelection
- tv.setSelection(new StructuredSelection(child));
- dblClick.run();
- doubleClickAllChildren(child, tv, dblClick);
- }
- }
-
- /**
- * Find the number of ancestors of the given root that have children.
- * This includes the given root in the computation.
- *
- * @param root some element that will serve as the root
- * @return the number of elements under, and including the
- * given root, that have children elements.
- */
- private int getNumberOfParents(TreeParent root) {
- int ret = root.hasChildren() ? 1 : 0;
- for (TreeParent child : root.getChildren()) {
- ret += getNumberOfParents(child);
- }
- return ret;
- }
-
- /**
- * Build model based on perf data file report.
- * @param perfDataLoc location of perf data file
- * @param perfTextDataLoc location of perf data text file
- * @param perfErrorDataLoc location of error log file
- * @return tree model based on perf data report.
- */
- private TreeParent buildModel(String perfDataLoc, String perfTextDataLoc,
- String perfErrorDataLoc) {
- TreeParent invisibleRoot = new TreeParent("");
- BufferedReader input = null;
- BufferedReader error = null;
-
- try {
- input = new BufferedReader(new FileReader(perfTextDataLoc));
- error = new BufferedReader(new FileReader(perfErrorDataLoc));
- } catch (IOException e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
-
- PerfCore.parseReport(config, null, null, perfDataLoc, null,
- invisibleRoot, false, input, error);
- return invisibleRoot;
- }
-
- /**
- * Check whether the command labels in model rooted at cmd exist in
- * list of labels cmdLabels.
- * @param cmdLabels list of command labels
- * @param cmd root of tree model
- */
- private void checkCommadLabels(String[] cmdLabels, TreeParent cmd) {
- List<String> cmdList = new ArrayList<>(Arrays.asList(cmdLabels));
-
- for (TreeParent dso : cmd.getChildren()) {
- assertTrue(cmdList.get(0).equals(dso.getName()));
- cmdList.remove(0);
- }
- }
+ private ILaunchConfiguration config;
+ private Stack<Class<?>> stack;
+
+ @Before
+ public void setUp() throws Exception {
+ proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), "fibTest"); //$NON-NLS-1$
+ config = createConfiguration(proj.getProject());
+
+ Class<?>[] klassList = new Class<?>[] { PMSymbol.class, PMFile.class,
+ PMDso.class, PMCommand.class, PMEvent.class };
+ stack = new Stack<>();
+ stack.addAll(Arrays.asList(klassList));
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ deleteProject(proj);
+ }
+
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(PerfPlugin.LAUNCHCONF_ID);
+ }
+
+ @Override
+ protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ PerfEventsTab eventsTab = new PerfEventsTab();
+ PerfOptionsTab optionsTab = new PerfOptionsTab();
+ wc.setAttribute(PerfPlugin.ATTR_SourceLineNumbers, false);
+ eventsTab.setDefaults(wc);
+ optionsTab.setDefaults(wc);
+ }
+ @Test
+ public void testModelDefaultGenericStructure() {
+ TreeParent invisibleRoot = buildModel(
+ "resources/defaultevent-data/perf.data",
+ "resources/defaultevent-data/perf.data.txt",
+ "resources/defaultevent-data/perf.data.err.log");
+
+ checkChildrenStructure(invisibleRoot, stack);
+ }
+ @Test
+ public void testModelMultiEventGenericStructure() {
+ TreeParent invisibleRoot = buildModel(
+ "resources/multievent-data/perf.data",
+ "resources/multievent-data/perf.data.txt",
+ "resources/multievent-data/perf.data.err.log");
+
+ checkChildrenStructure(invisibleRoot, stack);
+ }
+ @Test
+ public void testPercentages() {
+ TreeParent invisibleRoot = buildModel(
+ "resources/defaultevent-data/perf.data",
+ "resources/defaultevent-data/perf.data.txt",
+ "resources/defaultevent-data/perf.data.err.log");
+
+ checkChildrenPercentages(invisibleRoot, invisibleRoot.getPercent());
+ }
+ @Test
+ public void testDoubleClickAction () {
+ TreeParent invisibleRoot = buildModel(
+ "resources/defaultevent-data/perf.data",
+ "resources/defaultevent-data/perf.data.txt",
+ "resources/defaultevent-data/perf.data.err.log");
+
+ PerfPlugin.getDefault().setModelRoot(invisibleRoot);
+ // update the model root for the view
+ PerfCore.refreshView("resources/defaultevent-data/perf.data");
+
+ // number of parents excluding invisibleRoot
+ int numOfParents = getNumberOfParents(invisibleRoot) - 1;
+
+ // create a double click action to act on the tree viewer
+ try {
+ PerfProfileView view = (PerfProfileView) PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage()
+ .showView(PerfPlugin.VIEW_ID);
+ TreeViewer tv = view.getTreeViewer();
+ PerfDoubleClickAction dblClick = new PerfDoubleClickAction(tv);
+
+ // double click every element
+ doubleClickAllChildren(invisibleRoot, tv, dblClick);
+
+ // If all elements are expanded, this is the number of elements
+ // in our model that have children.
+ assertEquals(numOfParents, tv.getExpandedElements().length);
+ } catch (PartInitException e) {
+ fail("Failed to open the Profiling View.");
+ }
+ }
+ @Test
+ public void testParserMultiEvent() {
+ TreeParent invisibleRoot = buildModel(
+ "resources/multievent-data/perf.data",
+ "resources/multievent-data/perf.data.txt",
+ "resources/multievent-data/perf.data.err.log");
+
+ assertEquals(invisibleRoot.getChildren().length, 5);
+
+ String cur = null;
+
+ for (TreeParent event : invisibleRoot.getChildren()) {
+
+ cur = event.getName();
+
+ // Assert specific properties extracted by the parser.
+ if ("cpu-clock".equals(cur)) {
+ assertTrue(event.hasChildren());
+ assertEquals(event.getChildren().length, 1);
+
+ TreeParent cmd = event.getChildren()[0];
+ assertEquals(cmd.getChildren().length, 1);
+
+ String[] cmdLabels = { "hellotest" };
+ checkCommadLabels(cmdLabels, cmd);
+ } else if ("task-clock".equals(cur)) {
+ assertTrue(event.hasChildren());
+ assertEquals(event.getChildren().length, 1);
+
+ TreeParent cmd = event.getChildren()[0];
+ assertEquals(cmd.getChildren().length, 1);
+
+ String[] cmdLabels = { "hellotest" };
+ checkCommadLabels(cmdLabels, cmd);
+ } else if ("page-faults".equals(cur)) {
+ assertTrue(event.hasChildren());
+ assertEquals(event.getChildren().length, 1);
+
+ TreeParent cmd = event.getChildren()[0];
+ assertEquals(cmd.getChildren().length, 3);
+
+ String[] cmdLabels = { "ld-2.14.90.so", "[kernel.kallsyms]",
+ "libc-2.14.90.so" };
+ checkCommadLabels(cmdLabels, cmd);
+ } else if ("minor-faults".equals(cur)) {
+ assertTrue(event.hasChildren());
+ assertEquals(event.getChildren().length, 1);
+
+ TreeParent cmd = event.getChildren()[0];
+ assertEquals(cmd.getChildren().length, 3);
+
+ String[] cmdLabels = { "ld-2.14.90.so", "[kernel.kallsyms]",
+ "libc-2.14.90.so" };
+ checkCommadLabels(cmdLabels, cmd);
+ } else if ("major-faults".equals(cur)) {
+ assertFalse(event.hasChildren());
+ }
+
+ }
+ }
+ @Test
+ public void testParserDefaultEvent() {
+ TreeParent invisibleRoot = buildModel(
+ "resources/defaultevent-data/perf.data",
+ "resources/defaultevent-data/perf.data.txt",
+ "resources/defaultevent-data/perf.data.err.log");
+
+ // Assert specific properties extracted by the parser.
+ assertEquals(invisibleRoot.getChildren().length, 1);
+
+ TreeParent event = invisibleRoot.getChildren()[0];
+ assertEquals(event.getName(), "cycles");
+ assertTrue(event.hasChildren());
+ assertEquals(event.getChildren().length, 1);
+
+ TreeParent cmd = event.getChildren()[0];
+ assertTrue(cmd.hasChildren());
+ assertEquals(cmd.getChildren().length, 4);
+
+ String[] cmdLabels = { "hellotest", "[kernel.kallsyms]",
+ "ld-2.14.90.so", "perf" };
+ checkCommadLabels(cmdLabels, cmd);
+ }
+ @Test
+ public void testParseEventList() throws FileNotFoundException {
+ BufferedReader input = new BufferedReader(new FileReader("resources/simple-perf-event-list"));
+
+ Map<String, List<String>> eventList = PerfCore.parseEventList(input);
+ for(String key : eventList.keySet()){
+ if ("Raw hardware event descriptor".equals(key)) {
+ assertTrue(eventList.get(key).contains("rNNN"));
+ assertTrue(eventList.get(key).contains("cpu/t1=v1"));
+ } else if ("Hardware breakpoint".equals(key)) {
+ assertTrue(eventList.get(key).contains("mem:<addr>"));
+ } else if ("Software event".equals(key)) {
+ assertTrue(eventList.get(key).contains("cpu-clock"));
+ assertTrue(eventList.get(key).contains("task-clock"));
+ } else if ("Hardware cache event".equals(key)) {
+ assertTrue(eventList.get(key).contains("L1-dcache-loads"));
+ assertTrue(eventList.get(key).contains("L1-dcache-load-misses"));
+ } else if ("Tracepoint event".equals(key)) {
+ assertTrue(eventList.get(key).contains("mac80211:drv_return_void"));
+ assertTrue(eventList.get(key).contains("mac80211:drv_return_int"));
+ } else if ("Hardware event".equals(key)) {
+ assertTrue(eventList.get(key).contains("cpu-cycles"));
+ assertTrue(eventList.get(key).contains("stalled-cycles-frontend"));
+ }
+ }
+ }
+ @Test
+ public void testParseAnnotation() throws FileNotFoundException {
+ BufferedReader input = new BufferedReader(new FileReader(
+ "resources/perf-annotation-data"));
+
+ // Set up arguments for the annotation parser.
+ IPath workingDir = Path.fromOSString("/working/directory/");
+ PMCommand cmd = new PMCommand("testCommand");
+ PMDso dso = new PMDso("testDso", false);
+ PMFile tmpFile = new PMFile(PerfPlugin.STRINGS_UnfiledSymbols);
+ PMSymbol sym = new PMSymbol("testSym", 0, 0);
+
+ // Set children and respective parents.
+ cmd.addChild(dso);
+ dso.addChild(tmpFile);
+ tmpFile.addChild(sym);
+
+ dso.setParent(cmd);
+ tmpFile.setParent(dso);
+ sym.setParent(tmpFile);
+
+ PerfCore.parseAnnotation(null, input, workingDir, dso, sym);
+
+ // Expected results data.
+ String expectedDsoPath = "/working/directory/fibonacci";
+ String expectedFilePath = "/home/user/workspace/fibonacci/Debug/../src/fibonacci.cpp";
+
+ assertTrue(expectedDsoPath.equals(dso.getPath()));
+ assertEquals(dso.getChildren().length, 2);
+
+ for (TreeParent dsoChild : dso.getChildren()) {
+ String filePath = ((PMFile) dsoChild).getPath();
+
+ if (PerfPlugin.STRINGS_UnfiledSymbols.equals(filePath)) {
+ assertFalse(dsoChild.hasChildren());
+ } else {
+ assertTrue(expectedFilePath.equals(filePath));
+ assertTrue(dsoChild.hasChildren());
+ assertEquals(dsoChild.getChildren().length, 1);
+
+ TreeParent curSym = dsoChild.getChildren()[0];
+ assertTrue(curSym.hasChildren());
+ assertEquals(curSym.getChildren().length, 5);
+
+ float percentCount = 0;
+ for (TreeParent symChild : curSym.getChildren()) {
+ percentCount += symChild.getPercent();
+ }
+
+ assertEquals(Math.ceil(percentCount), 100.0, 0.0);
+
+ }
+ }
+ }
+
+ @Test
+ public void testAnnotateString() throws CoreException {
+ ILaunchConfigurationWorkingCopy tempConfig = config.copy("test-config");
+ tempConfig
+ .setAttribute(PerfPlugin.ATTR_Kernel_Location, "/boot/kernel");
+ tempConfig.setAttribute(PerfPlugin.ATTR_ModuleSymbols, true);
+
+ String[] annotateString = PerfCore.getAnnotateString(tempConfig, "dso",
+ "symbol", "resources/defaultevent-data/perf.data", false);
+
+ String[] expectedString = new String[] { PerfPlugin.PERF_COMMAND,
+ "annotate", "-d", "dso", "-s", "symbol", "-l", "-P",
+ "--vmlinux", "/boot/kernel", "-m", "-i",
+ "resources/defaultevent-data/perf.data" };
+
+ assertArrayEquals(expectedString, annotateString);
+ }
+
+ @Test
+ public void testRecordString() throws CoreException {
+ ILaunchConfigurationWorkingCopy tempConfig = config.copy("test-config");
+ tempConfig.setAttribute(PerfPlugin.ATTR_Record_Realtime, true);
+ tempConfig.setAttribute(PerfPlugin.ATTR_Record_Realtime_Priority, 2);
+ tempConfig.setAttribute(PerfPlugin.ATTR_Record_Verbose, true);
+ tempConfig.setAttribute(PerfPlugin.ATTR_Multiplex, true);
+
+ ArrayList<String> selectedEvents = new ArrayList<>();
+ selectedEvents.add("cpu-cycles");
+ selectedEvents.add("cache-misses");
+ selectedEvents.add("cpu-clock");
+ tempConfig.setAttribute(PerfPlugin.ATTR_SelectedEvents, selectedEvents);
+
+ tempConfig.setAttribute(PerfPlugin.ATTR_DefaultEvent, false);
+
+ String[] recordString = PerfCore.getRecordString(tempConfig, new Version(0, 0, 0));
+ assertNotNull(recordString);
+
+ String[] expectedString = { PerfPlugin.PERF_COMMAND, "record", "-f",
+ "-r", "2", "-v", "-M", "-e", "cpu-cycles", "-e", "cache-misses",
+ "-e", "cpu-clock" };
+ assertArrayEquals(expectedString, recordString);
+ }
+
+ @Test
+ public void testReportString() throws CoreException {
+ ILaunchConfigurationWorkingCopy tempConfig = null;
+ tempConfig = config.copy("test-config");
+ tempConfig
+ .setAttribute(PerfPlugin.ATTR_Kernel_Location, "/boot/kernel");
+ tempConfig.setAttribute(PerfPlugin.ATTR_ModuleSymbols, true);
+
+ String[] reportString = PerfCore.getReportString(tempConfig,
+ "resources/defaultevent-data/perf.data");
+ assertNotNull(reportString);
+
+ String[] expectedString = { PerfPlugin.PERF_COMMAND, "report",
+ "--sort", "comm,dso,sym", "-n", "-t", "" + (char) 1,
+ "--vmlinux", "/boot/kernel", "-m", "-i",
+ "resources/defaultevent-data/perf.data" };
+ assertArrayEquals(expectedString, reportString);
+ }
+
+ /**
+ * @param root some element that will serve as the root
+ * @param sum the expected sum of the percentages of this root's
+ * immediate children
+ */
+ private void checkChildrenPercentages (TreeParent root, float sum) {
+ float actualSum = 0;
+ // If a root has no children we're done
+ if (root.getChildren().length != 0) {
+ for (TreeParent child : root.getChildren()) {
+ actualSum += child.getPercent();
+ checkChildrenPercentages(child, child.getPercent());
+ }
+ // some top-level elements have an undefined percentage but
+ // their children have defined percentages
+ // eg. the invisible root, and PMCommand
+ if (actualSum != 100 && sum != -1){
+ assertTrue(actualSum/sum <= 1.0 && actualSum/sum >= 0.99);
+ }
+ }
+ }
+
+ /**
+ * @param root some element that will serve as the root
+ * @param stack a stack of classes
+ */
+ private void checkChildrenStructure (TreeParent root, Stack<Class<?>> stack){
+ if (!stack.isEmpty()){
+ // children of root must be instances of the top class on the stack
+ Class<?> klass = stack.pop();
+ for (TreeParent tp : root.getChildren()){
+ // tp.getClass() instanceof klass
+ assertTrue(klass.isAssignableFrom(tp.getClass()));
+ // each sibling needs its own stack
+ Stack<Class<?>> newStack = new Stack<>();
+ newStack.addAll(Arrays.asList(stack.toArray(new Class<?> [] {})));
+ checkChildrenStructure(tp, newStack);
+ }
+ }
+ }
+
+ /**
+ * Performs a Perf double-click action on every element in the
+ * TreeViewer model.
+ *
+ * @param root some element that will serve as the root
+ * @param tv a TreeViewer containing elements from the Perf model
+ * @param dblClick the double-click action to perform on every
+ * element of the TreeViewer.
+ */
+ private void doubleClickAllChildren(TreeParent root, TreeViewer tv,
+ PerfDoubleClickAction dblClick) {
+
+ for (TreeParent child : root.getChildren()) {
+ // see PerfDoubleClickAction for IStructuredSelection
+ tv.setSelection(new StructuredSelection(child));
+ dblClick.run();
+ doubleClickAllChildren(child, tv, dblClick);
+ }
+ }
+
+ /**
+ * Find the number of ancestors of the given root that have children.
+ * This includes the given root in the computation.
+ *
+ * @param root some element that will serve as the root
+ * @return the number of elements under, and including the
+ * given root, that have children elements.
+ */
+ private int getNumberOfParents(TreeParent root) {
+ int ret = root.hasChildren() ? 1 : 0;
+ for (TreeParent child : root.getChildren()) {
+ ret += getNumberOfParents(child);
+ }
+ return ret;
+ }
+
+ /**
+ * Build model based on perf data file report.
+ * @param perfDataLoc location of perf data file
+ * @param perfTextDataLoc location of perf data text file
+ * @param perfErrorDataLoc location of error log file
+ * @return tree model based on perf data report.
+ */
+ private TreeParent buildModel(String perfDataLoc, String perfTextDataLoc,
+ String perfErrorDataLoc) {
+ TreeParent invisibleRoot = new TreeParent("");
+ BufferedReader input = null;
+ BufferedReader error = null;
+
+ try {
+ input = new BufferedReader(new FileReader(perfTextDataLoc));
+ error = new BufferedReader(new FileReader(perfErrorDataLoc));
+ } catch (IOException e) {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+
+ PerfCore.parseReport(config, null, null, perfDataLoc, null,
+ invisibleRoot, false, input, error);
+ return invisibleRoot;
+ }
+
+ /**
+ * Check whether the command labels in model rooted at cmd exist in
+ * list of labels cmdLabels.
+ * @param cmdLabels list of command labels
+ * @param cmd root of tree model
+ */
+ private void checkCommadLabels(String[] cmdLabels, TreeParent cmd) {
+ List<String> cmdList = new ArrayList<>(Arrays.asList(cmdLabels));
+
+ for (TreeParent dso : cmd.getChildren()) {
+ assertTrue(cmdList.get(0).equals(dso.getName()));
+ cmdList.remove(0);
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/SaveSessionTest.java b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/SaveSessionTest.java
index bdd905bfbc..3bf23d0035 100644
--- a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/SaveSessionTest.java
+++ b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/SaveSessionTest.java
@@ -30,111 +30,111 @@ import org.junit.After;
import org.junit.Test;
public class SaveSessionTest {
- private static final String WORKING_DIR = "resources/"; //$NON-NLS-1$
- private static final String DATA_FILE_PATH = "/mock/data/path"; //$NON-NLS-1$
- private static final String PERF_DATA_FILE_PATH = "resources/perf.data"; //$NON-NLS-1$
- private static final String PERF_STATS_FILE_PATH = "stat_data"; //$NON-NLS-1$
- private static final String DATA_FILE_NAME = "data"; //$NON-NLS-1$
- private static final String DATA_FILE_EXT = "ext"; //$NON-NLS-1$
- private ArrayList<IPath> testFiles = new ArrayList<>();
-
- @After
- public void tearDown(){
- for (IPath f : testFiles) {
- File file = f.toFile();
- assertTrue(file.delete());
- }
- }
-
- @Test
- public void testGenericHandler() {
- GenericSaveDataHandler handler = new GenericSaveDataHandler();
- assertTrue(handler.canSave(Path.fromOSString(DATA_FILE_PATH)));
- assertEquals(WORKING_DIR, handler.getWorkingDir().toOSString());
-
- IPath path = handler.getNewDataLocation(DATA_FILE_NAME, DATA_FILE_EXT);
- assertEquals(WORKING_DIR + DATA_FILE_NAME + '.' + DATA_FILE_EXT,
- path.toOSString());
-
- assertTrue(handler.isEnabled());
- assertTrue(handler.isHandled());
- }
- @Test
- public void testPerfSaveSessionHandler() {
- PerfSaveSessionTestHandler handler = new PerfSaveSessionTestHandler();
-
- PerfPlugin.getDefault().setPerfProfileData(null);
- assertFalse(handler.verifyData());
-
- PerfPlugin.getDefault().setPerfProfileData(
- new Path(PERF_DATA_FILE_PATH));
- assertTrue(handler.verifyData());
-
- IPath data = handler.saveData(DATA_FILE_NAME);
- assertNotNull(data);
- assertTrue(!data.toFile().canWrite());
- testFiles.add(data);
-
- }
-
- // mock handlers
- @Test
- public void testPerfSaveStatsHandler() {
- PerfSaveStatsTestHandler handler = new PerfSaveStatsTestHandler();
-
- PerfPlugin.getDefault().setStatData(null);
- assertFalse(handler.verifyData());
-
- PerfPlugin.getDefault().setStatData(
- new StatData("title", null, "prog", new String[] {}, 1, null) { //$NON-NLS-1$ //$NON-NLS-2$
- @Override
- public String getPerfData() {
- return PERF_STATS_FILE_PATH;
- }
- });
- assertTrue(handler.verifyData());
-
- IPath stats = handler.saveData(DATA_FILE_NAME);
- assertNotNull(stats);
- assertTrue(!stats.toFile().canWrite());
-
- testFiles.add(stats);
- }
-
- private static class GenericSaveDataHandler extends AbstractSaveDataHandler {
- @Override
- public Object execute(ExecutionEvent event) {
- return null;
- }
-
- @Override
- public IPath saveData(String filename) {
- return null;
- }
-
- @Override
- public boolean verifyData() {
- return true;
- }
-
- @Override
- protected IPath getWorkingDir() {
- return new Path(WORKING_DIR);
- }
- }
-
- private static class PerfSaveSessionTestHandler extends PerfSaveSessionHandler {
- @Override
- protected IPath getWorkingDir() {
- return new Path(WORKING_DIR);
- }
- }
-
- private static class PerfSaveStatsTestHandler extends PerfSaveStatsHandler {
- @Override
- protected IPath getWorkingDir() {
- return new Path(WORKING_DIR);
- }
- }
+ private static final String WORKING_DIR = "resources/"; //$NON-NLS-1$
+ private static final String DATA_FILE_PATH = "/mock/data/path"; //$NON-NLS-1$
+ private static final String PERF_DATA_FILE_PATH = "resources/perf.data"; //$NON-NLS-1$
+ private static final String PERF_STATS_FILE_PATH = "stat_data"; //$NON-NLS-1$
+ private static final String DATA_FILE_NAME = "data"; //$NON-NLS-1$
+ private static final String DATA_FILE_EXT = "ext"; //$NON-NLS-1$
+ private ArrayList<IPath> testFiles = new ArrayList<>();
+
+ @After
+ public void tearDown(){
+ for (IPath f : testFiles) {
+ File file = f.toFile();
+ assertTrue(file.delete());
+ }
+ }
+
+ @Test
+ public void testGenericHandler() {
+ GenericSaveDataHandler handler = new GenericSaveDataHandler();
+ assertTrue(handler.canSave(Path.fromOSString(DATA_FILE_PATH)));
+ assertEquals(WORKING_DIR, handler.getWorkingDir().toOSString());
+
+ IPath path = handler.getNewDataLocation(DATA_FILE_NAME, DATA_FILE_EXT);
+ assertEquals(WORKING_DIR + DATA_FILE_NAME + '.' + DATA_FILE_EXT,
+ path.toOSString());
+
+ assertTrue(handler.isEnabled());
+ assertTrue(handler.isHandled());
+ }
+ @Test
+ public void testPerfSaveSessionHandler() {
+ PerfSaveSessionTestHandler handler = new PerfSaveSessionTestHandler();
+
+ PerfPlugin.getDefault().setPerfProfileData(null);
+ assertFalse(handler.verifyData());
+
+ PerfPlugin.getDefault().setPerfProfileData(
+ new Path(PERF_DATA_FILE_PATH));
+ assertTrue(handler.verifyData());
+
+ IPath data = handler.saveData(DATA_FILE_NAME);
+ assertNotNull(data);
+ assertTrue(!data.toFile().canWrite());
+ testFiles.add(data);
+
+ }
+
+ // mock handlers
+ @Test
+ public void testPerfSaveStatsHandler() {
+ PerfSaveStatsTestHandler handler = new PerfSaveStatsTestHandler();
+
+ PerfPlugin.getDefault().setStatData(null);
+ assertFalse(handler.verifyData());
+
+ PerfPlugin.getDefault().setStatData(
+ new StatData("title", null, "prog", new String[] {}, 1, null) { //$NON-NLS-1$ //$NON-NLS-2$
+ @Override
+ public String getPerfData() {
+ return PERF_STATS_FILE_PATH;
+ }
+ });
+ assertTrue(handler.verifyData());
+
+ IPath stats = handler.saveData(DATA_FILE_NAME);
+ assertNotNull(stats);
+ assertTrue(!stats.toFile().canWrite());
+
+ testFiles.add(stats);
+ }
+
+ private static class GenericSaveDataHandler extends AbstractSaveDataHandler {
+ @Override
+ public Object execute(ExecutionEvent event) {
+ return null;
+ }
+
+ @Override
+ public IPath saveData(String filename) {
+ return null;
+ }
+
+ @Override
+ public boolean verifyData() {
+ return true;
+ }
+
+ @Override
+ protected IPath getWorkingDir() {
+ return new Path(WORKING_DIR);
+ }
+ }
+
+ private static class PerfSaveSessionTestHandler extends PerfSaveSessionHandler {
+ @Override
+ protected IPath getWorkingDir() {
+ return new Path(WORKING_DIR);
+ }
+ }
+
+ private static class PerfSaveStatsTestHandler extends PerfSaveStatsHandler {
+ @Override
+ protected IPath getWorkingDir() {
+ return new Path(WORKING_DIR);
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/StatsComparisonTest.java b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/StatsComparisonTest.java
index e987cfed5f..282a0b910d 100644
--- a/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/StatsComparisonTest.java
+++ b/perf/org.eclipse.linuxtools.perf.tests/src/org/eclipse/linuxtools/internal/perf/tests/StatsComparisonTest.java
@@ -29,178 +29,178 @@ import org.junit.Before;
import org.junit.Test;
public class StatsComparisonTest {
- private PMStatEntry statEntry;
- private PMStatEntry statEntry2;
- private PMStatEntry statEntry3;
- private PMStatEntry statEntry4;
- private static final String STAT_RES = "resources/stat-data/";
-
- @Before
- public void setUp() {
- String event = "event";
- String units = "unit";
- float samples = 1;
- float metrics = 2;
- float deviation = 3;
- float scaling = 4;
-
- statEntry = new PMStatEntry(samples, event, metrics, units, deviation,
- scaling);
- statEntry2 = new PMStatEntry(samples, event, metrics, units, deviation,
- scaling);
- statEntry3 = new PMStatEntry(samples++, event, metrics++, units,
- deviation++, scaling);
- statEntry4 = new PMStatEntry(samples--, "event2", metrics--, units,
- deviation--, scaling);
- }
-
- @Test
- public void testPMStatEntryGetters() {
- assertEquals("event", statEntry.getEvent());
- assertEquals("unit", statEntry.getUnits());
- assertEquals(1, statEntry.getSamples(), 0);
- assertEquals(2, statEntry.getMetrics(), 0);
- assertEquals(3, statEntry.getDeviation(), 0);
- assertEquals(4, statEntry.getScaling(), 0);
- }
-
- @Test
- public void testPMStatEntryEquality() {
- assertTrue(statEntry.equalEvents(statEntry3));
- assertFalse(statEntry.equalEvents(statEntry4));
- assertTrue(statEntry.equals(statEntry2));
- }
-
- @Test
- public void testPMStatEntryArray() {
- String[] expectedList = new String[] {
- String.valueOf(statEntry.getSamples()), statEntry.getEvent(),
- String.valueOf(statEntry.getFormattedMetrics()), statEntry.getUnits(),
- String.valueOf(statEntry.getFormattedDeviation()) };
-
- String[] actualList = statEntry.toStringArray();
-
- // test string array representation
- assertArrayEquals(expectedList, actualList);
- }
-
- @Test
- public void testPMStatEntryComparison() {
- String expectedEvent = "event";
- String expectedUnits = "unit";
- float expectedSamples = statEntry.getSamples() - statEntry2.getSamples();
- float expectedMetrics = statEntry.getMetrics() - statEntry2.getMetrics();
- float expectedDeviation = statEntry.getDeviation() + statEntry2.getDeviation();
- float expectedScaling = statEntry.getScaling() + statEntry2.getScaling();
-
- PMStatEntry expectedDiff = new PMStatEntry(expectedSamples,
- expectedEvent, expectedMetrics, expectedUnits,
- expectedDeviation, expectedScaling);
-
- PMStatEntry actualDiff = statEntry.compare(statEntry2);
-
- // test stat entry comparison
- assertEquals(expectedDiff,actualDiff);
-
- }
-
- @Test
- public void testStatDataComparisonFieldGetters() {
- IPath oldStatData = Path.fromOSString(STAT_RES + "perf_old.stat");
- IPath newStatData = Path.fromOSString(STAT_RES + "perf_new.stat");
- String dataTitle = "title";
- StatComparisonData diffData = new StatComparisonData(dataTitle,
- oldStatData, newStatData);
-
- assertEquals(dataTitle, diffData.getTitle());
- assertEquals("", diffData.getPerfData());
- assertNotNull(diffData.getDataID());
- assertEquals(oldStatData.toOSString(), diffData.getOldDataPath());
- assertEquals(newStatData.toOSString(), diffData.getNewDataPath());
- assertEquals(oldStatData.toOSString() + diffData.getDataID(),diffData.getOldDataID());
- assertEquals(newStatData.toOSString() + diffData.getDataID(),diffData.getNewDataID());
- }
-
- @Test
- public void testStatDataComparison() {
- IPath oldStatData = Path.fromOSString(STAT_RES + "perf_old.stat");
- IPath newStatData = Path.fromOSString(STAT_RES + "perf_new.stat");
- StatComparisonData diffData = new StatComparisonData("title",
- oldStatData, newStatData);
-
- // expected comparison list
- ArrayList<PMStatEntry> expectedDiff = new ArrayList<>();
-
- expectedDiff.add(new PMStatEntry((float) -4.0, "cpu-clock",
- (float) 0.0, null, (float) 0.54, (float) 0.0));
- expectedDiff.add(new PMStatEntry((float) -2000.0, "page-faults",
- (float) -0.31, "M/sec", (float) 0.02, (float) 0.0));
- expectedDiff.add(new PMStatEntry((float) 0.0, "context-switches",
- (float) -0.13, "K/sec", (float) 36.34, (float) 0.0));
- expectedDiff.add(new PMStatEntry((float) -1000.0, "minor-faults",
- (float) -0.3, "M/sec", (float) 0.02, (float) 0.0));
- expectedDiff.add(new PMStatEntry((float) 0.0, "major-faults",
- (float) 0.0, "K/sec", (float) 0.0, (float) 0.0));
- expectedDiff.add(new PMStatEntry((float) -0.008,
- "seconds time elapsed", (float) 0.0, null, (float) 0.92,
- (float) 0.0));
-
- ArrayList<PMStatEntry> actualDiff = diffData.getComparisonStats();
-
- assertFalse(actualDiff.isEmpty());
-
- for (PMStatEntry expectedEntry : expectedDiff) {
- assertTrue(actualDiff.contains(expectedEntry));
- }
- }
-
- @Test
- public void testStatComparisonResult() throws IOException {
- IPath oldStatData = Path.fromOSString(STAT_RES + "perf_old.stat");
- IPath newStatData = Path.fromOSString(STAT_RES + "perf_new.stat");
- IPath diffStatData = Path.fromOSString(STAT_RES + "perf_diff.stat");
-
- try (BufferedReader diffDataReader = new BufferedReader(new FileReader(
- diffStatData.toFile()))) {
- StatComparisonData diffData = new StatComparisonData("title",
- oldStatData, newStatData);
-
- diffData.runComparison();
- String actualResult = diffData.getPerfData();
- String[] actualResultLines = actualResult.split("\n");
-
- String curLine;
- for (int i = 0; i < actualResultLines.length; i++) {
- curLine = diffDataReader.readLine();
-
- /**
- * Elapsed seconds are usually very close to zero, and thus
- * prone to some small formatting differences across systems.
- * Total time entry items are checked more thoroughly to avoid
- * test failures.
- */
- if (curLine.contains(PMStatEntry.TIME)) {
- String expectedEntry = curLine.trim();
- String actualEntry = actualResultLines[i].trim();
-
- String expectedSamples = expectedEntry.substring(0,
- expectedEntry.indexOf(" "));
- String expectedRest = expectedEntry.substring(expectedEntry
- .indexOf(" ") + 1);
-
- String actualSamples = actualEntry.substring(0,
- actualEntry.indexOf(" "));
- String actualRest = actualEntry.substring(actualEntry
- .indexOf(" ") + 1);
-
- assertEquals(StatComparisonData.toFloat(actualSamples),
- StatComparisonData.toFloat(expectedSamples), 0);
- assertEquals(actualRest, expectedRest);
- } else {
- assertEquals(actualResultLines[i], curLine);
- }
- }
- }
-
- }
+ private PMStatEntry statEntry;
+ private PMStatEntry statEntry2;
+ private PMStatEntry statEntry3;
+ private PMStatEntry statEntry4;
+ private static final String STAT_RES = "resources/stat-data/";
+
+ @Before
+ public void setUp() {
+ String event = "event";
+ String units = "unit";
+ float samples = 1;
+ float metrics = 2;
+ float deviation = 3;
+ float scaling = 4;
+
+ statEntry = new PMStatEntry(samples, event, metrics, units, deviation,
+ scaling);
+ statEntry2 = new PMStatEntry(samples, event, metrics, units, deviation,
+ scaling);
+ statEntry3 = new PMStatEntry(samples++, event, metrics++, units,
+ deviation++, scaling);
+ statEntry4 = new PMStatEntry(samples--, "event2", metrics--, units,
+ deviation--, scaling);
+ }
+
+ @Test
+ public void testPMStatEntryGetters() {
+ assertEquals("event", statEntry.getEvent());
+ assertEquals("unit", statEntry.getUnits());
+ assertEquals(1, statEntry.getSamples(), 0);
+ assertEquals(2, statEntry.getMetrics(), 0);
+ assertEquals(3, statEntry.getDeviation(), 0);
+ assertEquals(4, statEntry.getScaling(), 0);
+ }
+
+ @Test
+ public void testPMStatEntryEquality() {
+ assertTrue(statEntry.equalEvents(statEntry3));
+ assertFalse(statEntry.equalEvents(statEntry4));
+ assertTrue(statEntry.equals(statEntry2));
+ }
+
+ @Test
+ public void testPMStatEntryArray() {
+ String[] expectedList = new String[] {
+ String.valueOf(statEntry.getSamples()), statEntry.getEvent(),
+ String.valueOf(statEntry.getFormattedMetrics()), statEntry.getUnits(),
+ String.valueOf(statEntry.getFormattedDeviation()) };
+
+ String[] actualList = statEntry.toStringArray();
+
+ // test string array representation
+ assertArrayEquals(expectedList, actualList);
+ }
+
+ @Test
+ public void testPMStatEntryComparison() {
+ String expectedEvent = "event";
+ String expectedUnits = "unit";
+ float expectedSamples = statEntry.getSamples() - statEntry2.getSamples();
+ float expectedMetrics = statEntry.getMetrics() - statEntry2.getMetrics();
+ float expectedDeviation = statEntry.getDeviation() + statEntry2.getDeviation();
+ float expectedScaling = statEntry.getScaling() + statEntry2.getScaling();
+
+ PMStatEntry expectedDiff = new PMStatEntry(expectedSamples,
+ expectedEvent, expectedMetrics, expectedUnits,
+ expectedDeviation, expectedScaling);
+
+ PMStatEntry actualDiff = statEntry.compare(statEntry2);
+
+ // test stat entry comparison
+ assertEquals(expectedDiff,actualDiff);
+
+ }
+
+ @Test
+ public void testStatDataComparisonFieldGetters() {
+ IPath oldStatData = Path.fromOSString(STAT_RES + "perf_old.stat");
+ IPath newStatData = Path.fromOSString(STAT_RES + "perf_new.stat");
+ String dataTitle = "title";
+ StatComparisonData diffData = new StatComparisonData(dataTitle,
+ oldStatData, newStatData);
+
+ assertEquals(dataTitle, diffData.getTitle());
+ assertEquals("", diffData.getPerfData());
+ assertNotNull(diffData.getDataID());
+ assertEquals(oldStatData.toOSString(), diffData.getOldDataPath());
+ assertEquals(newStatData.toOSString(), diffData.getNewDataPath());
+ assertEquals(oldStatData.toOSString() + diffData.getDataID(),diffData.getOldDataID());
+ assertEquals(newStatData.toOSString() + diffData.getDataID(),diffData.getNewDataID());
+ }
+
+ @Test
+ public void testStatDataComparison() {
+ IPath oldStatData = Path.fromOSString(STAT_RES + "perf_old.stat");
+ IPath newStatData = Path.fromOSString(STAT_RES + "perf_new.stat");
+ StatComparisonData diffData = new StatComparisonData("title",
+ oldStatData, newStatData);
+
+ // expected comparison list
+ ArrayList<PMStatEntry> expectedDiff = new ArrayList<>();
+
+ expectedDiff.add(new PMStatEntry((float) -4.0, "cpu-clock",
+ (float) 0.0, null, (float) 0.54, (float) 0.0));
+ expectedDiff.add(new PMStatEntry((float) -2000.0, "page-faults",
+ (float) -0.31, "M/sec", (float) 0.02, (float) 0.0));
+ expectedDiff.add(new PMStatEntry((float) 0.0, "context-switches",
+ (float) -0.13, "K/sec", (float) 36.34, (float) 0.0));
+ expectedDiff.add(new PMStatEntry((float) -1000.0, "minor-faults",
+ (float) -0.3, "M/sec", (float) 0.02, (float) 0.0));
+ expectedDiff.add(new PMStatEntry((float) 0.0, "major-faults",
+ (float) 0.0, "K/sec", (float) 0.0, (float) 0.0));
+ expectedDiff.add(new PMStatEntry((float) -0.008,
+ "seconds time elapsed", (float) 0.0, null, (float) 0.92,
+ (float) 0.0));
+
+ ArrayList<PMStatEntry> actualDiff = diffData.getComparisonStats();
+
+ assertFalse(actualDiff.isEmpty());
+
+ for (PMStatEntry expectedEntry : expectedDiff) {
+ assertTrue(actualDiff.contains(expectedEntry));
+ }
+ }
+
+ @Test
+ public void testStatComparisonResult() throws IOException {
+ IPath oldStatData = Path.fromOSString(STAT_RES + "perf_old.stat");
+ IPath newStatData = Path.fromOSString(STAT_RES + "perf_new.stat");
+ IPath diffStatData = Path.fromOSString(STAT_RES + "perf_diff.stat");
+
+ try (BufferedReader diffDataReader = new BufferedReader(new FileReader(
+ diffStatData.toFile()))) {
+ StatComparisonData diffData = new StatComparisonData("title",
+ oldStatData, newStatData);
+
+ diffData.runComparison();
+ String actualResult = diffData.getPerfData();
+ String[] actualResultLines = actualResult.split("\n");
+
+ String curLine;
+ for (int i = 0; i < actualResultLines.length; i++) {
+ curLine = diffDataReader.readLine();
+
+ /**
+ * Elapsed seconds are usually very close to zero, and thus
+ * prone to some small formatting differences across systems.
+ * Total time entry items are checked more thoroughly to avoid
+ * test failures.
+ */
+ if (curLine.contains(PMStatEntry.TIME)) {
+ String expectedEntry = curLine.trim();
+ String actualEntry = actualResultLines[i].trim();
+
+ String expectedSamples = expectedEntry.substring(0,
+ expectedEntry.indexOf(" "));
+ String expectedRest = expectedEntry.substring(expectedEntry
+ .indexOf(" ") + 1);
+
+ String actualSamples = actualEntry.substring(0,
+ actualEntry.indexOf(" "));
+ String actualRest = actualEntry.substring(actualEntry
+ .indexOf(" ") + 1);
+
+ assertEquals(StatComparisonData.toFloat(actualSamples),
+ StatComparisonData.toFloat(expectedSamples), 0);
+ assertEquals(actualRest, expectedRest);
+ } else {
+ assertEquals(actualResultLines[i], curLine);
+ }
+ }
+ }
+
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/contexts.xml b/perf/org.eclipse.linuxtools.perf/contexts.xml
index 64aff45a3a..31f8840df9 100644
--- a/perf/org.eclipse.linuxtools.perf/contexts.xml
+++ b/perf/org.eclipse.linuxtools.perf/contexts.xml
@@ -1,12 +1,12 @@
<contexts>
- <context id="viewer" title="Sample View">
- <description>This is the context help for the sample view with a tree viewer. It was generated by a PDE template.</description>
- <topic href="/PLUGINS_ROOT/org.eclipse.platform.doc.isv/guide/ua_help_context.htm" label="Context-sensitive help">
- <enablement>
- <with variable="platform">
- <test property="org.eclipse.core.runtime.isBundleInstalled" args="org.eclipse.platform.doc.isv"/>
- </with>
- </enablement>
- </topic>
- </context>
+ <context id="viewer" title="Sample View">
+ <description>This is the context help for the sample view with a tree viewer. It was generated by a PDE template.</description>
+ <topic href="/PLUGINS_ROOT/org.eclipse.platform.doc.isv/guide/ua_help_context.htm" label="Context-sensitive help">
+ <enablement>
+ <with variable="platform">
+ <test property="org.eclipse.core.runtime.isBundleInstalled" args="org.eclipse.platform.doc.isv"/>
+ </with>
+ </enablement>
+ </topic>
+ </context>
</contexts>
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/AbstractDataManipulator.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/AbstractDataManipulator.java
index 921e49c3dd..4eba7451c6 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/AbstractDataManipulator.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/AbstractDataManipulator.java
@@ -38,162 +38,162 @@ import org.eclipse.swt.widgets.Display;
public abstract class AbstractDataManipulator extends BaseDataManipulator
implements IPerfData {
- private String text;
- private String title;
- private ILaunch launch;
- private IPath pathWorkDir;
- private List<Thread> threads;
- private IProject project;
-
- AbstractDataManipulator (String title, IPath pathWorkDir, IProject project) {
- this(title, pathWorkDir);
- this.project=project;
- }
-
- AbstractDataManipulator (String title, IPath pathWorkDir) {
- this.title = title;
- this.pathWorkDir=pathWorkDir;
- threads = new ArrayList<>();
- }
-
- @Override
- public String getPerfData() {
- return text;
- }
-
- protected IPath getWorkDir(){
- return pathWorkDir;
- }
-
- @Override
- public String getTitle () {
- return title;
- }
-
- public void setLaunch (ILaunch launch) {
- this.launch = launch;
- }
-
- public void performCommand(String[] cmd, int fd) {
- BufferedReader buffData = null;
- BufferedReader buffTemp = null;
- URI pathWorkDirURI = null;
- try {
-
- Process proc = null;
- RemoteConnection exeRC = null;
- try {
- pathWorkDirURI = new URI(pathWorkDir.toOSString());
- exeRC = new RemoteConnection(pathWorkDirURI);
- } catch (RemoteConnectionException e) {
- MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
- } catch (URISyntaxException e) {
- MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
- }
- IFileStore workDirStore = exeRC.getRmtFileProxy().getResource(pathWorkDirURI.getPath());
- proc = RuntimeProcessFactory.getFactory().exec(cmd, null, workDirStore, project);
- StringBuffer data = new StringBuffer();
- StringBuffer temp = new StringBuffer();
-
- switch (fd) {
- case 2:
- buffData = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
- buffTemp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
- readStream(buffTemp, temp);
- readStream(buffData, data);
- break;
- case 1:
- // fall through to default case
- default:
- buffData = new BufferedReader(new InputStreamReader(proc.getInputStream()));
- buffTemp = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
- readStream(buffData, data);
- readStream(buffTemp, temp);
- break;
- }
- joinAll();
- text = data.toString();
- } catch (IOException|InterruptedException e) {
- text = ""; //$NON-NLS-1$
- }finally {
- try {
- if (buffData != null) {
- buffData.close();
- }
- if (buffTemp != null) {
- buffTemp.close();
- }
- } catch (IOException e) {
- // continue
- }
- }
- }
-
- public void performCommand(String[] cmd, String file) {
- URI pathWorkDirURI = null;
- Process proc = null;
- RemoteConnection exeRC = null;
- try {
- try {
- pathWorkDirURI = new URI(pathWorkDir.toOSString());
- exeRC = new RemoteConnection(pathWorkDirURI);
- } catch (RemoteConnectionException e) {
- MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
- } catch (URISyntaxException e) {
- MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
- }
- IFileStore workDirStore = exeRC.getRmtFileProxy().getResource(pathWorkDirURI.getPath());
- proc = RuntimeProcessFactory.getFactory().exec(cmd, null, workDirStore, project, new PTY());
- DebugPlugin.newProcess(launch, proc, ""); //$NON-NLS-1$
- proc.waitFor();
-
- StringBuffer data = new StringBuffer();
+ private String text;
+ private String title;
+ private ILaunch launch;
+ private IPath pathWorkDir;
+ private List<Thread> threads;
+ private IProject project;
+
+ AbstractDataManipulator (String title, IPath pathWorkDir, IProject project) {
+ this(title, pathWorkDir);
+ this.project=project;
+ }
+
+ AbstractDataManipulator (String title, IPath pathWorkDir) {
+ this.title = title;
+ this.pathWorkDir=pathWorkDir;
+ threads = new ArrayList<>();
+ }
+
+ @Override
+ public String getPerfData() {
+ return text;
+ }
+
+ protected IPath getWorkDir(){
+ return pathWorkDir;
+ }
+
+ @Override
+ public String getTitle () {
+ return title;
+ }
+
+ public void setLaunch (ILaunch launch) {
+ this.launch = launch;
+ }
+
+ public void performCommand(String[] cmd, int fd) {
+ BufferedReader buffData = null;
+ BufferedReader buffTemp = null;
+ URI pathWorkDirURI = null;
+ try {
+
+ Process proc = null;
+ RemoteConnection exeRC = null;
+ try {
+ pathWorkDirURI = new URI(pathWorkDir.toOSString());
+ exeRC = new RemoteConnection(pathWorkDirURI);
+ } catch (RemoteConnectionException e) {
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
+ } catch (URISyntaxException e) {
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
+ }
+ IFileStore workDirStore = exeRC.getRmtFileProxy().getResource(pathWorkDirURI.getPath());
+ proc = RuntimeProcessFactory.getFactory().exec(cmd, null, workDirStore, project);
+ StringBuffer data = new StringBuffer();
+ StringBuffer temp = new StringBuffer();
+
+ switch (fd) {
+ case 2:
+ buffData = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
+ buffTemp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
+ readStream(buffTemp, temp);
+ readStream(buffData, data);
+ break;
+ case 1:
+ // fall through to default case
+ default:
+ buffData = new BufferedReader(new InputStreamReader(proc.getInputStream()));
+ buffTemp = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
+ readStream(buffData, data);
+ readStream(buffTemp, temp);
+ break;
+ }
+ joinAll();
+ text = data.toString();
+ } catch (IOException|InterruptedException e) {
+ text = ""; //$NON-NLS-1$
+ }finally {
+ try {
+ if (buffData != null) {
+ buffData.close();
+ }
+ if (buffTemp != null) {
+ buffTemp.close();
+ }
+ } catch (IOException e) {
+ // continue
+ }
+ }
+ }
+
+ public void performCommand(String[] cmd, String file) {
+ URI pathWorkDirURI = null;
+ Process proc = null;
+ RemoteConnection exeRC = null;
+ try {
+ try {
+ pathWorkDirURI = new URI(pathWorkDir.toOSString());
+ exeRC = new RemoteConnection(pathWorkDirURI);
+ } catch (RemoteConnectionException e) {
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
+ } catch (URISyntaxException e) {
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
+ }
+ IFileStore workDirStore = exeRC.getRmtFileProxy().getResource(pathWorkDirURI.getPath());
+ proc = RuntimeProcessFactory.getFactory().exec(cmd, null, workDirStore, project, new PTY());
+ DebugPlugin.newProcess(launch, proc, ""); //$NON-NLS-1$
+ proc.waitFor();
+
+ StringBuffer data = new StringBuffer();
try (BufferedReader buffData = new BufferedReader(
new InputStreamReader(new FileInputStream(file)))) {
readStream(buffData, data);
joinAll();
}
- text = data.toString();
- } catch (IOException e) {
- text = ""; //$NON-NLS-1$
- } catch (InterruptedException e){
- text = ""; //$NON-NLS-1$
- }
- }
-
- /**
- * Write entire contents of BufferedReader into given StringBuffer.
- *
- * @param buff BufferedReader to read from.
- * @param strBuff StringBuffer to write to.
- */
- private void readStream(final BufferedReader buff,
- final StringBuffer strBuff) {
- Thread readThread = new Thread(new Runnable() {
- @Override
- public void run() {
- strBuff.append(getBufferContents(buff));
- }
- });
- readThread.start();
- threads.add(readThread);
- }
-
- /**
- * Wait for all working threads to finish.
- *
- * @throws InterruptedException
- */
- private void joinAll() throws InterruptedException {
- for (Thread thread : threads) {
- thread.join();
- }
- }
-
- /**
- * A combination of setting up the command to run and executing it.
- * This often calls performCommand(String [] cmd).
- */
- public abstract void parse();
+ text = data.toString();
+ } catch (IOException e) {
+ text = ""; //$NON-NLS-1$
+ } catch (InterruptedException e){
+ text = ""; //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Write entire contents of BufferedReader into given StringBuffer.
+ *
+ * @param buff BufferedReader to read from.
+ * @param strBuff StringBuffer to write to.
+ */
+ private void readStream(final BufferedReader buff,
+ final StringBuffer strBuff) {
+ Thread readThread = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ strBuff.append(getBufferContents(buff));
+ }
+ });
+ readThread.start();
+ threads.add(readThread);
+ }
+
+ /**
+ * Wait for all working threads to finish.
+ *
+ * @throws InterruptedException
+ */
+ private void joinAll() throws InterruptedException {
+ for (Thread thread : threads) {
+ thread.join();
+ }
+ }
+
+ /**
+ * A combination of setting up the command to run and executing it.
+ * This often calls performCommand(String [] cmd).
+ */
+ public abstract void parse();
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/BaseDataManipulator.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/BaseDataManipulator.java
index fd26e9995c..e6682f5cd5 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/BaseDataManipulator.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/BaseDataManipulator.java
@@ -19,44 +19,44 @@ import java.io.IOException;
*/
public class BaseDataManipulator {
- /**
- * Get contents of specified BufferedReader as a String
- *
- * @param buffer BufferedReader to read from.
- * @return String contents of BufferedReader.
- */
- public String getBufferContents(BufferedReader buffer) {
- if (buffer == null) {
- return ""; //$NON-NLS-1$
- }
- StringBuilder fileStr = new StringBuilder();
- try {
- String line;
+ /**
+ * Get contents of specified BufferedReader as a String
+ *
+ * @param buffer BufferedReader to read from.
+ * @return String contents of BufferedReader.
+ */
+ public String getBufferContents(BufferedReader buffer) {
+ if (buffer == null) {
+ return ""; //$NON-NLS-1$
+ }
+ StringBuilder fileStr = new StringBuilder();
+ try {
+ String line;
- while ((line = buffer.readLine()) != null) {
- fileStr.append(line);
- fileStr.append("\n"); //$NON-NLS-1$
- }
+ while ((line = buffer.readLine()) != null) {
+ fileStr.append(line);
+ fileStr.append("\n"); //$NON-NLS-1$
+ }
- } catch (IOException e) {
- PerfPlugin.getDefault().openError(e, ""); //$NON-NLS-1$
- }
+ } catch (IOException e) {
+ PerfPlugin.getDefault().openError(e, ""); //$NON-NLS-1$
+ }
- return fileStr.toString();
- }
+ return fileStr.toString();
+ }
- /**
- * Close specified resource
- *
- * @param resrc resource to close
- */
- public void closeResource(Closeable resrc) {
- if (resrc != null) {
- try {
- resrc.close();
- } catch (IOException e) {
- PerfPlugin.getDefault().openError(e, ""); //$NON-NLS-1$
- }
- }
- }
+ /**
+ * Close specified resource
+ *
+ * @param resrc resource to close
+ */
+ public void closeResource(Closeable resrc) {
+ if (resrc != null) {
+ try {
+ resrc.close();
+ } catch (IOException e) {
+ PerfPlugin.getDefault().openError(e, ""); //$NON-NLS-1$
+ }
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/IPerfData.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/IPerfData.java
index 391d9d9732..e8c5993295 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/IPerfData.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/IPerfData.java
@@ -15,15 +15,15 @@ package org.eclipse.linuxtools.internal.perf;
*/
public interface IPerfData {
- /**
- * Get string representation of the data.
- * @return String perf data
- */
- String getPerfData();
+ /**
+ * Get string representation of the data.
+ * @return String perf data
+ */
+ String getPerfData();
- /**
- * Get title for this data.
- * @return title for perf data
- */
- String getTitle();
+ /**
+ * Get title for this data.
+ * @return title for perf data
+ */
+ String getTitle();
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/Messages.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/Messages.java
index 05b2d1e376..c7eb3d7fa2 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/Messages.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/Messages.java
@@ -14,13 +14,13 @@ package org.eclipse.linuxtools.internal.perf;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.perf.messages"; //$NON-NLS-1$
- public static String MsgProxyError;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.perf.messages"; //$NON-NLS-1$
+ public static String MsgProxyError;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/PerfCore.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/PerfCore.java
index c5bfd8a9ec..c04d94cbb8 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/PerfCore.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/PerfCore.java
@@ -46,632 +46,632 @@ import org.osgi.framework.Version;
public class PerfCore {
- private static String spitStream(BufferedReader br, String blockTitle, PrintStream print) {
-
- StringBuffer strBuf = new StringBuffer();
- String line = null;
- try {
- while (( line = br.readLine()) != null){
- strBuf.append(line);
- strBuf.append("\n"); //$NON-NLS-1$
- }
- } catch (IOException e) {
- logException(e);
- }
- String str = strBuf.toString();
- if (!str.trim().isEmpty() && print != null) {
- print.println(blockTitle + ": \n" +str + "\n END OF " + blockTitle); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return str;
- }
- // Maps event lists to host names for caching
- private static Map<String,Map<String, List<String>>> eventsHostMap = null;
- private static Map<String,List<String>> eventList = null;
-
- /**
- * Gets the list of events for a given launch configuration. Uses a cache for each host
- * @param config
- * @return
- */
- public static Map<String,List<String>> getEventList(ILaunchConfiguration config) {
- String projectHost = getHostName(config);
-
- if(eventsHostMap == null){
- eventsHostMap = new HashMap<>();
- }
-
- // local projects have null hosts
- if(projectHost == null){
- projectHost = "local"; //$NON-NLS-1$
- }
-
- eventList = eventsHostMap.get(projectHost);
-
- if(eventList == null){
- eventList = loadEventList(config);
- eventsHostMap.put(projectHost, eventList);
- }
- return eventList;
- }
-
-
- /**
- *
- * @param config
- * @return the name of the host in which the config's project is stored
- */
- private static String getHostName(ILaunchConfiguration config){
- String projectName = null;
- try {
- projectName = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
- } catch (CoreException e) {
- return null;
- }
- if (projectName.isEmpty()) {
- return null;
- }
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
- if(project == null){
- return null;
- }
- return project.getLocationURI().getHost();
-
- }
-
- private static IProject getProject(ILaunchConfiguration config){
- if(config == null){
- return null;
- } else {
- try {
- String projectName = ConfigUtils.getProjectName(config);
- // an empty string is not a legal path to file argument for ConfigUtils.getProject
- if (projectName != null && !projectName.isEmpty()) {
- return ConfigUtils.getProject(projectName);
- }
- } catch (CoreException e1) {
- logException(e1);
- }
- }
-
- return null;
- }
-
- private static Map<String,List<String>> loadEventList(ILaunchConfiguration config){
- Map<String,List<String>> events = new HashMap<>();
- IProject project = getProject(config);
-
- if (!PerfCore.checkPerfInPath(project)) {
- return events;
- }
-
- Process p = null;
- BufferedReader input = null;
- try {
- // Execute "perf list" to get list of all symbolic event types.
- // Alternatively can try with -i flag.
- p = RuntimeProcessFactory.getFactory().exec(new String[] {PerfPlugin.PERF_COMMAND, "list"}, project); //(char 1 as -t is a custom field seperator //$NON-NLS-1$
-
- /*
- * Old versions of Perf will send events list to stderr instead of stdout
- * Checking if stdout is empty then read from stderr
- */
- input = new BufferedReader(new InputStreamReader(p.getInputStream()));
-
- } catch( IOException e ) {
- logException(e);
- }
- return parseEventList(input);
- }
-
- public static Map<String,List<String>> parseEventList (BufferedReader input){
- Map<String,List<String>> events = new HashMap<>();
- String line;
- try {
- // Process list of events. Each line is of the form <event>\s+<category>.
- while (( line = input.readLine()) != null){
- if (line.contains("[")) { //$NON-NLS-1$
- String event;
- String category;
- if (line.contains(PerfPlugin.STRINGS_HWBREAKPOINTS)) {
- category = PerfPlugin.STRINGS_HWBREAKPOINTS;
- event = line.substring(1,line.indexOf('[', 0)).trim();
- } else if (line.contains(PerfPlugin.STRINGS_RAWHWEvents)) {
- category = PerfPlugin.STRINGS_RAWHWEvents;
- event = line.substring(1,line.indexOf('[', 0)).trim();
- } else {
- event = line.substring(1,line.indexOf('[', 0)).trim();
- if (event.contains("OR")) { //$NON-NLS-1$
- event = event.split("OR")[0]; //filter out the abbreviations. //$NON-NLS-1$
- }
- category = line.replaceFirst(".*\\[(.+)\\]", "$1").trim(); //$NON-NLS-1$ //$NON-NLS-2$
- }
- List<String> categoryEvents = events.get(category);
- if (categoryEvents == null) {
- categoryEvents = new ArrayList<>();
- events.put(category, categoryEvents);
- }
- categoryEvents.add(event.trim());
- }
- }
- } catch (IOException e) {
- logException(e);
- } finally {
- if (null != input) {
- try {
- input.close();
- } catch (IOException e) {
- }
- }
- }
- return events;
- }
-
- //Gets the current version of perf
- public static Version getPerfVersion(ILaunchConfiguration config) {
- IProject project = getProject(config);
- Process p = null;
-
- try {
- p = RuntimeProcessFactory.getFactory().exec(new String [] {PerfPlugin.PERF_COMMAND, "--version"}, project); //$NON-NLS-1$
- } catch (IOException e) {
- logException(e);
- }
- if (p == null) {
- return null;
- }
-
- BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
-
- String perfVersion = spitStream(input, "Perf --version", null); //$NON-NLS-1$
- int index = perfVersion.indexOf('-');
- if (index > 0) {
- perfVersion = perfVersion.substring(0, index);
- }
- perfVersion = perfVersion.replace("perf version", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$
- return new Version(perfVersion);
- }
-
-
- public static boolean checkPerfInPath(IProject project) {
- try {
- Process p = RuntimeProcessFactory.getFactory().exec(new String [] {PerfPlugin.PERF_COMMAND, "--version"}, project); //$NON-NLS-1$
- return (p != null);
- } catch (IOException e) {
- return false;
- }
- }
-
- //Generates a perf record command string with the options set in the given config. (If null uses default).
- public static String [] getRecordString(ILaunchConfiguration config, Version perfVersion) {
- String [] base = new String [] {PerfPlugin.PERF_COMMAND, "record"}; //$NON-NLS-1$
- if (config == null) {
- return base;
- } else {
- ArrayList<String> newCommand = new ArrayList<>();
- newCommand.addAll(Arrays.asList(base));
- try {
- if (new Version(3, 11, 0).compareTo(perfVersion) > 0) {
- // Removed as of 4a4d371a4dfbd3b84a7eab8d535d4c7c3647b09e from perf upstream (kernel)
- newCommand.add("-f"); //$NON-NLS-1$
- }
- if (config.getAttribute(PerfPlugin.ATTR_Record_Realtime, PerfPlugin.ATTR_Record_Realtime_default)) {
- newCommand.add("-r"); //$NON-NLS-1$
- int priority = config.getAttribute(PerfPlugin.ATTR_Record_Realtime_Priority, PerfPlugin.ATTR_Record_Realtime_Priority_default);
- newCommand.add(Integer.toString(priority));
- }
- if (config.getAttribute(PerfPlugin.ATTR_Record_Verbose, PerfPlugin.ATTR_Record_Verbose_default))
- newCommand.add("-v"); //$NON-NLS-1$
- if (config.getAttribute(PerfPlugin.ATTR_Multiplex, PerfPlugin.ATTR_Multiplex_default))
- newCommand.add("-M"); //$NON-NLS-1$
- List<?> selE = config.getAttribute(PerfPlugin.ATTR_SelectedEvents, PerfPlugin.ATTR_SelectedEvents_default);
- if (!config.getAttribute(PerfPlugin.ATTR_DefaultEvent, PerfPlugin.ATTR_DefaultEvent_default)
- && selE != null) {
- for(Object e : selE) {
- newCommand.add("-e"); //$NON-NLS-1$
- newCommand.add((String)e);
- }
- }
- } catch (CoreException e) { }
- return newCommand.toArray(new String[] {});
- }
- }
-
- public static String[] getReportString(ILaunchConfiguration config, String perfDataLoc) {
- ArrayList<String> base = new ArrayList<>();
- base.addAll(Arrays.asList(new String [] {PerfPlugin.PERF_COMMAND, "report", "--sort", "comm,dso,sym", "-n", "-t", "" + (char)1 }));//(char 1 as -t is a custom field seperator) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- if (config != null) {
- try {
- String kernelLoc = config.getAttribute(PerfPlugin.ATTR_Kernel_Location, PerfPlugin.ATTR_Kernel_Location_default);
- if (kernelLoc != PerfPlugin.ATTR_Kernel_Location_default) {
- base.add("--vmlinux"); //$NON-NLS-1$
- base.add(kernelLoc);
- }
- if (config.getAttribute(PerfPlugin.ATTR_ModuleSymbols, PerfPlugin.ATTR_ModuleSymbols_default))
- base.add("-m"); //$NON-NLS-1$
-
- /*
- * danielhb, 12/14/2011 - some systems, like ubuntu and sles, does not have
- * the -U option. The binary fails to execute in those systems when this
- * option is enabled.
- * I'm disabling it to make the plug-in runnable for them. This
- * will probably need to be revisited in the future, probably when this
- * flag is implemented by the Perf binary of those systems.
- */
- /*
- if (config.getAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, PerfPlugin.ATTR_HideUnresolvedSymbols_default))
- base.add("-U");
- */
- if (perfDataLoc != null) {
- base.add("-i"); //$NON-NLS-1$
- base.add(perfDataLoc);
- }
- } catch (CoreException e) { }
- }
- return base.toArray( new String[base.size()] );
- }
-
- public static String[] getAnnotateString(ILaunchConfiguration config, String dso, String symbol, String perfDataLoc, boolean OldPerfVersion) {
- ArrayList<String> base = new ArrayList<>();
- if (OldPerfVersion) {
- base.addAll( Arrays.asList( new String[]{PerfPlugin.PERF_COMMAND, "annotate", "-s", symbol, "-l", "-P"} ) ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- } else {
- base.addAll( Arrays.asList( new String[]{PerfPlugin.PERF_COMMAND, "annotate", "-d", dso, "-s", symbol, "-l", "-P"} ) ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
- if (config != null) {
- try {
- String kernelLoc = config.getAttribute(PerfPlugin.ATTR_Kernel_Location, PerfPlugin.ATTR_Kernel_Location_default);
- if (kernelLoc != PerfPlugin.ATTR_Kernel_Location_default) {
- base.add("--vmlinux"); //$NON-NLS-1$
- base.add(kernelLoc);
- }
- if (config.getAttribute(PerfPlugin.ATTR_ModuleSymbols, PerfPlugin.ATTR_ModuleSymbols_default))
- base.add("-m"); //$NON-NLS-1$
- if (perfDataLoc != null) {
- base.add("-i"); //$NON-NLS-1$
- base.add(perfDataLoc);
- }
- } catch (CoreException e) { }
- }
-
- //(Annotate string per symbol)
- return base.toArray( new String[base.size()] );
- }
-
- // Runs assuming perf.data has already been recorded, environ and workingDir can be set to null to use default
- //perfDataLoc is optional - it is used to provide a pre-existing data file instead of something recorded from
- //whatever project is being profiled. It is only used for junit tests atm.
- public static void Report(ILaunchConfiguration config, String[] environ, IPath workingDir, IProgressMonitor monitor, String perfDataLoc, PrintStream print) {
- IProject project = getProject(config);
-
- TreeParent invisibleRoot = PerfPlugin.getDefault().clearModelRoot();
-
- Version perfVersion = getPerfVersion(config);
- boolean OldPerfVersion = false;
- if (new Version(0, 0, 2).compareTo(perfVersion) > 0) {
- OldPerfVersion = true;
- if (print != null) { print.println("WARNING: You are running an older version of Perf, please update if you can. The plugin may produce unpredictable results."); }
- }
-
-
- BufferedReader input = null;
- BufferedReader error = null;
- Process p = null;
-
- if (monitor != null && monitor.isCanceled()) {
- return;
- }
-
- try {
- if (workingDir==null) {
- p = RuntimeProcessFactory.getFactory().exec(getReportString(config, perfDataLoc), project);
- PerfPlugin.getDefault().setPerfProfileData(new Path(perfDataLoc));
- PerfPlugin.getDefault().setWorkingDir(project.getLocation());
- } else {
- String defaultPerfDataLoc = workingDir.toOSString() + PerfPlugin.PERF_DEFAULT_DATA;
- p = RuntimeProcessFactory.getFactory().exec(getReportString(config, defaultPerfDataLoc), project);
- PerfPlugin.getDefault().setPerfProfileData(new Path(defaultPerfDataLoc));
- PerfPlugin.getDefault().setWorkingDir(workingDir);
- }
-
- input = new BufferedReader(new InputStreamReader(p.getInputStream()));
- error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
- //spitting error stream moved to end of while loop, due to commenting of p.waitFor()
- } catch( IOException e ) {
- logException(e);
- }
-
- PerfCore.parseRemoteReport(config, workingDir, monitor, perfDataLoc, print,
- invisibleRoot, OldPerfVersion, input, error, project);
- }
-
- /**
- * Parse and build a tree model from the report of a perf data file
- * @param config launch configuration
- * @param workingDir working directory configuration
- * @param monitor monitor
- * @param perfDataLoc location of perf data file
- * @param print print stream
- * @param invisibleRoot root of the model
- * @param OldPerfVersion boolean old perf version flag
- * @param input input stream from perf data file report
- * @param error output stream to where all standard error is written to
- */
- public static void parseReport(ILaunchConfiguration config,
- IPath workingDir, IProgressMonitor monitor, String perfDataLoc,
- PrintStream print, TreeParent invisibleRoot,
- boolean OldPerfVersion, BufferedReader input, BufferedReader error) {
- PerfCore.parseRemoteReport(config, workingDir, monitor, perfDataLoc, print,
- invisibleRoot, OldPerfVersion, input, error, null);
- }
-
- private static void parseRemoteReport(ILaunchConfiguration config,
- IPath workingDir, IProgressMonitor monitor, String perfDataLoc,
- PrintStream print, TreeParent invisibleRoot,
- boolean OldPerfVersion, BufferedReader input, BufferedReader error, IProject project) {
-
- if (monitor != null && monitor.isCanceled()) {
- return;
- }
- String line = null;
- String items[];
- float percent;
-
- Process p = null;
- double samples;
- String comm,dso,symbol;
- boolean kernelFlag;
- PMEvent currentEvent = null;
- PMCommand currentCommand = null;
- PMDso currentDso = null;
- PMFile currentFile = null;
- PMSymbol currentSym = null;
- try {
- while (( line = input.readLine()) != null){
- if (monitor != null && monitor.isCanceled()) {
- return;
- }
- // line containing report information
- if ((line.startsWith("#"))) { //$NON-NLS-1$
- if (line.contains("Events:") || line.contains("Samples:")) { //$NON-NLS-1$ //$NON-NLS-2$
- String[] tmp = line.trim().split(" "); //$NON-NLS-1$
- String event = tmp[tmp.length - 1];
- // In this case, the event name is single quoted
- if (line.contains("Samples:")){ //$NON-NLS-1$
- event = event.substring(1, event.length() -1);
- }
- currentEvent = new PMEvent(event);
- invisibleRoot.addChild(currentEvent);
- currentCommand = null;
- currentDso = null;
- } else if (line.contains("Samples:")) { //"samples" was used instead of events in an older version, some incompatibilities may arise. //$NON-NLS-1$
- if (print != null) { print.println("WARNING: You are running an older version of Perf, please update if you can. The plugin may produce unpredictable results."); }
- invisibleRoot.addChild(new PMEvent("WARNING: You are running an older version of Perf, the plugin may produce unpredictable results."));
- }
- // contains profiled information
- } else {
- items = line.trim().split(""+(char)1); // using custom field separator. for default whitespace use " +" //$NON-NLS-1$
- if (items.length != 5) {
- continue;
- }
- percent = Float.parseFloat(items[0]); //percent column
- samples = Double.parseDouble(items[1].trim()); //samples column
- comm = items[2].trim(); //command column
- dso = items[3].trim(); //dso column
- symbol = items[4].trim(); //symbol column
- kernelFlag = (""+symbol.charAt(1)).equals("k"); //$NON-NLS-1$ //$NON-NLS-2$
-
- // initialize current command if it doesn't exist
- if ((currentCommand == null) || (!currentCommand.getName().equals(comm))) {
- currentCommand = (PMCommand) currentEvent.getChild(comm);
- if(currentCommand == null) {
- currentCommand = new PMCommand(comm);
- currentEvent.addChild(currentCommand);
- }
- }
-
- // initialize current dso if it doesn't exist
- if ((currentDso == null) || (!currentDso.getName().equals(dso))) {
- currentDso = (PMDso) currentCommand.getChild(dso);
- if (currentDso == null) {
- currentDso = new PMDso(dso,kernelFlag);
- currentCommand.addChild(currentDso);
- }
- }
-
- /*
- * Initialize the current file, and symbol
- *
- * We won't know the name of the file containing the symbol
- * until we run 'perf annotate' to resolve it, so for now we
- * attach all symbols as children of 'Unfiled Symbols'.
- */
- currentFile = currentDso.getFile(PerfPlugin.STRINGS_UnfiledSymbols);
- currentSym = new PMSymbol(symbol, percent, samples);
- currentFile.addChild(currentSym);
- }
- }
- } catch (IOException e) {
- logException(e);
- }
- spitStream(error,"Perf Report", print);
-
- boolean SourceLineNumbers = PerfPlugin.ATTR_SourceLineNumbers_default;
- boolean Kernel_SourceLineNumbers = PerfPlugin.ATTR_Kernel_SourceLineNumbers_default;
- try {
- // Check if resolving source file/line numbers is selected
- SourceLineNumbers = config.getAttribute(PerfPlugin.ATTR_SourceLineNumbers, PerfPlugin.ATTR_SourceLineNumbers_default);
- Kernel_SourceLineNumbers = config.getAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, PerfPlugin.ATTR_Kernel_SourceLineNumbers_default);
- } catch (CoreException e2) {
- SourceLineNumbers = false;
- }
-
- if (monitor != null && monitor.isCanceled()) {
- return;
- }
-
- boolean hasProfileData = invisibleRoot.getChildren().length != 0;
-
- if (SourceLineNumbers) {
- for (TreeParent ev : invisibleRoot.getChildren()) {
- if (!(ev instanceof PMEvent)) continue;
- for (TreeParent cmd : ev.getChildren()) {
- if (!(cmd instanceof PMCommand)) continue;
- for (TreeParent d : cmd.getChildren()) {
- if (!(d instanceof PMDso)) continue;
- currentDso = (PMDso)d;
- if ((!Kernel_SourceLineNumbers) && currentDso.isKernelDso()) continue;
- for (TreeParent s : currentDso.getFile(PerfPlugin.STRINGS_UnfiledSymbols).getChildren()) {
- if (!(s instanceof PMSymbol)) continue;
-
- if (monitor != null && monitor.isCanceled()) {
- return;
- }
- currentSym = (PMSymbol)s;
- String[] annotateCmd;
- if (workingDir == null) {
- annotateCmd = getAnnotateString(config, currentDso.getName(), currentSym.getName().substring(4), perfDataLoc, OldPerfVersion);
- } else {
- String perfDefaultDataLoc = workingDir + "/" + PerfPlugin.PERF_DEFAULT_DATA;
- annotateCmd = getAnnotateString(config, currentDso.getName(), currentSym.getName().substring(4), perfDefaultDataLoc, OldPerfVersion);
- }
-
- try {
- if(project==null) p = Runtime.getRuntime().exec(annotateCmd);
- else p = RuntimeProcessFactory.getFactory().exec(annotateCmd, project);
- input = new BufferedReader(new InputStreamReader(p.getInputStream()));
- error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
- } catch (IOException e) {
- logException(e);
- }
-
- PerfCore.parseAnnotation(monitor, input, workingDir, currentDso, currentSym);
- }
-
- if (currentDso.getFile(PerfPlugin.STRINGS_UnfiledSymbols).getChildren().length == 0) {
- currentDso.removeChild(currentDso.getFile(PerfPlugin.STRINGS_UnfiledSymbols));
- }
- spitStream(error,"Perf Annotate", print);
- }
- }
- }
- }
-
- if (print != null) {
- if (hasProfileData) {
- print.println("Profile data loaded into Perf Profile View.");
- } else {
- print.println("No profile data generated to be displayed.");
- }
- }
- }
-
- /**
- * Parse annotation file for a dso given a symbol
- * @param monitor monitor
- * @param input annotation file input stream
- * @param workingDir working directory configuration
- * @param currentDso dso
- * @param currentSym symbol
- */
- public static void parseAnnotation(IProgressMonitor monitor,
- BufferedReader input, IPath workingDir, PMDso currentDso,
- PMSymbol currentSym) {
-
- if (monitor != null && monitor.isCanceled()) {
- return;
- }
-
- boolean grabBlock = false;
- boolean blockStarted = false;
- String dsoName,lineRef;
- String line = null;
- String items[];
- float percent;
-
- try {
- while (( line = input.readLine()) != null){
- if (line.startsWith("Sorted summary for file")) { //$NON-NLS-1$
- grabBlock = true;
- dsoName = line.replace("Sorted summary for file ",""); //$NON-NLS-1$ //$NON-NLS-2$
- blockStarted = false;
- if ((workingDir != null) && (dsoName.startsWith("./"))) { //$NON-NLS-1$
- if (workingDir.toOSString().endsWith("/")) { //$NON-NLS-1$
- dsoName = workingDir.toOSString() + dsoName.substring(2); // path already ends with '/', so trim './'
- } else {
- dsoName = workingDir.toOSString() + dsoName.substring(1); // path doesn't have '/', so trim just the '.'
- }
- }
- currentDso.setPath(dsoName);
- } else if (line.startsWith("---")) { //$NON-NLS-1$
- if (blockStarted) {
- blockStarted = false;
- grabBlock = false;
- } else {
- blockStarted = true;
- }
- } else if (grabBlock && blockStarted) {
- //process the line.
- items = line.trim().split(" +"); //$NON-NLS-1$
- if (items.length != 2) {
- continue;
- }
- percent = Float.parseFloat(items[0]);
- lineRef = items[1];
- items = lineRef.split(":"); //$NON-NLS-1$
- if (currentDso == null) {
- //if (PerfPlugin.DEBUG_ON) System.err.println("Parsed line ref without being in valid block, shouldn't happen.");
- break;
- } else {
- int lineNum = -1;
- try {
- lineNum = Integer.parseInt(items[1]);
- } catch (NumberFormatException e) {
- // leave line number as -1
- }
- currentSym.addPercent(lineNum, percent);
- // Symbol currently in 'Unfiled Symbols' but we now know the actual parent
- if (currentSym.getParent().getName().equals(PerfPlugin.STRINGS_UnfiledSymbols)) {
- currentSym.getParent().removeChild(currentSym);
- currentDso.getFile(items[0]).addChild(currentSym);
- // Symbol has 2 (or more) parents
- } else if (!((PMFile)currentSym.getParent()).getPath().equals(items[0])) {
- currentSym.markConflict();
- currentSym.getParent().removeChild(currentSym);
- currentDso.getFile(PerfPlugin.STRINGS_MultipleFilesForSymbol).addChild(currentSym);
- }
- }
- }
- }
- } catch (IOException e) {
- logException(e);
- }
- }
-
- public static void refreshView (final String title) {
- Display.getDefault().syncExec(new Runnable() {
-
- @Override
- public void run() {
- try {
- PerfProfileView view = (PerfProfileView) PlatformUI
- .getWorkbench().getActiveWorkbenchWindow()
- .getActivePage().showView(PerfPlugin.VIEW_ID);
- view.setContentDescription(title);
- view.refreshModel();
- } catch (PartInitException e) {
- logException(e);
- }
- }
- });
- }
-
- /**
- * Log specified exception.
- * @param e Exception to log.
- */
- public static void logException(Exception e) {
- Status status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID,
- e.getMessage());
- PerfPlugin.getDefault().getLog().log(status);
- }
+ private static String spitStream(BufferedReader br, String blockTitle, PrintStream print) {
+
+ StringBuffer strBuf = new StringBuffer();
+ String line = null;
+ try {
+ while (( line = br.readLine()) != null){
+ strBuf.append(line);
+ strBuf.append("\n"); //$NON-NLS-1$
+ }
+ } catch (IOException e) {
+ logException(e);
+ }
+ String str = strBuf.toString();
+ if (!str.trim().isEmpty() && print != null) {
+ print.println(blockTitle + ": \n" +str + "\n END OF " + blockTitle); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return str;
+ }
+ // Maps event lists to host names for caching
+ private static Map<String,Map<String, List<String>>> eventsHostMap = null;
+ private static Map<String,List<String>> eventList = null;
+
+ /**
+ * Gets the list of events for a given launch configuration. Uses a cache for each host
+ * @param config
+ * @return
+ */
+ public static Map<String,List<String>> getEventList(ILaunchConfiguration config) {
+ String projectHost = getHostName(config);
+
+ if(eventsHostMap == null){
+ eventsHostMap = new HashMap<>();
+ }
+
+ // local projects have null hosts
+ if(projectHost == null){
+ projectHost = "local"; //$NON-NLS-1$
+ }
+
+ eventList = eventsHostMap.get(projectHost);
+
+ if(eventList == null){
+ eventList = loadEventList(config);
+ eventsHostMap.put(projectHost, eventList);
+ }
+ return eventList;
+ }
+
+
+ /**
+ *
+ * @param config
+ * @return the name of the host in which the config's project is stored
+ */
+ private static String getHostName(ILaunchConfiguration config){
+ String projectName = null;
+ try {
+ projectName = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
+ } catch (CoreException e) {
+ return null;
+ }
+ if (projectName.isEmpty()) {
+ return null;
+ }
+ IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
+ if(project == null){
+ return null;
+ }
+ return project.getLocationURI().getHost();
+
+ }
+
+ private static IProject getProject(ILaunchConfiguration config){
+ if(config == null){
+ return null;
+ } else {
+ try {
+ String projectName = ConfigUtils.getProjectName(config);
+ // an empty string is not a legal path to file argument for ConfigUtils.getProject
+ if (projectName != null && !projectName.isEmpty()) {
+ return ConfigUtils.getProject(projectName);
+ }
+ } catch (CoreException e1) {
+ logException(e1);
+ }
+ }
+
+ return null;
+ }
+
+ private static Map<String,List<String>> loadEventList(ILaunchConfiguration config){
+ Map<String,List<String>> events = new HashMap<>();
+ IProject project = getProject(config);
+
+ if (!PerfCore.checkPerfInPath(project)) {
+ return events;
+ }
+
+ Process p = null;
+ BufferedReader input = null;
+ try {
+ // Execute "perf list" to get list of all symbolic event types.
+ // Alternatively can try with -i flag.
+ p = RuntimeProcessFactory.getFactory().exec(new String[] {PerfPlugin.PERF_COMMAND, "list"}, project); //(char 1 as -t is a custom field seperator //$NON-NLS-1$
+
+ /*
+ * Old versions of Perf will send events list to stderr instead of stdout
+ * Checking if stdout is empty then read from stderr
+ */
+ input = new BufferedReader(new InputStreamReader(p.getInputStream()));
+
+ } catch( IOException e ) {
+ logException(e);
+ }
+ return parseEventList(input);
+ }
+
+ public static Map<String,List<String>> parseEventList (BufferedReader input){
+ Map<String,List<String>> events = new HashMap<>();
+ String line;
+ try {
+ // Process list of events. Each line is of the form <event>\s+<category>.
+ while (( line = input.readLine()) != null){
+ if (line.contains("[")) { //$NON-NLS-1$
+ String event;
+ String category;
+ if (line.contains(PerfPlugin.STRINGS_HWBREAKPOINTS)) {
+ category = PerfPlugin.STRINGS_HWBREAKPOINTS;
+ event = line.substring(1,line.indexOf('[', 0)).trim();
+ } else if (line.contains(PerfPlugin.STRINGS_RAWHWEvents)) {
+ category = PerfPlugin.STRINGS_RAWHWEvents;
+ event = line.substring(1,line.indexOf('[', 0)).trim();
+ } else {
+ event = line.substring(1,line.indexOf('[', 0)).trim();
+ if (event.contains("OR")) { //$NON-NLS-1$
+ event = event.split("OR")[0]; //filter out the abbreviations. //$NON-NLS-1$
+ }
+ category = line.replaceFirst(".*\\[(.+)\\]", "$1").trim(); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ List<String> categoryEvents = events.get(category);
+ if (categoryEvents == null) {
+ categoryEvents = new ArrayList<>();
+ events.put(category, categoryEvents);
+ }
+ categoryEvents.add(event.trim());
+ }
+ }
+ } catch (IOException e) {
+ logException(e);
+ } finally {
+ if (null != input) {
+ try {
+ input.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ return events;
+ }
+
+ //Gets the current version of perf
+ public static Version getPerfVersion(ILaunchConfiguration config) {
+ IProject project = getProject(config);
+ Process p = null;
+
+ try {
+ p = RuntimeProcessFactory.getFactory().exec(new String [] {PerfPlugin.PERF_COMMAND, "--version"}, project); //$NON-NLS-1$
+ } catch (IOException e) {
+ logException(e);
+ }
+ if (p == null) {
+ return null;
+ }
+
+ BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
+
+ String perfVersion = spitStream(input, "Perf --version", null); //$NON-NLS-1$
+ int index = perfVersion.indexOf('-');
+ if (index > 0) {
+ perfVersion = perfVersion.substring(0, index);
+ }
+ perfVersion = perfVersion.replace("perf version", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$
+ return new Version(perfVersion);
+ }
+
+
+ public static boolean checkPerfInPath(IProject project) {
+ try {
+ Process p = RuntimeProcessFactory.getFactory().exec(new String [] {PerfPlugin.PERF_COMMAND, "--version"}, project); //$NON-NLS-1$
+ return (p != null);
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ //Generates a perf record command string with the options set in the given config. (If null uses default).
+ public static String [] getRecordString(ILaunchConfiguration config, Version perfVersion) {
+ String [] base = new String [] {PerfPlugin.PERF_COMMAND, "record"}; //$NON-NLS-1$
+ if (config == null) {
+ return base;
+ } else {
+ ArrayList<String> newCommand = new ArrayList<>();
+ newCommand.addAll(Arrays.asList(base));
+ try {
+ if (new Version(3, 11, 0).compareTo(perfVersion) > 0) {
+ // Removed as of 4a4d371a4dfbd3b84a7eab8d535d4c7c3647b09e from perf upstream (kernel)
+ newCommand.add("-f"); //$NON-NLS-1$
+ }
+ if (config.getAttribute(PerfPlugin.ATTR_Record_Realtime, PerfPlugin.ATTR_Record_Realtime_default)) {
+ newCommand.add("-r"); //$NON-NLS-1$
+ int priority = config.getAttribute(PerfPlugin.ATTR_Record_Realtime_Priority, PerfPlugin.ATTR_Record_Realtime_Priority_default);
+ newCommand.add(Integer.toString(priority));
+ }
+ if (config.getAttribute(PerfPlugin.ATTR_Record_Verbose, PerfPlugin.ATTR_Record_Verbose_default))
+ newCommand.add("-v"); //$NON-NLS-1$
+ if (config.getAttribute(PerfPlugin.ATTR_Multiplex, PerfPlugin.ATTR_Multiplex_default))
+ newCommand.add("-M"); //$NON-NLS-1$
+ List<?> selE = config.getAttribute(PerfPlugin.ATTR_SelectedEvents, PerfPlugin.ATTR_SelectedEvents_default);
+ if (!config.getAttribute(PerfPlugin.ATTR_DefaultEvent, PerfPlugin.ATTR_DefaultEvent_default)
+ && selE != null) {
+ for(Object e : selE) {
+ newCommand.add("-e"); //$NON-NLS-1$
+ newCommand.add((String)e);
+ }
+ }
+ } catch (CoreException e) { }
+ return newCommand.toArray(new String[] {});
+ }
+ }
+
+ public static String[] getReportString(ILaunchConfiguration config, String perfDataLoc) {
+ ArrayList<String> base = new ArrayList<>();
+ base.addAll(Arrays.asList(new String [] {PerfPlugin.PERF_COMMAND, "report", "--sort", "comm,dso,sym", "-n", "-t", "" + (char)1 }));//(char 1 as -t is a custom field seperator) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ if (config != null) {
+ try {
+ String kernelLoc = config.getAttribute(PerfPlugin.ATTR_Kernel_Location, PerfPlugin.ATTR_Kernel_Location_default);
+ if (kernelLoc != PerfPlugin.ATTR_Kernel_Location_default) {
+ base.add("--vmlinux"); //$NON-NLS-1$
+ base.add(kernelLoc);
+ }
+ if (config.getAttribute(PerfPlugin.ATTR_ModuleSymbols, PerfPlugin.ATTR_ModuleSymbols_default))
+ base.add("-m"); //$NON-NLS-1$
+
+ /*
+ * danielhb, 12/14/2011 - some systems, like ubuntu and sles, does not have
+ * the -U option. The binary fails to execute in those systems when this
+ * option is enabled.
+ * I'm disabling it to make the plug-in runnable for them. This
+ * will probably need to be revisited in the future, probably when this
+ * flag is implemented by the Perf binary of those systems.
+ */
+ /*
+ if (config.getAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, PerfPlugin.ATTR_HideUnresolvedSymbols_default))
+ base.add("-U");
+ */
+ if (perfDataLoc != null) {
+ base.add("-i"); //$NON-NLS-1$
+ base.add(perfDataLoc);
+ }
+ } catch (CoreException e) { }
+ }
+ return base.toArray( new String[base.size()] );
+ }
+
+ public static String[] getAnnotateString(ILaunchConfiguration config, String dso, String symbol, String perfDataLoc, boolean OldPerfVersion) {
+ ArrayList<String> base = new ArrayList<>();
+ if (OldPerfVersion) {
+ base.addAll( Arrays.asList( new String[]{PerfPlugin.PERF_COMMAND, "annotate", "-s", symbol, "-l", "-P"} ) ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ } else {
+ base.addAll( Arrays.asList( new String[]{PerfPlugin.PERF_COMMAND, "annotate", "-d", dso, "-s", symbol, "-l", "-P"} ) ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+ if (config != null) {
+ try {
+ String kernelLoc = config.getAttribute(PerfPlugin.ATTR_Kernel_Location, PerfPlugin.ATTR_Kernel_Location_default);
+ if (kernelLoc != PerfPlugin.ATTR_Kernel_Location_default) {
+ base.add("--vmlinux"); //$NON-NLS-1$
+ base.add(kernelLoc);
+ }
+ if (config.getAttribute(PerfPlugin.ATTR_ModuleSymbols, PerfPlugin.ATTR_ModuleSymbols_default))
+ base.add("-m"); //$NON-NLS-1$
+ if (perfDataLoc != null) {
+ base.add("-i"); //$NON-NLS-1$
+ base.add(perfDataLoc);
+ }
+ } catch (CoreException e) { }
+ }
+
+ //(Annotate string per symbol)
+ return base.toArray( new String[base.size()] );
+ }
+
+ // Runs assuming perf.data has already been recorded, environ and workingDir can be set to null to use default
+ //perfDataLoc is optional - it is used to provide a pre-existing data file instead of something recorded from
+ //whatever project is being profiled. It is only used for junit tests atm.
+ public static void Report(ILaunchConfiguration config, String[] environ, IPath workingDir, IProgressMonitor monitor, String perfDataLoc, PrintStream print) {
+ IProject project = getProject(config);
+
+ TreeParent invisibleRoot = PerfPlugin.getDefault().clearModelRoot();
+
+ Version perfVersion = getPerfVersion(config);
+ boolean OldPerfVersion = false;
+ if (new Version(0, 0, 2).compareTo(perfVersion) > 0) {
+ OldPerfVersion = true;
+ if (print != null) { print.println("WARNING: You are running an older version of Perf, please update if you can. The plugin may produce unpredictable results."); }
+ }
+
+
+ BufferedReader input = null;
+ BufferedReader error = null;
+ Process p = null;
+
+ if (monitor != null && monitor.isCanceled()) {
+ return;
+ }
+
+ try {
+ if (workingDir==null) {
+ p = RuntimeProcessFactory.getFactory().exec(getReportString(config, perfDataLoc), project);
+ PerfPlugin.getDefault().setPerfProfileData(new Path(perfDataLoc));
+ PerfPlugin.getDefault().setWorkingDir(project.getLocation());
+ } else {
+ String defaultPerfDataLoc = workingDir.toOSString() + PerfPlugin.PERF_DEFAULT_DATA;
+ p = RuntimeProcessFactory.getFactory().exec(getReportString(config, defaultPerfDataLoc), project);
+ PerfPlugin.getDefault().setPerfProfileData(new Path(defaultPerfDataLoc));
+ PerfPlugin.getDefault().setWorkingDir(workingDir);
+ }
+
+ input = new BufferedReader(new InputStreamReader(p.getInputStream()));
+ error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
+ //spitting error stream moved to end of while loop, due to commenting of p.waitFor()
+ } catch( IOException e ) {
+ logException(e);
+ }
+
+ PerfCore.parseRemoteReport(config, workingDir, monitor, perfDataLoc, print,
+ invisibleRoot, OldPerfVersion, input, error, project);
+ }
+
+ /**
+ * Parse and build a tree model from the report of a perf data file
+ * @param config launch configuration
+ * @param workingDir working directory configuration
+ * @param monitor monitor
+ * @param perfDataLoc location of perf data file
+ * @param print print stream
+ * @param invisibleRoot root of the model
+ * @param OldPerfVersion boolean old perf version flag
+ * @param input input stream from perf data file report
+ * @param error output stream to where all standard error is written to
+ */
+ public static void parseReport(ILaunchConfiguration config,
+ IPath workingDir, IProgressMonitor monitor, String perfDataLoc,
+ PrintStream print, TreeParent invisibleRoot,
+ boolean OldPerfVersion, BufferedReader input, BufferedReader error) {
+ PerfCore.parseRemoteReport(config, workingDir, monitor, perfDataLoc, print,
+ invisibleRoot, OldPerfVersion, input, error, null);
+ }
+
+ private static void parseRemoteReport(ILaunchConfiguration config,
+ IPath workingDir, IProgressMonitor monitor, String perfDataLoc,
+ PrintStream print, TreeParent invisibleRoot,
+ boolean OldPerfVersion, BufferedReader input, BufferedReader error, IProject project) {
+
+ if (monitor != null && monitor.isCanceled()) {
+ return;
+ }
+ String line = null;
+ String items[];
+ float percent;
+
+ Process p = null;
+ double samples;
+ String comm,dso,symbol;
+ boolean kernelFlag;
+ PMEvent currentEvent = null;
+ PMCommand currentCommand = null;
+ PMDso currentDso = null;
+ PMFile currentFile = null;
+ PMSymbol currentSym = null;
+ try {
+ while (( line = input.readLine()) != null){
+ if (monitor != null && monitor.isCanceled()) {
+ return;
+ }
+ // line containing report information
+ if ((line.startsWith("#"))) { //$NON-NLS-1$
+ if (line.contains("Events:") || line.contains("Samples:")) { //$NON-NLS-1$ //$NON-NLS-2$
+ String[] tmp = line.trim().split(" "); //$NON-NLS-1$
+ String event = tmp[tmp.length - 1];
+ // In this case, the event name is single quoted
+ if (line.contains("Samples:")){ //$NON-NLS-1$
+ event = event.substring(1, event.length() -1);
+ }
+ currentEvent = new PMEvent(event);
+ invisibleRoot.addChild(currentEvent);
+ currentCommand = null;
+ currentDso = null;
+ } else if (line.contains("Samples:")) { //"samples" was used instead of events in an older version, some incompatibilities may arise. //$NON-NLS-1$
+ if (print != null) { print.println("WARNING: You are running an older version of Perf, please update if you can. The plugin may produce unpredictable results."); }
+ invisibleRoot.addChild(new PMEvent("WARNING: You are running an older version of Perf, the plugin may produce unpredictable results."));
+ }
+ // contains profiled information
+ } else {
+ items = line.trim().split(""+(char)1); // using custom field separator. for default whitespace use " +" //$NON-NLS-1$
+ if (items.length != 5) {
+ continue;
+ }
+ percent = Float.parseFloat(items[0]); //percent column
+ samples = Double.parseDouble(items[1].trim()); //samples column
+ comm = items[2].trim(); //command column
+ dso = items[3].trim(); //dso column
+ symbol = items[4].trim(); //symbol column
+ kernelFlag = (""+symbol.charAt(1)).equals("k"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ // initialize current command if it doesn't exist
+ if ((currentCommand == null) || (!currentCommand.getName().equals(comm))) {
+ currentCommand = (PMCommand) currentEvent.getChild(comm);
+ if(currentCommand == null) {
+ currentCommand = new PMCommand(comm);
+ currentEvent.addChild(currentCommand);
+ }
+ }
+
+ // initialize current dso if it doesn't exist
+ if ((currentDso == null) || (!currentDso.getName().equals(dso))) {
+ currentDso = (PMDso) currentCommand.getChild(dso);
+ if (currentDso == null) {
+ currentDso = new PMDso(dso,kernelFlag);
+ currentCommand.addChild(currentDso);
+ }
+ }
+
+ /*
+ * Initialize the current file, and symbol
+ *
+ * We won't know the name of the file containing the symbol
+ * until we run 'perf annotate' to resolve it, so for now we
+ * attach all symbols as children of 'Unfiled Symbols'.
+ */
+ currentFile = currentDso.getFile(PerfPlugin.STRINGS_UnfiledSymbols);
+ currentSym = new PMSymbol(symbol, percent, samples);
+ currentFile.addChild(currentSym);
+ }
+ }
+ } catch (IOException e) {
+ logException(e);
+ }
+ spitStream(error,"Perf Report", print);
+
+ boolean SourceLineNumbers = PerfPlugin.ATTR_SourceLineNumbers_default;
+ boolean Kernel_SourceLineNumbers = PerfPlugin.ATTR_Kernel_SourceLineNumbers_default;
+ try {
+ // Check if resolving source file/line numbers is selected
+ SourceLineNumbers = config.getAttribute(PerfPlugin.ATTR_SourceLineNumbers, PerfPlugin.ATTR_SourceLineNumbers_default);
+ Kernel_SourceLineNumbers = config.getAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, PerfPlugin.ATTR_Kernel_SourceLineNumbers_default);
+ } catch (CoreException e2) {
+ SourceLineNumbers = false;
+ }
+
+ if (monitor != null && monitor.isCanceled()) {
+ return;
+ }
+
+ boolean hasProfileData = invisibleRoot.getChildren().length != 0;
+
+ if (SourceLineNumbers) {
+ for (TreeParent ev : invisibleRoot.getChildren()) {
+ if (!(ev instanceof PMEvent)) continue;
+ for (TreeParent cmd : ev.getChildren()) {
+ if (!(cmd instanceof PMCommand)) continue;
+ for (TreeParent d : cmd.getChildren()) {
+ if (!(d instanceof PMDso)) continue;
+ currentDso = (PMDso)d;
+ if ((!Kernel_SourceLineNumbers) && currentDso.isKernelDso()) continue;
+ for (TreeParent s : currentDso.getFile(PerfPlugin.STRINGS_UnfiledSymbols).getChildren()) {
+ if (!(s instanceof PMSymbol)) continue;
+
+ if (monitor != null && monitor.isCanceled()) {
+ return;
+ }
+ currentSym = (PMSymbol)s;
+ String[] annotateCmd;
+ if (workingDir == null) {
+ annotateCmd = getAnnotateString(config, currentDso.getName(), currentSym.getName().substring(4), perfDataLoc, OldPerfVersion);
+ } else {
+ String perfDefaultDataLoc = workingDir + "/" + PerfPlugin.PERF_DEFAULT_DATA;
+ annotateCmd = getAnnotateString(config, currentDso.getName(), currentSym.getName().substring(4), perfDefaultDataLoc, OldPerfVersion);
+ }
+
+ try {
+ if(project==null) p = Runtime.getRuntime().exec(annotateCmd);
+ else p = RuntimeProcessFactory.getFactory().exec(annotateCmd, project);
+ input = new BufferedReader(new InputStreamReader(p.getInputStream()));
+ error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
+ } catch (IOException e) {
+ logException(e);
+ }
+
+ PerfCore.parseAnnotation(monitor, input, workingDir, currentDso, currentSym);
+ }
+
+ if (currentDso.getFile(PerfPlugin.STRINGS_UnfiledSymbols).getChildren().length == 0) {
+ currentDso.removeChild(currentDso.getFile(PerfPlugin.STRINGS_UnfiledSymbols));
+ }
+ spitStream(error,"Perf Annotate", print);
+ }
+ }
+ }
+ }
+
+ if (print != null) {
+ if (hasProfileData) {
+ print.println("Profile data loaded into Perf Profile View.");
+ } else {
+ print.println("No profile data generated to be displayed.");
+ }
+ }
+ }
+
+ /**
+ * Parse annotation file for a dso given a symbol
+ * @param monitor monitor
+ * @param input annotation file input stream
+ * @param workingDir working directory configuration
+ * @param currentDso dso
+ * @param currentSym symbol
+ */
+ public static void parseAnnotation(IProgressMonitor monitor,
+ BufferedReader input, IPath workingDir, PMDso currentDso,
+ PMSymbol currentSym) {
+
+ if (monitor != null && monitor.isCanceled()) {
+ return;
+ }
+
+ boolean grabBlock = false;
+ boolean blockStarted = false;
+ String dsoName,lineRef;
+ String line = null;
+ String items[];
+ float percent;
+
+ try {
+ while (( line = input.readLine()) != null){
+ if (line.startsWith("Sorted summary for file")) { //$NON-NLS-1$
+ grabBlock = true;
+ dsoName = line.replace("Sorted summary for file ",""); //$NON-NLS-1$ //$NON-NLS-2$
+ blockStarted = false;
+ if ((workingDir != null) && (dsoName.startsWith("./"))) { //$NON-NLS-1$
+ if (workingDir.toOSString().endsWith("/")) { //$NON-NLS-1$
+ dsoName = workingDir.toOSString() + dsoName.substring(2); // path already ends with '/', so trim './'
+ } else {
+ dsoName = workingDir.toOSString() + dsoName.substring(1); // path doesn't have '/', so trim just the '.'
+ }
+ }
+ currentDso.setPath(dsoName);
+ } else if (line.startsWith("---")) { //$NON-NLS-1$
+ if (blockStarted) {
+ blockStarted = false;
+ grabBlock = false;
+ } else {
+ blockStarted = true;
+ }
+ } else if (grabBlock && blockStarted) {
+ //process the line.
+ items = line.trim().split(" +"); //$NON-NLS-1$
+ if (items.length != 2) {
+ continue;
+ }
+ percent = Float.parseFloat(items[0]);
+ lineRef = items[1];
+ items = lineRef.split(":"); //$NON-NLS-1$
+ if (currentDso == null) {
+ //if (PerfPlugin.DEBUG_ON) System.err.println("Parsed line ref without being in valid block, shouldn't happen.");
+ break;
+ } else {
+ int lineNum = -1;
+ try {
+ lineNum = Integer.parseInt(items[1]);
+ } catch (NumberFormatException e) {
+ // leave line number as -1
+ }
+ currentSym.addPercent(lineNum, percent);
+ // Symbol currently in 'Unfiled Symbols' but we now know the actual parent
+ if (currentSym.getParent().getName().equals(PerfPlugin.STRINGS_UnfiledSymbols)) {
+ currentSym.getParent().removeChild(currentSym);
+ currentDso.getFile(items[0]).addChild(currentSym);
+ // Symbol has 2 (or more) parents
+ } else if (!((PMFile)currentSym.getParent()).getPath().equals(items[0])) {
+ currentSym.markConflict();
+ currentSym.getParent().removeChild(currentSym);
+ currentDso.getFile(PerfPlugin.STRINGS_MultipleFilesForSymbol).addChild(currentSym);
+ }
+ }
+ }
+ }
+ } catch (IOException e) {
+ logException(e);
+ }
+ }
+
+ public static void refreshView (final String title) {
+ Display.getDefault().syncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ PerfProfileView view = (PerfProfileView) PlatformUI
+ .getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage().showView(PerfPlugin.VIEW_ID);
+ view.setContentDescription(title);
+ view.refreshModel();
+ } catch (PartInitException e) {
+ logException(e);
+ }
+ }
+ });
+ }
+
+ /**
+ * Log specified exception.
+ * @param e Exception to log.
+ */
+ public static void logException(Exception e) {
+ Status status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID,
+ e.getMessage());
+ PerfPlugin.getDefault().getLog().log(status);
+ }
} \ No newline at end of file
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/PerfPlugin.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/PerfPlugin.java
index cedab0e40a..f165cde241 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/PerfPlugin.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/PerfPlugin.java
@@ -33,235 +33,235 @@ import org.osgi.framework.BundleContext;
*/
public class PerfPlugin extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.perf"; //$NON-NLS-1$
-
- // View ID
- public static final String VIEW_ID = "org.eclipse.linuxtools.perf.ui.ProfileView"; //$NON-NLS-1$
- public static final String SOURCE_DISASSEMBLY_VIEW_ID = "org.eclipse.linuxtools.perf.ui.SourceDisassemblyView"; //$NON-NLS-1$
- public static final String STAT_VIEW_ID = "org.eclipse.linuxtools.perf.ui.StatView"; //$NON-NLS-1$
- public static final String STAT_DIFF_VIEW_ID = "org.eclipse.linuxtools.perf.ui.StatViewDiff"; //$NON-NLS-1$
- public static final String REPORT_DIFF_VIEW_ID = "org.eclipse.linuxtools.perf.ui.ReportViewDiff"; //$NON-NLS-1$
-
- // Launch Config ID
- public static final String LAUNCHCONF_ID = "org.eclipse.linuxtools.perf.launch.profile"; //$NON-NLS-1$
-
- //Perf Options tab attribs.
- public static final String ATTR_Kernel_Location = "org.eclipse.linuxtools.internal.perf.attr.Kernel.Location"; //$NON-NLS-1$
- public static final String ATTR_Kernel_Location_default = ""; //$NON-NLS-1$
- public static final String ATTR_Record_Realtime = "org.eclipse.linuxtools.internal.perf.attr.Record.Realtime"; //$NON-NLS-1$
- public static final boolean ATTR_Record_Realtime_default = false;
- public static final String ATTR_Record_Realtime_Priority = "org.eclipse.linuxtools.internal.perf.attr.Record.Realtime.Priority"; //$NON-NLS-1$
- public static final int ATTR_Record_Realtime_Priority_default = 1;
- public static final String ATTR_Record_Verbose = "org.eclipse.linuxtools.internal.perf.attr.Record.Verbose"; //$NON-NLS-1$
- public static final boolean ATTR_Record_Verbose_default = false;
- public static final String ATTR_SourceLineNumbers = "org.eclipse.linuxtools.internal.perf.attr.SourceLineNumbers"; //$NON-NLS-1$
- public static final boolean ATTR_SourceLineNumbers_default = true;
- public static final String ATTR_Kernel_SourceLineNumbers = "org.eclipse.linuxtools.internal.perf.attr.Kernel.SourceLineNumbers"; //$NON-NLS-1$
- public static final boolean ATTR_Kernel_SourceLineNumbers_default = false;
- public static final String ATTR_Multiplex = "org.eclipse.linuxtools.internal.perf.attr.Multiplex"; //$NON-NLS-1$
- public static final boolean ATTR_Multiplex_default = false;
- public static final String ATTR_ModuleSymbols = "org.eclipse.linuxtools.internal.perf.attr.ModuleSymbols"; //$NON-NLS-1$
- public static final boolean ATTR_ModuleSymbols_default = false;
- public static final String ATTR_HideUnresolvedSymbols = "org.eclipse.linuxtools.internal.perf.attr.HideUnresolvedSymbols"; //$NON-NLS-1$
- public static final boolean ATTR_HideUnresolvedSymbols_default = true;
- public static final String ATTR_ShowSourceDisassembly = "org.eclipse.linuxtools.internal.perf.attr.ShowSourceDisassembly"; //$NON-NLS-1$
- public static final boolean ATTR_ShowSourceDisassembly_default = false;
- public static final String ATTR_ShowStat = "org.eclipse.linuxtools.internal.perf.attr.ShowStat"; //$NON-NLS-1$
- public static final boolean ATTR_ShowStat_default = false;
- public static final String ATTR_StatRunCount = "org.eclipse.linuxtools.internal.perf.attr.StatRunCount"; //$NON-NLS-1$
- public static final int ATTR_StatRunCount_default = 1;
-
- //Perf Events tab attribs.
- public static final String ATTR_DefaultEvent = "org.eclipse.linuxtools.internal.perf.attr.DefaultEvent"; //$NON-NLS-1$
- public static final boolean ATTR_DefaultEvent_default = true;
- public static final String ATTR_MultipleEvents = "org.eclipse.linuxtools.internal.perf.attr.MultipleEvents"; //$NON-NLS-1$
- public static final boolean ATTR_MultipleEvents_default = false;
- public static final String ATTR_SelectedEvents = "org.eclipse.linuxtools.internal.perf.attr.SelectedEvents"; //$NON-NLS-1$
- public static final List<String> ATTR_SelectedEvents_default = null;
- public static final String ATTR_RawHwEvents = "org.eclipse.linuxtools.internal.perf.attr.RawHwEvents"; //$NON-NLS-1$
- public static final List<String> ATTR_RawHwEvents_default = null;
- public static final String ATTR_HwBreakpointEvents = "org.eclipse.linuxtools.internal.perf.attr.HwBreakpointEvents"; //$NON-NLS-1$
- public static final List<String> ATTR_HwBreakpointEvents_default = null;
-
- //Strings
- public static final String STRINGS_Kernel_Location = "Location of kernel image file (optional): "; //$NON-NLS-1$
- public static final String STRINGS_Record_Realtime = "Record with realtime priority (RT SCHED_FIFO)"; //$NON-NLS-1$
- public static final String STRINGS_Record_Verbose = "Record with verbose output"; //$NON-NLS-1$
- public static final String STRINGS_ModuleSymbols = "Load Module Symbols"; //$NON-NLS-1$
- public static final String STRINGS_HideUnresolvedSymbols = "Hide Unresolved Symbols"; //$NON-NLS-1$
- public static final String STRINGS_SourceLineNumbers = "Obtain source line numbers from profile data"; //$NON-NLS-1$
- public static final String STRINGS_Kernel_SourceLineNumbers = "Obtain kernel source line numbers from profile data (Warning: May be very slow)"; //$NON-NLS-1$
- public static final String STRINGS_Multiplex = "Multiplex counter output in a single channel"; //$NON-NLS-1$
- public static final String STRINGS_RAWHWEvents = "Raw hardware event descriptor"; //$NON-NLS-1$
- public static final String STRINGS_HWBREAKPOINTS = "Hardware breakpoint"; //$NON-NLS-1$
- public static final String STRINGS_UnfiledSymbols = "Unfiled Symbols"; //$NON-NLS-1$
- public static final String STRINGS_MultipleFilesForSymbol = "Symbols conflicting in multiple files"; //$NON-NLS-1$
- public static final String STRINGS_ShowSourceDisassembly = "Show Source Disassembly View"; //$NON-NLS-1$
- public static final String STRINGS_ShowStat = "Show Stat View"; //$NON-NLS-1$
- public static final String STRINGS_SearchSourceDisassembly = "Search Source Disassembly"; //$NON-NLS-1$
-
- public static final String PERF_COMMAND = "perf"; //$NON-NLS-1$
- public static final String PERF_DEFAULT_DATA = "perf.data"; //$NON-NLS-1$
- public static final String PERF_DEFAULT_STAT= "perf.stat"; //$NON-NLS-1$
- public static final String PERF_DEAFULT_OLD_STAT = "perf.old.stat"; //$NON-NLS-1$
- public static final boolean DEBUG_ON = false; //Spew debug messages or not.
-
-
- // The shared instance
- private static PerfPlugin plugin;
-
- // Model Root
- private TreeParent _modelRoot;
-
- // Source Disassembly Data
- private IPerfData sourceDisassemblyData;
-
- // Stat Data
- private IPerfData statData;
-
- // Current profile data
- private IPath curProfileData;
-
- // Current working directory
- private IPath curWorkingDir;
-
- public TreeParent getModelRoot() {
- return _modelRoot;
- }
-
- public IPerfData getSourceDisassemblyData () {
- return sourceDisassemblyData;
- }
-
- public IPerfData getStatData () {
- return statData;
- }
-
- public IPath getPerfProfileData() {
- return curProfileData;
- }
-
- public IPath getWorkingDir(){
- return curWorkingDir;
- }
-
- /**
- * Get perf file with specified name under the current profiled project.
- *
- * @param fileName file name.
- * @return File corresponding to given file or null if no working directory
- * has been set.
- */
- public IPath getPerfFile(String fileName) {
- if (curWorkingDir != null) {
- return curWorkingDir.append(fileName);
- }
- return null;
- }
-
- /**
- * Return cleared model root.
- * @return TreeParent cleared model root.
- */
- public TreeParent clearModelRoot(){
- if (_modelRoot == null) {
- _modelRoot = new TreeParent(""); //$NON-NLS-1$
- } else {
- _modelRoot.clear();
- }
- return _modelRoot;
- }
-
- public void setModelRoot(TreeParent rootnode) {
- this._modelRoot = rootnode;
- }
-
- public void setSourceDisassemblyData (IPerfData sourceDisassemblyData) {
- this.sourceDisassemblyData = sourceDisassemblyData;
- }
-
- public void setStatData (IPerfData statData) {
- this.statData = statData;
- }
-
- public void setPerfProfileData(IPath perfProfileData) {
- this.curProfileData = perfProfileData;
- }
-
- public void setWorkingDir(IPath workingDir){
- curWorkingDir = workingDir;
- }
-
- /**
- * The constructor
- */
- public PerfPlugin() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static PerfPlugin getDefault() {
- return plugin;
- }
-
- /**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-
- /**
- * Log the given exception and display the message/reason in an error
- * message box. (From org.eclipse.linuxtools.packagekit.ui.Activator)
- *
- * @param ex the given exception to display
- * @since 2.0
- */
- public void openError(Exception ex, final String title) {
- StringWriter writer = new StringWriter();
- ex.printStackTrace(new PrintWriter(writer));
-
- final String message = ex.getMessage();
- final String formattedMessage = PLUGIN_ID + " : " + message; //$NON-NLS-1$
- final Status status = new Status(IStatus.ERROR, PLUGIN_ID, formattedMessage, new Throwable(writer.toString()));
-
- getLog().log(status);
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- ErrorDialog.openError(Display.getDefault().getActiveShell(),
- title, message, status);
- }
- });
- }
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.perf"; //$NON-NLS-1$
+
+ // View ID
+ public static final String VIEW_ID = "org.eclipse.linuxtools.perf.ui.ProfileView"; //$NON-NLS-1$
+ public static final String SOURCE_DISASSEMBLY_VIEW_ID = "org.eclipse.linuxtools.perf.ui.SourceDisassemblyView"; //$NON-NLS-1$
+ public static final String STAT_VIEW_ID = "org.eclipse.linuxtools.perf.ui.StatView"; //$NON-NLS-1$
+ public static final String STAT_DIFF_VIEW_ID = "org.eclipse.linuxtools.perf.ui.StatViewDiff"; //$NON-NLS-1$
+ public static final String REPORT_DIFF_VIEW_ID = "org.eclipse.linuxtools.perf.ui.ReportViewDiff"; //$NON-NLS-1$
+
+ // Launch Config ID
+ public static final String LAUNCHCONF_ID = "org.eclipse.linuxtools.perf.launch.profile"; //$NON-NLS-1$
+
+ //Perf Options tab attribs.
+ public static final String ATTR_Kernel_Location = "org.eclipse.linuxtools.internal.perf.attr.Kernel.Location"; //$NON-NLS-1$
+ public static final String ATTR_Kernel_Location_default = ""; //$NON-NLS-1$
+ public static final String ATTR_Record_Realtime = "org.eclipse.linuxtools.internal.perf.attr.Record.Realtime"; //$NON-NLS-1$
+ public static final boolean ATTR_Record_Realtime_default = false;
+ public static final String ATTR_Record_Realtime_Priority = "org.eclipse.linuxtools.internal.perf.attr.Record.Realtime.Priority"; //$NON-NLS-1$
+ public static final int ATTR_Record_Realtime_Priority_default = 1;
+ public static final String ATTR_Record_Verbose = "org.eclipse.linuxtools.internal.perf.attr.Record.Verbose"; //$NON-NLS-1$
+ public static final boolean ATTR_Record_Verbose_default = false;
+ public static final String ATTR_SourceLineNumbers = "org.eclipse.linuxtools.internal.perf.attr.SourceLineNumbers"; //$NON-NLS-1$
+ public static final boolean ATTR_SourceLineNumbers_default = true;
+ public static final String ATTR_Kernel_SourceLineNumbers = "org.eclipse.linuxtools.internal.perf.attr.Kernel.SourceLineNumbers"; //$NON-NLS-1$
+ public static final boolean ATTR_Kernel_SourceLineNumbers_default = false;
+ public static final String ATTR_Multiplex = "org.eclipse.linuxtools.internal.perf.attr.Multiplex"; //$NON-NLS-1$
+ public static final boolean ATTR_Multiplex_default = false;
+ public static final String ATTR_ModuleSymbols = "org.eclipse.linuxtools.internal.perf.attr.ModuleSymbols"; //$NON-NLS-1$
+ public static final boolean ATTR_ModuleSymbols_default = false;
+ public static final String ATTR_HideUnresolvedSymbols = "org.eclipse.linuxtools.internal.perf.attr.HideUnresolvedSymbols"; //$NON-NLS-1$
+ public static final boolean ATTR_HideUnresolvedSymbols_default = true;
+ public static final String ATTR_ShowSourceDisassembly = "org.eclipse.linuxtools.internal.perf.attr.ShowSourceDisassembly"; //$NON-NLS-1$
+ public static final boolean ATTR_ShowSourceDisassembly_default = false;
+ public static final String ATTR_ShowStat = "org.eclipse.linuxtools.internal.perf.attr.ShowStat"; //$NON-NLS-1$
+ public static final boolean ATTR_ShowStat_default = false;
+ public static final String ATTR_StatRunCount = "org.eclipse.linuxtools.internal.perf.attr.StatRunCount"; //$NON-NLS-1$
+ public static final int ATTR_StatRunCount_default = 1;
+
+ //Perf Events tab attribs.
+ public static final String ATTR_DefaultEvent = "org.eclipse.linuxtools.internal.perf.attr.DefaultEvent"; //$NON-NLS-1$
+ public static final boolean ATTR_DefaultEvent_default = true;
+ public static final String ATTR_MultipleEvents = "org.eclipse.linuxtools.internal.perf.attr.MultipleEvents"; //$NON-NLS-1$
+ public static final boolean ATTR_MultipleEvents_default = false;
+ public static final String ATTR_SelectedEvents = "org.eclipse.linuxtools.internal.perf.attr.SelectedEvents"; //$NON-NLS-1$
+ public static final List<String> ATTR_SelectedEvents_default = null;
+ public static final String ATTR_RawHwEvents = "org.eclipse.linuxtools.internal.perf.attr.RawHwEvents"; //$NON-NLS-1$
+ public static final List<String> ATTR_RawHwEvents_default = null;
+ public static final String ATTR_HwBreakpointEvents = "org.eclipse.linuxtools.internal.perf.attr.HwBreakpointEvents"; //$NON-NLS-1$
+ public static final List<String> ATTR_HwBreakpointEvents_default = null;
+
+ //Strings
+ public static final String STRINGS_Kernel_Location = "Location of kernel image file (optional): "; //$NON-NLS-1$
+ public static final String STRINGS_Record_Realtime = "Record with realtime priority (RT SCHED_FIFO)"; //$NON-NLS-1$
+ public static final String STRINGS_Record_Verbose = "Record with verbose output"; //$NON-NLS-1$
+ public static final String STRINGS_ModuleSymbols = "Load Module Symbols"; //$NON-NLS-1$
+ public static final String STRINGS_HideUnresolvedSymbols = "Hide Unresolved Symbols"; //$NON-NLS-1$
+ public static final String STRINGS_SourceLineNumbers = "Obtain source line numbers from profile data"; //$NON-NLS-1$
+ public static final String STRINGS_Kernel_SourceLineNumbers = "Obtain kernel source line numbers from profile data (Warning: May be very slow)"; //$NON-NLS-1$
+ public static final String STRINGS_Multiplex = "Multiplex counter output in a single channel"; //$NON-NLS-1$
+ public static final String STRINGS_RAWHWEvents = "Raw hardware event descriptor"; //$NON-NLS-1$
+ public static final String STRINGS_HWBREAKPOINTS = "Hardware breakpoint"; //$NON-NLS-1$
+ public static final String STRINGS_UnfiledSymbols = "Unfiled Symbols"; //$NON-NLS-1$
+ public static final String STRINGS_MultipleFilesForSymbol = "Symbols conflicting in multiple files"; //$NON-NLS-1$
+ public static final String STRINGS_ShowSourceDisassembly = "Show Source Disassembly View"; //$NON-NLS-1$
+ public static final String STRINGS_ShowStat = "Show Stat View"; //$NON-NLS-1$
+ public static final String STRINGS_SearchSourceDisassembly = "Search Source Disassembly"; //$NON-NLS-1$
+
+ public static final String PERF_COMMAND = "perf"; //$NON-NLS-1$
+ public static final String PERF_DEFAULT_DATA = "perf.data"; //$NON-NLS-1$
+ public static final String PERF_DEFAULT_STAT= "perf.stat"; //$NON-NLS-1$
+ public static final String PERF_DEAFULT_OLD_STAT = "perf.old.stat"; //$NON-NLS-1$
+ public static final boolean DEBUG_ON = false; //Spew debug messages or not.
+
+
+ // The shared instance
+ private static PerfPlugin plugin;
+
+ // Model Root
+ private TreeParent _modelRoot;
+
+ // Source Disassembly Data
+ private IPerfData sourceDisassemblyData;
+
+ // Stat Data
+ private IPerfData statData;
+
+ // Current profile data
+ private IPath curProfileData;
+
+ // Current working directory
+ private IPath curWorkingDir;
+
+ public TreeParent getModelRoot() {
+ return _modelRoot;
+ }
+
+ public IPerfData getSourceDisassemblyData () {
+ return sourceDisassemblyData;
+ }
+
+ public IPerfData getStatData () {
+ return statData;
+ }
+
+ public IPath getPerfProfileData() {
+ return curProfileData;
+ }
+
+ public IPath getWorkingDir(){
+ return curWorkingDir;
+ }
+
+ /**
+ * Get perf file with specified name under the current profiled project.
+ *
+ * @param fileName file name.
+ * @return File corresponding to given file or null if no working directory
+ * has been set.
+ */
+ public IPath getPerfFile(String fileName) {
+ if (curWorkingDir != null) {
+ return curWorkingDir.append(fileName);
+ }
+ return null;
+ }
+
+ /**
+ * Return cleared model root.
+ * @return TreeParent cleared model root.
+ */
+ public TreeParent clearModelRoot(){
+ if (_modelRoot == null) {
+ _modelRoot = new TreeParent(""); //$NON-NLS-1$
+ } else {
+ _modelRoot.clear();
+ }
+ return _modelRoot;
+ }
+
+ public void setModelRoot(TreeParent rootnode) {
+ this._modelRoot = rootnode;
+ }
+
+ public void setSourceDisassemblyData (IPerfData sourceDisassemblyData) {
+ this.sourceDisassemblyData = sourceDisassemblyData;
+ }
+
+ public void setStatData (IPerfData statData) {
+ this.statData = statData;
+ }
+
+ public void setPerfProfileData(IPath perfProfileData) {
+ this.curProfileData = perfProfileData;
+ }
+
+ public void setWorkingDir(IPath workingDir){
+ curWorkingDir = workingDir;
+ }
+
+ /**
+ * The constructor
+ */
+ public PerfPlugin() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static PerfPlugin getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns an image descriptor for the image file at the given
+ * plug-in relative path
+ *
+ * @param path the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
+
+ /**
+ * Log the given exception and display the message/reason in an error
+ * message box. (From org.eclipse.linuxtools.packagekit.ui.Activator)
+ *
+ * @param ex the given exception to display
+ * @since 2.0
+ */
+ public void openError(Exception ex, final String title) {
+ StringWriter writer = new StringWriter();
+ ex.printStackTrace(new PrintWriter(writer));
+
+ final String message = ex.getMessage();
+ final String formattedMessage = PLUGIN_ID + " : " + message; //$NON-NLS-1$
+ final Status status = new Status(IStatus.ERROR, PLUGIN_ID, formattedMessage, new Throwable(writer.toString()));
+
+ getLog().log(status);
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ ErrorDialog.openError(Display.getDefault().getActiveShell(),
+ title, message, status);
+ }
+ });
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ReportComparisonData.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ReportComparisonData.java
index 7cf29417e6..baf8f14302 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ReportComparisonData.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ReportComparisonData.java
@@ -19,30 +19,30 @@ import org.eclipse.core.runtime.IPath;
*/
public class ReportComparisonData extends AbstractDataManipulator {
- private IPath oldFile;
- private IPath newFile;
+ private IPath oldFile;
+ private IPath newFile;
- public ReportComparisonData(String title, IPath oldFile, IPath newFile, IProject project) {
- super(title, newFile.removeLastSegments(1), project);
- this.oldFile = oldFile;
- this.newFile = newFile;
- }
+ public ReportComparisonData(String title, IPath oldFile, IPath newFile, IProject project) {
+ super(title, newFile.removeLastSegments(1), project);
+ this.oldFile = oldFile;
+ this.newFile = newFile;
+ }
- @Override
- public void parse() {
- performCommand(getCommand(), 1);
- }
+ @Override
+ public void parse() {
+ performCommand(getCommand(), 1);
+ }
- /**
- * Get perf diff command to execute.
- *
- * @return String array representing command to execute.
- */
- protected String[] getCommand() {
- return new String[] { PerfPlugin.PERF_COMMAND,
- "diff", //$NON-NLS-1$
- oldFile.toOSString(),
- newFile.toOSString() };
- }
+ /**
+ * Get perf diff command to execute.
+ *
+ * @return String array representing command to execute.
+ */
+ protected String[] getCommand() {
+ return new String[] { PerfPlugin.PERF_COMMAND,
+ "diff", //$NON-NLS-1$
+ oldFile.toOSString(),
+ newFile.toOSString() };
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/SourceDisassemblyData.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/SourceDisassemblyData.java
index aba3091741..e63da557c1 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/SourceDisassemblyData.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/SourceDisassemblyData.java
@@ -24,30 +24,30 @@ import org.eclipse.swt.widgets.Display;
*/
public class SourceDisassemblyData extends AbstractDataManipulator {
- public SourceDisassemblyData(String title, IPath workingDir, IProject project) {
- super(title, workingDir, project);
- }
-
- public SourceDisassemblyData(String title, IPath workingDir) {
- super(title, workingDir);
- }
-
- @Override
- public void parse() {
- URI workingDirURI = null;
- try {
- workingDirURI = new URI(getWorkDir().toOSString());
- } catch (URISyntaxException e) {
- MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
- }
- String [] cmd = getCommand(workingDirURI.getPath());
- // perf annotate prints the data to standard output
- performCommand(cmd, 1);
- }
-
- protected String [] getCommand(String workingDir) {
- return new String[] { "perf", "annotate", //$NON-NLS-1$ //$NON-NLS-2$
- "-i", workingDir + "perf.data" }; //$NON-NLS-1$ //$NON-NLS-2$
- }
+ public SourceDisassemblyData(String title, IPath workingDir, IProject project) {
+ super(title, workingDir, project);
+ }
+
+ public SourceDisassemblyData(String title, IPath workingDir) {
+ super(title, workingDir);
+ }
+
+ @Override
+ public void parse() {
+ URI workingDirURI = null;
+ try {
+ workingDirURI = new URI(getWorkDir().toOSString());
+ } catch (URISyntaxException e) {
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
+ }
+ String [] cmd = getCommand(workingDirURI.getPath());
+ // perf annotate prints the data to standard output
+ performCommand(cmd, 1);
+ }
+
+ protected String [] getCommand(String workingDir) {
+ return new String[] { "perf", "annotate", //$NON-NLS-1$ //$NON-NLS-2$
+ "-i", workingDir + "perf.data" }; //$NON-NLS-1$ //$NON-NLS-2$
+ }
} \ No newline at end of file
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/StatComparisonData.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/StatComparisonData.java
index 8d5716a8da..2de5882e33 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/StatComparisonData.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/StatComparisonData.java
@@ -35,273 +35,273 @@ import org.eclipse.linuxtools.profiling.launch.RemoteProxyManager;
* Class containing all functionality for comparting perf statistics data.
*/
public class StatComparisonData extends BaseDataManipulator implements IPerfData {
- // Old stats file.
- private IPath oldFile;
-
- // New stats file.
- private IPath newFile;
-
- // Comparison result string.
- private String result = ""; //$NON-NLS-1$
-
- // Title for this comparison run.
- private String title;
-
- // Unique data identifier.
- private String dataID;
-
- public StatComparisonData(String title, IPath oldFile, IPath newFile) {
- this.title = title;
- this.oldFile = oldFile;
- this.newFile = newFile;
- this.dataID = String.valueOf(((new Date().getTime())));
- }
-
- @Override
- public String getPerfData() {
- return result;
- }
-
- @Override
- public String getTitle() {
- return title;
- }
-
- /**
- * Get unique identifier for this data object.
- *
- * @return String unique identifier based on this object's creation time.
- */
- public String getDataID(){
- return dataID;
- }
-
- /**
- * Generate a unique identifier based on the given file. The generation is a
- * simple concatenation between the file path and the time of this object's
- * creation.
- *
- * @param file File to generate uniqure id from.
- * @return String unique id for specified file.
- */
- private String generateFileID(IPath file) {
- return file.toOSString() + dataID;
- }
-
- /**
- * Get path to old perf data file.
- *
- * @return String path corresponding to old perf data.
- */
- public String getOldDataPath() {
- return oldFile.toPortableString();
- }
-
- /**
- * Get path to new perf data file.
- *
- * @return String path corresponding to new perf data.
- */
- public String getNewDataPath() {
- return newFile.toOSString();
- }
-
- /**
- * Get a unique to for the old perf data file.
- *
- * @return String unique id.
- */
- public String getOldDataID() {
- return generateFileID(oldFile);
- }
-
- /**
- * Get a unique to for the old perf data file.
- *
- * @return String unique id.
- */
- public String getNewDataID() {
- return generateFileID(newFile);
- }
-
- /**
- * Compare stat data files and store the result in the result field.
- */
- public void runComparison() {
- ArrayList<PMStatEntry> statsDiff = getComparisonStats();
-
- if (!statsDiff.isEmpty()) {
- String[][] statsDiffStr = new String[statsDiff.size()][];
- int currentRow = 0;
-
- // gather comparison results in a string array
- for (PMStatEntry statEntry : statsDiff) {
- statsDiffStr[currentRow] = statEntry.toStringArray();
- currentRow++;
- }
-
- // apply format to each entry and set the result
- String format = getFormat(statsDiffStr);
- String curLine;
- for (String[] statEntry : statsDiffStr) {
- curLine = String.format(format, (Object[]) statEntry);
- curLine = curLine.contains(PMStatEntry.TIME) ? "\n" + curLine //$NON-NLS-1$
- : curLine;
- result += curLine;
- }
- } else{
-
- }
- }
-
- /**
- * Return a PMStatEntry array with the result of the comparison between the
- * old and new stat data files
- * @return
- */
- public ArrayList<PMStatEntry> getComparisonStats() {
- ArrayList<PMStatEntry> oldStats = collectStats(oldFile);
- ArrayList<PMStatEntry> newStats = collectStats(newFile);
- ArrayList<PMStatEntry> result = new ArrayList<>();
-
- for (PMStatEntry oldEntry : oldStats) {
- for (PMStatEntry newEntry : newStats) {
- if (oldEntry.equalEvents(newEntry)) {
- result.add(oldEntry.compare(newEntry));
- continue;
- }
- }
- }
-
- return result;
- }
-
- /**
- * Collect statistics entries from the specified stat data file.
- *
- * @param file file to collect from
- * @return List containing statistics entries from the given file.
- */
- private static ArrayList<PMStatEntry> collectStats(IPath file) {
- ArrayList<PMStatEntry> result = new ArrayList<>();
- BufferedReader statReader = null;
- URI fileURI = null;
- try {
- fileURI = new URI(file.toPortableString());
- IRemoteFileProxy proxy = null;
- proxy = RemoteProxyManager.getInstance().getFileProxy(fileURI);
- IFileStore newDataFileStore = proxy.getResource(fileURI.getPath());
- statReader = new BufferedReader(new InputStreamReader(newDataFileStore.openInputStream(EFS.NONE, null)));
-
- // pattern for a valid perf stat entry
- Pattern entryPattern = Pattern.compile(PMStatEntry.getString(Type.ENTRY_PATTERN));
-
- // pattern for last stat entry (seconds elapsed):
- Pattern totalTimePattern = Pattern.compile(PMStatEntry.getString(Type.TIME_PATTERN));
-
- String line;
- while((line = statReader.readLine()) != null ){
- line = line.trim();
- Matcher match = entryPattern.matcher(line);
- String samples, event, usage, units, delta, scale;
- PMStatEntry statEntry;
-
- if(match.find()){
-
- // extract information from groups
- samples = match.group(1);
- event = match.group(2);
- usage = match.group(6);
- units = match.group(7);
- delta = match.group(9);
- scale = match.group(13);
-
- // create stat entry
- statEntry = new PMStatEntry(toFloat(samples), event,
- toFloat(usage), units, toFloat(delta),
- toFloat(scale));
-
- // add stat entry to results list
- result.add(statEntry);
-
- } else if(line.contains(PMStatEntry.TIME)){
-
- // match seconds elapsed pattern
- match = totalTimePattern.matcher(line);
- if(match.find()){
- samples = match.group(1);
- event = match.group(2);
- delta = match.group(4);
-
- // create stat entry
- statEntry = new PMStatEntry(toFloat(samples),
- event, 0, null, toFloat(delta), 0);
-
- result.add(statEntry);
- }
- }
- }
- return result;
- } catch (IOException|CoreException|URISyntaxException e) {
- PerfPlugin.getDefault().openError(e, Messages.MsgError);
- } finally {
- try {
- if (statReader != null) {
- statReader.close();
- }
- } catch (IOException e) {
- PerfPlugin.getDefault().openError(e, Messages.PerfResourceLeak_title);
- }
- }
-
- return result;
- }
-
- /**
- * Get formatting string from unformatted table.
- *
- * @param table array to construct formatting for.
- * @return Formatting string representing the proper way to format the given
- * table.
- */
- private String getFormat(String[][] table) {
- // all entries have the same number of columns
- int[] maxCharLen = new int[table[0].length];
-
- // collect max number of characters per column
- for (int i = 0; i < table.length; i++) {
- for (int j = 0; j < table[i].length; j++) {
- maxCharLen[j] = Math.max(maxCharLen[j], table[i][j].length());
- }
- }
-
- // prepare format arguments
- ArrayList<Integer> arguments = new ArrayList<>();
- for (int length : maxCharLen) {
- arguments.add(length);
- }
-
- // generate format string
- String entryFormat = String.format(
- PMStatEntry.getString(Type.ENTRY_FORMAT),
- arguments.toArray());
-
- return entryFormat;
- }
-
- /**
- * Get float representation of specified string.
- *
- * @param str String convert
- * @return Float representation of string.
- */
- public static float toFloat(String str) {
- try {
- // remove commas from number string representation
- return (str == null) ? 0
- : Float.parseFloat(str.replace(",", "")); //$NON-NLS-1$//$NON-NLS-2$
- } catch (NumberFormatException e) {
- return 0;
- }
- }
+ // Old stats file.
+ private IPath oldFile;
+
+ // New stats file.
+ private IPath newFile;
+
+ // Comparison result string.
+ private String result = ""; //$NON-NLS-1$
+
+ // Title for this comparison run.
+ private String title;
+
+ // Unique data identifier.
+ private String dataID;
+
+ public StatComparisonData(String title, IPath oldFile, IPath newFile) {
+ this.title = title;
+ this.oldFile = oldFile;
+ this.newFile = newFile;
+ this.dataID = String.valueOf(((new Date().getTime())));
+ }
+
+ @Override
+ public String getPerfData() {
+ return result;
+ }
+
+ @Override
+ public String getTitle() {
+ return title;
+ }
+
+ /**
+ * Get unique identifier for this data object.
+ *
+ * @return String unique identifier based on this object's creation time.
+ */
+ public String getDataID(){
+ return dataID;
+ }
+
+ /**
+ * Generate a unique identifier based on the given file. The generation is a
+ * simple concatenation between the file path and the time of this object's
+ * creation.
+ *
+ * @param file File to generate uniqure id from.
+ * @return String unique id for specified file.
+ */
+ private String generateFileID(IPath file) {
+ return file.toOSString() + dataID;
+ }
+
+ /**
+ * Get path to old perf data file.
+ *
+ * @return String path corresponding to old perf data.
+ */
+ public String getOldDataPath() {
+ return oldFile.toPortableString();
+ }
+
+ /**
+ * Get path to new perf data file.
+ *
+ * @return String path corresponding to new perf data.
+ */
+ public String getNewDataPath() {
+ return newFile.toOSString();
+ }
+
+ /**
+ * Get a unique to for the old perf data file.
+ *
+ * @return String unique id.
+ */
+ public String getOldDataID() {
+ return generateFileID(oldFile);
+ }
+
+ /**
+ * Get a unique to for the old perf data file.
+ *
+ * @return String unique id.
+ */
+ public String getNewDataID() {
+ return generateFileID(newFile);
+ }
+
+ /**
+ * Compare stat data files and store the result in the result field.
+ */
+ public void runComparison() {
+ ArrayList<PMStatEntry> statsDiff = getComparisonStats();
+
+ if (!statsDiff.isEmpty()) {
+ String[][] statsDiffStr = new String[statsDiff.size()][];
+ int currentRow = 0;
+
+ // gather comparison results in a string array
+ for (PMStatEntry statEntry : statsDiff) {
+ statsDiffStr[currentRow] = statEntry.toStringArray();
+ currentRow++;
+ }
+
+ // apply format to each entry and set the result
+ String format = getFormat(statsDiffStr);
+ String curLine;
+ for (String[] statEntry : statsDiffStr) {
+ curLine = String.format(format, (Object[]) statEntry);
+ curLine = curLine.contains(PMStatEntry.TIME) ? "\n" + curLine //$NON-NLS-1$
+ : curLine;
+ result += curLine;
+ }
+ } else{
+
+ }
+ }
+
+ /**
+ * Return a PMStatEntry array with the result of the comparison between the
+ * old and new stat data files
+ * @return
+ */
+ public ArrayList<PMStatEntry> getComparisonStats() {
+ ArrayList<PMStatEntry> oldStats = collectStats(oldFile);
+ ArrayList<PMStatEntry> newStats = collectStats(newFile);
+ ArrayList<PMStatEntry> result = new ArrayList<>();
+
+ for (PMStatEntry oldEntry : oldStats) {
+ for (PMStatEntry newEntry : newStats) {
+ if (oldEntry.equalEvents(newEntry)) {
+ result.add(oldEntry.compare(newEntry));
+ continue;
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Collect statistics entries from the specified stat data file.
+ *
+ * @param file file to collect from
+ * @return List containing statistics entries from the given file.
+ */
+ private static ArrayList<PMStatEntry> collectStats(IPath file) {
+ ArrayList<PMStatEntry> result = new ArrayList<>();
+ BufferedReader statReader = null;
+ URI fileURI = null;
+ try {
+ fileURI = new URI(file.toPortableString());
+ IRemoteFileProxy proxy = null;
+ proxy = RemoteProxyManager.getInstance().getFileProxy(fileURI);
+ IFileStore newDataFileStore = proxy.getResource(fileURI.getPath());
+ statReader = new BufferedReader(new InputStreamReader(newDataFileStore.openInputStream(EFS.NONE, null)));
+
+ // pattern for a valid perf stat entry
+ Pattern entryPattern = Pattern.compile(PMStatEntry.getString(Type.ENTRY_PATTERN));
+
+ // pattern for last stat entry (seconds elapsed):
+ Pattern totalTimePattern = Pattern.compile(PMStatEntry.getString(Type.TIME_PATTERN));
+
+ String line;
+ while((line = statReader.readLine()) != null ){
+ line = line.trim();
+ Matcher match = entryPattern.matcher(line);
+ String samples, event, usage, units, delta, scale;
+ PMStatEntry statEntry;
+
+ if(match.find()){
+
+ // extract information from groups
+ samples = match.group(1);
+ event = match.group(2);
+ usage = match.group(6);
+ units = match.group(7);
+ delta = match.group(9);
+ scale = match.group(13);
+
+ // create stat entry
+ statEntry = new PMStatEntry(toFloat(samples), event,
+ toFloat(usage), units, toFloat(delta),
+ toFloat(scale));
+
+ // add stat entry to results list
+ result.add(statEntry);
+
+ } else if(line.contains(PMStatEntry.TIME)){
+
+ // match seconds elapsed pattern
+ match = totalTimePattern.matcher(line);
+ if(match.find()){
+ samples = match.group(1);
+ event = match.group(2);
+ delta = match.group(4);
+
+ // create stat entry
+ statEntry = new PMStatEntry(toFloat(samples),
+ event, 0, null, toFloat(delta), 0);
+
+ result.add(statEntry);
+ }
+ }
+ }
+ return result;
+ } catch (IOException|CoreException|URISyntaxException e) {
+ PerfPlugin.getDefault().openError(e, Messages.MsgError);
+ } finally {
+ try {
+ if (statReader != null) {
+ statReader.close();
+ }
+ } catch (IOException e) {
+ PerfPlugin.getDefault().openError(e, Messages.PerfResourceLeak_title);
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Get formatting string from unformatted table.
+ *
+ * @param table array to construct formatting for.
+ * @return Formatting string representing the proper way to format the given
+ * table.
+ */
+ private String getFormat(String[][] table) {
+ // all entries have the same number of columns
+ int[] maxCharLen = new int[table[0].length];
+
+ // collect max number of characters per column
+ for (int i = 0; i < table.length; i++) {
+ for (int j = 0; j < table[i].length; j++) {
+ maxCharLen[j] = Math.max(maxCharLen[j], table[i][j].length());
+ }
+ }
+
+ // prepare format arguments
+ ArrayList<Integer> arguments = new ArrayList<>();
+ for (int length : maxCharLen) {
+ arguments.add(length);
+ }
+
+ // generate format string
+ String entryFormat = String.format(
+ PMStatEntry.getString(Type.ENTRY_FORMAT),
+ arguments.toArray());
+
+ return entryFormat;
+ }
+
+ /**
+ * Get float representation of specified string.
+ *
+ * @param str String convert
+ * @return Float representation of string.
+ */
+ public static float toFloat(String str) {
+ try {
+ // remove commas from number string representation
+ return (str == null) ? 0
+ : Float.parseFloat(str.replace(",", "")); //$NON-NLS-1$//$NON-NLS-2$
+ } catch (NumberFormatException e) {
+ return 0;
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/StatData.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/StatData.java
index 333ffe74da..513d3624d4 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/StatData.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/StatData.java
@@ -35,109 +35,109 @@ import org.eclipse.swt.widgets.Display;
*/
public class StatData extends AbstractDataManipulator {
- private String prog;
- private String [] args;
- private int runCount;
- private String [] events;
+ private String prog;
+ private String [] args;
+ private int runCount;
+ private String [] events;
- public StatData(String title, IPath workDir, String prog, String [] args, int runCount, String[] events) {
- super(title, workDir);
- this.prog = prog;
- this.args = args;
- this.runCount = runCount;
- this.events = events;
- }
+ public StatData(String title, IPath workDir, String prog, String [] args, int runCount, String[] events) {
+ super(title, workDir);
+ this.prog = prog;
+ this.args = args;
+ this.runCount = runCount;
+ this.events = events;
+ }
- public StatData(String title, IPath workDir, String prog, String [] args, int runCount, String[] events, IProject project) {
- super(title, workDir, project);
- this.prog = prog;
- this.args = args;
- this.runCount = runCount;
- this.events = events;
- }
+ public StatData(String title, IPath workDir, String prog, String [] args, int runCount, String[] events, IProject project) {
+ super(title, workDir, project);
+ this.prog = prog;
+ this.args = args;
+ this.runCount = runCount;
+ this.events = events;
+ }
- @Override
- public void parse() {
- String file;
- try {
- String prefix = PerfPlugin.PERF_DEFAULT_STAT.replace('.', '-');
- file = Files.createTempFile(prefix, "").toString(); //$NON-NLS-1$
- String [] cmd = getCommand(this.prog, this.args, file);
- performCommand(cmd, file);
- } catch (IOException e) {
- }
- }
+ @Override
+ public void parse() {
+ String file;
+ try {
+ String prefix = PerfPlugin.PERF_DEFAULT_STAT.replace('.', '-');
+ file = Files.createTempFile(prefix, "").toString(); //$NON-NLS-1$
+ String [] cmd = getCommand(this.prog, this.args, file);
+ performCommand(cmd, file);
+ } catch (IOException e) {
+ }
+ }
- protected String [] getCommand(String prog, String [] args, String file) {
- List<String> ret = new ArrayList<>(Arrays.asList(
- new String[] {"perf", "stat" })); //$NON-NLS-1$ //$NON-NLS-2$
- if (runCount > 1) {
- ret.add("-r"); //$NON-NLS-1$
- ret.add(String.valueOf(runCount));
- }
- if (events != null) {
- for (String event : events) {
- ret.add("-e"); //$NON-NLS-1$
- ret.add(event);
- }
- }
- ret.add("-o"); //$NON-NLS-1$
- ret.add(file);
- ret.add(prog);
- ret.addAll(Arrays.asList(args));
- return ret.toArray(new String [0]);
- }
+ protected String [] getCommand(String prog, String [] args, String file) {
+ List<String> ret = new ArrayList<>(Arrays.asList(
+ new String[] {"perf", "stat" })); //$NON-NLS-1$ //$NON-NLS-2$
+ if (runCount > 1) {
+ ret.add("-r"); //$NON-NLS-1$
+ ret.add(String.valueOf(runCount));
+ }
+ if (events != null) {
+ for (String event : events) {
+ ret.add("-e"); //$NON-NLS-1$
+ ret.add(event);
+ }
+ }
+ ret.add("-o"); //$NON-NLS-1$
+ ret.add(file);
+ ret.add(prog);
+ ret.addAll(Arrays.asList(args));
+ return ret.toArray(new String [0]);
+ }
- protected String getProgram () {
- return prog;
- }
+ protected String getProgram () {
+ return prog;
+ }
- protected String [] getArguments () {
- return args;
- }
+ protected String [] getArguments () {
+ return args;
+ }
- /**
- * Save latest perf stat result under $workingDirectory/perf.stat. If file
- * already exists rename it to perf.old.stat, in order to keep a reference
- * to the previous session and be consistent with the way perf handles perf
- * report data files.
- */
- public void updateStatData() {
- URI curStatPathURI = null;
- URI oldStatPathURI = null;
- // build file name format
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append(PerfPlugin.PERF_COMMAND);
- stringBuilder.append("%s."); //$NON-NLS-1$
- stringBuilder.append(PerfSaveStatsHandler.DATA_EXT);
- String statNameFormat = stringBuilder.toString();
+ /**
+ * Save latest perf stat result under $workingDirectory/perf.stat. If file
+ * already exists rename it to perf.old.stat, in order to keep a reference
+ * to the previous session and be consistent with the way perf handles perf
+ * report data files.
+ */
+ public void updateStatData() {
+ URI curStatPathURI = null;
+ URI oldStatPathURI = null;
+ // build file name format
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append(PerfPlugin.PERF_COMMAND);
+ stringBuilder.append("%s."); //$NON-NLS-1$
+ stringBuilder.append(PerfSaveStatsHandler.DATA_EXT);
+ String statNameFormat = stringBuilder.toString();
- // get current stat file
- IPath workingDir = getWorkDir();
- String curStatName = String.format(statNameFormat, ""); //$NON-NLS-1$
- IPath curStatPath = workingDir.append(curStatName);
- IRemoteFileProxy proxy = null;
- try {
- curStatPathURI = new URI(curStatPath.toPortableString());
- proxy = RemoteProxyManager.getInstance().getFileProxy(curStatPathURI);
+ // get current stat file
+ IPath workingDir = getWorkDir();
+ String curStatName = String.format(statNameFormat, ""); //$NON-NLS-1$
+ IPath curStatPath = workingDir.append(curStatName);
+ IRemoteFileProxy proxy = null;
+ try {
+ curStatPathURI = new URI(curStatPath.toPortableString());
+ proxy = RemoteProxyManager.getInstance().getFileProxy(curStatPathURI);
- IFileStore curFileStore = proxy.getResource(curStatPathURI.getPath());
- if (curFileStore.fetchInfo().exists()) {
- // get previous stat file
- String oldStatName = String.format(statNameFormat, ".old"); //$NON-NLS-1$
- IPath oldStatPath = workingDir.append(oldStatName);
- oldStatPathURI = new URI(oldStatPath.toPortableString());
- IFileStore oldFileStore = proxy.getResource(oldStatPathURI.getPath());
- if (oldFileStore.fetchInfo().exists()) {
- oldFileStore.delete(EFS.NONE, null);
- }
- curFileStore.copy(oldFileStore, EFS.NONE, null);
- curFileStore.delete(EFS.NONE, null);
- }
- PerfSaveStatsHandler saveStats = new PerfSaveStatsHandler();
- saveStats.saveData(PerfPlugin.PERF_COMMAND);
- } catch (URISyntaxException|CoreException e) {
- MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
- }
- }
+ IFileStore curFileStore = proxy.getResource(curStatPathURI.getPath());
+ if (curFileStore.fetchInfo().exists()) {
+ // get previous stat file
+ String oldStatName = String.format(statNameFormat, ".old"); //$NON-NLS-1$
+ IPath oldStatPath = workingDir.append(oldStatName);
+ oldStatPathURI = new URI(oldStatPath.toPortableString());
+ IFileStore oldFileStore = proxy.getResource(oldStatPathURI.getPath());
+ if (oldFileStore.fetchInfo().exists()) {
+ oldFileStore.delete(EFS.NONE, null);
+ }
+ curFileStore.copy(oldFileStore, EFS.NONE, null);
+ curFileStore.delete(EFS.NONE, null);
+ }
+ PerfSaveStatsHandler saveStats = new PerfSaveStatsHandler();
+ saveStats.saveData(PerfPlugin.PERF_COMMAND);
+ } catch (URISyntaxException|CoreException e) {
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/AbstractSaveDataHandler.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/AbstractSaveDataHandler.java
index 7f99215c2b..9575e1de01 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/AbstractSaveDataHandler.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/AbstractSaveDataHandler.java
@@ -36,126 +36,126 @@ import org.eclipse.swt.widgets.Display;
*/
public abstract class AbstractSaveDataHandler extends BaseDataManipulator implements IHandler {
- @Override
- public Object execute(ExecutionEvent event) {
- InputDialog dialog = new InputDialog(Display.getCurrent()
- .getActiveShell(), Messages.PerfSaveSession_title,
- Messages.PerfSaveSession_msg, "", new IInputValidator() { //$NON-NLS-1$
-
- @Override
- public String isValid(String newText) {
- if (newText.isEmpty()) {
- return Messages.PerfSaveSession_invalid_filename_msg;
- }
- return null;
- }
- });
-
- if (dialog.open() == Window.OK) {
- saveData(dialog.getValue());
- }
-
- return null;
- }
-
- @Override
- public boolean isEnabled() {
- IPath curWorkingDirectory = getWorkingDir();
- return curWorkingDirectory != null && !curWorkingDirectory.isEmpty()
- && verifyData();
- }
-
- /**
- * Get current working directory.
- * @return current working directory.
- */
- protected IPath getWorkingDir() {
- return PerfPlugin.getDefault().getWorkingDir();
- }
-
- /**
- * New data location based on specified name, which the specified
- * extension will be appended to.
- *
- * @param filename
- * @param extension
- * @return
- */
- public IPath getNewDataLocation(String filename, String extension) {
- IPath newFilename = getWorkingDir().append(filename);
- return newFilename.addFileExtension(extension);
-
- }
-
- /**
- * Verify that we can save the specified file.
- *
- * @param file <code>File</code> to save
- * @return true if we can go ahead and save the file, false otherwise
- */
- public boolean canSave(IPath file) {
- IRemoteFileProxy proxy = null;
- URI fileURI = null;
- try {
- fileURI = new URI(file.toPortableString());
- proxy = RemoteProxyManager.getInstance().getFileProxy(fileURI);
- } catch (URISyntaxException e) {
- MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
- } catch (CoreException e) {
- MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
- }
- IFileStore fileStore = proxy.getResource(fileURI.getPath());
- if (fileStore.fetchInfo().exists()) {
- String msg = MessageFormat.format(
- Messages.PerfSaveSession_file_exists_msg,
- new Object[] { fileStore.getName() });
- return MessageDialog.openQuestion(Display.getCurrent()
- .getActiveShell(),
- Messages.PerfSaveSession_file_exists_title, msg);
- }
- return true;
- }
-
- /**
- * Open error dialog informing user of saving failure.
- * @param filename
- */
- public void openErroDialog(String title, String pattern, String arg) {
- String errorMsg = MessageFormat.format(pattern, new Object[] { arg });
- MessageDialog.openError(Display.getCurrent().getActiveShell(), title,
- errorMsg);
- }
-
- /**
- * Save data to file with specified name and return handle
- *
- * @param filename the file name
- */
- public abstract IPath saveData(String filename);
-
- /**
- * Verify data to save.
- *
- * @return true if data is valid
- */
- public abstract boolean verifyData();
-
- @Override
- public boolean isHandled() {
- return isEnabled();
- }
-
- @Override
- public void removeHandlerListener(IHandlerListener handlerListener) {
- }
-
- @Override
- public void addHandlerListener(IHandlerListener handlerListener) {
-
- }
-
- @Override
- public void dispose() {
-
- }
+ @Override
+ public Object execute(ExecutionEvent event) {
+ InputDialog dialog = new InputDialog(Display.getCurrent()
+ .getActiveShell(), Messages.PerfSaveSession_title,
+ Messages.PerfSaveSession_msg, "", new IInputValidator() { //$NON-NLS-1$
+
+ @Override
+ public String isValid(String newText) {
+ if (newText.isEmpty()) {
+ return Messages.PerfSaveSession_invalid_filename_msg;
+ }
+ return null;
+ }
+ });
+
+ if (dialog.open() == Window.OK) {
+ saveData(dialog.getValue());
+ }
+
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ IPath curWorkingDirectory = getWorkingDir();
+ return curWorkingDirectory != null && !curWorkingDirectory.isEmpty()
+ && verifyData();
+ }
+
+ /**
+ * Get current working directory.
+ * @return current working directory.
+ */
+ protected IPath getWorkingDir() {
+ return PerfPlugin.getDefault().getWorkingDir();
+ }
+
+ /**
+ * New data location based on specified name, which the specified
+ * extension will be appended to.
+ *
+ * @param filename
+ * @param extension
+ * @return
+ */
+ public IPath getNewDataLocation(String filename, String extension) {
+ IPath newFilename = getWorkingDir().append(filename);
+ return newFilename.addFileExtension(extension);
+
+ }
+
+ /**
+ * Verify that we can save the specified file.
+ *
+ * @param file <code>File</code> to save
+ * @return true if we can go ahead and save the file, false otherwise
+ */
+ public boolean canSave(IPath file) {
+ IRemoteFileProxy proxy = null;
+ URI fileURI = null;
+ try {
+ fileURI = new URI(file.toPortableString());
+ proxy = RemoteProxyManager.getInstance().getFileProxy(fileURI);
+ } catch (URISyntaxException e) {
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
+ } catch (CoreException e) {
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
+ }
+ IFileStore fileStore = proxy.getResource(fileURI.getPath());
+ if (fileStore.fetchInfo().exists()) {
+ String msg = MessageFormat.format(
+ Messages.PerfSaveSession_file_exists_msg,
+ new Object[] { fileStore.getName() });
+ return MessageDialog.openQuestion(Display.getCurrent()
+ .getActiveShell(),
+ Messages.PerfSaveSession_file_exists_title, msg);
+ }
+ return true;
+ }
+
+ /**
+ * Open error dialog informing user of saving failure.
+ * @param filename
+ */
+ public void openErroDialog(String title, String pattern, String arg) {
+ String errorMsg = MessageFormat.format(pattern, new Object[] { arg });
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), title,
+ errorMsg);
+ }
+
+ /**
+ * Save data to file with specified name and return handle
+ *
+ * @param filename the file name
+ */
+ public abstract IPath saveData(String filename);
+
+ /**
+ * Verify data to save.
+ *
+ * @return true if data is valid
+ */
+ public abstract boolean verifyData();
+
+ @Override
+ public boolean isHandled() {
+ return isEnabled();
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+ }
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+
+ }
+
+ @Override
+ public void dispose() {
+
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/Messages.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/Messages.java
index 4823842385..c2c1d3dd32 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/Messages.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/Messages.java
@@ -13,36 +13,36 @@ package org.eclipse.linuxtools.internal.perf.handlers;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.perf.handlers.messages"; //$NON-NLS-1$
- public static String PerfSaveSession_title;
- public static String PerfSaveSession_msg;
- public static String PerfSaveSession_invalid_filename_msg;
- public static String PerfSaveSession_file_exists_title;
- public static String PerfSaveSession_file_exists_msg;
- public static String PerfSaveStat_error_title;
- public static String PerfSaveStat_error_msg;
- public static String PerfSaveSession_failure_title;
- public static String PerfSaveSession_failure_msg;
- public static String PerfResourceLeak_title;
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.perf.handlers.messages"; //$NON-NLS-1$
+ public static String PerfSaveSession_title;
+ public static String PerfSaveSession_msg;
+ public static String PerfSaveSession_invalid_filename_msg;
+ public static String PerfSaveSession_file_exists_title;
+ public static String PerfSaveSession_file_exists_msg;
+ public static String PerfSaveStat_error_title;
+ public static String PerfSaveStat_error_msg;
+ public static String PerfSaveSession_failure_title;
+ public static String PerfSaveSession_failure_msg;
+ public static String PerfResourceLeak_title;
- public static String MsgProxyError;
- public static String MsgError;
- public static String ContentDescription_0;
+ public static String MsgProxyError;
+ public static String MsgError;
+ public static String ContentDescription_0;
- public static String CompUnsupported;
- public static String PerfEditorLauncher_stat_title;
- public static String PerfEditorLauncher_file_dne_error;
- public static String PerfEditorLauncher_file_read_error;
- public static String ReportComparisonView_label;
- public static String StatComparisonView_label;
- public static String StatComparisonView_reverseToolTip;
- public static String StatComparisonView_reversedLabel;
+ public static String CompUnsupported;
+ public static String PerfEditorLauncher_stat_title;
+ public static String PerfEditorLauncher_file_dne_error;
+ public static String PerfEditorLauncher_file_read_error;
+ public static String ReportComparisonView_label;
+ public static String StatComparisonView_label;
+ public static String StatComparisonView_reverseToolTip;
+ public static String StatComparisonView_reversedLabel;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfSaveSessionHandler.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfSaveSessionHandler.java
index 8a75909448..c47f4363f3 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfSaveSessionHandler.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfSaveSessionHandler.java
@@ -30,62 +30,62 @@ import org.eclipse.ui.PlatformUI;
*/
public class PerfSaveSessionHandler extends AbstractSaveDataHandler {
- public static final String DATA_EXT = "data"; //$NON-NLS-1$
+ public static final String DATA_EXT = "data"; //$NON-NLS-1$
- @Override
- public IPath saveData(String filename) {
- // get paths
- IPath newDataLoc = getNewDataLocation(filename, DATA_EXT);
- IPath defaultDataLoc = PerfPlugin.getDefault().getPerfProfileData();
- URI newDataLocURI = null;
- URI defaultDataLocURI = null;
- // get files
- IRemoteFileProxy proxy = null;
- try {
- newDataLocURI = new URI(newDataLoc.toPortableString());
- defaultDataLocURI = new URI(defaultDataLoc.toPortableString());
- proxy = RemoteProxyManager.getInstance().getFileProxy(newDataLocURI);
- } catch (URISyntaxException e) {
- openErroDialog(Messages.MsgProxyError,
- Messages.MsgProxyError,
- newDataLoc.lastSegment());
- } catch (CoreException e) {
- openErroDialog(Messages.MsgProxyError,
- Messages.MsgProxyError,
- newDataLoc.lastSegment());
- }
- IFileStore newDataFileStore = proxy.getResource(newDataLocURI.getPath());
- IFileStore defaultDataFileStore = proxy.getResource(defaultDataLocURI.getPath());
+ @Override
+ public IPath saveData(String filename) {
+ // get paths
+ IPath newDataLoc = getNewDataLocation(filename, DATA_EXT);
+ IPath defaultDataLoc = PerfPlugin.getDefault().getPerfProfileData();
+ URI newDataLocURI = null;
+ URI defaultDataLocURI = null;
+ // get files
+ IRemoteFileProxy proxy = null;
+ try {
+ newDataLocURI = new URI(newDataLoc.toPortableString());
+ defaultDataLocURI = new URI(defaultDataLoc.toPortableString());
+ proxy = RemoteProxyManager.getInstance().getFileProxy(newDataLocURI);
+ } catch (URISyntaxException e) {
+ openErroDialog(Messages.MsgProxyError,
+ Messages.MsgProxyError,
+ newDataLoc.lastSegment());
+ } catch (CoreException e) {
+ openErroDialog(Messages.MsgProxyError,
+ Messages.MsgProxyError,
+ newDataLoc.lastSegment());
+ }
+ IFileStore newDataFileStore = proxy.getResource(newDataLocURI.getPath());
+ IFileStore defaultDataFileStore = proxy.getResource(defaultDataLocURI.getPath());
- if (canSave(newDataLoc)) {
- // copy default data into new location
- try {
- defaultDataFileStore.copy(newDataFileStore, EFS.OVERWRITE, null);
- PerfPlugin.getDefault().setPerfProfileData(newDataLoc);
- try {
- PerfProfileView view = (PerfProfileView) PlatformUI
- .getWorkbench().getActiveWorkbenchWindow()
- .getActivePage().showView(PerfPlugin.VIEW_ID);
- view.setContentDescription(newDataLoc.toOSString());
- } catch (PartInitException e) {
- // fail silently
- }
- IFileInfo info = newDataFileStore.fetchInfo();
- info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true);
- newDataFileStore.putInfo(info, EFS.SET_ATTRIBUTES, null);
- return newDataLoc;
- } catch (CoreException e) {
- openErroDialog(Messages.PerfSaveSession_failure_title,
- Messages.PerfSaveSession_failure_msg,
- newDataLoc.lastSegment());
- }
- }
- return null;
- }
+ if (canSave(newDataLoc)) {
+ // copy default data into new location
+ try {
+ defaultDataFileStore.copy(newDataFileStore, EFS.OVERWRITE, null);
+ PerfPlugin.getDefault().setPerfProfileData(newDataLoc);
+ try {
+ PerfProfileView view = (PerfProfileView) PlatformUI
+ .getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage().showView(PerfPlugin.VIEW_ID);
+ view.setContentDescription(newDataLoc.toOSString());
+ } catch (PartInitException e) {
+ // fail silently
+ }
+ IFileInfo info = newDataFileStore.fetchInfo();
+ info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true);
+ newDataFileStore.putInfo(info, EFS.SET_ATTRIBUTES, null);
+ return newDataLoc;
+ } catch (CoreException e) {
+ openErroDialog(Messages.PerfSaveSession_failure_title,
+ Messages.PerfSaveSession_failure_msg,
+ newDataLoc.lastSegment());
+ }
+ }
+ return null;
+ }
- @Override
- public boolean verifyData() {
- IPath defaultDataLoc = PerfPlugin.getDefault().getPerfProfileData();
- return defaultDataLoc != null && !defaultDataLoc.isEmpty();
- }
+ @Override
+ public boolean verifyData() {
+ IPath defaultDataLoc = PerfPlugin.getDefault().getPerfProfileData();
+ return defaultDataLoc != null && !defaultDataLoc.isEmpty();
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfSaveStatsHandler.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfSaveStatsHandler.java
index b043392aa5..f331bfed08 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfSaveStatsHandler.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfSaveStatsHandler.java
@@ -31,42 +31,42 @@ import org.eclipse.linuxtools.profiling.launch.RemoteProxyManager;
*/
public class PerfSaveStatsHandler extends AbstractSaveDataHandler {
- public static String DATA_EXT = "stat"; //$NON-NLS-1$
+ public static String DATA_EXT = "stat"; //$NON-NLS-1$
- @Override
- public IPath saveData(String filename) {
- IPath newDataLoc = getNewDataLocation(filename, DATA_EXT);
- IPerfData statData = PerfPlugin.getDefault().getStatData();
- BufferedWriter writer = null;
- OutputStreamWriter osw = null;
- URI newDataLocURI = null;
+ @Override
+ public IPath saveData(String filename) {
+ IPath newDataLoc = getNewDataLocation(filename, DATA_EXT);
+ IPerfData statData = PerfPlugin.getDefault().getStatData();
+ BufferedWriter writer = null;
+ OutputStreamWriter osw = null;
+ URI newDataLocURI = null;
- try {
- IRemoteFileProxy proxy = null;
- newDataLocURI = new URI(newDataLoc.toPortableString());
- proxy = RemoteProxyManager.getInstance().getFileProxy(newDataLocURI);
- IFileStore newDataFileStore = proxy.getResource(newDataLocURI.getPath());
- osw = new OutputStreamWriter(newDataFileStore.openOutputStream(EFS.NONE, null));
- writer = new BufferedWriter(osw);
- writer.write(statData.getPerfData());
- IFileInfo info = newDataFileStore.fetchInfo();
- info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true);
- newDataFileStore.putInfo(info, EFS.SET_ATTRIBUTES, null);
- return newDataLoc;
- } catch (IOException|CoreException|URISyntaxException e) {
- openErroDialog(Messages.PerfSaveStat_error_title,
- Messages.PerfSaveStat_error_msg,
- newDataLoc.lastSegment());
- } finally {
- closeResource(writer);
- }
- return null;
- }
+ try {
+ IRemoteFileProxy proxy = null;
+ newDataLocURI = new URI(newDataLoc.toPortableString());
+ proxy = RemoteProxyManager.getInstance().getFileProxy(newDataLocURI);
+ IFileStore newDataFileStore = proxy.getResource(newDataLocURI.getPath());
+ osw = new OutputStreamWriter(newDataFileStore.openOutputStream(EFS.NONE, null));
+ writer = new BufferedWriter(osw);
+ writer.write(statData.getPerfData());
+ IFileInfo info = newDataFileStore.fetchInfo();
+ info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true);
+ newDataFileStore.putInfo(info, EFS.SET_ATTRIBUTES, null);
+ return newDataLoc;
+ } catch (IOException|CoreException|URISyntaxException e) {
+ openErroDialog(Messages.PerfSaveStat_error_title,
+ Messages.PerfSaveStat_error_msg,
+ newDataLoc.lastSegment());
+ } finally {
+ closeResource(writer);
+ }
+ return null;
+ }
- @Override
- public boolean verifyData() {
- IPerfData statData = PerfPlugin.getDefault().getStatData();
- return statData != null && statData.getPerfData() != null;
- }
+ @Override
+ public boolean verifyData() {
+ IPerfData statData = PerfPlugin.getDefault().getStatData();
+ return statData != null && statData.getPerfData() != null;
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfStatDataOpenHandler.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfStatDataOpenHandler.java
index e99d6164bc..87d87a22f4 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfStatDataOpenHandler.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfStatDataOpenHandler.java
@@ -30,53 +30,53 @@ import org.eclipse.ui.IEditorLauncher;
*/
public class PerfStatDataOpenHandler implements IEditorLauncher {
- private static final String TITLE_EXCERPT = "Performance counter stats for"; //$NON-NLS-1$
+ private static final String TITLE_EXCERPT = "Performance counter stats for"; //$NON-NLS-1$
- @Override
- public void open(IPath file) {
- File statFile = file.toFile();
- try (BufferedReader fileReader = new BufferedReader(new FileReader(statFile))) {
- final StringBuilder contents = new StringBuilder();
- final StringBuilder title = new StringBuilder();
- String line;
+ @Override
+ public void open(IPath file) {
+ File statFile = file.toFile();
+ try (BufferedReader fileReader = new BufferedReader(new FileReader(statFile))) {
+ final StringBuilder contents = new StringBuilder();
+ final StringBuilder title = new StringBuilder();
+ String line;
- // read file contents
- while ((line = fileReader.readLine()) != null) {
- // set data title
- if (title.length() == 0 && line.contains(TITLE_EXCERPT)) {
- title.append(line);
- }
- contents.append(line);
- contents.append("\n"); //$NON-NLS-1$
- }
+ // read file contents
+ while ((line = fileReader.readLine()) != null) {
+ // set data title
+ if (title.length() == 0 && line.contains(TITLE_EXCERPT)) {
+ title.append(line);
+ }
+ contents.append(line);
+ contents.append("\n"); //$NON-NLS-1$
+ }
- // construct basic title if none was found in the file
- if (title.length() == 0) {
- title.append(NLS.bind(Messages.PerfEditorLauncher_stat_title,
- statFile.getName()));
- }
+ // construct basic title if none was found in the file
+ if (title.length() == 0) {
+ title.append(NLS.bind(Messages.PerfEditorLauncher_stat_title,
+ statFile.getName()));
+ }
- final String timestamp = DateFormat.getInstance().format(new Date(statFile.lastModified()));
- PerfPlugin.getDefault().setStatData(new IPerfData() {
+ final String timestamp = DateFormat.getInstance().format(new Date(statFile.lastModified()));
+ PerfPlugin.getDefault().setStatData(new IPerfData() {
- @Override
- public String getTitle() {
- return title.toString() + " (" + timestamp + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- }
+ @Override
+ public String getTitle() {
+ return title.toString() + " (" + timestamp + ")"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
- @Override
- public String getPerfData() {
- return contents.toString();
- }
- });
+ @Override
+ public String getPerfData() {
+ return contents.toString();
+ }
+ });
- StatView.refreshView();
- } catch (FileNotFoundException e) {
- PerfPlugin.getDefault().openError(e,
- NLS.bind(Messages.PerfEditorLauncher_file_dne_error, statFile.getName()));
- } catch (IOException e) {
- PerfPlugin.getDefault().openError(e,
- NLS.bind(Messages.PerfEditorLauncher_file_read_error, statFile.getName()));
- }
- }
+ StatView.refreshView();
+ } catch (FileNotFoundException e) {
+ PerfPlugin.getDefault().openError(e,
+ NLS.bind(Messages.PerfEditorLauncher_file_dne_error, statFile.getName()));
+ } catch (IOException e) {
+ PerfPlugin.getDefault().openError(e,
+ NLS.bind(Messages.PerfEditorLauncher_file_read_error, statFile.getName()));
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfStatsQuickDiffHandler.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfStatsQuickDiffHandler.java
index ce86579f8d..21f13724a9 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfStatsQuickDiffHandler.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/handlers/PerfStatsQuickDiffHandler.java
@@ -37,73 +37,73 @@ import org.eclipse.ui.commands.ICommandService;
* Command handler for quick comparison between current and previous sessions.
*/
public class PerfStatsQuickDiffHandler implements IHandler {
- @Override
- public Object execute(ExecutionEvent event) {
- // get default files
- PerfPlugin plugin = PerfPlugin.getDefault();
- IPath curStatData = plugin.getPerfFile(PerfPlugin.PERF_DEFAULT_STAT);
- IPath prevStatData = plugin.getPerfFile(PerfPlugin.PERF_DEAFULT_OLD_STAT);
+ @Override
+ public Object execute(ExecutionEvent event) {
+ // get default files
+ PerfPlugin plugin = PerfPlugin.getDefault();
+ IPath curStatData = plugin.getPerfFile(PerfPlugin.PERF_DEFAULT_STAT);
+ IPath prevStatData = plugin.getPerfFile(PerfPlugin.PERF_DEAFULT_OLD_STAT);
- IResource curStatFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(curStatData);
- IResource prevStatFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(prevStatData);
+ IResource curStatFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(curStatData);
+ IResource prevStatFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(prevStatData);
- // Inject our own selections into the context
- IEvaluationContext ctx = (IEvaluationContext) event.getApplicationContext();
- ctx.addVariable(ISources.ACTIVE_CURRENT_SELECTION_NAME,
- new StructuredSelection(new IResource [] {prevStatFile, curStatFile}));
+ // Inject our own selections into the context
+ IEvaluationContext ctx = (IEvaluationContext) event.getApplicationContext();
+ ctx.addVariable(ISources.ACTIVE_CURRENT_SELECTION_NAME,
+ new StructuredSelection(new IResource [] {prevStatFile, curStatFile}));
- ICommandService cmdService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
- Command cmd = cmdService.getCommand("org.eclipse.linuxtools.perf.CompareAction"); //$NON-NLS-1$
- try {
- cmd.executeWithChecks(event);
- } catch (Exception e) {
- }
- return null;
- }
+ ICommandService cmdService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
+ Command cmd = cmdService.getCommand("org.eclipse.linuxtools.perf.CompareAction"); //$NON-NLS-1$
+ try {
+ cmd.executeWithChecks(event);
+ } catch (Exception e) {
+ }
+ return null;
+ }
- @Override
- public boolean isEnabled() {
- PerfPlugin plugin = PerfPlugin.getDefault();
- IPath workingDir = plugin.getWorkingDir();
- URI curStatDataURI = null;
- URI prevStatDataURI = null;
- if (workingDir != null) {
- IPath curStatData = plugin.getPerfFile(PerfPlugin.PERF_DEFAULT_STAT);
- IPath prevStatData = plugin.getPerfFile(PerfPlugin.PERF_DEAFULT_OLD_STAT);
- IRemoteFileProxy proxy = null;
- try {
- curStatDataURI = new URI(curStatData.toPortableString());
- prevStatDataURI = new URI(prevStatData.toPortableString());
- proxy = RemoteProxyManager.getInstance().getFileProxy(curStatDataURI);
- } catch (URISyntaxException e) {
- MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
- } catch (CoreException e) {
- MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
- }
- IFileStore curFileStore = proxy.getResource(curStatDataURI.getPath());
- IFileStore prevFileStore = proxy.getResource(prevStatDataURI.getPath());
- return (curFileStore.fetchInfo().exists() && prevFileStore.fetchInfo().exists());
- }
- return false;
- }
+ @Override
+ public boolean isEnabled() {
+ PerfPlugin plugin = PerfPlugin.getDefault();
+ IPath workingDir = plugin.getWorkingDir();
+ URI curStatDataURI = null;
+ URI prevStatDataURI = null;
+ if (workingDir != null) {
+ IPath curStatData = plugin.getPerfFile(PerfPlugin.PERF_DEFAULT_STAT);
+ IPath prevStatData = plugin.getPerfFile(PerfPlugin.PERF_DEAFULT_OLD_STAT);
+ IRemoteFileProxy proxy = null;
+ try {
+ curStatDataURI = new URI(curStatData.toPortableString());
+ prevStatDataURI = new URI(prevStatData.toPortableString());
+ proxy = RemoteProxyManager.getInstance().getFileProxy(curStatDataURI);
+ } catch (URISyntaxException e) {
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
+ } catch (CoreException e) {
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
+ }
+ IFileStore curFileStore = proxy.getResource(curStatDataURI.getPath());
+ IFileStore prevFileStore = proxy.getResource(prevStatDataURI.getPath());
+ return (curFileStore.fetchInfo().exists() && prevFileStore.fetchInfo().exists());
+ }
+ return false;
+ }
- @Override
- public boolean isHandled() {
- return isEnabled();
- }
+ @Override
+ public boolean isHandled() {
+ return isEnabled();
+ }
- @Override
- public void addHandlerListener(IHandlerListener handlerListener) {
- // TODO Auto-generated method stub
- }
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+ }
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
- }
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+ }
- @Override
- public void removeHandlerListener(IHandlerListener handlerListener) {
- // TODO Auto-generated method stub
- }
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/Messages.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/Messages.java
index 29b15a771d..f193c89f6f 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/Messages.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/Messages.java
@@ -13,23 +13,23 @@ package org.eclipse.linuxtools.internal.perf.launch;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.perf.launch.messages"; //$NON-NLS-1$
- public static String MsgProxyError;
- public static String PerfLaunchConfigDelegate_perf_not_found;
- public static String PerfLaunchConfigDelegate_analyzing;
- public static String PerfLaunchConfigDelegate_stat_title;
- public static String PerfOptionsTab_Browse;
- public static String PerfOptionsTab_File_DNE;
- public static String PerfOptionsTab_Kernel_Prompt;
- public static String PerfOptionsTab_Loc_DNE;
- public static String PerfOptionsTab_Options;
- public static String PerfOptionsTab_Requires_LTE;
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.perf.launch.messages"; //$NON-NLS-1$
+ public static String MsgProxyError;
+ public static String PerfLaunchConfigDelegate_perf_not_found;
+ public static String PerfLaunchConfigDelegate_analyzing;
+ public static String PerfLaunchConfigDelegate_stat_title;
+ public static String PerfOptionsTab_Browse;
+ public static String PerfOptionsTab_File_DNE;
+ public static String PerfOptionsTab_Kernel_Prompt;
+ public static String PerfOptionsTab_Loc_DNE;
+ public static String PerfOptionsTab_Options;
+ public static String PerfOptionsTab_Requires_LTE;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfEventsTab.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfEventsTab.java
index f08adc741e..916485d06b 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfEventsTab.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfEventsTab.java
@@ -45,351 +45,351 @@ import org.eclipse.swt.widgets.Text;
public class PerfEventsTab extends AbstractLaunchConfigurationTab {
- private static final String EMPTY_STRING = ""; //$NON-NLS-1$
-
- // checkbox for selecting default event
- protected Button chkDefaultEvent;
-
- // the event tabs within the tab folder
- protected TabItem[] eventTabItems;
-
- // the table within the corresponding event tab
- protected Table[] eventTable;
-
- protected TabFolder tabFolder;
- private int rawTabIndex = 0;
- private int bpTabIndex = 0;
- protected Text rawText;
- protected Text bpText;
- private Composite top;
- private IProject previousProject = null;
-
-
- /**
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage()
- */
- @Override
- public Image getImage() {
- return PerfPlugin.getImageDescriptor("icons/event.gif").createImage(); //$NON-NLS-1$
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite top = new Composite(parent, SWT.NONE);
- setControl(top);
- top.setLayout(new GridLayout());
- this.top = top;
- }
-
- private void createEventTabs(Composite top, ILaunchConfiguration config){
- //Maybe not the best place to load the event list but we'll see.
- Map<String,List<String>> events = PerfCore.getEventList(config);
-
- // the special counters should be last
- ArrayList<String> tmpTabNames = new ArrayList<>(events.keySet());
- final List<String> SPECIAL_EVENTS = Arrays.asList(new String[] {
- PerfPlugin.STRINGS_HWBREAKPOINTS,
- PerfPlugin.STRINGS_RAWHWEvents });
- tmpTabNames.removeAll(SPECIAL_EVENTS);
- tmpTabNames.addAll(SPECIAL_EVENTS);
-
- String [] tabNames = tmpTabNames.toArray(new String [0]);
- eventTabItems = new TabItem[tabNames.length];
- eventTable = new Table[tabNames.length];
-
- tabFolder = new TabFolder(top, SWT.NONE);
- tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- // Initialize each tab.
- for (int i = 0; i < tabNames.length; i++) {
-
- eventTabItems[i] = new TabItem(tabFolder, SWT.NONE);
- eventTabItems[i].setText(tabNames[i]);
-
- // These are for the two special tabs for custom events.
- if (tabNames[i].equals(PerfPlugin.STRINGS_HWBREAKPOINTS)
- || tabNames[i].equals(PerfPlugin.STRINGS_RAWHWEvents)) {
-
- // Composite to contain it all
- Composite c = new Composite(tabFolder, SWT.NONE);
- c.setLayout(new GridLayout(2, false));
-
- // A list to check off existing custom events (or show the new ones added)
- Table table = new Table(c, SWT.CHECK | SWT.MULTI);
- eventTable[i] = table;
- table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- table.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent se) {
- updateLaunchConfigurationDialog();
- }
- });
-
- // Right side to enter new events and delete old ones
- Composite right = new Composite(c, SWT.NONE);
- right.setLayout(new GridLayout(2,false));
- right.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, true));
-
- // for adding
- Label l = new Label(right, SWT.NONE);
- l.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,2,1));
- Text t = new Text(right, SWT.SINGLE | SWT.BORDER);
- t.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- if (tabNames[i].equals(PerfPlugin.STRINGS_HWBREAKPOINTS)) {
- bpTabIndex = i;
- bpText = t;
- l.setText("Please enter the hardware breakpoint in the form mem:<addr>[:access].");
- }
- if (tabNames[i].equals(PerfPlugin.STRINGS_RAWHWEvents)) {
- rawTabIndex = i;
- rawText = t;
- l.setText("Please enter the raw register encoding in the form rNNN.");
- }
-
- Button b = new Button(right, SWT.PUSH);
- b.setText("Add");
- b.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
- b.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent se) {
- int i = tabFolder.getSelectionIndex();
- if (rawTabIndex == i) {
- new TableItem(eventTable[i], SWT.NONE).setText(rawText.getText());
- } else if(bpTabIndex == i) {
- new TableItem(eventTable[i], SWT.NONE).setText(bpText.getText());
- }
- updateLaunchConfigurationDialog();
- }
- });
- l = new Label(right, SWT.NONE);
- l.setForeground(new Color(right.getDisplay(), 100,100,100));
- if (tabNames[i].equals(PerfPlugin.STRINGS_HWBREAKPOINTS)) {
- l.setText("For example, .........");
- }
- if (tabNames[i].equals(PerfPlugin.STRINGS_RAWHWEvents)) {
- l.setText("For example, r1a8");
- }
- l.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,2,1));
-
- // spacer label.
- l = new Label(right, SWT.NONE);
- l.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,2,1));
-
- // for removing
- b = new Button(right, SWT.PUSH);
- b.setText("Remove Selected Events");
- b.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false,2,1));
- b.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent se) {
- eventTable[tabFolder.getSelectionIndex()].remove(eventTable[tabFolder.getSelectionIndex()].getSelectionIndices());
- updateLaunchConfigurationDialog();
- }
- });
- l = new Label(right, SWT.NONE);
- l.setForeground(new Color(right.getDisplay(), 100,100,100));
- l.setText("Note: Select by highlighting, not by checking.");
- l.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false,2,1));
-
- eventTabItems[i].setControl(c);
-
- } else {
- // This loads all the events 'perf list' gives into their respective tabs.
- Table table = new Table(tabFolder, SWT.CHECK);
- eventTable[i] = table;
-
- List<String> eventList = events.get(tabNames[i]);
- for (String event : eventList) {
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(event);
- }
-
- table.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent se) {
- updateLaunchConfigurationDialog();
- }
- });
-
- eventTabItems[i].setControl(table);
- }
- }
- }
-
- private void refreshDefaultEnabled() {
- boolean state = !chkDefaultEvent.getSelection();
- for (Table tab : eventTable) {
- tab.setEnabled(state);
- }
- }
-
- @Override
- public String getName() {
- return "Perf Events";
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration config) {
- IProject project = getProject(config);
-
- try {
- if(previousProject == null || (previousProject != null && !previousProject.equals(project))){
- Control[] children = top.getChildren();
-
- for (Control control : children) {
- control.dispose();
- }
-
- createVerticalSpacer(top, 1);
-
- // Default event checkbox
- chkDefaultEvent = new Button(top, SWT.CHECK);
- chkDefaultEvent.setText("Default Event"); //$NON-NLS-1$
- chkDefaultEvent.setLayoutData(new GridData());
- chkDefaultEvent.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent se) {
- refreshDefaultEnabled();
- updateLaunchConfigurationDialog();
- }
- });
-
- createEventTabs(top, config);
- }
-
- // restore whether things are default event/enabled or not.
- chkDefaultEvent.setSelection(config.getAttribute(PerfPlugin.ATTR_DefaultEvent, PerfPlugin.ATTR_DefaultEvent_default));
- refreshDefaultEnabled();
-
- // restore custom hw breakpoints
- List<?> hwbps = config.getAttribute(PerfPlugin.ATTR_HwBreakpointEvents, PerfPlugin.ATTR_HwBreakpointEvents_default);
- if (hwbps != null) {
- for (int i = 0; i < eventTable.length; i++) {
- if (eventTabItems[i].getText().equals(PerfPlugin.STRINGS_HWBREAKPOINTS)) {
- eventTable[i].removeAll();
- for (Object e : hwbps) {
- TableItem x = new TableItem(eventTable[i], SWT.NONE);
- x.setText((String)e);
- }
- }
- }
- }
-
- // restore custom raw hw events
- List<?> rawhe = config.getAttribute(PerfPlugin.ATTR_RawHwEvents, PerfPlugin.ATTR_RawHwEvents_default);
- if (rawhe != null) {
- for (int i = 0; i < eventTable.length; i++) {
- if (eventTabItems[i].getText().equals(PerfPlugin.STRINGS_RAWHWEvents)) {
- eventTable[i].removeAll();
- for (Object e : rawhe) {
- TableItem x = new TableItem(eventTable[i], SWT.NONE);
- x.setText((String)e);
- }
- }
- }
- }
-
- // tick all the boxes that are checked
- List<?> selectedEvents = config.getAttribute(PerfPlugin.ATTR_SelectedEvents, PerfPlugin.ATTR_SelectedEvents_default);
-
- if(selectedEvents != null){
- for (int i = 0; i < eventTable.length; i++) {
- for(TableItem event : eventTable[i].getItems()) {
- if(selectedEvents.contains(event.getText())){
- event.setChecked(true);
- } else {
- event.setChecked(false);
- }
- }
- }
- }
- previousProject = project;
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy wconfig) {
- //Store default event checkbox
- wconfig.setAttribute(PerfPlugin.ATTR_DefaultEvent, chkDefaultEvent.getSelection());
-
- //Store which events are selected
- ArrayList<String> selectedEvents = new ArrayList<>();
- for (int i = 0; i < eventTable.length; i++) {
- for(TableItem x : eventTable[i].getItems()) {
- if (x.getChecked())
- selectedEvents.add(x.getText());
- }
- }
-
- if (selectedEvents.size() == 0) {
- wconfig.setAttribute(PerfPlugin.ATTR_SelectedEvents, (String) null);
- } else {
- wconfig.setAttribute(PerfPlugin.ATTR_SelectedEvents, selectedEvents);
- }
-
- //Flag for multiple events
- if ((chkDefaultEvent.getSelection() == false) && (selectedEvents.size() >= 1)) {
- wconfig.setAttribute(PerfPlugin.ATTR_MultipleEvents, true);
- } else {
- wconfig.setAttribute(PerfPlugin.ATTR_MultipleEvents, false);
- }
- if (selectedEvents.size() <= 0) {
- //If they unticked the default box but didn't select any events revert to default.
- wconfig.setAttribute(PerfPlugin.ATTR_DefaultEvent, true);
- }
-
- //Store any custom HW BreakPoints they added (even if unchecked).
- ArrayList<String> hwbps = new ArrayList<>();
- for (int i = 0; i < eventTable.length; i++) {
- if (eventTabItems[i].getText().equals(PerfPlugin.STRINGS_HWBREAKPOINTS)) {
- for(TableItem x : eventTable[i].getItems()) {
- hwbps.add(x.getText());
- }
- }
- }
- if (hwbps.size() == 0) {
- hwbps = null; // to match with default value.
- }
- wconfig.setAttribute(PerfPlugin.ATTR_HwBreakpointEvents, hwbps);
-
- //Store any custom Raw HW Events they added (even if unchecked).
- ArrayList<String> rawhwe = new ArrayList<>();
- for (int i = 0; i < eventTable.length; i++) {
- if (eventTabItems[i].getText().equals(PerfPlugin.STRINGS_RAWHWEvents)) {
- for(TableItem x : eventTable[i].getItems()) {
- rawhwe.add(x.getText());
- }
- }
- }
- if (rawhwe.size() == 0) {
- rawhwe = null; //to match with default value.
- }
- wconfig.setAttribute(PerfPlugin.ATTR_RawHwEvents, rawhwe);
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy wconfig) {
- wconfig.setAttribute(PerfPlugin.ATTR_DefaultEvent, PerfPlugin.ATTR_DefaultEvent_default);
- wconfig.setAttribute(PerfPlugin.ATTR_MultipleEvents, PerfPlugin.ATTR_MultipleEvents_default);
- wconfig.setAttribute(PerfPlugin.ATTR_SelectedEvents, PerfPlugin.ATTR_SelectedEvents_default);
- wconfig.setAttribute(PerfPlugin.ATTR_HwBreakpointEvents, PerfPlugin.ATTR_HwBreakpointEvents_default);
- wconfig.setAttribute(PerfPlugin.ATTR_RawHwEvents, PerfPlugin.ATTR_RawHwEvents_default);
- }
-
- private IProject getProject(ILaunchConfiguration config){
- String name = null;
- try {
- name = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, EMPTY_STRING);
- } catch (CoreException e) {
- return null;
- }
- if (name.isEmpty()){
- return null;
- }
-
- return ResourcesPlugin.getWorkspace().getRoot().getProject(name);
- }
+ private static final String EMPTY_STRING = ""; //$NON-NLS-1$
+
+ // checkbox for selecting default event
+ protected Button chkDefaultEvent;
+
+ // the event tabs within the tab folder
+ protected TabItem[] eventTabItems;
+
+ // the table within the corresponding event tab
+ protected Table[] eventTable;
+
+ protected TabFolder tabFolder;
+ private int rawTabIndex = 0;
+ private int bpTabIndex = 0;
+ protected Text rawText;
+ protected Text bpText;
+ private Composite top;
+ private IProject previousProject = null;
+
+
+ /**
+ * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage()
+ */
+ @Override
+ public Image getImage() {
+ return PerfPlugin.getImageDescriptor("icons/event.gif").createImage(); //$NON-NLS-1$
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ Composite top = new Composite(parent, SWT.NONE);
+ setControl(top);
+ top.setLayout(new GridLayout());
+ this.top = top;
+ }
+
+ private void createEventTabs(Composite top, ILaunchConfiguration config){
+ //Maybe not the best place to load the event list but we'll see.
+ Map<String,List<String>> events = PerfCore.getEventList(config);
+
+ // the special counters should be last
+ ArrayList<String> tmpTabNames = new ArrayList<>(events.keySet());
+ final List<String> SPECIAL_EVENTS = Arrays.asList(new String[] {
+ PerfPlugin.STRINGS_HWBREAKPOINTS,
+ PerfPlugin.STRINGS_RAWHWEvents });
+ tmpTabNames.removeAll(SPECIAL_EVENTS);
+ tmpTabNames.addAll(SPECIAL_EVENTS);
+
+ String [] tabNames = tmpTabNames.toArray(new String [0]);
+ eventTabItems = new TabItem[tabNames.length];
+ eventTable = new Table[tabNames.length];
+
+ tabFolder = new TabFolder(top, SWT.NONE);
+ tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+
+ // Initialize each tab.
+ for (int i = 0; i < tabNames.length; i++) {
+
+ eventTabItems[i] = new TabItem(tabFolder, SWT.NONE);
+ eventTabItems[i].setText(tabNames[i]);
+
+ // These are for the two special tabs for custom events.
+ if (tabNames[i].equals(PerfPlugin.STRINGS_HWBREAKPOINTS)
+ || tabNames[i].equals(PerfPlugin.STRINGS_RAWHWEvents)) {
+
+ // Composite to contain it all
+ Composite c = new Composite(tabFolder, SWT.NONE);
+ c.setLayout(new GridLayout(2, false));
+
+ // A list to check off existing custom events (or show the new ones added)
+ Table table = new Table(c, SWT.CHECK | SWT.MULTI);
+ eventTable[i] = table;
+ table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ table.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent se) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ // Right side to enter new events and delete old ones
+ Composite right = new Composite(c, SWT.NONE);
+ right.setLayout(new GridLayout(2,false));
+ right.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, true));
+
+ // for adding
+ Label l = new Label(right, SWT.NONE);
+ l.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,2,1));
+ Text t = new Text(right, SWT.SINGLE | SWT.BORDER);
+ t.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
+ if (tabNames[i].equals(PerfPlugin.STRINGS_HWBREAKPOINTS)) {
+ bpTabIndex = i;
+ bpText = t;
+ l.setText("Please enter the hardware breakpoint in the form mem:<addr>[:access].");
+ }
+ if (tabNames[i].equals(PerfPlugin.STRINGS_RAWHWEvents)) {
+ rawTabIndex = i;
+ rawText = t;
+ l.setText("Please enter the raw register encoding in the form rNNN.");
+ }
+
+ Button b = new Button(right, SWT.PUSH);
+ b.setText("Add");
+ b.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
+ b.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent se) {
+ int i = tabFolder.getSelectionIndex();
+ if (rawTabIndex == i) {
+ new TableItem(eventTable[i], SWT.NONE).setText(rawText.getText());
+ } else if(bpTabIndex == i) {
+ new TableItem(eventTable[i], SWT.NONE).setText(bpText.getText());
+ }
+ updateLaunchConfigurationDialog();
+ }
+ });
+ l = new Label(right, SWT.NONE);
+ l.setForeground(new Color(right.getDisplay(), 100,100,100));
+ if (tabNames[i].equals(PerfPlugin.STRINGS_HWBREAKPOINTS)) {
+ l.setText("For example, .........");
+ }
+ if (tabNames[i].equals(PerfPlugin.STRINGS_RAWHWEvents)) {
+ l.setText("For example, r1a8");
+ }
+ l.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false,2,1));
+
+ // spacer label.
+ l = new Label(right, SWT.NONE);
+ l.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,2,1));
+
+ // for removing
+ b = new Button(right, SWT.PUSH);
+ b.setText("Remove Selected Events");
+ b.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false,2,1));
+ b.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent se) {
+ eventTable[tabFolder.getSelectionIndex()].remove(eventTable[tabFolder.getSelectionIndex()].getSelectionIndices());
+ updateLaunchConfigurationDialog();
+ }
+ });
+ l = new Label(right, SWT.NONE);
+ l.setForeground(new Color(right.getDisplay(), 100,100,100));
+ l.setText("Note: Select by highlighting, not by checking.");
+ l.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false,2,1));
+
+ eventTabItems[i].setControl(c);
+
+ } else {
+ // This loads all the events 'perf list' gives into their respective tabs.
+ Table table = new Table(tabFolder, SWT.CHECK);
+ eventTable[i] = table;
+
+ List<String> eventList = events.get(tabNames[i]);
+ for (String event : eventList) {
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(event);
+ }
+
+ table.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent se) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ eventTabItems[i].setControl(table);
+ }
+ }
+ }
+
+ private void refreshDefaultEnabled() {
+ boolean state = !chkDefaultEvent.getSelection();
+ for (Table tab : eventTable) {
+ tab.setEnabled(state);
+ }
+ }
+
+ @Override
+ public String getName() {
+ return "Perf Events";
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration config) {
+ IProject project = getProject(config);
+
+ try {
+ if(previousProject == null || (previousProject != null && !previousProject.equals(project))){
+ Control[] children = top.getChildren();
+
+ for (Control control : children) {
+ control.dispose();
+ }
+
+ createVerticalSpacer(top, 1);
+
+ // Default event checkbox
+ chkDefaultEvent = new Button(top, SWT.CHECK);
+ chkDefaultEvent.setText("Default Event"); //$NON-NLS-1$
+ chkDefaultEvent.setLayoutData(new GridData());
+ chkDefaultEvent.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent se) {
+ refreshDefaultEnabled();
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ createEventTabs(top, config);
+ }
+
+ // restore whether things are default event/enabled or not.
+ chkDefaultEvent.setSelection(config.getAttribute(PerfPlugin.ATTR_DefaultEvent, PerfPlugin.ATTR_DefaultEvent_default));
+ refreshDefaultEnabled();
+
+ // restore custom hw breakpoints
+ List<?> hwbps = config.getAttribute(PerfPlugin.ATTR_HwBreakpointEvents, PerfPlugin.ATTR_HwBreakpointEvents_default);
+ if (hwbps != null) {
+ for (int i = 0; i < eventTable.length; i++) {
+ if (eventTabItems[i].getText().equals(PerfPlugin.STRINGS_HWBREAKPOINTS)) {
+ eventTable[i].removeAll();
+ for (Object e : hwbps) {
+ TableItem x = new TableItem(eventTable[i], SWT.NONE);
+ x.setText((String)e);
+ }
+ }
+ }
+ }
+
+ // restore custom raw hw events
+ List<?> rawhe = config.getAttribute(PerfPlugin.ATTR_RawHwEvents, PerfPlugin.ATTR_RawHwEvents_default);
+ if (rawhe != null) {
+ for (int i = 0; i < eventTable.length; i++) {
+ if (eventTabItems[i].getText().equals(PerfPlugin.STRINGS_RAWHWEvents)) {
+ eventTable[i].removeAll();
+ for (Object e : rawhe) {
+ TableItem x = new TableItem(eventTable[i], SWT.NONE);
+ x.setText((String)e);
+ }
+ }
+ }
+ }
+
+ // tick all the boxes that are checked
+ List<?> selectedEvents = config.getAttribute(PerfPlugin.ATTR_SelectedEvents, PerfPlugin.ATTR_SelectedEvents_default);
+
+ if(selectedEvents != null){
+ for (int i = 0; i < eventTable.length; i++) {
+ for(TableItem event : eventTable[i].getItems()) {
+ if(selectedEvents.contains(event.getText())){
+ event.setChecked(true);
+ } else {
+ event.setChecked(false);
+ }
+ }
+ }
+ }
+ previousProject = project;
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy wconfig) {
+ //Store default event checkbox
+ wconfig.setAttribute(PerfPlugin.ATTR_DefaultEvent, chkDefaultEvent.getSelection());
+
+ //Store which events are selected
+ ArrayList<String> selectedEvents = new ArrayList<>();
+ for (int i = 0; i < eventTable.length; i++) {
+ for(TableItem x : eventTable[i].getItems()) {
+ if (x.getChecked())
+ selectedEvents.add(x.getText());
+ }
+ }
+
+ if (selectedEvents.size() == 0) {
+ wconfig.setAttribute(PerfPlugin.ATTR_SelectedEvents, (String) null);
+ } else {
+ wconfig.setAttribute(PerfPlugin.ATTR_SelectedEvents, selectedEvents);
+ }
+
+ //Flag for multiple events
+ if ((chkDefaultEvent.getSelection() == false) && (selectedEvents.size() >= 1)) {
+ wconfig.setAttribute(PerfPlugin.ATTR_MultipleEvents, true);
+ } else {
+ wconfig.setAttribute(PerfPlugin.ATTR_MultipleEvents, false);
+ }
+ if (selectedEvents.size() <= 0) {
+ //If they unticked the default box but didn't select any events revert to default.
+ wconfig.setAttribute(PerfPlugin.ATTR_DefaultEvent, true);
+ }
+
+ //Store any custom HW BreakPoints they added (even if unchecked).
+ ArrayList<String> hwbps = new ArrayList<>();
+ for (int i = 0; i < eventTable.length; i++) {
+ if (eventTabItems[i].getText().equals(PerfPlugin.STRINGS_HWBREAKPOINTS)) {
+ for(TableItem x : eventTable[i].getItems()) {
+ hwbps.add(x.getText());
+ }
+ }
+ }
+ if (hwbps.size() == 0) {
+ hwbps = null; // to match with default value.
+ }
+ wconfig.setAttribute(PerfPlugin.ATTR_HwBreakpointEvents, hwbps);
+
+ //Store any custom Raw HW Events they added (even if unchecked).
+ ArrayList<String> rawhwe = new ArrayList<>();
+ for (int i = 0; i < eventTable.length; i++) {
+ if (eventTabItems[i].getText().equals(PerfPlugin.STRINGS_RAWHWEvents)) {
+ for(TableItem x : eventTable[i].getItems()) {
+ rawhwe.add(x.getText());
+ }
+ }
+ }
+ if (rawhwe.size() == 0) {
+ rawhwe = null; //to match with default value.
+ }
+ wconfig.setAttribute(PerfPlugin.ATTR_RawHwEvents, rawhwe);
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy wconfig) {
+ wconfig.setAttribute(PerfPlugin.ATTR_DefaultEvent, PerfPlugin.ATTR_DefaultEvent_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_MultipleEvents, PerfPlugin.ATTR_MultipleEvents_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_SelectedEvents, PerfPlugin.ATTR_SelectedEvents_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_HwBreakpointEvents, PerfPlugin.ATTR_HwBreakpointEvents_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_RawHwEvents, PerfPlugin.ATTR_RawHwEvents_default);
+ }
+
+ private IProject getProject(ILaunchConfiguration config){
+ String name = null;
+ try {
+ name = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, EMPTY_STRING);
+ } catch (CoreException e) {
+ return null;
+ }
+ if (name.isEmpty()){
+ return null;
+ }
+
+ return ResourcesPlugin.getWorkspace().getRoot().getProject(name);
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchConfigDelegate.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchConfigDelegate.java
index f621dbc537..4c7fb8e9c9 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchConfigDelegate.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchConfigDelegate.java
@@ -55,177 +55,177 @@ import org.osgi.framework.Version;
public class PerfLaunchConfigDelegate extends AbstractCLaunchDelegate {
- @Override
- protected String getPluginID() {
- return PerfPlugin.PLUGIN_ID;
- }
-
- @Override
- public void launch(ILaunchConfiguration config, String mode,
- ILaunch launch, IProgressMonitor monitor) throws CoreException {
- // check if Perf exists in $PATH
- if (! PerfCore.checkPerfInPath(null)) {
- IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID,
- Messages.PerfLaunchConfigDelegate_perf_not_found);
- throw new CoreException(status);
- }
-
- // Get working directory
- File wd = getWorkingDirectory(config);
- if (wd == null) {
- wd = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
- }
- IPath workingDir = Path.fromOSString(wd.toURI().getPath());
- PerfPlugin.getDefault().setWorkingDir(workingDir);
-
- if (config.getAttribute(PerfPlugin.ATTR_ShowStat,
- PerfPlugin.ATTR_ShowStat_default)) {
- showStat(config, launch);
- } else {
-
- //Find the binary path
- IPath exePath = CDebugUtils.verifyProgramPath( config );
-
- // Build the commandline string to run perf recording the given project
- // Program args from launch config.
- String arguments[] = getProgramArgumentsArray(config);
-
- ArrayList<String> command = new ArrayList<>();
- // Get the base commandline string (with flags/options based on config)
- Version perfVersion = PerfCore.getPerfVersion(config);
- command.addAll(Arrays.asList(PerfCore.getRecordString(config, perfVersion)));
- // Add the path to the executable
- command.add(exePath.toOSString());
- command.addAll(Arrays.asList( arguments));
- String[] commandArray = command.toArray(new String[] {});
- boolean usePty = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL,
- ICDTLaunchConfigurationConstants.USE_TERMINAL_DEFAULT);
-
- Process process;
- try {
- //Spawn the process
- process = CdtSpawnerProcessFactory.getFactory().exec( commandArray, getEnvironment( config ), wd, usePty );
- DebugPlugin.newProcess(launch, process,
- renderProcessLabel(commandArray[0])); //Spawn IProcess using Debug plugin (CDT)
-
- //Wait for recording to complete.
- process.waitFor();
- PrintStream print = null;
- if (config.getAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true)) {
- //Get the console to output to.
- //This may not be the best way to accomplish this but it shall do for now.
- ConsolePlugin plugin = ConsolePlugin.getDefault();
- IConsoleManager conMan = plugin.getConsoleManager();
- IConsole[] existing = conMan.getConsoles();
- IOConsole binaryOutCons = null;
-
- // Find the console
- for(IConsole x : existing) {
- if (x.getName().contains(renderProcessLabel(commandArray[0]))
- && x instanceof IOConsole) {
- binaryOutCons = (IOConsole)x;
- }
- }
- // If can't be found get the most recent opened, this should probably never happen.
- if ((binaryOutCons == null) && (existing.length != 0)) {
- if (existing[existing.length - 1] instanceof IOConsole)
- binaryOutCons = (IOConsole)existing[existing.length - 1];
- }
-
- //Get the printstream via the outputstream.
- //Get ouput stream
- OutputStream outputTo;
- if (binaryOutCons != null) {
- outputTo = binaryOutCons.newOutputStream();
- print = new PrintStream(outputTo);
-
- for (int i = 0; i < commandArray.length; i++) {
- print.print(commandArray[i] + " "); //$NON-NLS-1$
- }
-
- // Print Message
- print.println();
- print.println(Messages.PerfLaunchConfigDelegate_analyzing);
- // Possibly should pass this (the console reference) on to
- // PerfCore.Report if theres anything we ever want to spit
- // out to user.
- }
- }
-
- PerfCore.Report(config, getEnvironment(config), workingDir, monitor, null, print);
- PerfPlugin.getDefault().getPerfProfileData().toFile().setReadOnly();
- PerfCore.refreshView(renderProcessLabel(exePath.toOSString()));
-
- if (config.getAttribute(PerfPlugin.ATTR_ShowSourceDisassembly,
- PerfPlugin.ATTR_ShowSourceDisassembly_default)) {
- showSourceDisassembly(workingDir);
- }
-
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
-
- /**
- * Show source disassembly view.
- * @param workingDir working directory.
- */
- private void showSourceDisassembly(IPath workingDir) {
- String title = renderProcessLabel(workingDir + "perf.data"); //$NON-NLS-1$
- SourceDisassemblyData sdData = new SourceDisassemblyData(title, workingDir);
- sdData.parse();
- PerfPlugin.getDefault().setSourceDisassemblyData(sdData);
- SourceDisassemblyView.refreshView();
- }
-
- /**
- * Show statistics view.
- * @param config launch configuration
- * @param launch launch
- * @throws CoreException
- */
- private void showStat(ILaunchConfiguration config, ILaunch launch)
- throws CoreException {
- //Find the binary path
- IPath exePath = CDebugUtils.verifyProgramPath( config );
-
- // Build the command line string
- String arguments[] = getProgramArgumentsArray(config);
-
- // Get working directory
- IPath workingDir = PerfPlugin.getDefault().getWorkingDir();
-
- int runCount = config.getAttribute(PerfPlugin.ATTR_StatRunCount,
- PerfPlugin.ATTR_StatRunCount_default);
- StringBuffer args = new StringBuffer();
- for (String arg : arguments) {
- args.append(arg);
- args.append(" "); //$NON-NLS-1$
- }
-
- Object[] titleArgs = new Object[]{exePath.toOSString(), args.toString(), String.valueOf(runCount)};
- String title = renderProcessLabel(MessageFormat.format(Messages.PerfLaunchConfigDelegate_stat_title, titleArgs));
-
- List<String> configEvents = config.getAttribute(PerfPlugin.ATTR_SelectedEvents,
- PerfPlugin.ATTR_SelectedEvents_default);
-
- String[] statEvents = new String [] {};
-
- if(!config.getAttribute(PerfPlugin.ATTR_DefaultEvent, PerfPlugin.ATTR_DefaultEvent_default)){
- // gather selected events
- statEvents = (configEvents == null) ? statEvents : configEvents.toArray(new String[]{});
- }
-
- StatData sd = new StatData(title, workingDir, exePath.toOSString(), arguments, runCount, statEvents);
- sd.setLaunch(launch);
- sd.parse();
- PerfPlugin.getDefault().setStatData(sd);
-
- sd.updateStatData();
-
- StatView.refreshView();
- }
+ @Override
+ protected String getPluginID() {
+ return PerfPlugin.PLUGIN_ID;
+ }
+
+ @Override
+ public void launch(ILaunchConfiguration config, String mode,
+ ILaunch launch, IProgressMonitor monitor) throws CoreException {
+ // check if Perf exists in $PATH
+ if (! PerfCore.checkPerfInPath(null)) {
+ IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID,
+ Messages.PerfLaunchConfigDelegate_perf_not_found);
+ throw new CoreException(status);
+ }
+
+ // Get working directory
+ File wd = getWorkingDirectory(config);
+ if (wd == null) {
+ wd = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ IPath workingDir = Path.fromOSString(wd.toURI().getPath());
+ PerfPlugin.getDefault().setWorkingDir(workingDir);
+
+ if (config.getAttribute(PerfPlugin.ATTR_ShowStat,
+ PerfPlugin.ATTR_ShowStat_default)) {
+ showStat(config, launch);
+ } else {
+
+ //Find the binary path
+ IPath exePath = CDebugUtils.verifyProgramPath( config );
+
+ // Build the commandline string to run perf recording the given project
+ // Program args from launch config.
+ String arguments[] = getProgramArgumentsArray(config);
+
+ ArrayList<String> command = new ArrayList<>();
+ // Get the base commandline string (with flags/options based on config)
+ Version perfVersion = PerfCore.getPerfVersion(config);
+ command.addAll(Arrays.asList(PerfCore.getRecordString(config, perfVersion)));
+ // Add the path to the executable
+ command.add(exePath.toOSString());
+ command.addAll(Arrays.asList( arguments));
+ String[] commandArray = command.toArray(new String[] {});
+ boolean usePty = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL,
+ ICDTLaunchConfigurationConstants.USE_TERMINAL_DEFAULT);
+
+ Process process;
+ try {
+ //Spawn the process
+ process = CdtSpawnerProcessFactory.getFactory().exec( commandArray, getEnvironment( config ), wd, usePty );
+ DebugPlugin.newProcess(launch, process,
+ renderProcessLabel(commandArray[0])); //Spawn IProcess using Debug plugin (CDT)
+
+ //Wait for recording to complete.
+ process.waitFor();
+ PrintStream print = null;
+ if (config.getAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true)) {
+ //Get the console to output to.
+ //This may not be the best way to accomplish this but it shall do for now.
+ ConsolePlugin plugin = ConsolePlugin.getDefault();
+ IConsoleManager conMan = plugin.getConsoleManager();
+ IConsole[] existing = conMan.getConsoles();
+ IOConsole binaryOutCons = null;
+
+ // Find the console
+ for(IConsole x : existing) {
+ if (x.getName().contains(renderProcessLabel(commandArray[0]))
+ && x instanceof IOConsole) {
+ binaryOutCons = (IOConsole)x;
+ }
+ }
+ // If can't be found get the most recent opened, this should probably never happen.
+ if ((binaryOutCons == null) && (existing.length != 0)) {
+ if (existing[existing.length - 1] instanceof IOConsole)
+ binaryOutCons = (IOConsole)existing[existing.length - 1];
+ }
+
+ //Get the printstream via the outputstream.
+ //Get ouput stream
+ OutputStream outputTo;
+ if (binaryOutCons != null) {
+ outputTo = binaryOutCons.newOutputStream();
+ print = new PrintStream(outputTo);
+
+ for (int i = 0; i < commandArray.length; i++) {
+ print.print(commandArray[i] + " "); //$NON-NLS-1$
+ }
+
+ // Print Message
+ print.println();
+ print.println(Messages.PerfLaunchConfigDelegate_analyzing);
+ // Possibly should pass this (the console reference) on to
+ // PerfCore.Report if theres anything we ever want to spit
+ // out to user.
+ }
+ }
+
+ PerfCore.Report(config, getEnvironment(config), workingDir, monitor, null, print);
+ PerfPlugin.getDefault().getPerfProfileData().toFile().setReadOnly();
+ PerfCore.refreshView(renderProcessLabel(exePath.toOSString()));
+
+ if (config.getAttribute(PerfPlugin.ATTR_ShowSourceDisassembly,
+ PerfPlugin.ATTR_ShowSourceDisassembly_default)) {
+ showSourceDisassembly(workingDir);
+ }
+
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /**
+ * Show source disassembly view.
+ * @param workingDir working directory.
+ */
+ private void showSourceDisassembly(IPath workingDir) {
+ String title = renderProcessLabel(workingDir + "perf.data"); //$NON-NLS-1$
+ SourceDisassemblyData sdData = new SourceDisassemblyData(title, workingDir);
+ sdData.parse();
+ PerfPlugin.getDefault().setSourceDisassemblyData(sdData);
+ SourceDisassemblyView.refreshView();
+ }
+
+ /**
+ * Show statistics view.
+ * @param config launch configuration
+ * @param launch launch
+ * @throws CoreException
+ */
+ private void showStat(ILaunchConfiguration config, ILaunch launch)
+ throws CoreException {
+ //Find the binary path
+ IPath exePath = CDebugUtils.verifyProgramPath( config );
+
+ // Build the command line string
+ String arguments[] = getProgramArgumentsArray(config);
+
+ // Get working directory
+ IPath workingDir = PerfPlugin.getDefault().getWorkingDir();
+
+ int runCount = config.getAttribute(PerfPlugin.ATTR_StatRunCount,
+ PerfPlugin.ATTR_StatRunCount_default);
+ StringBuffer args = new StringBuffer();
+ for (String arg : arguments) {
+ args.append(arg);
+ args.append(" "); //$NON-NLS-1$
+ }
+
+ Object[] titleArgs = new Object[]{exePath.toOSString(), args.toString(), String.valueOf(runCount)};
+ String title = renderProcessLabel(MessageFormat.format(Messages.PerfLaunchConfigDelegate_stat_title, titleArgs));
+
+ List<String> configEvents = config.getAttribute(PerfPlugin.ATTR_SelectedEvents,
+ PerfPlugin.ATTR_SelectedEvents_default);
+
+ String[] statEvents = new String [] {};
+
+ if(!config.getAttribute(PerfPlugin.ATTR_DefaultEvent, PerfPlugin.ATTR_DefaultEvent_default)){
+ // gather selected events
+ statEvents = (configEvents == null) ? statEvents : configEvents.toArray(new String[]{});
+ }
+
+ StatData sd = new StatData(title, workingDir, exePath.toOSString(), arguments, runCount, statEvents);
+ sd.setLaunch(launch);
+ sd.parse();
+ PerfPlugin.getDefault().setStatData(sd);
+
+ sd.updateStatData();
+
+ StatView.refreshView();
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchConfigurationTabGroup.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchConfigurationTabGroup.java
index 804cf38d5c..9b15d7e147 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchConfigurationTabGroup.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchConfigurationTabGroup.java
@@ -10,15 +10,15 @@
* Kent Sebastian <ksebasti@redhat.com> - initial API and implementation
* Thavidu Ranatunga (IBM) - derived from
* org.eclipse.linuxtools.oprofile.launch.configuration.OprofileLaunchConfigurationTabGroup
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.perf.launch;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTabGroup;
public class PerfLaunchConfigurationTabGroup extends ProfileLaunchConfigurationTabGroup {
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- return new AbstractLaunchConfigurationTab[] { new PerfOptionsTab(), new PerfEventsTab() };
- }
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ return new AbstractLaunchConfigurationTab[] { new PerfOptionsTab(), new PerfEventsTab() };
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchShortcut.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchShortcut.java
index 08a4ce4b1d..8327d59d9c 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchShortcut.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfLaunchShortcut.java
@@ -7,7 +7,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * Kent Sebastian <ksebasti@redhat.com> - initial API and implementation
+ * Kent Sebastian <ksebasti@redhat.com> - initial API and implementation
* Thavidu Ranatunga (IBM) - derived from
* org.eclipse.linuxtools.oprofile.launch.launching.OprofileLaunchShortcut
*******************************************************************************/
@@ -21,17 +21,17 @@ import org.eclipse.linuxtools.profiling.launch.ProfileLaunchShortcut;
public class PerfLaunchShortcut extends ProfileLaunchShortcut {
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(PerfPlugin.LAUNCHCONF_ID);
- }
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(PerfPlugin.LAUNCHCONF_ID);
+ }
- @Override
- protected void setDefaultProfileAttributes(
- ILaunchConfigurationWorkingCopy wc) {
- //These settings make it appear smoother.
- wc.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false);
- wc.setAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true);
- }
+ @Override
+ protected void setDefaultProfileAttributes(
+ ILaunchConfigurationWorkingCopy wc) {
+ //These settings make it appear smoother.
+ wc.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false);
+ wc.setAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true);
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfOpenData.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfOpenData.java
index 719b8f445d..16f1d40fe8 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfOpenData.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfOpenData.java
@@ -34,7 +34,7 @@ import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
public class PerfOpenData extends ProfileLaunchShortcut implements
- IEditorLauncher {
+ IEditorLauncher {
@Override
public void open(IPath file) {
@@ -67,39 +67,39 @@ public class PerfOpenData extends ProfileLaunchShortcut implements
}
}
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(
- PerfPlugin.LAUNCHCONF_ID);
- }
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(
+ PerfPlugin.LAUNCHCONF_ID);
+ }
- @Override
- protected void setDefaultProfileAttributes(
- ILaunchConfigurationWorkingCopy wc) {
- wc.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false);
- wc.setAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true);
- }
+ @Override
+ protected void setDefaultProfileAttributes(
+ ILaunchConfigurationWorkingCopy wc) {
+ wc.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false);
+ wc.setAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true);
+ }
- /**
- * Create an ILaunchConfiguration instance given the project's name.
- *
- * @param projectName
- * @return ILaunchConfiguration based on String projectName
- */
- private ILaunchConfiguration createDefaultConfiguration(String projectName) {
- ILaunchConfiguration config = null;
- try {
- ILaunchConfigurationType configType = getLaunchConfigType();
- ILaunchConfigurationWorkingCopy wc = configType.newInstance(
- null,
- getLaunchManager().generateLaunchConfigurationName(
- projectName));
- wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, projectName);
- config = wc;
+ /**
+ * Create an ILaunchConfiguration instance given the project's name.
+ *
+ * @param projectName
+ * @return ILaunchConfiguration based on String projectName
+ */
+ private ILaunchConfiguration createDefaultConfiguration(String projectName) {
+ ILaunchConfiguration config = null;
+ try {
+ ILaunchConfigurationType configType = getLaunchConfigType();
+ ILaunchConfigurationWorkingCopy wc = configType.newInstance(
+ null,
+ getLaunchManager().generateLaunchConfigurationName(
+ projectName));
+ wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, projectName);
+ config = wc;
- } catch (CoreException e) {
- PerfCore.logException(e);
- }
- return config;
- }
+ } catch (CoreException e) {
+ PerfCore.logException(e);
+ }
+ return config;
+ }
} \ No newline at end of file
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfOptionsTab.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfOptionsTab.java
index 7279a4394f..acd13ea252 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfOptionsTab.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/launch/PerfOptionsTab.java
@@ -47,354 +47,354 @@ import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Version;
public class PerfOptionsTab extends AbstractLaunchConfigurationTab {
- private ILaunchConfiguration lastConfig;
-
- protected Text txtKernelLocation;
- protected Button chkRecordRealtime;
- protected Spinner rtPriority;
- protected Button chkRecordVerbose;
- protected Button chkSourceLineNumbers;
- protected Button chkKernelSourceLineNumbers;
- protected Button chkMultiplexEvents;
- protected Button chkModuleSymbols;
- protected Button chkHideUnresolvedSymbols;
- protected Button chkShowSourceDisassembly;
- protected Button chkShowStat;
- protected Spinner statRunCount;
-
- private Composite top;
- private ScrolledComposite scrollTop;
-
- protected final Version multiplexEventsVersion = new Version (2, 6, 35);
-
- /**
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage()
- */
- @Override
- public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
- }
-
- @Override
- public boolean isValid(ILaunchConfiguration config) {
- if (txtKernelLocation != null) {
- String filename = txtKernelLocation.getText();
- if (filename.length() > 0) {
- File file = new File(filename);
- return (file.exists() && file.isFile());
- }
- }
- return true;
- }
-
- @Override
- public void createControl(Composite parent) {
- scrollTop = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
- scrollTop.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- scrollTop.setExpandVertical(true);
- scrollTop.setExpandHorizontal(true);
-
- setControl(scrollTop);
-
- top = new Composite(scrollTop, SWT.NONE);
- top.setLayout(new GridLayout());
-
- createVerticalSpacer(top, 1);
- GridData data;
-
- // Kernel Selection
- Composite kernelComp = new Composite(top, SWT.NONE);
- GridLayout parallelLayout = new GridLayout(2, false);
- data = new GridData(GridData.FILL_HORIZONTAL);
- parallelLayout.marginHeight = 0;
- parallelLayout.marginWidth = 0;
- kernelComp.setLayout(parallelLayout);
- kernelComp.setLayoutData(data);
-
- Label kernelLabel = new Label(kernelComp, SWT.NONE);
- kernelLabel.setText(PerfPlugin.STRINGS_Kernel_Location);
- data = new GridData();
- data.horizontalSpan = 2;
- kernelLabel.setLayoutData(data);
-
- txtKernelLocation = new Text(kernelComp, SWT.SINGLE | SWT.BORDER);
- data = new GridData(GridData.FILL_HORIZONTAL);
- txtKernelLocation.setLayoutData(data);
- txtKernelLocation.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent mev) {
- handleKernelImageFileTextModify(txtKernelLocation);
- }
- });
-
- Button button = createPushButton(kernelComp, Messages.PerfOptionsTab_Browse, null);
- final Shell shell = top.getShell();
- button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent sev) {
- showFileDialog(shell);
- }
- });
-
- createVerticalSpacer(top, 1);
-
- // Create checkbox options container
- Composite chkBoxComp = new Composite(top, SWT.NONE);
- GridLayout chkBoxLayout = new GridLayout();
- chkBoxLayout.marginHeight = 0;
- chkBoxLayout.marginWidth = 0;
- chkBoxComp.setLayout(chkBoxLayout);
-
- chkRecordVerbose = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_Record_Verbose);
- chkModuleSymbols = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_ModuleSymbols);
- chkHideUnresolvedSymbols = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_HideUnresolvedSymbols);
- chkSourceLineNumbers = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_SourceLineNumbers);
- chkShowSourceDisassembly = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_ShowSourceDisassembly);
-
- Composite showStatComp = new Composite(top, SWT.NONE);
- showStatComp.setLayout(parallelLayout);
-
- chkShowStat = createCheckButtonHelper(showStatComp, PerfPlugin.STRINGS_ShowStat);
- chkShowStat.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent se) {
- Version perfVersion = PerfCore.getPerfVersion(lastConfig);
- handleShowStatSelection(perfVersion);
- }
- });
- statRunCount = new Spinner(showStatComp, SWT.BORDER);
- statRunCount.setEnabled(false);
- statRunCount.setMinimum(1);
- statRunCount.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- });
-
- chkSourceLineNumbers.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent se) {
- if ((chkKernelSourceLineNumbers != null) && (!chkSourceLineNumbers.getSelection())) {
- chkKernelSourceLineNumbers.setEnabled(false);
- } else {
- chkKernelSourceLineNumbers.setEnabled(true);
- }
- }
- });
- chkKernelSourceLineNumbers = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_Kernel_SourceLineNumbers);
-
- Composite realtimeComp = new Composite(top, SWT.NONE);
- realtimeComp.setLayout(parallelLayout);
-
- chkRecordRealtime = createCheckButtonHelper(realtimeComp, PerfPlugin.STRINGS_Record_Realtime);
- chkRecordRealtime.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent se) {
- rtPriority.setEnabled(chkRecordRealtime.getSelection());
- }
- });
- rtPriority = new Spinner(realtimeComp, SWT.BORDER);
- rtPriority.setEnabled(chkRecordRealtime.getSelection());
- rtPriority.setMinimum(1);
- rtPriority.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- });
-
- // A disabled button does not respond to mouse events so use a composite.
- final Composite multiplexEventsComp = new Composite(chkBoxComp, SWT.NONE);
- multiplexEventsComp.setLayout(chkBoxLayout);
- multiplexEventsComp.addListener(SWT.MouseHover, new Listener() {
- @Override
- public void handleEvent(Event event) {
- multiplexEventsComp.setToolTipText(Messages.PerfOptionsTab_Requires_LTE + multiplexEventsVersion);
- }
- });
- chkMultiplexEvents = createCheckButtonHelper(multiplexEventsComp, PerfPlugin.STRINGS_Multiplex);
-
- scrollTop.setContent(top);
- recomputeSize();
- updateLaunchConfigurationDialog();
- }
-
- private void recomputeSize() {
- Point point = top.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- top.setSize(point);
- scrollTop.setMinSize(point);
- }
-
- // Helper function for creating buttons.
- private Button createCheckButtonHelper(Composite parent, String label) {
- final Button b = new Button(parent, SWT.CHECK);
- b.setText(label);
- b.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent se) {
- setDirty(true);
- updateLaunchConfigurationDialog();
- }
- });
- return b;
- }
-
- // handles text modification event for kernel file location
- private void handleKernelImageFileTextModify(Text text) {
- String errorMessage = null;
- String filename = text.getText();
-
- if (filename.length() > 0) {
- File file = new File(filename);
- if (!file.exists() || !file.isFile()) {
- errorMessage = Messages.PerfOptionsTab_Loc_DNE;
- }
- }
-
- // Update dialog and error message
- setErrorMessage(errorMessage);
- updateLaunchConfigurationDialog();
- }
-
- /**
- * Handle selection of show stat button
- */
- private void handleShowStatSelection(Version version) {
- if (chkShowStat.getSelection()) {
- statRunCount.setEnabled(true);
- toggleButtonsEnablement(false, version);
- } else {
- statRunCount.setEnabled(false);
- toggleButtonsEnablement(true, version);
- }
- }
-
- // Displays a file dialog to allow the user to select the kernel image file
- private void showFileDialog(Shell shell) {
- FileDialog fDialog = new FileDialog(shell, SWT.OPEN);
- File kernel = new File(txtKernelLocation.getText());
- if (!kernel.exists()) {
- kernel = new File("/boot"); //$NON-NLS-1$
- if (!kernel.exists()) {
- kernel = new File("/"); //$NON-NLS-1$
- }
- }
- fDialog.setFileName(kernel.toString());
- fDialog.setText(Messages.PerfOptionsTab_Kernel_Prompt);
- String newKernel = fDialog.open();
- if (newKernel != null) {
- kernel = new File(newKernel);
- if (!kernel.exists()) {
- MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
- mb.setMessage(Messages.PerfOptionsTab_File_DNE);
- switch (mb.open()) {
- case SWT.RETRY:
- showFileDialog(shell);
- break;
- default:
- }
- } else {
- txtKernelLocation.setText(newKernel);
- }
- }
- }
-
- /**
- * Toggle enablement of all buttons, excluding the stat button.
- * @param enable enablement of buttons
- */
- private void toggleButtonsEnablement(boolean enable, Version version) {
- txtKernelLocation.setEnabled(enable);
- chkRecordRealtime.setEnabled(enable);
- chkRecordVerbose.setEnabled(enable);
- chkSourceLineNumbers.setEnabled(enable);
- chkKernelSourceLineNumbers.setEnabled(enable);
- if (version != null && multiplexEventsVersion.compareTo(version) > 0) {
- chkMultiplexEvents.setEnabled(enable);
- } else {
- chkMultiplexEvents.setEnabled(false);
- }
- chkModuleSymbols.setEnabled(enable);
- chkHideUnresolvedSymbols.setEnabled(enable);
- chkShowSourceDisassembly.setEnabled(enable);
- }
-
- @Override
- public String getName() {
- return Messages.PerfOptionsTab_Options;
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration config) {
-
- // Keep track of the last configuration loaded
- lastConfig = config;
- Version perfVersion = PerfCore.getPerfVersion(config);
-
- try {
-
- if (perfVersion != null && multiplexEventsVersion.compareTo(perfVersion) > 0) {
- chkMultiplexEvents.setSelection(config.getAttribute(PerfPlugin.ATTR_Multiplex, PerfPlugin.ATTR_Multiplex_default));
- }
-
- txtKernelLocation.setText(config.getAttribute(PerfPlugin.ATTR_Kernel_Location, PerfPlugin.ATTR_Kernel_Location_default));
- chkRecordRealtime.setSelection(config.getAttribute(PerfPlugin.ATTR_Record_Realtime, PerfPlugin.ATTR_Record_Realtime_default));
- int priority = config.getAttribute(PerfPlugin.ATTR_Record_Realtime_Priority, PerfPlugin.ATTR_Record_Realtime_Priority_default);
- rtPriority.setEnabled(chkRecordRealtime.getSelection());
- rtPriority.setSelection(priority);
- chkRecordVerbose.setSelection(config.getAttribute(PerfPlugin.ATTR_Record_Verbose, PerfPlugin.ATTR_Record_Verbose_default));
- chkSourceLineNumbers.setSelection(config.getAttribute(PerfPlugin.ATTR_SourceLineNumbers, PerfPlugin.ATTR_SourceLineNumbers_default));
- chkKernelSourceLineNumbers.setSelection(config.getAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, PerfPlugin.ATTR_Kernel_SourceLineNumbers_default));
-
- chkModuleSymbols.setSelection(config.getAttribute(PerfPlugin.ATTR_ModuleSymbols, PerfPlugin.ATTR_ModuleSymbols_default));
- chkHideUnresolvedSymbols.setSelection(config.getAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, PerfPlugin.ATTR_HideUnresolvedSymbols_default));
- chkShowSourceDisassembly.setSelection(config.getAttribute(PerfPlugin.ATTR_ShowSourceDisassembly, PerfPlugin.ATTR_ShowSourceDisassembly_default));
- chkShowStat.setSelection(config.getAttribute(PerfPlugin.ATTR_ShowStat, PerfPlugin.ATTR_ShowStat_default));
- int runCount = config.getAttribute(PerfPlugin.ATTR_StatRunCount, PerfPlugin.ATTR_StatRunCount_default);
- statRunCount.setSelection(runCount);
- handleShowStatSelection(perfVersion);
- } catch (CoreException e) {
- // do nothing
- }
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy wconfig) {
-
- Version perfVersion = PerfCore.getPerfVersion(wconfig);
-
- if (perfVersion != null && multiplexEventsVersion.compareTo(perfVersion) > 0) {
- wconfig.setAttribute(PerfPlugin.ATTR_Multiplex, chkMultiplexEvents.getSelection());
- }
-
- wconfig.setAttribute(PerfPlugin.ATTR_Kernel_Location, txtKernelLocation.getText());
- wconfig.setAttribute(PerfPlugin.ATTR_Record_Realtime, chkRecordRealtime.getSelection());
- wconfig.setAttribute(PerfPlugin.ATTR_Record_Realtime_Priority, rtPriority.getSelection());
- wconfig.setAttribute(PerfPlugin.ATTR_Record_Verbose, chkRecordVerbose.getSelection());
- wconfig.setAttribute(PerfPlugin.ATTR_SourceLineNumbers, chkSourceLineNumbers.getSelection());
- wconfig.setAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, chkKernelSourceLineNumbers.getSelection());
- wconfig.setAttribute(PerfPlugin.ATTR_ModuleSymbols, chkModuleSymbols.getSelection());
- wconfig.setAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, chkHideUnresolvedSymbols.getSelection());
- wconfig.setAttribute(PerfPlugin.ATTR_ShowSourceDisassembly, chkShowSourceDisassembly.getSelection());
- wconfig.setAttribute(PerfPlugin.ATTR_ShowStat, chkShowStat.getSelection());
- wconfig.setAttribute(PerfPlugin.ATTR_StatRunCount, statRunCount.getSelection());
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy wconfig) {
- wconfig.setAttribute(PerfPlugin.ATTR_Kernel_Location, PerfPlugin.ATTR_Kernel_Location_default);
- wconfig.setAttribute(PerfPlugin.ATTR_Record_Realtime, PerfPlugin.ATTR_Record_Realtime_default);
- wconfig.setAttribute(PerfPlugin.ATTR_Record_Realtime_Priority, PerfPlugin.ATTR_Record_Realtime_Priority_default);
- wconfig.setAttribute(PerfPlugin.ATTR_Record_Verbose, PerfPlugin.ATTR_Record_Verbose_default);
- wconfig.setAttribute(PerfPlugin.ATTR_SourceLineNumbers, PerfPlugin.ATTR_SourceLineNumbers_default);
- wconfig.setAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, PerfPlugin.ATTR_Kernel_SourceLineNumbers_default);
- wconfig.setAttribute(PerfPlugin.ATTR_Multiplex, PerfPlugin.ATTR_Multiplex_default);
- wconfig.setAttribute(PerfPlugin.ATTR_ModuleSymbols, PerfPlugin.ATTR_ModuleSymbols_default);
- wconfig.setAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, PerfPlugin.ATTR_HideUnresolvedSymbols_default);
- wconfig.setAttribute(PerfPlugin.ATTR_ShowSourceDisassembly, PerfPlugin.ATTR_ShowSourceDisassembly_default);
- wconfig.setAttribute(PerfPlugin.ATTR_ShowStat, PerfPlugin.ATTR_ShowStat_default);
- wconfig.setAttribute(PerfPlugin.ATTR_StatRunCount, PerfPlugin.ATTR_StatRunCount_default);
- }
+ private ILaunchConfiguration lastConfig;
+
+ protected Text txtKernelLocation;
+ protected Button chkRecordRealtime;
+ protected Spinner rtPriority;
+ protected Button chkRecordVerbose;
+ protected Button chkSourceLineNumbers;
+ protected Button chkKernelSourceLineNumbers;
+ protected Button chkMultiplexEvents;
+ protected Button chkModuleSymbols;
+ protected Button chkHideUnresolvedSymbols;
+ protected Button chkShowSourceDisassembly;
+ protected Button chkShowStat;
+ protected Spinner statRunCount;
+
+ private Composite top;
+ private ScrolledComposite scrollTop;
+
+ protected final Version multiplexEventsVersion = new Version (2, 6, 35);
+
+ /**
+ * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage()
+ */
+ @Override
+ public Image getImage() {
+ return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
+ }
+
+ @Override
+ public boolean isValid(ILaunchConfiguration config) {
+ if (txtKernelLocation != null) {
+ String filename = txtKernelLocation.getText();
+ if (filename.length() > 0) {
+ File file = new File(filename);
+ return (file.exists() && file.isFile());
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ scrollTop = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
+ scrollTop.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ scrollTop.setExpandVertical(true);
+ scrollTop.setExpandHorizontal(true);
+
+ setControl(scrollTop);
+
+ top = new Composite(scrollTop, SWT.NONE);
+ top.setLayout(new GridLayout());
+
+ createVerticalSpacer(top, 1);
+ GridData data;
+
+ // Kernel Selection
+ Composite kernelComp = new Composite(top, SWT.NONE);
+ GridLayout parallelLayout = new GridLayout(2, false);
+ data = new GridData(GridData.FILL_HORIZONTAL);
+ parallelLayout.marginHeight = 0;
+ parallelLayout.marginWidth = 0;
+ kernelComp.setLayout(parallelLayout);
+ kernelComp.setLayoutData(data);
+
+ Label kernelLabel = new Label(kernelComp, SWT.NONE);
+ kernelLabel.setText(PerfPlugin.STRINGS_Kernel_Location);
+ data = new GridData();
+ data.horizontalSpan = 2;
+ kernelLabel.setLayoutData(data);
+
+ txtKernelLocation = new Text(kernelComp, SWT.SINGLE | SWT.BORDER);
+ data = new GridData(GridData.FILL_HORIZONTAL);
+ txtKernelLocation.setLayoutData(data);
+ txtKernelLocation.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent mev) {
+ handleKernelImageFileTextModify(txtKernelLocation);
+ }
+ });
+
+ Button button = createPushButton(kernelComp, Messages.PerfOptionsTab_Browse, null);
+ final Shell shell = top.getShell();
+ button.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent sev) {
+ showFileDialog(shell);
+ }
+ });
+
+ createVerticalSpacer(top, 1);
+
+ // Create checkbox options container
+ Composite chkBoxComp = new Composite(top, SWT.NONE);
+ GridLayout chkBoxLayout = new GridLayout();
+ chkBoxLayout.marginHeight = 0;
+ chkBoxLayout.marginWidth = 0;
+ chkBoxComp.setLayout(chkBoxLayout);
+
+ chkRecordVerbose = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_Record_Verbose);
+ chkModuleSymbols = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_ModuleSymbols);
+ chkHideUnresolvedSymbols = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_HideUnresolvedSymbols);
+ chkSourceLineNumbers = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_SourceLineNumbers);
+ chkShowSourceDisassembly = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_ShowSourceDisassembly);
+
+ Composite showStatComp = new Composite(top, SWT.NONE);
+ showStatComp.setLayout(parallelLayout);
+
+ chkShowStat = createCheckButtonHelper(showStatComp, PerfPlugin.STRINGS_ShowStat);
+ chkShowStat.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent se) {
+ Version perfVersion = PerfCore.getPerfVersion(lastConfig);
+ handleShowStatSelection(perfVersion);
+ }
+ });
+ statRunCount = new Spinner(showStatComp, SWT.BORDER);
+ statRunCount.setEnabled(false);
+ statRunCount.setMinimum(1);
+ statRunCount.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ chkSourceLineNumbers.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent se) {
+ if ((chkKernelSourceLineNumbers != null) && (!chkSourceLineNumbers.getSelection())) {
+ chkKernelSourceLineNumbers.setEnabled(false);
+ } else {
+ chkKernelSourceLineNumbers.setEnabled(true);
+ }
+ }
+ });
+ chkKernelSourceLineNumbers = createCheckButtonHelper(chkBoxComp, PerfPlugin.STRINGS_Kernel_SourceLineNumbers);
+
+ Composite realtimeComp = new Composite(top, SWT.NONE);
+ realtimeComp.setLayout(parallelLayout);
+
+ chkRecordRealtime = createCheckButtonHelper(realtimeComp, PerfPlugin.STRINGS_Record_Realtime);
+ chkRecordRealtime.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent se) {
+ rtPriority.setEnabled(chkRecordRealtime.getSelection());
+ }
+ });
+ rtPriority = new Spinner(realtimeComp, SWT.BORDER);
+ rtPriority.setEnabled(chkRecordRealtime.getSelection());
+ rtPriority.setMinimum(1);
+ rtPriority.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ // A disabled button does not respond to mouse events so use a composite.
+ final Composite multiplexEventsComp = new Composite(chkBoxComp, SWT.NONE);
+ multiplexEventsComp.setLayout(chkBoxLayout);
+ multiplexEventsComp.addListener(SWT.MouseHover, new Listener() {
+ @Override
+ public void handleEvent(Event event) {
+ multiplexEventsComp.setToolTipText(Messages.PerfOptionsTab_Requires_LTE + multiplexEventsVersion);
+ }
+ });
+ chkMultiplexEvents = createCheckButtonHelper(multiplexEventsComp, PerfPlugin.STRINGS_Multiplex);
+
+ scrollTop.setContent(top);
+ recomputeSize();
+ updateLaunchConfigurationDialog();
+ }
+
+ private void recomputeSize() {
+ Point point = top.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ top.setSize(point);
+ scrollTop.setMinSize(point);
+ }
+
+ // Helper function for creating buttons.
+ private Button createCheckButtonHelper(Composite parent, String label) {
+ final Button b = new Button(parent, SWT.CHECK);
+ b.setText(label);
+ b.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent se) {
+ setDirty(true);
+ updateLaunchConfigurationDialog();
+ }
+ });
+ return b;
+ }
+
+ // handles text modification event for kernel file location
+ private void handleKernelImageFileTextModify(Text text) {
+ String errorMessage = null;
+ String filename = text.getText();
+
+ if (filename.length() > 0) {
+ File file = new File(filename);
+ if (!file.exists() || !file.isFile()) {
+ errorMessage = Messages.PerfOptionsTab_Loc_DNE;
+ }
+ }
+
+ // Update dialog and error message
+ setErrorMessage(errorMessage);
+ updateLaunchConfigurationDialog();
+ }
+
+ /**
+ * Handle selection of show stat button
+ */
+ private void handleShowStatSelection(Version version) {
+ if (chkShowStat.getSelection()) {
+ statRunCount.setEnabled(true);
+ toggleButtonsEnablement(false, version);
+ } else {
+ statRunCount.setEnabled(false);
+ toggleButtonsEnablement(true, version);
+ }
+ }
+
+ // Displays a file dialog to allow the user to select the kernel image file
+ private void showFileDialog(Shell shell) {
+ FileDialog fDialog = new FileDialog(shell, SWT.OPEN);
+ File kernel = new File(txtKernelLocation.getText());
+ if (!kernel.exists()) {
+ kernel = new File("/boot"); //$NON-NLS-1$
+ if (!kernel.exists()) {
+ kernel = new File("/"); //$NON-NLS-1$
+ }
+ }
+ fDialog.setFileName(kernel.toString());
+ fDialog.setText(Messages.PerfOptionsTab_Kernel_Prompt);
+ String newKernel = fDialog.open();
+ if (newKernel != null) {
+ kernel = new File(newKernel);
+ if (!kernel.exists()) {
+ MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
+ mb.setMessage(Messages.PerfOptionsTab_File_DNE);
+ switch (mb.open()) {
+ case SWT.RETRY:
+ showFileDialog(shell);
+ break;
+ default:
+ }
+ } else {
+ txtKernelLocation.setText(newKernel);
+ }
+ }
+ }
+
+ /**
+ * Toggle enablement of all buttons, excluding the stat button.
+ * @param enable enablement of buttons
+ */
+ private void toggleButtonsEnablement(boolean enable, Version version) {
+ txtKernelLocation.setEnabled(enable);
+ chkRecordRealtime.setEnabled(enable);
+ chkRecordVerbose.setEnabled(enable);
+ chkSourceLineNumbers.setEnabled(enable);
+ chkKernelSourceLineNumbers.setEnabled(enable);
+ if (version != null && multiplexEventsVersion.compareTo(version) > 0) {
+ chkMultiplexEvents.setEnabled(enable);
+ } else {
+ chkMultiplexEvents.setEnabled(false);
+ }
+ chkModuleSymbols.setEnabled(enable);
+ chkHideUnresolvedSymbols.setEnabled(enable);
+ chkShowSourceDisassembly.setEnabled(enable);
+ }
+
+ @Override
+ public String getName() {
+ return Messages.PerfOptionsTab_Options;
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration config) {
+
+ // Keep track of the last configuration loaded
+ lastConfig = config;
+ Version perfVersion = PerfCore.getPerfVersion(config);
+
+ try {
+
+ if (perfVersion != null && multiplexEventsVersion.compareTo(perfVersion) > 0) {
+ chkMultiplexEvents.setSelection(config.getAttribute(PerfPlugin.ATTR_Multiplex, PerfPlugin.ATTR_Multiplex_default));
+ }
+
+ txtKernelLocation.setText(config.getAttribute(PerfPlugin.ATTR_Kernel_Location, PerfPlugin.ATTR_Kernel_Location_default));
+ chkRecordRealtime.setSelection(config.getAttribute(PerfPlugin.ATTR_Record_Realtime, PerfPlugin.ATTR_Record_Realtime_default));
+ int priority = config.getAttribute(PerfPlugin.ATTR_Record_Realtime_Priority, PerfPlugin.ATTR_Record_Realtime_Priority_default);
+ rtPriority.setEnabled(chkRecordRealtime.getSelection());
+ rtPriority.setSelection(priority);
+ chkRecordVerbose.setSelection(config.getAttribute(PerfPlugin.ATTR_Record_Verbose, PerfPlugin.ATTR_Record_Verbose_default));
+ chkSourceLineNumbers.setSelection(config.getAttribute(PerfPlugin.ATTR_SourceLineNumbers, PerfPlugin.ATTR_SourceLineNumbers_default));
+ chkKernelSourceLineNumbers.setSelection(config.getAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, PerfPlugin.ATTR_Kernel_SourceLineNumbers_default));
+
+ chkModuleSymbols.setSelection(config.getAttribute(PerfPlugin.ATTR_ModuleSymbols, PerfPlugin.ATTR_ModuleSymbols_default));
+ chkHideUnresolvedSymbols.setSelection(config.getAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, PerfPlugin.ATTR_HideUnresolvedSymbols_default));
+ chkShowSourceDisassembly.setSelection(config.getAttribute(PerfPlugin.ATTR_ShowSourceDisassembly, PerfPlugin.ATTR_ShowSourceDisassembly_default));
+ chkShowStat.setSelection(config.getAttribute(PerfPlugin.ATTR_ShowStat, PerfPlugin.ATTR_ShowStat_default));
+ int runCount = config.getAttribute(PerfPlugin.ATTR_StatRunCount, PerfPlugin.ATTR_StatRunCount_default);
+ statRunCount.setSelection(runCount);
+ handleShowStatSelection(perfVersion);
+ } catch (CoreException e) {
+ // do nothing
+ }
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy wconfig) {
+
+ Version perfVersion = PerfCore.getPerfVersion(wconfig);
+
+ if (perfVersion != null && multiplexEventsVersion.compareTo(perfVersion) > 0) {
+ wconfig.setAttribute(PerfPlugin.ATTR_Multiplex, chkMultiplexEvents.getSelection());
+ }
+
+ wconfig.setAttribute(PerfPlugin.ATTR_Kernel_Location, txtKernelLocation.getText());
+ wconfig.setAttribute(PerfPlugin.ATTR_Record_Realtime, chkRecordRealtime.getSelection());
+ wconfig.setAttribute(PerfPlugin.ATTR_Record_Realtime_Priority, rtPriority.getSelection());
+ wconfig.setAttribute(PerfPlugin.ATTR_Record_Verbose, chkRecordVerbose.getSelection());
+ wconfig.setAttribute(PerfPlugin.ATTR_SourceLineNumbers, chkSourceLineNumbers.getSelection());
+ wconfig.setAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, chkKernelSourceLineNumbers.getSelection());
+ wconfig.setAttribute(PerfPlugin.ATTR_ModuleSymbols, chkModuleSymbols.getSelection());
+ wconfig.setAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, chkHideUnresolvedSymbols.getSelection());
+ wconfig.setAttribute(PerfPlugin.ATTR_ShowSourceDisassembly, chkShowSourceDisassembly.getSelection());
+ wconfig.setAttribute(PerfPlugin.ATTR_ShowStat, chkShowStat.getSelection());
+ wconfig.setAttribute(PerfPlugin.ATTR_StatRunCount, statRunCount.getSelection());
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy wconfig) {
+ wconfig.setAttribute(PerfPlugin.ATTR_Kernel_Location, PerfPlugin.ATTR_Kernel_Location_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_Record_Realtime, PerfPlugin.ATTR_Record_Realtime_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_Record_Realtime_Priority, PerfPlugin.ATTR_Record_Realtime_Priority_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_Record_Verbose, PerfPlugin.ATTR_Record_Verbose_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_SourceLineNumbers, PerfPlugin.ATTR_SourceLineNumbers_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_Kernel_SourceLineNumbers, PerfPlugin.ATTR_Kernel_SourceLineNumbers_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_Multiplex, PerfPlugin.ATTR_Multiplex_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_ModuleSymbols, PerfPlugin.ATTR_ModuleSymbols_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_HideUnresolvedSymbols, PerfPlugin.ATTR_HideUnresolvedSymbols_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_ShowSourceDisassembly, PerfPlugin.ATTR_ShowSourceDisassembly_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_ShowStat, PerfPlugin.ATTR_ShowStat_default);
+ wconfig.setAttribute(PerfPlugin.ATTR_StatRunCount, PerfPlugin.ATTR_StatRunCount_default);
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMCommand.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMCommand.java
index 709bfb968e..29d97e4d81 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMCommand.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMCommand.java
@@ -12,22 +12,22 @@ package org.eclipse.linuxtools.internal.perf.model;
public class PMCommand extends TreeParent {
- public PMCommand(String name) {
- super(name, 100);
- /*
- * The underlying report truncates percentages in some cases
- * so taking a sum will not always give 100, but we know that
- * the only command that could have run is the binary we specified.
- */
- }
+ public PMCommand(String name) {
+ super(name, 100);
+ /*
+ * The underlying report truncates percentages in some cases
+ * so taking a sum will not always give 100, but we know that
+ * the only command that could have run is the binary we specified.
+ */
+ }
- @Override
- public String toString() {
- String prefix = "";
- if (getPercent() != -1) {
- prefix = getPercent() + "% (" + getFormattedSamples() + " samples) in ";
- }
- return prefix + getName();
- }
+ @Override
+ public String toString() {
+ String prefix = "";
+ if (getPercent() != -1) {
+ prefix = getPercent() + "% (" + getFormattedSamples() + " samples) in ";
+ }
+ return prefix + getName();
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMDso.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMDso.java
index 84694160c5..be7a8091ab 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMDso.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMDso.java
@@ -13,47 +13,47 @@ package org.eclipse.linuxtools.internal.perf.model;
import org.eclipse.linuxtools.internal.perf.model.PMFile;
public class PMDso extends TreeParent {
- private String path = null;
- private boolean kernel = false; //Is this DSO a kernel dso?
-
- public boolean isKernelDso() {
- return kernel;
- }
-
- public PMDso(String dsoName, boolean kernel) {
- super(dsoName, 0);
- this.kernel = kernel;
- }
+ private String path = null;
+ private boolean kernel = false; //Is this DSO a kernel dso?
- public PMFile getFile(String fileName) {
- //check if exists else make a new one.
- PMFile tmp = (PMFile) getChild(fileName);
- if (tmp != null) {
- } else {
- tmp = new PMFile(fileName);
- addChild(tmp);
- }
- return tmp;
- }
+ public boolean isKernelDso() {
+ return kernel;
+ }
- public void setPath(String filePath) {
- path = filePath;
- }
- @Override
- public String toString() {
- String prefix = ""; //$NON-NLS-1$
- if (getPercent() != -1) {
- prefix += getPercent() + "% (" + getFormattedSamples() + " samples) in "; //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (kernel == true) {
- prefix += "[k] "; //$NON-NLS-1$
- }
- if (path != null) {
- return prefix + getName() + " (at " + path + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- return prefix + getName();
- }
- public String getPath() {
- return path;
- }
+ public PMDso(String dsoName, boolean kernel) {
+ super(dsoName, 0);
+ this.kernel = kernel;
+ }
+
+ public PMFile getFile(String fileName) {
+ //check if exists else make a new one.
+ PMFile tmp = (PMFile) getChild(fileName);
+ if (tmp != null) {
+ } else {
+ tmp = new PMFile(fileName);
+ addChild(tmp);
+ }
+ return tmp;
+ }
+
+ public void setPath(String filePath) {
+ path = filePath;
+ }
+ @Override
+ public String toString() {
+ String prefix = ""; //$NON-NLS-1$
+ if (getPercent() != -1) {
+ prefix += getPercent() + "% (" + getFormattedSamples() + " samples) in "; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (kernel == true) {
+ prefix += "[k] "; //$NON-NLS-1$
+ }
+ if (path != null) {
+ return prefix + getName() + " (at " + path + ")"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return prefix + getName();
+ }
+ public String getPath() {
+ return path;
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMEvent.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMEvent.java
index 9cebdb969b..b17b920502 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMEvent.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMEvent.java
@@ -12,8 +12,8 @@ package org.eclipse.linuxtools.internal.perf.model;
public class PMEvent extends TreeParent {
- public PMEvent(String name) {
- super(name);
- }
+ public PMEvent(String name) {
+ super(name);
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMFile.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMFile.java
index a826fc404d..8c8d76dd11 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMFile.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMFile.java
@@ -11,23 +11,23 @@
package org.eclipse.linuxtools.internal.perf.model;
public class PMFile extends TreeParent {
- private String path;
-
- public PMFile(String fileName) {
- super(fileName, 0);
- path = fileName;
- }
+ private String path;
- public String getPath() {
- return this.path;
- }
-
- @Override
- public String toString() {
- String prefix = ""; //$NON-NLS-1$
- if (getPercent() != -1) {
- prefix = getPercent() + "% in "; //$NON-NLS-1$
- }
- return prefix + path;
- }
+ public PMFile(String fileName) {
+ super(fileName, 0);
+ path = fileName;
+ }
+
+ public String getPath() {
+ return this.path;
+ }
+
+ @Override
+ public String toString() {
+ String prefix = ""; //$NON-NLS-1$
+ if (getPercent() != -1) {
+ prefix = getPercent() + "% in "; //$NON-NLS-1$
+ }
+ return prefix + path;
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMLineRef.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMLineRef.java
index e41dc6688c..257b1aaf0f 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMLineRef.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMLineRef.java
@@ -11,19 +11,19 @@
package org.eclipse.linuxtools.internal.perf.model;
public class PMLineRef extends TreeParent {
- protected int ln;
+ protected int ln;
- public PMLineRef(int lineNum, float percent) {
- super(""+lineNum, percent); //$NON-NLS-1$
- ln = lineNum;
- }
+ public PMLineRef(int lineNum, float percent) {
+ super(""+lineNum, percent); //$NON-NLS-1$
+ ln = lineNum;
+ }
- public void addPercent(Float addpc) {
- setPercent(getPercent() + addpc);
- }
+ public void addPercent(Float addpc) {
+ setPercent(getPercent() + addpc);
+ }
- @Override
- public String toString() {
- return getPercent() + "% (" + getFormattedSamples() + " samples) on line " + ln; //$NON-NLS-1$ //$NON-NLS-2$
- }
+ @Override
+ public String toString() {
+ return getPercent() + "% (" + getFormattedSamples() + " samples) on line " + ln; //$NON-NLS-1$ //$NON-NLS-2$
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMStatEntry.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMStatEntry.java
index 66b3934b40..350518e783 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMStatEntry.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMStatEntry.java
@@ -14,204 +14,204 @@ package org.eclipse.linuxtools.internal.perf.model;
* Representation of a single entry in a perf stat report.
*/
public class PMStatEntry {
- // Samples of current event.
- private float samples;
-
- // Current event.
- private String event;
-
- // Metrics for current event.
- private float metrics;
-
- // Metrics' units.
- private String units;
-
- // Standard deviation of stats.
- private float deviation;
-
- // Scaling.
- private float scaling;
-
- // Types of relevant strings for a perf stat entry.
- public static enum Type {
- ENTRY_PATTERN, TIME_PATTERN, ENTRY_FORMAT, PERCENT_FORMAT, METRIC_FORMAT
- }
-
- // Reg-ex strings for elements in a perf stat entry.
- public static final String DECIMAL = "\\d+[\\.\\,\\d]*"; //$NON-NLS-1$
- public static final String PERCENTAGE = "(\\d+(\\.\\d+)?)\\%"; //$NON-NLS-1$
- public static final String SAMPLES = "(" + DECIMAL + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- public static final String EVENT = "(\\w+(\\-\\w+)*(:\\w+)?)";//$NON-NLS-1$
- public static final String METRICS = "(" + DECIMAL + ")"; //$NON-NLS-1$//$NON-NLS-2$
- public static final String UNITS = "([a-zA-Z\\/\\s\\%]*)"; //$NON-NLS-1$
- public static final String DELTA = "(\\(\\s\\+\\-\\s*" + PERCENTAGE + "\\s\\))"; //$NON-NLS-1$ //$NON-NLS-2$
- public static final String SCALE = "(\\[\\s*" + PERCENTAGE + "\\])"; //$NON-NLS-1$ //$NON-NLS-2$
- public static final String TIME_UNIT = "(seconds\\stime\\selapsed)"; //$NON-NLS-1$
- public static final String TIME = "seconds time elapsed"; //$NON-NLS-1$
-
- public PMStatEntry(float samples, String event, float metrics,
- String units, float deviation, float scaling) {
- this.samples = samples;
- this.event = event;
- this.metrics = metrics;
- this.units = units;
- this.deviation = deviation;
- this.scaling = scaling;
- }
-
- public float getSamples() {
- return samples;
- }
-
- public String getEvent() {
- return (event == null) ? "" : event; //$NON-NLS-1$
- }
-
-
- public float getMetrics() {
- return metrics;
- }
-
- public String getUnits() {
- return (units == null) ? "" : units.trim(); //$NON-NLS-1$
- }
-
- public float getDeviation() {
- return deviation;
- }
-
-
- public float getScaling() {
- return scaling;
- }
-
- public String getFormattedMetrics(){
- return String.format("%.3f", metrics); //$NON-NLS-1$
- }
-
- public String getFormattedDeviation(){
- return String.format("%.2f%%", deviation); //$NON-NLS-1$
- }
-
- @Override
- public boolean equals(Object entry) {
- PMStatEntry statEntry = (PMStatEntry) entry;
- if (statEntry == null
- || samples != statEntry.getSamples()
- || metrics != statEntry.getMetrics()
- || deviation != statEntry.getDeviation()
- || scaling != statEntry.getScaling()) {
- return false;
- }
-
- if (!getEvent().equals(statEntry.getEvent())
- || !getUnits().equals(statEntry.getUnits())) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Check if PMStatEntry refer to the same event.
- * @param entry PMStatEntry to check against
- * @return true if events are equals, false otherwise.
- */
- public boolean equalEvents(PMStatEntry entry) {
- String event = entry.getEvent();
- if (this.event != null && event != null) {
- return this.event.equals(event);
- }
- return false;
- }
-
- /**
- * Auto-generated hashCode method.
- */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + Float.floatToIntBits(deviation);
- result = prime * result + ((event == null) ? 0 : event.hashCode());
- result = prime * result + Float.floatToIntBits(metrics);
- result = prime * result + Float.floatToIntBits(samples);
- result = prime * result + Float.floatToIntBits(scaling);
- result = prime * result + ((units == null) ? 0 : units.hashCode());
- return result;
- }
-
- /**
- * Compare this PMStatEntry with the specified one, and return an object
- * with the result.
- *
- * @param entry PMStatEntry to compare against
- * @return a PMStatEntry representing the resulting comparison.
- */
- public PMStatEntry compare(PMStatEntry entry){
- float occurrenceDiff = entry.getSamples() - this.samples;
- float metricsDiff = entry.getMetrics() - this.metrics;
- float deviationDiff = entry.getDeviation() + this.deviation;
- float scalingDiff = entry.getScaling() + this.scaling;
-
- return new PMStatEntry(occurrenceDiff, event, metricsDiff, units, deviationDiff, scalingDiff);
- }
-
- /**
- * Return formatted String values of fields in a string array.
- *
- * @return String[] String array containing string value of fields.
- */
- public String[] toStringArray(){
- return new String[] { String.valueOf(samples),
- getEvent(),
- getFormattedMetrics(),
- getUnits(),
- getFormattedDeviation()};
- }
-
- /**
- * Get string related to specified type of perf stat entry:
- * <p>
- * ENTRY_PATTERN: - Regex for a generic entry.</br>
- * TIME_PATTERN: - Regex for total time entry.</br>
- * ENTRY_FORMAT: - Format string for a generic entry.
- * </p>
- *
- * @param type
- * @return
- */
- public static String getString(Type type) {
- String stringRes = ""; //$NON-NLS-1$
- switch (type) {
- case ENTRY_PATTERN:
- // samples, event, metrics, units, deviation, scaling
- stringRes = "^" + SAMPLES; //$NON-NLS-1$
- stringRes += "\\s" + EVENT; //$NON-NLS-1$
- stringRes += "\\s*(\\#\\s+" + METRICS + UNITS + ")?"; //$NON-NLS-1$ //$NON-NLS-2$
- stringRes += DELTA + "?"; //$NON-NLS-1$
- stringRes += "(\\s" + SCALE + ")?$"; //$NON-NLS-1$ //$NON-NLS-2$
-
- return stringRes;
- case TIME_PATTERN:
- // samples, time elapsed, deviation
- stringRes += "^" + SAMPLES; //$NON-NLS-1$
- stringRes += "\\s" + TIME_UNIT; //$NON-NLS-1$
- stringRes += "\\s+" + DELTA; //$NON-NLS-1$
-
- return stringRes;
- case ENTRY_FORMAT:
- // Stat entry format
- stringRes += " %%1$%1$1ds "; //$NON-NLS-1$
- stringRes += "%%2$-%2$1ds # "; //$NON-NLS-1$
- stringRes += "%%3$%3$1ds "; //$NON-NLS-1$
- stringRes += "%%4$-%4$1ds "; //$NON-NLS-1$
- stringRes += "( +- %%5$%5$1ds )\n"; //$NON-NLS-1$
-
- return stringRes;
- default:
- return stringRes;
- }
- }
+ // Samples of current event.
+ private float samples;
+
+ // Current event.
+ private String event;
+
+ // Metrics for current event.
+ private float metrics;
+
+ // Metrics' units.
+ private String units;
+
+ // Standard deviation of stats.
+ private float deviation;
+
+ // Scaling.
+ private float scaling;
+
+ // Types of relevant strings for a perf stat entry.
+ public static enum Type {
+ ENTRY_PATTERN, TIME_PATTERN, ENTRY_FORMAT, PERCENT_FORMAT, METRIC_FORMAT
+ }
+
+ // Reg-ex strings for elements in a perf stat entry.
+ public static final String DECIMAL = "\\d+[\\.\\,\\d]*"; //$NON-NLS-1$
+ public static final String PERCENTAGE = "(\\d+(\\.\\d+)?)\\%"; //$NON-NLS-1$
+ public static final String SAMPLES = "(" + DECIMAL + ")"; //$NON-NLS-1$ //$NON-NLS-2$
+ public static final String EVENT = "(\\w+(\\-\\w+)*(:\\w+)?)";//$NON-NLS-1$
+ public static final String METRICS = "(" + DECIMAL + ")"; //$NON-NLS-1$//$NON-NLS-2$
+ public static final String UNITS = "([a-zA-Z\\/\\s\\%]*)"; //$NON-NLS-1$
+ public static final String DELTA = "(\\(\\s\\+\\-\\s*" + PERCENTAGE + "\\s\\))"; //$NON-NLS-1$ //$NON-NLS-2$
+ public static final String SCALE = "(\\[\\s*" + PERCENTAGE + "\\])"; //$NON-NLS-1$ //$NON-NLS-2$
+ public static final String TIME_UNIT = "(seconds\\stime\\selapsed)"; //$NON-NLS-1$
+ public static final String TIME = "seconds time elapsed"; //$NON-NLS-1$
+
+ public PMStatEntry(float samples, String event, float metrics,
+ String units, float deviation, float scaling) {
+ this.samples = samples;
+ this.event = event;
+ this.metrics = metrics;
+ this.units = units;
+ this.deviation = deviation;
+ this.scaling = scaling;
+ }
+
+ public float getSamples() {
+ return samples;
+ }
+
+ public String getEvent() {
+ return (event == null) ? "" : event; //$NON-NLS-1$
+ }
+
+
+ public float getMetrics() {
+ return metrics;
+ }
+
+ public String getUnits() {
+ return (units == null) ? "" : units.trim(); //$NON-NLS-1$
+ }
+
+ public float getDeviation() {
+ return deviation;
+ }
+
+
+ public float getScaling() {
+ return scaling;
+ }
+
+ public String getFormattedMetrics(){
+ return String.format("%.3f", metrics); //$NON-NLS-1$
+ }
+
+ public String getFormattedDeviation(){
+ return String.format("%.2f%%", deviation); //$NON-NLS-1$
+ }
+
+ @Override
+ public boolean equals(Object entry) {
+ PMStatEntry statEntry = (PMStatEntry) entry;
+ if (statEntry == null
+ || samples != statEntry.getSamples()
+ || metrics != statEntry.getMetrics()
+ || deviation != statEntry.getDeviation()
+ || scaling != statEntry.getScaling()) {
+ return false;
+ }
+
+ if (!getEvent().equals(statEntry.getEvent())
+ || !getUnits().equals(statEntry.getUnits())) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Check if PMStatEntry refer to the same event.
+ * @param entry PMStatEntry to check against
+ * @return true if events are equals, false otherwise.
+ */
+ public boolean equalEvents(PMStatEntry entry) {
+ String event = entry.getEvent();
+ if (this.event != null && event != null) {
+ return this.event.equals(event);
+ }
+ return false;
+ }
+
+ /**
+ * Auto-generated hashCode method.
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + Float.floatToIntBits(deviation);
+ result = prime * result + ((event == null) ? 0 : event.hashCode());
+ result = prime * result + Float.floatToIntBits(metrics);
+ result = prime * result + Float.floatToIntBits(samples);
+ result = prime * result + Float.floatToIntBits(scaling);
+ result = prime * result + ((units == null) ? 0 : units.hashCode());
+ return result;
+ }
+
+ /**
+ * Compare this PMStatEntry with the specified one, and return an object
+ * with the result.
+ *
+ * @param entry PMStatEntry to compare against
+ * @return a PMStatEntry representing the resulting comparison.
+ */
+ public PMStatEntry compare(PMStatEntry entry){
+ float occurrenceDiff = entry.getSamples() - this.samples;
+ float metricsDiff = entry.getMetrics() - this.metrics;
+ float deviationDiff = entry.getDeviation() + this.deviation;
+ float scalingDiff = entry.getScaling() + this.scaling;
+
+ return new PMStatEntry(occurrenceDiff, event, metricsDiff, units, deviationDiff, scalingDiff);
+ }
+
+ /**
+ * Return formatted String values of fields in a string array.
+ *
+ * @return String[] String array containing string value of fields.
+ */
+ public String[] toStringArray(){
+ return new String[] { String.valueOf(samples),
+ getEvent(),
+ getFormattedMetrics(),
+ getUnits(),
+ getFormattedDeviation()};
+ }
+
+ /**
+ * Get string related to specified type of perf stat entry:
+ * <p>
+ * ENTRY_PATTERN: - Regex for a generic entry.</br>
+ * TIME_PATTERN: - Regex for total time entry.</br>
+ * ENTRY_FORMAT: - Format string for a generic entry.
+ * </p>
+ *
+ * @param type
+ * @return
+ */
+ public static String getString(Type type) {
+ String stringRes = ""; //$NON-NLS-1$
+ switch (type) {
+ case ENTRY_PATTERN:
+ // samples, event, metrics, units, deviation, scaling
+ stringRes = "^" + SAMPLES; //$NON-NLS-1$
+ stringRes += "\\s" + EVENT; //$NON-NLS-1$
+ stringRes += "\\s*(\\#\\s+" + METRICS + UNITS + ")?"; //$NON-NLS-1$ //$NON-NLS-2$
+ stringRes += DELTA + "?"; //$NON-NLS-1$
+ stringRes += "(\\s" + SCALE + ")?$"; //$NON-NLS-1$ //$NON-NLS-2$
+
+ return stringRes;
+ case TIME_PATTERN:
+ // samples, time elapsed, deviation
+ stringRes += "^" + SAMPLES; //$NON-NLS-1$
+ stringRes += "\\s" + TIME_UNIT; //$NON-NLS-1$
+ stringRes += "\\s+" + DELTA; //$NON-NLS-1$
+
+ return stringRes;
+ case ENTRY_FORMAT:
+ // Stat entry format
+ stringRes += " %%1$%1$1ds "; //$NON-NLS-1$
+ stringRes += "%%2$-%2$1ds # "; //$NON-NLS-1$
+ stringRes += "%%3$%3$1ds "; //$NON-NLS-1$
+ stringRes += "%%4$-%4$1ds "; //$NON-NLS-1$
+ stringRes += "( +- %%5$%5$1ds )\n"; //$NON-NLS-1$
+
+ return stringRes;
+ default:
+ return stringRes;
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMSymbol.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMSymbol.java
index b069cf3f36..4fbe9cce28 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMSymbol.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/PMSymbol.java
@@ -13,45 +13,45 @@ package org.eclipse.linuxtools.internal.perf.model;
import org.eclipse.linuxtools.internal.perf.model.PMLineRef;
public class PMSymbol extends TreeParent {
- private boolean pathConflictFound = false;
-
- public String getFunctionName() {
- String tmpName = getName();
- if (tmpName.startsWith("[")) { // filer out the "[.] " //$NON-NLS-1$
- tmpName = tmpName.substring(4);
- }
- int argloc = tmpName.indexOf("("); // and the (.... //$NON-NLS-1$
- if (argloc != -1) {
- tmpName = tmpName.substring(0,argloc);
- }
- return tmpName;
- }
-
- public PMSymbol(String symbolName, float pc, double samples) {
- super(symbolName, pc, samples);
- }
-
- public void addPercent(Integer lineNum, Float percent) { //Adds percent to a lineref within this symbol.
- PMLineRef current = (PMLineRef)getChild(lineNum.toString());
- if (current == null) {
- current = new PMLineRef(lineNum, percent);
- addChild(current);
- } else {
- current.addPercent(percent);
- }
- }
-
- @Override
- public String toString() {
- return getPercent()
- + "% (" + getFormattedSamples() + " samples) in " + getName() + (pathConflictFound ? "(Warning multiple paths found for this symbol!)" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- public void markConflict() {
- pathConflictFound = true;
- }
-
- public boolean conflicted() {
- return pathConflictFound;
- }
+ private boolean pathConflictFound = false;
+
+ public String getFunctionName() {
+ String tmpName = getName();
+ if (tmpName.startsWith("[")) { // filer out the "[.] " //$NON-NLS-1$
+ tmpName = tmpName.substring(4);
+ }
+ int argloc = tmpName.indexOf("("); // and the (.... //$NON-NLS-1$
+ if (argloc != -1) {
+ tmpName = tmpName.substring(0,argloc);
+ }
+ return tmpName;
+ }
+
+ public PMSymbol(String symbolName, float pc, double samples) {
+ super(symbolName, pc, samples);
+ }
+
+ public void addPercent(Integer lineNum, Float percent) { //Adds percent to a lineref within this symbol.
+ PMLineRef current = (PMLineRef)getChild(lineNum.toString());
+ if (current == null) {
+ current = new PMLineRef(lineNum, percent);
+ addChild(current);
+ } else {
+ current.addPercent(percent);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return getPercent()
+ + "% (" + getFormattedSamples() + " samples) in " + getName() + (pathConflictFound ? "(Warning multiple paths found for this symbol!)" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ public void markConflict() {
+ pathConflictFound = true;
+ }
+
+ public boolean conflicted() {
+ return pathConflictFound;
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/TreeParent.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/TreeParent.java
index a07c486847..33d5b73a11 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/TreeParent.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/model/TreeParent.java
@@ -14,141 +14,141 @@ import java.util.ArrayList;
import java.util.List;
public class TreeParent {
- private String name;
- private TreeParent parent;
- private List<TreeParent> children;
- private float percent = -1;
- private double samples = -1;
-
- public TreeParent(String name, float percent) {
- this.name = name;
- this.percent = percent;
- children = new ArrayList<>();
- }
-
- public TreeParent(String name, float percent, double samples) {
- this(name, percent);
- this.samples = samples;
- }
-
- public String getName() {
- return name;
- }
-
- public void setParent(TreeParent parent) {
- this.parent = parent;
- }
-
- public TreeParent getParent() {
- return parent;
- }
-
- @Override
- public String toString() {
- return getName() + " (" + getFormattedSamples() + " samples)"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- public Boolean equals(String s) {
- return getName().equals(s);
- }
-
- public float getPercent() {
- return percent;
- }
-
- public void setPercent(float percent) {
- this.percent = percent;
- }
-
- /**
- * Get the number of samples collected for this element.
- *
- * If this element is a child of PMSymbol (eg. PMLineRef) we should
- * calculate its samples using its given percentage and the number of
- * samples from its parent. If this element is a parent of PMSymbol we
- * should calculate its samples by accumulating all samples from its
- * children.
- *
- * @return the number of samples
- */
- private double getSamples () {
- // Child of PMSymbol, distribute samples by percentage
- if (this instanceof PMLineRef) {
- if (samples == -1) {
- samples = (int) (getParent().getSamples() * (getPercent() / 100));
- }
- } else {
- // Parent of PMSymbol, accumulate from children elements
- if (samples == -1) {
- int sampleSum = 0;
-
- for (TreeParent child : getChildren()) {
- sampleSum += child.getSamples();
- }
- samples = sampleSum;
- }
- }
-
- return samples;
- }
-
- public String getFormattedSamples () {
- double samples = getSamples();
- return (samples <= Integer.MAX_VALUE)
- ? String.format("%.0f", samples) //$NON-NLS-1$
- : String.format("%.4G", samples); //$NON-NLS-1$
- }
-
- public TreeParent(String name) {
- this.name = name;
- children = new ArrayList<>();
- }
-
- public void addChild(TreeParent child) {
- children.add(child);
- child.setParent(this);
- recalculatePercentage();
- }
-
- public TreeParent getChild(String name) {
- //check if it exists
- for(TreeParent t : children) {
- if (t.equals(name))
- return t;
- }
- return null;
- }
-
- public void removeChild(TreeParent child) {
- children.remove(child);
- child.setParent(null);
- recalculatePercentage();
- }
-
- public TreeParent [] getChildren() {
- return children.toArray(new TreeParent[children.size()]);
- }
-
- public boolean hasChildren() {
- return children.size() > 0;
- }
-
- public void clear() {
- children.clear();
- }
-
- private void recalculatePercentage() {
- if (getPercent() != -1 && (this instanceof PMDso || this instanceof PMFile)){
- percent = 0;
- // Re-sum its children percentages
- for (TreeParent c : getChildren()) {
- percent += c.getPercent();
- }
- // Tell its parent to re-sum too.
- if (getParent().getPercent() != -1) {
- getParent().recalculatePercentage();
- }
- }
- }
+ private String name;
+ private TreeParent parent;
+ private List<TreeParent> children;
+ private float percent = -1;
+ private double samples = -1;
+
+ public TreeParent(String name, float percent) {
+ this.name = name;
+ this.percent = percent;
+ children = new ArrayList<>();
+ }
+
+ public TreeParent(String name, float percent, double samples) {
+ this(name, percent);
+ this.samples = samples;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setParent(TreeParent parent) {
+ this.parent = parent;
+ }
+
+ public TreeParent getParent() {
+ return parent;
+ }
+
+ @Override
+ public String toString() {
+ return getName() + " (" + getFormattedSamples() + " samples)"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ public Boolean equals(String s) {
+ return getName().equals(s);
+ }
+
+ public float getPercent() {
+ return percent;
+ }
+
+ public void setPercent(float percent) {
+ this.percent = percent;
+ }
+
+ /**
+ * Get the number of samples collected for this element.
+ *
+ * If this element is a child of PMSymbol (eg. PMLineRef) we should
+ * calculate its samples using its given percentage and the number of
+ * samples from its parent. If this element is a parent of PMSymbol we
+ * should calculate its samples by accumulating all samples from its
+ * children.
+ *
+ * @return the number of samples
+ */
+ private double getSamples () {
+ // Child of PMSymbol, distribute samples by percentage
+ if (this instanceof PMLineRef) {
+ if (samples == -1) {
+ samples = (int) (getParent().getSamples() * (getPercent() / 100));
+ }
+ } else {
+ // Parent of PMSymbol, accumulate from children elements
+ if (samples == -1) {
+ int sampleSum = 0;
+
+ for (TreeParent child : getChildren()) {
+ sampleSum += child.getSamples();
+ }
+ samples = sampleSum;
+ }
+ }
+
+ return samples;
+ }
+
+ public String getFormattedSamples () {
+ double samples = getSamples();
+ return (samples <= Integer.MAX_VALUE)
+ ? String.format("%.0f", samples) //$NON-NLS-1$
+ : String.format("%.4G", samples); //$NON-NLS-1$
+ }
+
+ public TreeParent(String name) {
+ this.name = name;
+ children = new ArrayList<>();
+ }
+
+ public void addChild(TreeParent child) {
+ children.add(child);
+ child.setParent(this);
+ recalculatePercentage();
+ }
+
+ public TreeParent getChild(String name) {
+ //check if it exists
+ for(TreeParent t : children) {
+ if (t.equals(name))
+ return t;
+ }
+ return null;
+ }
+
+ public void removeChild(TreeParent child) {
+ children.remove(child);
+ child.setParent(null);
+ recalculatePercentage();
+ }
+
+ public TreeParent [] getChildren() {
+ return children.toArray(new TreeParent[children.size()]);
+ }
+
+ public boolean hasChildren() {
+ return children.size() > 0;
+ }
+
+ public void clear() {
+ children.clear();
+ }
+
+ private void recalculatePercentage() {
+ if (getPercent() != -1 && (this instanceof PMDso || this instanceof PMFile)){
+ percent = 0;
+ // Re-sum its children percentages
+ for (TreeParent c : getChildren()) {
+ percent += c.getPercent();
+ }
+ // Tell its parent to re-sum too.
+ if (getParent().getPercent() != -1) {
+ getParent().recalculatePercentage();
+ }
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigDelegate.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigDelegate.java
index 29f41b3151..725c2ddf24 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigDelegate.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigDelegate.java
@@ -72,234 +72,234 @@ import org.osgi.framework.Version;
public class PerfLaunchConfigDelegate extends AbstractCLaunchDelegate {
- private ConfigUtils configUtils;
- private static String OUTPUT_STR = "--output="; //$NON-NLS-1$
- private IPath binPath;
- private IPath workingDirPath;
- private IProject project;
+ private ConfigUtils configUtils;
+ private static String OUTPUT_STR = "--output="; //$NON-NLS-1$
+ private IPath binPath;
+ private IPath workingDirPath;
+ private IProject project;
- @Override
- protected String getPluginID() {
- return PerfPlugin.PLUGIN_ID;
- }
+ @Override
+ protected String getPluginID() {
+ return PerfPlugin.PLUGIN_ID;
+ }
- @Override
- public void launch(ILaunchConfiguration config, String mode,
- ILaunch launch, IProgressMonitor monitor) throws CoreException {
- try {
- this.configUtils = new ConfigUtils(config);
- project = configUtils.getProject();
- // check if Perf exists in $PATH
- if (! PerfCore.checkPerfInPath(project))
- {
- IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID, "Error: Perf was not found on PATH"); //$NON-NLS-1$
- throw new CoreException(status);
- }
- URI binURI = new URI(configUtils.getExecutablePath());
- binPath=Path.fromPortableString(binURI.toString());
- workingDirPath=Path.fromPortableString(Path.fromPortableString(binURI.toString()).removeLastSegments(2).toPortableString());
- PerfPlugin.getDefault().setWorkingDir(workingDirPath);
- if (config.getAttribute(PerfPlugin.ATTR_ShowStat,
- PerfPlugin.ATTR_ShowStat_default)) {
- showStat(config, launch);
- } else {
- URI exeURI = new URI(configUtils.getExecutablePath());
- String configWorkingDir = configUtils.getWorkingDirectory() + IPath.SEPARATOR;
- RemoteConnection exeRC = new RemoteConnection(exeURI);
- String perfPathString = RuntimeProcessFactory.getFactory().whichCommand(PerfPlugin.PERF_COMMAND, project);
- boolean copyExecutable = configUtils.getCopyExecutable();
- if (copyExecutable) {
- URI copyExeURI = new URI(configUtils.getCopyFromExecutablePath());
- RemoteConnection copyExeRC = new RemoteConnection(copyExeURI);
- IRemoteFileProxy copyExeRFP = copyExeRC.getRmtFileProxy();
- IFileStore copyExeFS = copyExeRFP.getResource(copyExeURI.getPath());
- IRemoteFileProxy exeRFP = exeRC.getRmtFileProxy();
- IFileStore exeFS = exeRFP.getResource(exeURI.getPath());
- IFileInfo exeFI = exeFS.fetchInfo();
- if (exeFI.isDirectory()) {
- // Assume the user wants to copy the file to the given directory, using
- // the same filename as the "copy from" executable.
- IPath copyExePath = Path.fromOSString(copyExeURI.getPath());
- IPath newExePath = Path.fromOSString(exeURI.getPath()).append(copyExePath.lastSegment());
- // update the exeURI with the new path.
- exeURI = new URI(exeURI.getScheme(), exeURI.getAuthority(), newExePath.toString(), exeURI.getQuery(), exeURI.getFragment());
- exeFS = exeRFP.getResource(exeURI.getPath());
- }
- copyExeFS.copy(exeFS, EFS.OVERWRITE | EFS.SHALLOW, new SubProgressMonitor(monitor, 1));
- // Note: assume that we don't need to create a new exeRC since the
- // scheme and authority remain the same between the original exeURI and the new one.
- }
- IPath remoteBinFile = Path.fromOSString(exeURI.getPath());
- IFileStore workingDir;
- URI workingDirURI = new URI(RemoteProxyManager.getInstance().getRemoteProjectLocation(project));
- RemoteConnection workingDirRC = new RemoteConnection(workingDirURI);
- IRemoteFileProxy workingDirRFP = workingDirRC.getRmtFileProxy();
- workingDir = workingDirRFP.getResource(workingDirURI.getPath());
- //Build the commandline string to run perf recording the given project
- String arguments[] = getProgramArgumentsArray( config ); //Program args from launch config.
- ArrayList<String> command = new ArrayList<>( 4 + arguments.length );
- Version perfVersion = PerfCore.getPerfVersion(config);
- command.addAll(Arrays.asList(PerfCore.getRecordString(config, perfVersion))); //Get the base commandline string (with flags/options based on config)
- command.add( remoteBinFile.toOSString() ); // Add the path to the executable
- command.set(0, perfPathString);
- command.add(2,OUTPUT_STR + configWorkingDir + PerfPlugin.PERF_DEFAULT_DATA);
- //Compile string
- command.addAll( Arrays.asList( arguments ) );
+ @Override
+ public void launch(ILaunchConfiguration config, String mode,
+ ILaunch launch, IProgressMonitor monitor) throws CoreException {
+ try {
+ this.configUtils = new ConfigUtils(config);
+ project = configUtils.getProject();
+ // check if Perf exists in $PATH
+ if (! PerfCore.checkPerfInPath(project))
+ {
+ IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID, "Error: Perf was not found on PATH"); //$NON-NLS-1$
+ throw new CoreException(status);
+ }
+ URI binURI = new URI(configUtils.getExecutablePath());
+ binPath=Path.fromPortableString(binURI.toString());
+ workingDirPath=Path.fromPortableString(Path.fromPortableString(binURI.toString()).removeLastSegments(2).toPortableString());
+ PerfPlugin.getDefault().setWorkingDir(workingDirPath);
+ if (config.getAttribute(PerfPlugin.ATTR_ShowStat,
+ PerfPlugin.ATTR_ShowStat_default)) {
+ showStat(config, launch);
+ } else {
+ URI exeURI = new URI(configUtils.getExecutablePath());
+ String configWorkingDir = configUtils.getWorkingDirectory() + IPath.SEPARATOR;
+ RemoteConnection exeRC = new RemoteConnection(exeURI);
+ String perfPathString = RuntimeProcessFactory.getFactory().whichCommand(PerfPlugin.PERF_COMMAND, project);
+ boolean copyExecutable = configUtils.getCopyExecutable();
+ if (copyExecutable) {
+ URI copyExeURI = new URI(configUtils.getCopyFromExecutablePath());
+ RemoteConnection copyExeRC = new RemoteConnection(copyExeURI);
+ IRemoteFileProxy copyExeRFP = copyExeRC.getRmtFileProxy();
+ IFileStore copyExeFS = copyExeRFP.getResource(copyExeURI.getPath());
+ IRemoteFileProxy exeRFP = exeRC.getRmtFileProxy();
+ IFileStore exeFS = exeRFP.getResource(exeURI.getPath());
+ IFileInfo exeFI = exeFS.fetchInfo();
+ if (exeFI.isDirectory()) {
+ // Assume the user wants to copy the file to the given directory, using
+ // the same filename as the "copy from" executable.
+ IPath copyExePath = Path.fromOSString(copyExeURI.getPath());
+ IPath newExePath = Path.fromOSString(exeURI.getPath()).append(copyExePath.lastSegment());
+ // update the exeURI with the new path.
+ exeURI = new URI(exeURI.getScheme(), exeURI.getAuthority(), newExePath.toString(), exeURI.getQuery(), exeURI.getFragment());
+ exeFS = exeRFP.getResource(exeURI.getPath());
+ }
+ copyExeFS.copy(exeFS, EFS.OVERWRITE | EFS.SHALLOW, new SubProgressMonitor(monitor, 1));
+ // Note: assume that we don't need to create a new exeRC since the
+ // scheme and authority remain the same between the original exeURI and the new one.
+ }
+ IPath remoteBinFile = Path.fromOSString(exeURI.getPath());
+ IFileStore workingDir;
+ URI workingDirURI = new URI(RemoteProxyManager.getInstance().getRemoteProjectLocation(project));
+ RemoteConnection workingDirRC = new RemoteConnection(workingDirURI);
+ IRemoteFileProxy workingDirRFP = workingDirRC.getRmtFileProxy();
+ workingDir = workingDirRFP.getResource(workingDirURI.getPath());
+ //Build the commandline string to run perf recording the given project
+ String arguments[] = getProgramArgumentsArray( config ); //Program args from launch config.
+ ArrayList<String> command = new ArrayList<>( 4 + arguments.length );
+ Version perfVersion = PerfCore.getPerfVersion(config);
+ command.addAll(Arrays.asList(PerfCore.getRecordString(config, perfVersion))); //Get the base commandline string (with flags/options based on config)
+ command.add( remoteBinFile.toOSString() ); // Add the path to the executable
+ command.set(0, perfPathString);
+ command.add(2,OUTPUT_STR + configWorkingDir + PerfPlugin.PERF_DEFAULT_DATA);
+ //Compile string
+ command.addAll( Arrays.asList( arguments ) );
- //Spawn the process
- String[] commandArray = command.toArray(new String[command.size()]);
- Process pProxy = RuntimeProcessFactory.getFactory().exec(commandArray, getEnvironment(config), workingDir, project);
- MessageConsole console = new MessageConsole("Perf Console", null); //$NON-NLS-1$
- console.activate();
- ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { console });
- MessageConsoleStream stream = console.newMessageStream();
+ //Spawn the process
+ String[] commandArray = command.toArray(new String[command.size()]);
+ Process pProxy = RuntimeProcessFactory.getFactory().exec(commandArray, getEnvironment(config), workingDir, project);
+ MessageConsole console = new MessageConsole("Perf Console", null); //$NON-NLS-1$
+ console.activate();
+ ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { console });
+ MessageConsoleStream stream = console.newMessageStream();
- if (pProxy != null) {
- try (BufferedReader error = new BufferedReader(
- new InputStreamReader(pProxy.getErrorStream()))) {
- String err = error.readLine();
- while (err != null) {
- stream.println(err);
- err = error.readLine();
- }
- }
- }
+ if (pProxy != null) {
+ try (BufferedReader error = new BufferedReader(
+ new InputStreamReader(pProxy.getErrorStream()))) {
+ String err = error.readLine();
+ while (err != null) {
+ stream.println(err);
+ err = error.readLine();
+ }
+ }
+ }
- /* This commented part is the basic method to run perf record without integrating into eclipse.
- String binCall = exePath.toOSString();
- for(String arg : arguments) {
- binCall.concat(" " + arg);
- }
- PerfCore.Run(binCall);*/
+ /* This commented part is the basic method to run perf record without integrating into eclipse.
+ String binCall = exePath.toOSString();
+ for(String arg : arguments) {
+ binCall.concat(" " + arg);
+ }
+ PerfCore.Run(binCall);*/
- pProxy.destroy();
- PrintStream print = null;
- if (config.getAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true)) {
- //Get the console to output to.
- //This may not be the best way to accomplish this but it shall do for now.
- ConsolePlugin plugin = ConsolePlugin.getDefault();
- IConsoleManager conMan = plugin.getConsoleManager();
- IConsole[] existing = conMan.getConsoles();
- IOConsole binaryOutCons = null;
+ pProxy.destroy();
+ PrintStream print = null;
+ if (config.getAttribute(IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true)) {
+ //Get the console to output to.
+ //This may not be the best way to accomplish this but it shall do for now.
+ ConsolePlugin plugin = ConsolePlugin.getDefault();
+ IConsoleManager conMan = plugin.getConsoleManager();
+ IConsole[] existing = conMan.getConsoles();
+ IOConsole binaryOutCons = null;
- //Find the console
- for(IConsole x : existing) {
- if (x.getName().contains(renderProcessLabel(commandArray[0]))) {
- binaryOutCons = (IOConsole)x;
- }
- }
- if ((binaryOutCons == null) && (existing.length != 0)) { //if can't be found get the most recent opened, this should probably never happen.
- if (existing[existing.length - 1] instanceof IOConsole)
- binaryOutCons = (IOConsole)existing[existing.length - 1];
- }
+ //Find the console
+ for(IConsole x : existing) {
+ if (x.getName().contains(renderProcessLabel(commandArray[0]))) {
+ binaryOutCons = (IOConsole)x;
+ }
+ }
+ if ((binaryOutCons == null) && (existing.length != 0)) { //if can't be found get the most recent opened, this should probably never happen.
+ if (existing[existing.length - 1] instanceof IOConsole)
+ binaryOutCons = (IOConsole)existing[existing.length - 1];
+ }
- //Get the printstream via the outputstream.
- //Get ouput stream
- OutputStream outputTo;
- if (binaryOutCons != null) {
- outputTo = binaryOutCons.newOutputStream();
- //Get the printstream for that console
- print = new PrintStream(outputTo);
- }
+ //Get the printstream via the outputstream.
+ //Get ouput stream
+ OutputStream outputTo;
+ if (binaryOutCons != null) {
+ outputTo = binaryOutCons.newOutputStream();
+ //Get the printstream for that console
+ print = new PrintStream(outputTo);
+ }
- for (int i = 0; i < command.size(); i++) {
- print.print(command.get(i) + " "); //$NON-NLS-1$
- }
+ for (int i = 0; i < command.size(); i++) {
+ print.print(command.get(i) + " "); //$NON-NLS-1$
+ }
- //Print Message
- print.println();
- print.println("Analysing recorded perf.data, please wait..."); //$NON-NLS-1$
- //Possibly should pass this (the console reference) on to PerfCore.Report if theres anything we ever want to spit out to user.
- }
- PerfCore.Report(config, getEnvironment(config), Path.fromOSString(configWorkingDir), monitor, null, print);
+ //Print Message
+ print.println();
+ print.println("Analysing recorded perf.data, please wait..."); //$NON-NLS-1$
+ //Possibly should pass this (the console reference) on to PerfCore.Report if theres anything we ever want to spit out to user.
+ }
+ PerfCore.Report(config, getEnvironment(config), Path.fromOSString(configWorkingDir), monitor, null, print);
- URI perfDataURI = null;
- IRemoteFileProxy proxy = null;
- perfDataURI = new URI(RemoteProxyManager.getInstance().getRemoteProjectLocation(project) + PerfPlugin.PERF_DEFAULT_DATA);
- proxy = RemoteProxyManager.getInstance().getFileProxy(perfDataURI);
- IFileStore perfDataFileStore = proxy.getResource(perfDataURI.getPath());
- IFileInfo info = perfDataFileStore.fetchInfo();
- info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true);
- perfDataFileStore.putInfo(info, EFS.SET_ATTRIBUTES, null);
+ URI perfDataURI = null;
+ IRemoteFileProxy proxy = null;
+ perfDataURI = new URI(RemoteProxyManager.getInstance().getRemoteProjectLocation(project) + PerfPlugin.PERF_DEFAULT_DATA);
+ proxy = RemoteProxyManager.getInstance().getFileProxy(perfDataURI);
+ IFileStore perfDataFileStore = proxy.getResource(perfDataURI.getPath());
+ IFileInfo info = perfDataFileStore.fetchInfo();
+ info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true);
+ perfDataFileStore.putInfo(info, EFS.SET_ATTRIBUTES, null);
- PerfCore.refreshView(renderProcessLabel(exeURI.getPath()));
- if (config.getAttribute(PerfPlugin.ATTR_ShowSourceDisassembly,
- PerfPlugin.ATTR_ShowSourceDisassembly_default)) {
- showSourceDisassembly(Path.fromPortableString(workingDirURI.toString() + IPath.SEPARATOR));
- }
+ PerfCore.refreshView(renderProcessLabel(exeURI.getPath()));
+ if (config.getAttribute(PerfPlugin.ATTR_ShowSourceDisassembly,
+ PerfPlugin.ATTR_ShowSourceDisassembly_default)) {
+ showSourceDisassembly(Path.fromPortableString(workingDirURI.toString() + IPath.SEPARATOR));
+ }
- }
- } catch (IOException e) {
- e.printStackTrace();
- abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
- } catch (RemoteConnectionException e) {
- e.printStackTrace();
- abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
- } catch (URISyntaxException e) {
- e.printStackTrace();
- abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
- }
- }
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
+ } catch (RemoteConnectionException e) {
+ e.printStackTrace();
+ abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
+ } catch (URISyntaxException e) {
+ e.printStackTrace();
+ abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
+ }
+ }
- /**
- * Show source disassembly view.
- * @param workingDir working directory.
- */
- private void showSourceDisassembly(IPath workingDir) {
- String title = renderProcessLabel(workingDir.toPortableString() + PerfPlugin.PERF_DEFAULT_DATA);
- SourceDisassemblyData sdData = new SourceDisassemblyData(title, workingDir, project);
- sdData.parse();
- PerfPlugin.getDefault().setSourceDisassemblyData(sdData);
- SourceDisassemblyView.refreshView();
- }
+ /**
+ * Show source disassembly view.
+ * @param workingDir working directory.
+ */
+ private void showSourceDisassembly(IPath workingDir) {
+ String title = renderProcessLabel(workingDir.toPortableString() + PerfPlugin.PERF_DEFAULT_DATA);
+ SourceDisassemblyData sdData = new SourceDisassemblyData(title, workingDir, project);
+ sdData.parse();
+ PerfPlugin.getDefault().setSourceDisassemblyData(sdData);
+ SourceDisassemblyView.refreshView();
+ }
- /**
- * Show statistics view.
- * @param config launch configuration
- * @param launch launch
- * @throws CoreException
- */
- private void showStat(ILaunchConfiguration config, ILaunch launch)
- throws CoreException {
- // Build the command line string
- String arguments[] = getProgramArgumentsArray(config);
+ /**
+ * Show statistics view.
+ * @param config launch configuration
+ * @param launch launch
+ * @throws CoreException
+ */
+ private void showStat(ILaunchConfiguration config, ILaunch launch)
+ throws CoreException {
+ // Build the command line string
+ String arguments[] = getProgramArgumentsArray(config);
- // Get working directory
- int runCount = config.getAttribute(PerfPlugin.ATTR_StatRunCount,
- PerfPlugin.ATTR_StatRunCount_default);
- StringBuffer args = new StringBuffer();
- for (String arg : arguments) {
- args.append(arg);
- args.append(" "); //$NON-NLS-1$
- }
- URI binURI = null;
- try {
- binURI = new URI(binPath.toPortableString());
- } catch (URISyntaxException e) {
- MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
- }
- Object[] titleArgs = new Object[]{binURI.getPath(), args.toString(), String.valueOf(runCount)};
- String title = renderProcessLabel(MessageFormat.format(Messages.PerfLaunchConfigDelegate_stat_title, titleArgs));
+ // Get working directory
+ int runCount = config.getAttribute(PerfPlugin.ATTR_StatRunCount,
+ PerfPlugin.ATTR_StatRunCount_default);
+ StringBuffer args = new StringBuffer();
+ for (String arg : arguments) {
+ args.append(arg);
+ args.append(" "); //$NON-NLS-1$
+ }
+ URI binURI = null;
+ try {
+ binURI = new URI(binPath.toPortableString());
+ } catch (URISyntaxException e) {
+ MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError);
+ }
+ Object[] titleArgs = new Object[]{binURI.getPath(), args.toString(), String.valueOf(runCount)};
+ String title = renderProcessLabel(MessageFormat.format(Messages.PerfLaunchConfigDelegate_stat_title, titleArgs));
- List<String> configEvents = config.getAttribute(PerfPlugin.ATTR_SelectedEvents,
- PerfPlugin.ATTR_SelectedEvents_default);
+ List<String> configEvents = config.getAttribute(PerfPlugin.ATTR_SelectedEvents,
+ PerfPlugin.ATTR_SelectedEvents_default);
- String[] statEvents = new String [] {};
+ String[] statEvents = new String [] {};
- if(!config.getAttribute(PerfPlugin.ATTR_DefaultEvent, PerfPlugin.ATTR_DefaultEvent_default)){
- // gather selected events
- statEvents = (configEvents == null) ? statEvents : configEvents.toArray(new String[]{});
- }
+ if(!config.getAttribute(PerfPlugin.ATTR_DefaultEvent, PerfPlugin.ATTR_DefaultEvent_default)){
+ // gather selected events
+ statEvents = (configEvents == null) ? statEvents : configEvents.toArray(new String[]{});
+ }
- StatData sd = new StatData(title, workingDirPath, binURI.getPath(), arguments, runCount, statEvents, project);
- sd.setLaunch(launch);
- sd.parse();
- PerfPlugin.getDefault().setStatData(sd);
- sd.updateStatData();
- StatView.refreshView();
- }
+ StatData sd = new StatData(title, workingDirPath, binURI.getPath(), arguments, runCount, statEvents, project);
+ sd.setLaunch(launch);
+ sd.parse();
+ PerfPlugin.getDefault().setStatData(sd);
+ sd.updateStatData();
+ StatView.refreshView();
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigurationTabGroup.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigurationTabGroup.java
index a0d0e2da92..652b428215 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigurationTabGroup.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfLaunchConfigurationTabGroup.java
@@ -18,8 +18,8 @@ import org.eclipse.linuxtools.internal.perf.launch.PerfEventsTab;
import org.eclipse.linuxtools.profiling.launch.RemoteProxyProfileLaunchConfigurationTabGroup;
public class PerfLaunchConfigurationTabGroup extends RemoteProxyProfileLaunchConfigurationTabGroup {
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- return new AbstractLaunchConfigurationTab[] { new PerfOptionsTab(), new PerfEventsTab() };
- }
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ return new AbstractLaunchConfigurationTab[] { new PerfOptionsTab(), new PerfEventsTab() };
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfOptionsTab.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfOptionsTab.java
index c9c6ef9253..6d423ad17f 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfOptionsTab.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/remote/launch/PerfOptionsTab.java
@@ -8,7 +8,7 @@
*
* Contributors:
* Keith Seitz <keiths@redhat.com> - initial API and implementation
- * Kent Sebastian <ksebasti@redhat.com> -
+ * Kent Sebastian <ksebasti@redhat.com> -
* Thavidu Ranatunga (IBM) - derived from
* org.eclipse.linuxtools.oprofile.launch.configuration.OprofileSetupTab
*******************************************************************************/
@@ -18,19 +18,19 @@ import org.eclipse.debug.core.ILaunchConfiguration;
public class PerfOptionsTab extends org.eclipse.linuxtools.internal.perf.launch.PerfOptionsTab {
- private Exception ex;
+ private Exception ex;
- @Override
- public void initializeFrom(ILaunchConfiguration config) {
- super.initializeFrom(config);
- }
+ @Override
+ public void initializeFrom(ILaunchConfiguration config) {
+ super.initializeFrom(config);
+ }
- @Override
- public boolean isValid (ILaunchConfiguration config) {
- if (ex != null) {
- setErrorMessage(ex.getLocalizedMessage());
- return false;
- }
- return super.isValid(config);
- }
+ @Override
+ public boolean isValid (ILaunchConfiguration config) {
+ if (ex != null) {
+ setErrorMessage(ex.getLocalizedMessage());
+ return false;
+ }
+ return super.isValid(config);
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfDoubleClickAction.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfDoubleClickAction.java
index 8e23a80fb6..8d8d5a4fb3 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfDoubleClickAction.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfDoubleClickAction.java
@@ -31,49 +31,49 @@ import org.eclipse.linuxtools.profiling.ui.ProfileUIUtils;
*/
public class PerfDoubleClickAction extends Action {
- private TreeViewer viewer;
+ private TreeViewer viewer;
- public PerfDoubleClickAction(TreeViewer v) {
- viewer = v;
- }
- @Override
- public void run() {
- ISelection selection = viewer.getSelection();
- Object obj = ((IStructuredSelection)selection).getFirstElement();
+ public PerfDoubleClickAction(TreeViewer v) {
+ viewer = v;
+ }
+ @Override
+ public void run() {
+ ISelection selection = viewer.getSelection();
+ Object obj = ((IStructuredSelection)selection).getFirstElement();
- try {
- if (obj instanceof PMLineRef) {
- // Open in editor
- PMLineRef line = (PMLineRef) obj;
- PMFile file = (PMFile) ((PMSymbol) line.getParent()).getParent();
- ProfileUIUtils.openEditorAndSelect(file.getPath(),Integer.parseInt(line.getName()));
- } else if (obj instanceof PMFile) {
- PMFile file = (PMFile) obj;
- ProfileUIUtils.openEditorAndSelect(file.getName(), 1);
- } else if (obj instanceof PMSymbol) {
- PMSymbol sym = (PMSymbol) obj;
- PMFile file = (PMFile) sym.getParent();
- PMDso dso = (PMDso) file.getParent();
+ try {
+ if (obj instanceof PMLineRef) {
+ // Open in editor
+ PMLineRef line = (PMLineRef) obj;
+ PMFile file = (PMFile) ((PMSymbol) line.getParent()).getParent();
+ ProfileUIUtils.openEditorAndSelect(file.getPath(),Integer.parseInt(line.getName()));
+ } else if (obj instanceof PMFile) {
+ PMFile file = (PMFile) obj;
+ ProfileUIUtils.openEditorAndSelect(file.getName(), 1);
+ } else if (obj instanceof PMSymbol) {
+ PMSymbol sym = (PMSymbol) obj;
+ PMFile file = (PMFile) sym.getParent();
+ PMDso dso = (PMDso) file.getParent();
- if (file.getName().equals(PerfPlugin.STRINGS_UnfiledSymbols))
- return; // Don't try to do anything if we don't know where or what the symbol is.
+ if (file.getName().equals(PerfPlugin.STRINGS_UnfiledSymbols))
+ return; // Don't try to do anything if we don't know where or what the symbol is.
- String binaryPath = dso.getPath();
- ICProject project;
- project = ProfileUIUtils.findCProjectWithAbsolutePath(binaryPath);
- Map<String, int[]> map = ProfileUIUtils.findFunctionsInProject(project, sym.getFunctionName(), -1, file.getPath(), true);
- boolean bFound = false;
- for (Map.Entry<String, int[]> entry : map.entrySet()) {
- ProfileUIUtils.openEditorAndSelect(entry.getKey(), entry.getValue()[0], entry.getValue()[1]);
- bFound = true;
- }
- if (!bFound) {
- ProfileUIUtils.openEditorAndSelect(file.getPath(), 1);
- }
- }
- // if we encounter an exception, act as though no corresponding source exists
- } catch (NumberFormatException|BadLocationException|CoreException e) {
- }
- }
+ String binaryPath = dso.getPath();
+ ICProject project;
+ project = ProfileUIUtils.findCProjectWithAbsolutePath(binaryPath);
+ Map<String, int[]> map = ProfileUIUtils.findFunctionsInProject(project, sym.getFunctionName(), -1, file.getPath(), true);
+ boolean bFound = false;
+ for (Map.Entry<String, int[]> entry : map.entrySet()) {
+ ProfileUIUtils.openEditorAndSelect(entry.getKey(), entry.getValue()[0], entry.getValue()[1]);
+ bFound = true;
+ }
+ if (!bFound) {
+ ProfileUIUtils.openEditorAndSelect(file.getPath(), 1);
+ }
+ }
+ // if we encounter an exception, act as though no corresponding source exists
+ } catch (NumberFormatException|BadLocationException|CoreException e) {
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfProfileView.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfProfileView.java
index 4b3fd0a43c..22f789928a 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfProfileView.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfProfileView.java
@@ -35,105 +35,105 @@ import org.eclipse.ui.part.ViewPart;
public class PerfProfileView extends ViewPart {
- /**
- * The ID of the view as specified by the extension.
- */
- public static final String ID = "org.eclipse.linuxtools.internal.perf.views.ProfileView"; //$NON-NLS-1$
-
- private TreeViewer viewer;
- private DrillDownAdapter drillDownAdapter;
- private Action doubleClickAction;
-
- static class NameSorter extends ViewerSorter {
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- return (((TreeParent) e1).getPercent()
- <= ((TreeParent) e2).getPercent()) ? 1 : -1;
- }
- }
-
- /**
- * This is a callback that will allow us
- * to create the viewer and initialize it.
- */
- @Override
- public void createPartControl(Composite parent) {
- viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- drillDownAdapter = new DrillDownAdapter(viewer);
- viewer.setContentProvider(new PerfViewContentProvider());
-
- viewer.setLabelProvider(new PerfViewLabelProvider());
- viewer.setSorter(new NameSorter());
-
- // Create the help context id for the viewer's control
- PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "org.eclipse.linuxtools.internal.perf.viewer"); //$NON-NLS-1$
- hookContextMenu();
- hookDoubleClickAction();
- contributeToActionBars();
- }
-
- public void refreshModel() {
- viewer.setInput(PerfPlugin.getDefault().getModelRoot());
- viewer.refresh();
- }
-
- private void hookContextMenu() {
- MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
- menuMgr.setRemoveAllWhenShown(true);
- menuMgr.addMenuListener(new IMenuListener() {
- @Override
- public void menuAboutToShow(IMenuManager manager) {
- PerfProfileView.this.fillContextMenu(manager);
- }
- });
- Menu menu = menuMgr.createContextMenu(viewer.getControl());
- viewer.getControl().setMenu(menu);
- getSite().registerContextMenu(menuMgr, viewer);
- }
-
- private void contributeToActionBars() {
- IActionBars bars = getViewSite().getActionBars();
- fillLocalPullDown(bars.getMenuManager());
- fillLocalToolBar(bars.getToolBarManager());
- }
-
- private void fillLocalPullDown(IMenuManager manager) {
- }
-
- private void fillContextMenu(IMenuManager manager) {
- drillDownAdapter.addNavigationActions(manager);
- // Other plug-ins can contribute there actions here
- manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
- }
-
- private void fillLocalToolBar(IToolBarManager manager) {
- drillDownAdapter.addNavigationActions(manager);
- }
-
- private void hookDoubleClickAction() {
- doubleClickAction = new PerfDoubleClickAction(viewer);
- viewer.addDoubleClickListener(new IDoubleClickListener() {
- @Override
- public void doubleClick(DoubleClickEvent event) {
- doubleClickAction.run();
- }
- });
- }
-
- public TreeViewer getTreeViewer () {
- return viewer;
- }
-
- /**
- * Passing the focus request to the viewer's control.
- */
- @Override
- public void setFocus() {
- viewer.getControl().setFocus();
- }
-
- @Override
- public void setContentDescription (String name) {
- super.setContentDescription(name);
- }
+ /**
+ * The ID of the view as specified by the extension.
+ */
+ public static final String ID = "org.eclipse.linuxtools.internal.perf.views.ProfileView"; //$NON-NLS-1$
+
+ private TreeViewer viewer;
+ private DrillDownAdapter drillDownAdapter;
+ private Action doubleClickAction;
+
+ static class NameSorter extends ViewerSorter {
+ @Override
+ public int compare(Viewer viewer, Object e1, Object e2) {
+ return (((TreeParent) e1).getPercent()
+ <= ((TreeParent) e2).getPercent()) ? 1 : -1;
+ }
+ }
+
+ /**
+ * This is a callback that will allow us
+ * to create the viewer and initialize it.
+ */
+ @Override
+ public void createPartControl(Composite parent) {
+ viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
+ drillDownAdapter = new DrillDownAdapter(viewer);
+ viewer.setContentProvider(new PerfViewContentProvider());
+
+ viewer.setLabelProvider(new PerfViewLabelProvider());
+ viewer.setSorter(new NameSorter());
+
+ // Create the help context id for the viewer's control
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "org.eclipse.linuxtools.internal.perf.viewer"); //$NON-NLS-1$
+ hookContextMenu();
+ hookDoubleClickAction();
+ contributeToActionBars();
+ }
+
+ public void refreshModel() {
+ viewer.setInput(PerfPlugin.getDefault().getModelRoot());
+ viewer.refresh();
+ }
+
+ private void hookContextMenu() {
+ MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
+ menuMgr.setRemoveAllWhenShown(true);
+ menuMgr.addMenuListener(new IMenuListener() {
+ @Override
+ public void menuAboutToShow(IMenuManager manager) {
+ PerfProfileView.this.fillContextMenu(manager);
+ }
+ });
+ Menu menu = menuMgr.createContextMenu(viewer.getControl());
+ viewer.getControl().setMenu(menu);
+ getSite().registerContextMenu(menuMgr, viewer);
+ }
+
+ private void contributeToActionBars() {
+ IActionBars bars = getViewSite().getActionBars();
+ fillLocalPullDown(bars.getMenuManager());
+ fillLocalToolBar(bars.getToolBarManager());
+ }
+
+ private void fillLocalPullDown(IMenuManager manager) {
+ }
+
+ private void fillContextMenu(IMenuManager manager) {
+ drillDownAdapter.addNavigationActions(manager);
+ // Other plug-ins can contribute there actions here
+ manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
+ }
+
+ private void fillLocalToolBar(IToolBarManager manager) {
+ drillDownAdapter.addNavigationActions(manager);
+ }
+
+ private void hookDoubleClickAction() {
+ doubleClickAction = new PerfDoubleClickAction(viewer);
+ viewer.addDoubleClickListener(new IDoubleClickListener() {
+ @Override
+ public void doubleClick(DoubleClickEvent event) {
+ doubleClickAction.run();
+ }
+ });
+ }
+
+ public TreeViewer getTreeViewer () {
+ return viewer;
+ }
+
+ /**
+ * Passing the focus request to the viewer's control.
+ */
+ @Override
+ public void setFocus() {
+ viewer.getControl().setFocus();
+ }
+
+ @Override
+ public void setContentDescription (String name) {
+ super.setContentDescription(name);
+ }
} \ No newline at end of file
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfViewContentProvider.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfViewContentProvider.java
index 97016c0efc..6d86fac214 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfViewContentProvider.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfViewContentProvider.java
@@ -15,40 +15,40 @@ import org.eclipse.jface.viewers.Viewer;
import org.eclipse.linuxtools.internal.perf.model.TreeParent;
public class PerfViewContentProvider implements ITreeContentProvider {
-
- @Override
- public void inputChanged(Viewer v, Object oldInput, Object newInput) {
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public Object[] getElements(Object parent) {
- return getChildren(parent);
- }
-
- @Override
- public Object getParent(Object child) {
- if (child instanceof TreeParent) {
- return ((TreeParent) child).getParent();
- }
- return null;
- }
-
- @Override
- public Object[] getChildren(Object parent) {
- if (parent instanceof TreeParent) {
- return ((TreeParent) parent).getChildren();
- }
- return new Object[0];
- }
-
- @Override
- public boolean hasChildren(Object parent) {
- if (parent instanceof TreeParent)
- return ((TreeParent) parent).hasChildren();
- return false;
- }
+
+ @Override
+ public void inputChanged(Viewer v, Object oldInput, Object newInput) {
+ }
+
+ @Override
+ public void dispose() {
+ }
+
+ @Override
+ public Object[] getElements(Object parent) {
+ return getChildren(parent);
+ }
+
+ @Override
+ public Object getParent(Object child) {
+ if (child instanceof TreeParent) {
+ return ((TreeParent) child).getParent();
+ }
+ return null;
+ }
+
+ @Override
+ public Object[] getChildren(Object parent) {
+ if (parent instanceof TreeParent) {
+ return ((TreeParent) parent).getChildren();
+ }
+ return new Object[0];
+ }
+
+ @Override
+ public boolean hasChildren(Object parent) {
+ if (parent instanceof TreeParent)
+ return ((TreeParent) parent).hasChildren();
+ return false;
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfViewLabelProvider.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfViewLabelProvider.java
index fc1aaac166..0ad73a11ab 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfViewLabelProvider.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/PerfViewLabelProvider.java
@@ -24,36 +24,36 @@ import org.eclipse.ui.PlatformUI;
public class PerfViewLabelProvider extends LabelProvider {
- @Override
- public String getText(Object obj) {
- return obj.toString();
- }
- @Override
- public Image getImage(Object obj) {
- String imageKey;
+ @Override
+ public String getText(Object obj) {
+ return obj.toString();
+ }
+ @Override
+ public Image getImage(Object obj) {
+ String imageKey;
- if (obj instanceof PMDso) {
- imageKey = "icons/dso.gif"; //$NON-NLS-1$
- } else if (obj instanceof PMSymbol) {
- imageKey = "icons/symbol.gif"; //$NON-NLS-1$
- if (((PMSymbol)obj).conflicted())
- return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_ERROR_TSK);
- } else if (obj instanceof PMLineRef) {
- imageKey = "icons/line.gif"; //$NON-NLS-1$
- } else if (obj instanceof PMEvent) {
- imageKey = "icons/event.gif"; //$NON-NLS-1$
- } else if (obj instanceof PMFile) {
- imageKey = "icons/file.gif"; //$NON-NLS-1$
- if (((PMFile)obj).getName().equals(PerfPlugin.STRINGS_MultipleFilesForSymbol)) {
- return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_ERROR_TSK);
- }
- } else if (obj instanceof TreeParent) {
- imageKey = ISharedImages.IMG_OBJ_FOLDER;
- return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
- } else {
- imageKey = ISharedImages.IMG_OBJ_ELEMENT;
- return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
- }
- return PerfPlugin.getImageDescriptor(imageKey).createImage();
- }
+ if (obj instanceof PMDso) {
+ imageKey = "icons/dso.gif"; //$NON-NLS-1$
+ } else if (obj instanceof PMSymbol) {
+ imageKey = "icons/symbol.gif"; //$NON-NLS-1$
+ if (((PMSymbol)obj).conflicted())
+ return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_ERROR_TSK);
+ } else if (obj instanceof PMLineRef) {
+ imageKey = "icons/line.gif"; //$NON-NLS-1$
+ } else if (obj instanceof PMEvent) {
+ imageKey = "icons/event.gif"; //$NON-NLS-1$
+ } else if (obj instanceof PMFile) {
+ imageKey = "icons/file.gif"; //$NON-NLS-1$
+ if (((PMFile)obj).getName().equals(PerfPlugin.STRINGS_MultipleFilesForSymbol)) {
+ return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_ERROR_TSK);
+ }
+ } else if (obj instanceof TreeParent) {
+ imageKey = ISharedImages.IMG_OBJ_FOLDER;
+ return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
+ } else {
+ imageKey = ISharedImages.IMG_OBJ_ELEMENT;
+ return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
+ }
+ return PerfPlugin.getImageDescriptor(imageKey).createImage();
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/ReportComparisonView.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/ReportComparisonView.java
index 8c3e2b37eb..f6b46db492 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/ReportComparisonView.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/ReportComparisonView.java
@@ -55,200 +55,200 @@ import org.eclipse.ui.PlatformUI;
*/
public class ReportComparisonView extends Viewer {
- // Color values constants
- private static final Color BLACK = new Color(Display.getDefault(), 0, 0, 0);
- private static final Color RED = new Color(Display.getDefault(), 150, 0, 0);
- private static final Color GREEN = new Color(Display.getDefault(), 0, 50, 0);
- private static final Color LIGHT_GREEN = new Color(Display.getDefault(), 0, 105, 0);
- private static final Color ORANGE = new Color(Display.getDefault(), 150, 100, 0);
-
- // Regex for a generic entry in a perf comparison report.
- private static final String DIFF_ENTRY = "\\s+(\\d+(\\.\\d+)?)\\%\\s+([\\+\\-]?\\d+(\\.\\d+)?)\\%.*"; //$NON-NLS-1$
-
- private Composite fComposite;
- private ICompareInput fInput;
-
- // Comparison result.
- private StyledText result;
- private Label reverseLabel;
- private boolean reverse;
-
- public ReportComparisonView (Composite parent, CompareConfiguration config) {
- fComposite = new Composite (parent, SWT.NONE);
- fComposite.setLayout(new GridLayout(2, false));
- fComposite.setData(CompareUI.COMPARE_VIEWER_TITLE, Messages.ReportComparisonView_label);
-
- reverseLabel = new Label(fComposite, SWT.NONE);
- reverseLabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false));
- reverseLabel.setText(Messages.StatComparisonView_reversedLabel);
- reverseLabel.setVisible(false);
-
- final Button reverse = new Button(fComposite, SWT.TOGGLE);
- reverse.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_ELCL_SYNCED));
- reverse.setToolTipText(Messages.StatComparisonView_reverseToolTip);
- reverse.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- reverse.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- toggleReverse();
- setInput(fInput);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- result = new StyledText(fComposite, SWT.V_SCROLL | SWT.H_SCROLL);
- result.setAlwaysShowScrollBars(false);
- GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
- gd.horizontalSpan = 2;
- result.setLayoutData(gd);
- result.setEditable(false);
- }
-
- /**
- * Set properties for StlyedText widget.
- * @param input String StyledText content.
- */
- private void setStyledText(String input) {
- result.setText(input);
- result.setJustify(true);
- result.setAlignment(SWT.LEFT);
-
- result.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT));
-
- List<StyleRange> styles = new ArrayList<>();
- int ptr = 0;
- String[] lines = input.split("\n"); //$NON-NLS-1$
-
- for(String line : lines){
- if (Pattern.matches(DIFF_ENTRY, line)) {
- Matcher m = Pattern.compile(DIFF_ENTRY).matcher(line);
- if (m.matches() && m.group(1) != null && m.group(3) != null) {
- try {
- float baseline = Float.parseFloat(m.group(1).trim());
- float delta = Float.parseFloat(m.group(3).trim());
- if (baseline > 1 && Math.abs(delta) > 1) {
- StyleRange curStyleRange = new StyleRange(ptr, line.length(), BLACK, null);
- if (delta < 0 ) {
- curStyleRange = delta < -5 ? new StyleRange(ptr, line.length(), LIGHT_GREEN, null) :
- new StyleRange(ptr, line.length(), GREEN, null);
- } else {
- curStyleRange = delta < 5 ? new StyleRange(ptr, line .length(), ORANGE, null) :
- new StyleRange(ptr, line.length(), RED, null);
- }
- styles.add(curStyleRange);
- }
- } catch (NumberFormatException e) {
- // set no StyleRange
- }
- }
- }
- // + 1 to skip over the '\n' at EOL that the tokenizer eats
- ptr += line.length() + 1;
- }
-
- result.setStyleRanges(styles.toArray(new StyleRange[0]));
- }
-
- @Override
- public Control getControl() {
- return fComposite;
- }
-
- @Override
- public Object getInput() {
- return fInput;
- }
-
- @Override
- public ISelection getSelection() {
- return null;
- }
-
- @Override
- public void refresh() {
- }
-
- @Override
- public void setInput(Object input) {
- if (input instanceof ICompareInput) {
- fInput = (ICompareInput) input;
-
- if (fInput.getAncestor() != null ||
- (fInput.getKind() & Differencer.DIRECTION_MASK) != 0) {
- setStyledText(Messages.CompUnsupported);
- } else {
- // get corresponding files
- IPath oldDatum;
- IPath newDatum;
- IProject proj = null;
-
- if (fInput.getLeft() instanceof ResourceNode) {
- ResourceNode left = (ResourceNode) fInput.getLeft();
- IResource oldData = left.getResource();
- oldDatum = oldData.getLocation();
- proj = oldData.getProject();
- } else {
- IEncodedStreamContentAccessor lStream = (IEncodedStreamContentAccessor) fInput.getLeft();
- oldDatum = generateTempFile(lStream);
- }
-
- if (fInput.getRight() instanceof ResourceNode) {
- ResourceNode right = (ResourceNode) fInput.getRight();
- IResource newData = right.getResource();
- newDatum = newData.getLocation();
- proj = newData.getProject();
- } else {
- IEncodedStreamContentAccessor rStream = (IEncodedStreamContentAccessor) fInput.getRight();
- newDatum = generateTempFile(rStream);
- }
-
- String title = MessageFormat.format(Messages.ContentDescription_0,
- new Object[] { oldDatum.toFile().getName(), newDatum.toFile().getName() });
-
- // create comparison data and run comparison.
- ReportComparisonData diffData;
- if (reverse) {
- diffData = new ReportComparisonData(title, oldDatum, newDatum, proj);
- } else {
- diffData = new ReportComparisonData(title, newDatum, oldDatum, proj);
- }
- diffData.parse();
-
- setStyledText(diffData.getPerfData());
- }
- }
-
- fComposite.layout();
- }
-
- @Override
- public void setSelection(ISelection selection, boolean reveal) {
- }
-
- private IPath generateTempFile(IEncodedStreamContentAccessor stream) {
- try {
- Path tmpFile = Files.createTempFile("perf-report-", ".data"); //$NON-NLS-1$ //$NON-NLS-2$
- tmpFile.toFile().delete();
- Files.copy(stream.getContents(), tmpFile);
- return new org.eclipse.core.runtime.Path(tmpFile.toString());
- } catch (IOException e) {
- return null;
- } catch (CoreException e) {
- return null;
- }
- }
-
- private void toggleReverse () {
- if (reverse) {
- reverse = false;
- reverseLabel.setVisible(false);
- } else {
- reverse = true;
- reverseLabel.setVisible(true);
- }
- }
+ // Color values constants
+ private static final Color BLACK = new Color(Display.getDefault(), 0, 0, 0);
+ private static final Color RED = new Color(Display.getDefault(), 150, 0, 0);
+ private static final Color GREEN = new Color(Display.getDefault(), 0, 50, 0);
+ private static final Color LIGHT_GREEN = new Color(Display.getDefault(), 0, 105, 0);
+ private static final Color ORANGE = new Color(Display.getDefault(), 150, 100, 0);
+
+ // Regex for a generic entry in a perf comparison report.
+ private static final String DIFF_ENTRY = "\\s+(\\d+(\\.\\d+)?)\\%\\s+([\\+\\-]?\\d+(\\.\\d+)?)\\%.*"; //$NON-NLS-1$
+
+ private Composite fComposite;
+ private ICompareInput fInput;
+
+ // Comparison result.
+ private StyledText result;
+ private Label reverseLabel;
+ private boolean reverse;
+
+ public ReportComparisonView (Composite parent, CompareConfiguration config) {
+ fComposite = new Composite (parent, SWT.NONE);
+ fComposite.setLayout(new GridLayout(2, false));
+ fComposite.setData(CompareUI.COMPARE_VIEWER_TITLE, Messages.ReportComparisonView_label);
+
+ reverseLabel = new Label(fComposite, SWT.NONE);
+ reverseLabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false));
+ reverseLabel.setText(Messages.StatComparisonView_reversedLabel);
+ reverseLabel.setVisible(false);
+
+ final Button reverse = new Button(fComposite, SWT.TOGGLE);
+ reverse.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_ELCL_SYNCED));
+ reverse.setToolTipText(Messages.StatComparisonView_reverseToolTip);
+ reverse.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
+ reverse.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ toggleReverse();
+ setInput(fInput);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+
+ result = new StyledText(fComposite, SWT.V_SCROLL | SWT.H_SCROLL);
+ result.setAlwaysShowScrollBars(false);
+ GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+ gd.horizontalSpan = 2;
+ result.setLayoutData(gd);
+ result.setEditable(false);
+ }
+
+ /**
+ * Set properties for StlyedText widget.
+ * @param input String StyledText content.
+ */
+ private void setStyledText(String input) {
+ result.setText(input);
+ result.setJustify(true);
+ result.setAlignment(SWT.LEFT);
+
+ result.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT));
+
+ List<StyleRange> styles = new ArrayList<>();
+ int ptr = 0;
+ String[] lines = input.split("\n"); //$NON-NLS-1$
+
+ for(String line : lines){
+ if (Pattern.matches(DIFF_ENTRY, line)) {
+ Matcher m = Pattern.compile(DIFF_ENTRY).matcher(line);
+ if (m.matches() && m.group(1) != null && m.group(3) != null) {
+ try {
+ float baseline = Float.parseFloat(m.group(1).trim());
+ float delta = Float.parseFloat(m.group(3).trim());
+ if (baseline > 1 && Math.abs(delta) > 1) {
+ StyleRange curStyleRange = new StyleRange(ptr, line.length(), BLACK, null);
+ if (delta < 0 ) {
+ curStyleRange = delta < -5 ? new StyleRange(ptr, line.length(), LIGHT_GREEN, null) :
+ new StyleRange(ptr, line.length(), GREEN, null);
+ } else {
+ curStyleRange = delta < 5 ? new StyleRange(ptr, line .length(), ORANGE, null) :
+ new StyleRange(ptr, line.length(), RED, null);
+ }
+ styles.add(curStyleRange);
+ }
+ } catch (NumberFormatException e) {
+ // set no StyleRange
+ }
+ }
+ }
+ // + 1 to skip over the '\n' at EOL that the tokenizer eats
+ ptr += line.length() + 1;
+ }
+
+ result.setStyleRanges(styles.toArray(new StyleRange[0]));
+ }
+
+ @Override
+ public Control getControl() {
+ return fComposite;
+ }
+
+ @Override
+ public Object getInput() {
+ return fInput;
+ }
+
+ @Override
+ public ISelection getSelection() {
+ return null;
+ }
+
+ @Override
+ public void refresh() {
+ }
+
+ @Override
+ public void setInput(Object input) {
+ if (input instanceof ICompareInput) {
+ fInput = (ICompareInput) input;
+
+ if (fInput.getAncestor() != null ||
+ (fInput.getKind() & Differencer.DIRECTION_MASK) != 0) {
+ setStyledText(Messages.CompUnsupported);
+ } else {
+ // get corresponding files
+ IPath oldDatum;
+ IPath newDatum;
+ IProject proj = null;
+
+ if (fInput.getLeft() instanceof ResourceNode) {
+ ResourceNode left = (ResourceNode) fInput.getLeft();
+ IResource oldData = left.getResource();
+ oldDatum = oldData.getLocation();
+ proj = oldData.getProject();
+ } else {
+ IEncodedStreamContentAccessor lStream = (IEncodedStreamContentAccessor) fInput.getLeft();
+ oldDatum = generateTempFile(lStream);
+ }
+
+ if (fInput.getRight() instanceof ResourceNode) {
+ ResourceNode right = (ResourceNode) fInput.getRight();
+ IResource newData = right.getResource();
+ newDatum = newData.getLocation();
+ proj = newData.getProject();
+ } else {
+ IEncodedStreamContentAccessor rStream = (IEncodedStreamContentAccessor) fInput.getRight();
+ newDatum = generateTempFile(rStream);
+ }
+
+ String title = MessageFormat.format(Messages.ContentDescription_0,
+ new Object[] { oldDatum.toFile().getName(), newDatum.toFile().getName() });
+
+ // create comparison data and run comparison.
+ ReportComparisonData diffData;
+ if (reverse) {
+ diffData = new ReportComparisonData(title, oldDatum, newDatum, proj);
+ } else {
+ diffData = new ReportComparisonData(title, newDatum, oldDatum, proj);
+ }
+ diffData.parse();
+
+ setStyledText(diffData.getPerfData());
+ }
+ }
+
+ fComposite.layout();
+ }
+
+ @Override
+ public void setSelection(ISelection selection, boolean reveal) {
+ }
+
+ private IPath generateTempFile(IEncodedStreamContentAccessor stream) {
+ try {
+ Path tmpFile = Files.createTempFile("perf-report-", ".data"); //$NON-NLS-1$ //$NON-NLS-2$
+ tmpFile.toFile().delete();
+ Files.copy(stream.getContents(), tmpFile);
+ return new org.eclipse.core.runtime.Path(tmpFile.toString());
+ } catch (IOException e) {
+ return null;
+ } catch (CoreException e) {
+ return null;
+ }
+ }
+
+ private void toggleReverse () {
+ if (reverse) {
+ reverse = false;
+ reverseLabel.setVisible(false);
+ } else {
+ reverse = true;
+ reverseLabel.setVisible(true);
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/ReportComparisonViewCreator.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/ReportComparisonViewCreator.java
index 905f3383ea..a6f7a19bef 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/ReportComparisonViewCreator.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/ReportComparisonViewCreator.java
@@ -17,9 +17,9 @@ import org.eclipse.swt.widgets.Composite;
public class ReportComparisonViewCreator implements IViewerCreator {
- @Override
- public Viewer createViewer(Composite parent, CompareConfiguration config) {
- return new ReportComparisonView(parent, config);
- }
+ @Override
+ public Viewer createViewer(Composite parent, CompareConfiguration config) {
+ return new ReportComparisonView(parent, config);
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/SourceDisassemblyView.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/SourceDisassemblyView.java
index 37e8104386..641ef5384b 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/SourceDisassemblyView.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/SourceDisassemblyView.java
@@ -43,193 +43,193 @@ import org.eclipse.ui.texteditor.FindReplaceAction;
*/
public class SourceDisassemblyView extends ViewPart implements IFindReplaceTarget{
- private static final Color RED = new Color(Display.getDefault(), 150, 0, 0);
- private static final Color ORANGE = new Color(Display.getDefault(), 150, 100, 0);
- private static final Color GREEN = new Color(Display.getDefault(), 0, 100, 0);
- private static String ASM = "\\s+([0-9]+\\.[0-9]+ )?:\\s+[0-9a-f]+:\\s+[0-9a-z]+\\s+.*"; //$NON-NLS-1$
- private static String CODE = "\\s+:\\s+.*"; //$NON-NLS-1$
- private static String WORD_BOUNDARY = "\\b"; //$NON-NLS-1$'
- private static int SECONDARY_ID = 0;
- private StyledText text;
- public SourceDisassemblyView() {
- }
-
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayoutData(new GridLayout(1, true));
-
- text = new StyledText(parent, SWT.WRAP | SWT.V_SCROLL);
- text.setEditable(false);
-
- IPerfData data = PerfPlugin.getDefault().getSourceDisassemblyData();
- if (data != null) {
- setStyledText(data.getPerfData());
- setContentDescription(data.getTitle());
- setupFindDialog();
- }
- }
-
- @Override
- public void setFocus() {
- return;
- }
-
- /**
- * Set styled text field (only used for testing).
- *
- * @param txt StyledText to set.
- */
- protected void setStyledText(StyledText txt) {
- text = txt;
- }
-
- /**
- * Get the text content of this view.
- *
- * @return String content of this view
- */
- public String getContent() {
- return (text == null) ? "" : text.getText(); //$NON-NLS-1$
- }
-
- /**
- * Set styled text field based on the specified string, which is parsed in
- * order to set appropriate styles to be used for rendering the widget
- * content.
- *
- * @param input text content of widget.
- */
- private void setStyledText (String input) {
- List<StyleRange> styles = new ArrayList<> ();
- int ptr = 0;
-
- text.setText(input);
-
- StringTokenizer tok = new StringTokenizer(input, "\n"); //$NON-NLS-1$
- while (tok.hasMoreTokens()) {
- String line = tok.nextToken();
- if (Pattern.matches(ASM, line)) {
- Matcher m = Pattern.compile(ASM).matcher(line);
- if (m.matches() && m.group(1) != null) {
-
- try {
- float percent = Float.parseFloat(m.group(1).trim());
- if (percent >= 20) {
- styles.add(new StyleRange(ptr, line.length(), RED, null));
- } else if (percent >= 5) {
- styles.add(new StyleRange(ptr, line.length(), ORANGE, null));
- }
- } catch (NumberFormatException e) {
- // set no StyleRange
- }
- }
- } else if (Pattern.matches(CODE, line)) {
- styles.add(new StyleRange(ptr, line.length(), GREEN, null));
- }
-
- // + 1 to skip over the '\n' at EOL that the tokenizer eats
- ptr += line.length() + 1;
- }
- text.setStyleRanges(styles.toArray(new StyleRange [0]));
- }
-
- public static void refreshView () {
- Display.getDefault().syncExec(new Runnable() {
-
- @Override
- public void run() {
- try {
- // A new view is created every time
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
- .showView(PerfPlugin.SOURCE_DISASSEMBLY_VIEW_ID,
- Integer.toString(SECONDARY_ID++),
- IWorkbenchPage.VIEW_CREATE);
- } catch (PartInitException e) {
- IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID, e.getMessage(), e);
- PerfPlugin.getDefault().getLog().log(status);
- }
- }
- });
- }
-
- /**
- * Create find dialog and set is as a toolbar action.
- */
- private void setupFindDialog() {
- FindReplaceAction findAction = new FindReplaceAction(
- Platform.getResourceBundle(PerfPlugin.getDefault().getBundle()),
- null, text.getShell(), this);
- findAction.setImageDescriptor(PerfPlugin
- .getImageDescriptor("icons/search.gif"));//$NON-NLS-1$
- findAction.setToolTipText(PerfPlugin.STRINGS_SearchSourceDisassembly);
- IActionBars bars = getViewSite().getActionBars();
- bars.getToolBarManager().add(findAction);
- bars.setGlobalActionHandler(ActionFactory.FIND.getId(), findAction);
- }
-
- @Override
- public boolean canPerformFind() {
- return text != null && !text.getText().isEmpty();
- }
-
- @Override
- public int findAndSelect(int widgetOffset, String findString,
- boolean searchForward, boolean caseSensitive, boolean wholeWord) {
- int matchIndex = -1;
- String searchString = text.getText();
- String findRegex = findString;
-
- // offset is -1 when text boundaries are reached during a wrapped search
- if (widgetOffset < 0) {
- widgetOffset = searchForward ? 0 : searchString.length();
- }
-
- if (wholeWord) {
- findRegex = WORD_BOUNDARY + findRegex + WORD_BOUNDARY;
- }
-
- int caseFlag = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE;
- Pattern pattern = Pattern.compile(findRegex, caseFlag);
- Matcher matcher = pattern.matcher(searchString);
-
- if (searchForward) {
- matchIndex = matcher.find(widgetOffset) ? matcher.start() : -1;
- } else {
- // backward search from 0 to offset (exclusive)
- matcher.region(0, widgetOffset);
-
- // get start index of last match
- while (matcher.find()) {
- matchIndex = matcher.start();
- }
- }
-
- // only select when a match has been found
- if (matchIndex != -1) {
- text.setSelection(matchIndex, matchIndex + findString.length());
- }
- return matchIndex;
- }
-
- @Override
- public Point getSelection() {
- Point selection = text.getSelection();
- // selection point consists of starting point x and lenght y - x.
- return new Point(selection.x, selection.y - selection.x);
- }
-
- @Override
- public String getSelectionText() {
- return text.getSelectionText();
- }
-
- @Override
- public boolean isEditable() {
- return false;
- }
-
- @Override
- public void replaceSelection(String text) {
- }
+ private static final Color RED = new Color(Display.getDefault(), 150, 0, 0);
+ private static final Color ORANGE = new Color(Display.getDefault(), 150, 100, 0);
+ private static final Color GREEN = new Color(Display.getDefault(), 0, 100, 0);
+ private static String ASM = "\\s+([0-9]+\\.[0-9]+ )?:\\s+[0-9a-f]+:\\s+[0-9a-z]+\\s+.*"; //$NON-NLS-1$
+ private static String CODE = "\\s+:\\s+.*"; //$NON-NLS-1$
+ private static String WORD_BOUNDARY = "\\b"; //$NON-NLS-1$'
+ private static int SECONDARY_ID = 0;
+ private StyledText text;
+ public SourceDisassemblyView() {
+ }
+
+ @Override
+ public void createPartControl(Composite parent) {
+ parent.setLayoutData(new GridLayout(1, true));
+
+ text = new StyledText(parent, SWT.WRAP | SWT.V_SCROLL);
+ text.setEditable(false);
+
+ IPerfData data = PerfPlugin.getDefault().getSourceDisassemblyData();
+ if (data != null) {
+ setStyledText(data.getPerfData());
+ setContentDescription(data.getTitle());
+ setupFindDialog();
+ }
+ }
+
+ @Override
+ public void setFocus() {
+ return;
+ }
+
+ /**
+ * Set styled text field (only used for testing).
+ *
+ * @param txt StyledText to set.
+ */
+ protected void setStyledText(StyledText txt) {
+ text = txt;
+ }
+
+ /**
+ * Get the text content of this view.
+ *
+ * @return String content of this view
+ */
+ public String getContent() {
+ return (text == null) ? "" : text.getText(); //$NON-NLS-1$
+ }
+
+ /**
+ * Set styled text field based on the specified string, which is parsed in
+ * order to set appropriate styles to be used for rendering the widget
+ * content.
+ *
+ * @param input text content of widget.
+ */
+ private void setStyledText (String input) {
+ List<StyleRange> styles = new ArrayList<> ();
+ int ptr = 0;
+
+ text.setText(input);
+
+ StringTokenizer tok = new StringTokenizer(input, "\n"); //$NON-NLS-1$
+ while (tok.hasMoreTokens()) {
+ String line = tok.nextToken();
+ if (Pattern.matches(ASM, line)) {
+ Matcher m = Pattern.compile(ASM).matcher(line);
+ if (m.matches() && m.group(1) != null) {
+
+ try {
+ float percent = Float.parseFloat(m.group(1).trim());
+ if (percent >= 20) {
+ styles.add(new StyleRange(ptr, line.length(), RED, null));
+ } else if (percent >= 5) {
+ styles.add(new StyleRange(ptr, line.length(), ORANGE, null));
+ }
+ } catch (NumberFormatException e) {
+ // set no StyleRange
+ }
+ }
+ } else if (Pattern.matches(CODE, line)) {
+ styles.add(new StyleRange(ptr, line.length(), GREEN, null));
+ }
+
+ // + 1 to skip over the '\n' at EOL that the tokenizer eats
+ ptr += line.length() + 1;
+ }
+ text.setStyleRanges(styles.toArray(new StyleRange [0]));
+ }
+
+ public static void refreshView () {
+ Display.getDefault().syncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ // A new view is created every time
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
+ .showView(PerfPlugin.SOURCE_DISASSEMBLY_VIEW_ID,
+ Integer.toString(SECONDARY_ID++),
+ IWorkbenchPage.VIEW_CREATE);
+ } catch (PartInitException e) {
+ IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID, e.getMessage(), e);
+ PerfPlugin.getDefault().getLog().log(status);
+ }
+ }
+ });
+ }
+
+ /**
+ * Create find dialog and set is as a toolbar action.
+ */
+ private void setupFindDialog() {
+ FindReplaceAction findAction = new FindReplaceAction(
+ Platform.getResourceBundle(PerfPlugin.getDefault().getBundle()),
+ null, text.getShell(), this);
+ findAction.setImageDescriptor(PerfPlugin
+ .getImageDescriptor("icons/search.gif"));//$NON-NLS-1$
+ findAction.setToolTipText(PerfPlugin.STRINGS_SearchSourceDisassembly);
+ IActionBars bars = getViewSite().getActionBars();
+ bars.getToolBarManager().add(findAction);
+ bars.setGlobalActionHandler(ActionFactory.FIND.getId(), findAction);
+ }
+
+ @Override
+ public boolean canPerformFind() {
+ return text != null && !text.getText().isEmpty();
+ }
+
+ @Override
+ public int findAndSelect(int widgetOffset, String findString,
+ boolean searchForward, boolean caseSensitive, boolean wholeWord) {
+ int matchIndex = -1;
+ String searchString = text.getText();
+ String findRegex = findString;
+
+ // offset is -1 when text boundaries are reached during a wrapped search
+ if (widgetOffset < 0) {
+ widgetOffset = searchForward ? 0 : searchString.length();
+ }
+
+ if (wholeWord) {
+ findRegex = WORD_BOUNDARY + findRegex + WORD_BOUNDARY;
+ }
+
+ int caseFlag = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE;
+ Pattern pattern = Pattern.compile(findRegex, caseFlag);
+ Matcher matcher = pattern.matcher(searchString);
+
+ if (searchForward) {
+ matchIndex = matcher.find(widgetOffset) ? matcher.start() : -1;
+ } else {
+ // backward search from 0 to offset (exclusive)
+ matcher.region(0, widgetOffset);
+
+ // get start index of last match
+ while (matcher.find()) {
+ matchIndex = matcher.start();
+ }
+ }
+
+ // only select when a match has been found
+ if (matchIndex != -1) {
+ text.setSelection(matchIndex, matchIndex + findString.length());
+ }
+ return matchIndex;
+ }
+
+ @Override
+ public Point getSelection() {
+ Point selection = text.getSelection();
+ // selection point consists of starting point x and lenght y - x.
+ return new Point(selection.x, selection.y - selection.x);
+ }
+
+ @Override
+ public String getSelectionText() {
+ return text.getSelectionText();
+ }
+
+ @Override
+ public boolean isEditable() {
+ return false;
+ }
+
+ @Override
+ public void replaceSelection(String text) {
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatComparisonView.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatComparisonView.java
index 0d0ec1591c..6b1bb089ab 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatComparisonView.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatComparisonView.java
@@ -55,202 +55,202 @@ import org.eclipse.ui.PlatformUI;
*/
public class StatComparisonView extends Viewer {
- // color values constasts
- private static final Color RED = new Color(Display.getDefault(), 150, 0, 0);
- private static final Color GREEN = new Color(Display.getDefault(), 0, 100, 0);
-
- // event occurrence reg-ex
- private static String OCCURRENCE = "\\s*(\\-?+" //$NON-NLS-1$
- + PMStatEntry.DECIMAL + ").*"; //$NON-NLS-1$
-
- private Composite fComposite;
- private ICompareInput fInput;
- private StyledText text;
- private Label reverseLabel;
- private boolean reverse;
-
- public StatComparisonView(Composite parent, CompareConfiguration config) {
- fComposite = new Composite(parent, SWT.NONE);
- fComposite.setLayout(new GridLayout(2, false));
- fComposite.setData(CompareUI.COMPARE_VIEWER_TITLE, Messages.StatComparisonView_label);
-
- reverseLabel = new Label(fComposite, SWT.NONE);
- reverseLabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false));
- reverseLabel.setText(Messages.StatComparisonView_reversedLabel);
- reverseLabel.setVisible(false);
-
- final Button reverse = new Button(fComposite, SWT.TOGGLE);
- reverse.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_ELCL_SYNCED));
- reverse.setToolTipText(Messages.StatComparisonView_reverseToolTip);
- reverse.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
- reverse.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- toggleReverse();
- setInput(fInput);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- text = new StyledText(fComposite, SWT.V_SCROLL | SWT.H_SCROLL);
- text.setAlwaysShowScrollBars(false);
- GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
- gd.horizontalSpan = 2;
- text.setLayoutData(gd);
- text.setEditable(false);
-
- }
-
- /**
- * Set String input in text display. Adapted from
- * org.eclipse.linuxtools.internal.perf.ui.SourceDisassemblyView.
- *
- * @param input text to display
- */
- private void setStyledText(String input) {
- text.setText(input);
- text.setAlignment(SWT.LEFT);
- // set default TextConsole font (monospaced).
- text.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT));
-
- List<StyleRange> styles = new ArrayList<>();
- int ptr = 0;
-
- String[] lines = input.split("\n"); //$NON-NLS-1$
-
- for (String line : lines) {
- if (Pattern.matches(OCCURRENCE, line)) {
- Matcher m = Pattern.compile(OCCURRENCE).matcher(line);
- if (m.matches() && m.group(1) != null) {
- try {
- float occurrence = StatComparisonData.toFloat(m
- .group(1).trim());
- if (occurrence > 0) {
- styles.add(new StyleRange(ptr, line.length(), RED,
- null));
- } else if (occurrence < 0) {
- styles.add(new StyleRange(ptr, line.length(),
- GREEN, null));
- }
- } catch (NumberFormatException e) {
- // set no StyleRange
- }
- }
- }
- // + 1 to skip over the '\n' at EOL that the tokenizer eats
- ptr += line.length() + 1;
- }
-
- text.setStyleRanges(styles.toArray(new StyleRange[0]));
- }
-
- /**
- * Update contents of current view, replacing the containing data and text styling.
- *
- * @param data IPerfData data replacement.
- */
- private void updateData(IPerfData data) {
- if (data != null) {
- setStyledText(data.getPerfData());
- }
- }
-
- @Override
- public Control getControl() {
- return fComposite;
- }
-
- @Override
- public Object getInput() {
- return fInput;
- }
-
- @Override
- public ISelection getSelection() {
- return null;
- }
-
- @Override
- public void refresh() {
- }
-
- @Override
- public void setInput(Object input) {
- if (input instanceof ICompareInput) {
- fInput = (ICompareInput) input;
-
- if (fInput.getAncestor() != null ||
- (fInput.getKind() & Differencer.DIRECTION_MASK) != 0) {
- setStyledText(Messages.CompUnsupported);
- } else {
- // get corresponding files
- IPath oldDatum;
- IPath newDatum;
-
- if (fInput.getLeft() instanceof ResourceNode) {
- ResourceNode left = (ResourceNode) fInput.getLeft();
- oldDatum = left.getResource().getLocation();
- } else {
- IEncodedStreamContentAccessor lStream = (IEncodedStreamContentAccessor) fInput.getLeft();
- oldDatum = generateTempFile(lStream);
- }
-
- if (fInput.getRight() instanceof ResourceNode) {
- ResourceNode right = (ResourceNode) fInput.getRight();
- newDatum = right.getResource().getLocation();
- } else {
- IEncodedStreamContentAccessor rStream = (IEncodedStreamContentAccessor) fInput.getRight();
- newDatum = generateTempFile(rStream);
- }
-
- String title = MessageFormat.format(Messages.ContentDescription_0,
- new Object[] { oldDatum.toFile().getName(), newDatum.toFile().getName() });
-
- // create comparison data and run comparison.
- StatComparisonData diffData;
- if (reverse) {
- diffData = new StatComparisonData(title, newDatum, oldDatum);
- } else {
- diffData = new StatComparisonData(title, oldDatum, newDatum);
- }
- diffData.runComparison();
- updateData(diffData);
- }
-
- }
-
- fComposite.layout();
- }
-
- private IPath generateTempFile(IEncodedStreamContentAccessor stream) {
- try {
- Path tmpFile = Files.createTempFile("perf-stat-", ".stat"); //$NON-NLS-1$ //$NON-NLS-2$
- tmpFile.toFile().delete();
- Files.copy(stream.getContents(), tmpFile);
- return new org.eclipse.core.runtime.Path(tmpFile.toString());
- } catch (IOException e) {
- return null;
- } catch (CoreException e) {
- return null;
- }
- }
-
- @Override
- public void setSelection(ISelection selection, boolean reveal) {
- }
-
- private void toggleReverse () {
- if (reverse) {
- reverse = false;
- reverseLabel.setVisible(false);
- } else {
- reverse = true;
- reverseLabel.setVisible(true);
- }
- }
+ // color values constasts
+ private static final Color RED = new Color(Display.getDefault(), 150, 0, 0);
+ private static final Color GREEN = new Color(Display.getDefault(), 0, 100, 0);
+
+ // event occurrence reg-ex
+ private static String OCCURRENCE = "\\s*(\\-?+" //$NON-NLS-1$
+ + PMStatEntry.DECIMAL + ").*"; //$NON-NLS-1$
+
+ private Composite fComposite;
+ private ICompareInput fInput;
+ private StyledText text;
+ private Label reverseLabel;
+ private boolean reverse;
+
+ public StatComparisonView(Composite parent, CompareConfiguration config) {
+ fComposite = new Composite(parent, SWT.NONE);
+ fComposite.setLayout(new GridLayout(2, false));
+ fComposite.setData(CompareUI.COMPARE_VIEWER_TITLE, Messages.StatComparisonView_label);
+
+ reverseLabel = new Label(fComposite, SWT.NONE);
+ reverseLabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false));
+ reverseLabel.setText(Messages.StatComparisonView_reversedLabel);
+ reverseLabel.setVisible(false);
+
+ final Button reverse = new Button(fComposite, SWT.TOGGLE);
+ reverse.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_ELCL_SYNCED));
+ reverse.setToolTipText(Messages.StatComparisonView_reverseToolTip);
+ reverse.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
+ reverse.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ toggleReverse();
+ setInput(fInput);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+
+ text = new StyledText(fComposite, SWT.V_SCROLL | SWT.H_SCROLL);
+ text.setAlwaysShowScrollBars(false);
+ GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+ gd.horizontalSpan = 2;
+ text.setLayoutData(gd);
+ text.setEditable(false);
+
+ }
+
+ /**
+ * Set String input in text display. Adapted from
+ * org.eclipse.linuxtools.internal.perf.ui.SourceDisassemblyView.
+ *
+ * @param input text to display
+ */
+ private void setStyledText(String input) {
+ text.setText(input);
+ text.setAlignment(SWT.LEFT);
+ // set default TextConsole font (monospaced).
+ text.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT));
+
+ List<StyleRange> styles = new ArrayList<>();
+ int ptr = 0;
+
+ String[] lines = input.split("\n"); //$NON-NLS-1$
+
+ for (String line : lines) {
+ if (Pattern.matches(OCCURRENCE, line)) {
+ Matcher m = Pattern.compile(OCCURRENCE).matcher(line);
+ if (m.matches() && m.group(1) != null) {
+ try {
+ float occurrence = StatComparisonData.toFloat(m
+ .group(1).trim());
+ if (occurrence > 0) {
+ styles.add(new StyleRange(ptr, line.length(), RED,
+ null));
+ } else if (occurrence < 0) {
+ styles.add(new StyleRange(ptr, line.length(),
+ GREEN, null));
+ }
+ } catch (NumberFormatException e) {
+ // set no StyleRange
+ }
+ }
+ }
+ // + 1 to skip over the '\n' at EOL that the tokenizer eats
+ ptr += line.length() + 1;
+ }
+
+ text.setStyleRanges(styles.toArray(new StyleRange[0]));
+ }
+
+ /**
+ * Update contents of current view, replacing the containing data and text styling.
+ *
+ * @param data IPerfData data replacement.
+ */
+ private void updateData(IPerfData data) {
+ if (data != null) {
+ setStyledText(data.getPerfData());
+ }
+ }
+
+ @Override
+ public Control getControl() {
+ return fComposite;
+ }
+
+ @Override
+ public Object getInput() {
+ return fInput;
+ }
+
+ @Override
+ public ISelection getSelection() {
+ return null;
+ }
+
+ @Override
+ public void refresh() {
+ }
+
+ @Override
+ public void setInput(Object input) {
+ if (input instanceof ICompareInput) {
+ fInput = (ICompareInput) input;
+
+ if (fInput.getAncestor() != null ||
+ (fInput.getKind() & Differencer.DIRECTION_MASK) != 0) {
+ setStyledText(Messages.CompUnsupported);
+ } else {
+ // get corresponding files
+ IPath oldDatum;
+ IPath newDatum;
+
+ if (fInput.getLeft() instanceof ResourceNode) {
+ ResourceNode left = (ResourceNode) fInput.getLeft();
+ oldDatum = left.getResource().getLocation();
+ } else {
+ IEncodedStreamContentAccessor lStream = (IEncodedStreamContentAccessor) fInput.getLeft();
+ oldDatum = generateTempFile(lStream);
+ }
+
+ if (fInput.getRight() instanceof ResourceNode) {
+ ResourceNode right = (ResourceNode) fInput.getRight();
+ newDatum = right.getResource().getLocation();
+ } else {
+ IEncodedStreamContentAccessor rStream = (IEncodedStreamContentAccessor) fInput.getRight();
+ newDatum = generateTempFile(rStream);
+ }
+
+ String title = MessageFormat.format(Messages.ContentDescription_0,
+ new Object[] { oldDatum.toFile().getName(), newDatum.toFile().getName() });
+
+ // create comparison data and run comparison.
+ StatComparisonData diffData;
+ if (reverse) {
+ diffData = new StatComparisonData(title, newDatum, oldDatum);
+ } else {
+ diffData = new StatComparisonData(title, oldDatum, newDatum);
+ }
+ diffData.runComparison();
+ updateData(diffData);
+ }
+
+ }
+
+ fComposite.layout();
+ }
+
+ private IPath generateTempFile(IEncodedStreamContentAccessor stream) {
+ try {
+ Path tmpFile = Files.createTempFile("perf-stat-", ".stat"); //$NON-NLS-1$ //$NON-NLS-2$
+ tmpFile.toFile().delete();
+ Files.copy(stream.getContents(), tmpFile);
+ return new org.eclipse.core.runtime.Path(tmpFile.toString());
+ } catch (IOException e) {
+ return null;
+ } catch (CoreException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public void setSelection(ISelection selection, boolean reveal) {
+ }
+
+ private void toggleReverse () {
+ if (reverse) {
+ reverse = false;
+ reverseLabel.setVisible(false);
+ } else {
+ reverse = true;
+ reverseLabel.setVisible(true);
+ }
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatComparisonViewCreator.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatComparisonViewCreator.java
index 7170f4e77d..db2efdb36b 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatComparisonViewCreator.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatComparisonViewCreator.java
@@ -17,8 +17,8 @@ import org.eclipse.swt.widgets.Composite;
public class StatComparisonViewCreator implements IViewerCreator {
- @Override
- public Viewer createViewer(Composite parent, CompareConfiguration config) {
- return new StatComparisonView(parent, config);
- }
+ @Override
+ public Viewer createViewer(Composite parent, CompareConfiguration config) {
+ return new StatComparisonView(parent, config);
+ }
}
diff --git a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatView.java b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatView.java
index 7275622cff..c28e142693 100644
--- a/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatView.java
+++ b/perf/org.eclipse.linuxtools.perf/src/org/eclipse/linuxtools/internal/perf/ui/StatView.java
@@ -29,66 +29,66 @@ import org.eclipse.ui.part.ViewPart;
*/
public class StatView extends ViewPart {
- private StyledText text;
+ private StyledText text;
- public StatView() {
- }
+ public StatView() {
+ }
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayoutData(new GridLayout(1, true));
+ @Override
+ public void createPartControl(Composite parent) {
+ parent.setLayoutData(new GridLayout(1, true));
- text = new StyledText(parent, SWT.H_SCROLL | SWT.V_SCROLL);
- text.setEditable(false);
+ text = new StyledText(parent, SWT.H_SCROLL | SWT.V_SCROLL);
+ text.setEditable(false);
- IPerfData data = PerfPlugin.getDefault().getStatData();
- if (data != null) {
- setStyledText(data.getPerfData());
- setContentDescription(data.getTitle());
- }
- }
+ IPerfData data = PerfPlugin.getDefault().getStatData();
+ if (data != null) {
+ setStyledText(data.getPerfData());
+ setContentDescription(data.getTitle());
+ }
+ }
- @Override
- public void setFocus() {
- return;
- }
+ @Override
+ public void setFocus() {
+ return;
+ }
- private void setStyledText (String input) {
- text.setText(input);
+ private void setStyledText (String input) {
+ text.setText(input);
- // the default TextConsole font (we want monospaced)
- text.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT));
- }
- /**
- * Update to most recent statistics data.
- */
- private void updateData(){
- IPerfData data = PerfPlugin.getDefault().getStatData();
- if (data != null) {
- setStyledText(data.getPerfData());
- setContentDescription(data.getTitle());
- }
- }
+ // the default TextConsole font (we want monospaced)
+ text.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT));
+ }
+ /**
+ * Update to most recent statistics data.
+ */
+ private void updateData(){
+ IPerfData data = PerfPlugin.getDefault().getStatData();
+ if (data != null) {
+ setStyledText(data.getPerfData());
+ setContentDescription(data.getTitle());
+ }
+ }
- /**
- * Refresh perf statistics view.
- */
- public static void refreshView () {
- Display.getDefault().syncExec(new Runnable() {
+ /**
+ * Refresh perf statistics view.
+ */
+ public static void refreshView () {
+ Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- try {
- // A new view is created every time
- StatView view = (StatView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
- .showView(PerfPlugin.STAT_VIEW_ID);
- view.updateData();
- } catch (PartInitException e) {
- IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID, e.getMessage(), e);
- PerfPlugin.getDefault().getLog().log(status);
- }
- }
- });
- }
+ @Override
+ public void run() {
+ try {
+ // A new view is created every time
+ StatView view = (StatView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
+ .showView(PerfPlugin.STAT_VIEW_ID);
+ view.updateData();
+ } catch (PartInitException e) {
+ IStatus status = new Status(IStatus.ERROR, PerfPlugin.PLUGIN_ID, e.getMessage(), e);
+ PerfPlugin.getDefault().getLog().log(status);
+ }
+ }
+ });
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.binutils/src/org/eclipse/linuxtools/binutils/utils/STSymbolManager.java b/profiling/org.eclipse.linuxtools.binutils/src/org/eclipse/linuxtools/binutils/utils/STSymbolManager.java
index 5565d896b6..3423adb503 100644
--- a/profiling/org.eclipse.linuxtools.binutils/src/org/eclipse/linuxtools/binutils/utils/STSymbolManager.java
+++ b/profiling/org.eclipse.linuxtools.binutils/src/org/eclipse/linuxtools/binutils/utils/STSymbolManager.java
@@ -73,10 +73,10 @@ public class STSymbolManager {
private long startTime;
}
- /** Map of all living instance of addr2line */
- private final HashMap<IBinaryObject, AutoDisposeAddr2line> addr2lines = new HashMap<>();
- /** Map of all living instance of cppfilt */
- private final HashMap<String, AutoDisposeCPPFilt> cppfilts = new HashMap<>();
+ /** Map of all living instance of addr2line */
+ private final HashMap<IBinaryObject, AutoDisposeAddr2line> addr2lines = new HashMap<>();
+ /** Map of all living instance of cppfilt */
+ private final HashMap<String, AutoDisposeCPPFilt> cppfilts = new HashMap<>();
/**
* Constructor
@@ -107,8 +107,8 @@ public class STSymbolManager {
}
/**
- * @since 4.1
- */
+ * @since 4.1
+ */
public synchronized void reset() {
Iterator<Entry<IBinaryObject, AutoDisposeAddr2line>> iter = addr2lines.entrySet().iterator();
while (iter.hasNext()) {
@@ -139,10 +139,10 @@ public class STSymbolManager {
AutoDisposeAddr2line ada2l = entry.getValue();
long diff = currentTime - ada2l.startTime;
if (diff > AUTO_DISPOSE_TIMEOUT) {
- if (ada2l.addr2line != null) {
- ada2l.addr2line.dispose();
- ada2l.addr2line = null;
- }
+ if (ada2l.addr2line != null) {
+ ada2l.addr2line.dispose();
+ ada2l.addr2line = null;
+ }
iter.remove();
}
}
diff --git a/profiling/org.eclipse.linuxtools.binutils/src/org/eclipse/linuxtools/internal/Activator.java b/profiling/org.eclipse.linuxtools.binutils/src/org/eclipse/linuxtools/internal/Activator.java
index 57250cc7d5..37f052d1bc 100644
--- a/profiling/org.eclipse.linuxtools.binutils/src/org/eclipse/linuxtools/internal/Activator.java
+++ b/profiling/org.eclipse.linuxtools.binutils/src/org/eclipse/linuxtools/internal/Activator.java
@@ -32,7 +32,7 @@ public class Activator extends AbstractUIPlugin {
/*
* (non-Javadoc)
- *
+ *
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext )
*/
@Override
@@ -43,7 +43,7 @@ public class Activator extends AbstractUIPlugin {
/*
* (non-Javadoc)
- *
+ *
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext )
*/
@Override
@@ -54,7 +54,7 @@ public class Activator extends AbstractUIPlugin {
/**
* Returns the shared instance
- *
+ *
* @return the shared instance
*/
public static Activator getDefault() {
diff --git a/profiling/org.eclipse.linuxtools.dataviewers-feature/pom.xml b/profiling/org.eclipse.linuxtools.dataviewers-feature/pom.xml
index cfc8d6a718..5da51bb364 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers-feature/pom.xml
+++ b/profiling/org.eclipse.linuxtools.dataviewers-feature/pom.xml
@@ -22,7 +22,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools Dataviewers Feature</name>
-
+
<build>
<plugins>
<plugin>
diff --git a/profiling/org.eclipse.linuxtools.dataviewers.charts/src/org/eclipse/linuxtools/dataviewers/charts/actions/ChartAction.java b/profiling/org.eclipse.linuxtools.dataviewers.charts/src/org/eclipse/linuxtools/dataviewers/charts/actions/ChartAction.java
index f6cbeec887..e53e056e75 100755
--- a/profiling/org.eclipse.linuxtools.dataviewers.charts/src/org/eclipse/linuxtools/dataviewers/charts/actions/ChartAction.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers.charts/src/org/eclipse/linuxtools/dataviewers/charts/actions/ChartAction.java
@@ -23,7 +23,7 @@ import org.swtchart.Chart;
/**
* An action that open a chart dialog from an <code>AbstractSTViewer</code>.
- *
+ *
* @see AbstractSTViewer
*/
public class ChartAction extends Action {
@@ -33,7 +33,7 @@ public class ChartAction extends Action {
/**
* The constructor.
- *
+ *
* @param shell
* the shell used by the dialog
* @param viewer
@@ -53,7 +53,7 @@ public class ChartAction extends Action {
/*
* (non-Javadoc)
- *
+ *
* @see org.eclipse.jface.action.Action#run()
*/
@Override
diff --git a/profiling/org.eclipse.linuxtools.dataviewers.piechart/src/org/eclipse/linuxtools/dataviewers/piechart/PieChart.java b/profiling/org.eclipse.linuxtools.dataviewers.piechart/src/org/eclipse/linuxtools/dataviewers/piechart/PieChart.java
index 7c92263821..8e0d10b252 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers.piechart/src/org/eclipse/linuxtools/dataviewers/piechart/PieChart.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers.piechart/src/org/eclipse/linuxtools/dataviewers/piechart/PieChart.java
@@ -24,15 +24,15 @@ import org.swtchart.ISeries;
public class PieChart extends Chart {
- protected List<RGB> colorList = new ArrayList<>();
- private Color[] customColors = null;
- private PieChartPaintListener pieChartPaintListener;
+ protected List<RGB> colorList = new ArrayList<>();
+ private Color[] customColors = null;
+ private PieChartPaintListener pieChartPaintListener;
public PieChart(Composite parent, int style) {
super(parent, style);
// Hide all original axes and plot area
for (IAxis axis : getAxisSet().getAxes()) {
- axis.getTitle().setVisible(false);
+ axis.getTitle().setVisible(false);
}
getPlotArea().setVisible(false);
addPaintListener(pieChartPaintListener = new PieChartPaintListener(this));
@@ -44,13 +44,13 @@ public class PieChart extends Chart {
@Override
public void addPaintListener(PaintListener listener) {
if (!listener.getClass().getName().startsWith("org.swtchart.internal.axis")) { //$NON-NLS-1$
- super.addPaintListener(listener);
- }
+ super.addPaintListener(listener);
+ }
}
/**
- * @since 2.0
- */
+ * @since 2.0
+ */
public void setCustomColors(Color[] customColors) {
this.customColors = customColors.clone();
}
@@ -65,21 +65,21 @@ public class PieChart extends Chart {
public void addPieChartSeries(String labels[], double val[][]) {
setSeriesNames(val[0].length);
for (ISeries s : this.getSeriesSet().getSeries()) {
- this.getSeriesSet().deleteSeries(s.getId());
- }
+ this.getSeriesSet().deleteSeries(s.getId());
+ }
int size = Math.min(labels.length, val.length);
for (int i = 0; i < size; i++) {
IBarSeries s = (IBarSeries) this.getSeriesSet().createSeries(ISeries.SeriesType.BAR, labels[i]);
double d[] = new double[val[i].length];
for (int j = 0; j < val[i].length; j++) {
- d[j] = val[i][j];
- }
+ d[j] = val[i][j];
+ }
s.setXSeries(d);
if (customColors != null) {
- s.setBarColor(customColors[i % customColors.length]);
+ s.setBarColor(customColors[i % customColors.length]);
} else {
- s.setBarColor(new Color(this.getDisplay(), sliceColor(i)));
+ s.setBarColor(new Color(this.getDisplay(), sliceColor(i)));
}
}
}
@@ -91,27 +91,27 @@ public class PieChart extends Chart {
* @param numExpected The number of pies / the expected number of category names.
*/
private void setSeriesNames(int numExpected) {
- IAxis xAxis = getAxisSet().getXAxis(0);
- if (xAxis.getCategorySeries().length != numExpected) {
- String[] seriesNames = new String[numExpected];
- for (int i = 0, n = Math.min(xAxis.getCategorySeries().length, numExpected); i < n; i++) {
- seriesNames[i] = xAxis.getCategorySeries()[i];
- }
- for (int i = xAxis.getCategorySeries().length; i < numExpected; i++) {
- seriesNames[i] = ""; //$NON-NLS-1$
- }
- xAxis.setCategorySeries(seriesNames);
- }
+ IAxis xAxis = getAxisSet().getXAxis(0);
+ if (xAxis.getCategorySeries().length != numExpected) {
+ String[] seriesNames = new String[numExpected];
+ for (int i = 0, n = Math.min(xAxis.getCategorySeries().length, numExpected); i < n; i++) {
+ seriesNames[i] = xAxis.getCategorySeries()[i];
+ }
+ for (int i = xAxis.getCategorySeries().length; i < numExpected; i++) {
+ seriesNames[i] = ""; //$NON-NLS-1$
+ }
+ xAxis.setCategorySeries(seriesNames);
+ }
}
protected RGB sliceColor(int i) {
- if (colorList.size() > i) {
- return colorList.get(i);
- }
+ if (colorList.size() > i) {
+ return colorList.get(i);
+ }
- RGB next = IColorsConstants.COLORS[i % IColorsConstants.COLORS.length];
- colorList.add(next);
- return next;
+ RGB next = IColorsConstants.COLORS[i % IColorsConstants.COLORS.length];
+ colorList.add(next);
+ return next;
}
/**
diff --git a/profiling/org.eclipse.linuxtools.dataviewers.piechart/src/org/eclipse/linuxtools/dataviewers/piechart/PieChartPaintListener.java b/profiling/org.eclipse.linuxtools.dataviewers.piechart/src/org/eclipse/linuxtools/dataviewers/piechart/PieChartPaintListener.java
index bd5f3b2129..373885e2ec 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers.piechart/src/org/eclipse/linuxtools/dataviewers/piechart/PieChartPaintListener.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers.piechart/src/org/eclipse/linuxtools/dataviewers/piechart/PieChartPaintListener.java
@@ -115,8 +115,8 @@ public class PieChartPaintListener implements PaintListener {
int pieY = bounds.y + (bounds.height - pieWidth) / 2;
pieCenters[chartnum] = new Point(pieX + pieWidth / 2, pieY + pieWidth / 2);
if (sumTotal == 0) {
- gc.drawOval(pieX, pieY, pieWidth, pieWidth);
- } else {
+ gc.drawOval(pieX, pieY, pieWidth, pieWidth);
+ } else {
double factor = 100 / sumTotal;
int sweepAngle = 0;
int incrementAngle = 0;
@@ -130,8 +130,8 @@ public class PieChartPaintListener implements PaintListener {
gc.setBackground(((IBarSeries) chart.getSeriesSet().getSeries()[i]).getBarColor());
if (i == (nelemSeries - 1)) {
- sweepAngle = 360 - incrementAngle;
- } else {
+ sweepAngle = 360 - incrementAngle;
+ } else {
double angle = series[i] * factor * 3.6;
sweepAngle = (int) Math.round(angle);
}
@@ -158,8 +158,8 @@ public class PieChartPaintListener implements PaintListener {
if (series == null || series.length == 0) {
seriesValues = new double[0][0];
seriesNames = new String[0];
- return;
- }
+ return;
+ }
String names[] = this.chart.getAxisSet().getXAxis(0).getCategorySeries();
Range range = chart.getAxisSet().getXAxis(0).getRange();
int itemRange = (int) range.upper - (int) range.lower + 1;
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractview/AbstractSTDataView.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractview/AbstractSTDataView.java
index dd85cd481a..e3442d1a44 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractview/AbstractSTDataView.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractview/AbstractSTDataView.java
@@ -94,7 +94,7 @@ public abstract class AbstractSTDataView extends ViewPart {
protected abstract void contributeToToolbar(IToolBarManager manager);
@Override
- public void createPartControl(Composite parent) {
+ public void createPartControl(Composite parent) {
GridLayout gridLayout = new GridLayout(1, true);
parent.setLayout(gridLayout);
createTitle(parent);
@@ -215,7 +215,7 @@ public abstract class AbstractSTDataView extends ViewPart {
mgr.setRemoveAllWhenShown(true);
mgr.addMenuListener(new IMenuListener() {
@Override
- public void menuAboutToShow(IMenuManager mgr) {
+ public void menuAboutToShow(IMenuManager mgr) {
getSTViewer().getViewer().cancelEditing();
fillContextMenu(mgr);
}
@@ -263,7 +263,7 @@ public abstract class AbstractSTDataView extends ViewPart {
}
@Override
- public void setFocus() {
+ public void setFocus() {
Viewer viewer = getSTViewer().getViewer();
if (viewer != null && !viewer.getControl().isDisposed()) {
viewer.getControl().setFocus();
@@ -299,7 +299,7 @@ public abstract class AbstractSTDataView extends ViewPart {
* @since 6.0
*/
protected void fillContextMenu(IMenuManager manager) {
- Control control = stViewer.getViewer().getControl();
+ Control control = stViewer.getViewer().getControl();
if (control instanceof Tree) {
Tree tree = (Tree) control;
TreeItem[] selection = tree.getSelection();
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractPercentageDrawerField.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractPercentageDrawerField.java
index 635af6bfa7..a400cebf12 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractPercentageDrawerField.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractPercentageDrawerField.java
@@ -35,7 +35,7 @@ public abstract class AbstractPercentageDrawerField extends AbstractSTDataViewer
}
@Override
- public String getValue(Object obj) {
+ public String getValue(Object obj) {
return getPercentage(obj) + "";
}
@@ -52,7 +52,7 @@ public abstract class AbstractPercentageDrawerField extends AbstractSTDataViewer
* Percentage drawer.
*/
@Override
- public void handleEvent(Event event) {
+ public void handleEvent(Event event) {
Item item = (Item) event.item;
Display display = event.widget.getDisplay();
int index = event.index;
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractSTDataViewersField.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractSTDataViewersField.java
index 4ffa0d0174..9218724218 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractSTDataViewersField.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractSTDataViewersField.java
@@ -79,8 +79,8 @@ public abstract class AbstractSTDataViewersField implements ISTDataViewersField
* @see org.eclipse.linuxtools.dataviewers.abstractviewers.ISTDataViewersField#isShowingByDefault()
*/
/**
- * @since 5.0
- */
+ * @since 5.0
+ */
@Override
public boolean isShowingByDefault() {
return true;
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractSTViewer.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractSTViewer.java
index c521d6346d..2996b3ea30 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractSTViewer.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/AbstractSTViewer.java
@@ -133,14 +133,14 @@ public abstract class AbstractSTViewer {
viewer.addOpenListener(new IOpenListener() {
@Override
- public void open(OpenEvent event) {
+ public void open(OpenEvent event) {
handleOpenEvent(event);
}
});
viewer.getControl().addKeyListener(new KeyAdapter() {
@Override
- public void keyPressed(KeyEvent e) {
+ public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
});
@@ -516,11 +516,11 @@ public abstract class AbstractSTViewer {
* protected IDialogSettings getDialogSettings() <br>
* IDialogSettings settings = </code>PLUGINActivator<code>.getDefault().getDialogSettings().getSection(</code>
* SECTION_NAME<code>); <br>
- * if (settings == null) { <br>
- * settings = </code>PLUGINActivator<code>.getDefault().getDialogSettings().addNewSection(</code>SECTION_NAME
+ * if (settings == null) { <br>
+ * settings = </code>PLUGINActivator<code>.getDefault().getDialogSettings().addNewSection(</code>SECTION_NAME
* <code>);<br>
- * }<br>
- * return settings;
+ * }<br>
+ * return settings;
* </code>
* </p>
* <p>
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersCSVExporter.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersCSVExporter.java
index d18c38df05..61fdff1ef7 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersCSVExporter.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersCSVExporter.java
@@ -410,7 +410,7 @@ public class STDataViewersCSVExporter {
private void collectViewerParameters() {
Display.getDefault().syncExec(new Runnable() {
@Override
- public void run() {
+ public void run() {
// getting columns with the right order
Item[] unOrdColumns = stViewer.getColumns();
Item[] columns = new Item[unOrdColumns.length];
@@ -649,7 +649,7 @@ public class STDataViewersCSVExporter {
}
@Override
- protected ISTDataViewersField getField(Item column) {
+ protected ISTDataViewersField getField(Item column) {
return fieldsMap.get(column);
}
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersComparator.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersComparator.java
index 719c93417e..d8e3164446 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersComparator.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersComparator.java
@@ -212,12 +212,12 @@ public class STDataViewersComparator extends ViewerComparator implements Compara
}
@Override
- public int compare(Object o1, Object o2) {
+ public int compare(Object o1, Object o2) {
return compare(o1, o2, 0, true);
}
@Override
- public int compare(Viewer viewer, Object e1, Object e2) {
+ public int compare(Viewer viewer, Object e1, Object e2) {
return compare(e1, e2, 0, true);
}
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersSettings.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersSettings.java
index 29ce37c4ac..8082c25165 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersSettings.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STDataViewersSettings.java
@@ -27,6 +27,6 @@ public class STDataViewersSettings {
public static final String TAG_HIDE_SHOW_COLUMN_WIDTH_ = "column_width_"; //$NON-NLS-1$
// Sorter
public static final String TAG_SECTION_SORTER = "sorter_section"; //$NON-NLS-1$
- public static final String TAG_SORTER_PRIORITY_ = "sort_priority_"; //$NON-NLS-1$
+ public static final String TAG_SORTER_PRIORITY_ = "sort_priority_"; //$NON-NLS-1$
public static final String TAG_SORTER_DIRECTION_ = "sort_direction_"; //$NON-NLS-1$
}
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STOwnerDrawLabelProvider.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STOwnerDrawLabelProvider.java
index 8bfc3f090e..5409b7915f 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STOwnerDrawLabelProvider.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/STOwnerDrawLabelProvider.java
@@ -56,29 +56,29 @@ public class STOwnerDrawLabelProvider extends OwnerDrawLabelProvider {
}
@Override
- public String getToolTipText(Object element) {
+ public String getToolTipText(Object element) {
return fields.getToolTipText(element);
}
@Override
- public boolean useNativeToolTip(Object object) {
+ public boolean useNativeToolTip(Object object) {
return true;
}
@Override
- protected void measure(Event event, Object element) {
+ protected void measure(Event event, Object element) {
}
@Override
- protected void paint(Event event, Object element) {
+ protected void paint(Event event, Object element) {
if (fields.getSpecialDrawer(element) != null) {
fields.getSpecialDrawer(element).handleEvent(event);
}
}
@Override
- public void update(ViewerCell cell) {
+ public void update(ViewerCell cell) {
if (fields.getSpecialDrawer(cell.getElement()) == null) {
Object element = cell.getElement();
cell.setText(getText(element));
@@ -89,7 +89,7 @@ public class STOwnerDrawLabelProvider extends OwnerDrawLabelProvider {
}
@Override
- protected void erase(Event event, Object element) {
+ protected void erase(Event event, Object element) {
}
}
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/TreeColumnViewerFilter.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/TreeColumnViewerFilter.java
index 29ba699954..984033c85f 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/TreeColumnViewerFilter.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/abstractviewers/TreeColumnViewerFilter.java
@@ -58,7 +58,7 @@ public class TreeColumnViewerFilter extends ViewerFilter {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
- ITreeContentProvider provider = (ITreeContentProvider) treeViewer.getContentProvider();
+ ITreeContentProvider provider = (ITreeContentProvider) treeViewer.getContentProvider();
String s = field.getValue(element);
if (s.contains(matchingText)) {
return true;
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCollapseAllTreeAction.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCollapseAllTreeAction.java
index a45cdd637d..82dbde84b0 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCollapseAllTreeAction.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCollapseAllTreeAction.java
@@ -41,7 +41,7 @@ public class STCollapseAllTreeAction extends Action {
* @see org.eclipse.jface.action.Action#run()
*/
@Override
- public void run() {
+ public void run() {
Object input = stViewer.getViewer().getInput();
if (input != null) {
stViewer.getViewer().collapseAll();
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCollapseSelectionAction.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCollapseSelectionAction.java
index 5ba03a47b9..f91a6ffd41 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCollapseSelectionAction.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCollapseSelectionAction.java
@@ -45,7 +45,7 @@ public class STCollapseSelectionAction extends Action {
* @see org.eclipse.jface.action.Action#run()
*/
@Override
- public void run() {
+ public void run() {
TreeSelection selection = (TreeSelection) stViewer.getViewer().getSelection();
if (selection != null && selection != TreeSelection.EMPTY) {
for (Iterator<?> itSel = selection.iterator(); itSel.hasNext();) {
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCopyAction.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCopyAction.java
index 94081189c6..7e45b75397 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCopyAction.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STCopyAction.java
@@ -40,7 +40,7 @@ public class STCopyAction extends Action {
}
@Override
- public void run() {
+ public void run() {
Clipboard cb = new Clipboard(Display.getDefault());
IStructuredSelection selections = (IStructuredSelection) stViewer.getViewer().getSelection();
Iterator<?> iterator = selections.iterator();
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STDataViewersSortAction.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STDataViewersSortAction.java
index 33df283aca..4dcce1cfb2 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STDataViewersSortAction.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STDataViewersSortAction.java
@@ -33,23 +33,23 @@ public class STDataViewersSortAction extends Action {
* @param stViewer The AbstractSTViewer to create the action for.
*/
public STDataViewersSortAction(AbstractSTViewer stViewer) {
- super(STDataViewersMessages.sortAction_title, STDataViewersImages
- .getImageDescriptor(STDataViewersImages.IMG_SORT));
- super.setToolTipText(STDataViewersMessages.sortAction_tooltip);
- this.stViewer = stViewer;
+ super(STDataViewersMessages.sortAction_title, STDataViewersImages
+ .getImageDescriptor(STDataViewersImages.IMG_SORT));
+ super.setToolTipText(STDataViewersMessages.sortAction_tooltip);
+ this.stViewer = stViewer;
- // building a sort dialog
- dialog = new STDataViewersSortDialog(stViewer.getViewer().getControl().getShell(), stViewer.getTableSorter());
+ // building a sort dialog
+ dialog = new STDataViewersSortDialog(stViewer.getViewer().getControl().getShell(), stViewer.getTableSorter());
- setEnabled(true);
+ setEnabled(true);
}
@Override
- public void run() {
+ public void run() {
if (dialog.open() == Window.OK && dialog.isDirty()) {
BusyIndicator.showWhile(null, new Runnable() {
@Override
- public void run() {
+ public void run() {
stViewer.setComparator(dialog.getSorter());
}
});
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExpandAllTreeAction.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExpandAllTreeAction.java
index 55cc2eb4da..aceaded6e6 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExpandAllTreeAction.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExpandAllTreeAction.java
@@ -41,7 +41,7 @@ public class STExpandAllTreeAction extends Action {
* @see org.eclipse.jface.action.Action#run()
*/
@Override
- public void run() {
+ public void run() {
Object input = stViewer.getViewer().getInput();
if (input != null) {
stViewer.getViewer().expandAll();
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExpandSelectionAction.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExpandSelectionAction.java
index a00e4a7d64..9ba913109e 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExpandSelectionAction.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExpandSelectionAction.java
@@ -45,7 +45,7 @@ public class STExpandSelectionAction extends Action {
* @see org.eclipse.jface.action.Action#run()
*/
@Override
- public void run() {
+ public void run() {
TreeSelection selection = (TreeSelection) stViewer.getViewer().getSelection();
if (selection != null && selection != TreeSelection.EMPTY) {
for (Iterator<?> itSel = selection.iterator(); itSel.hasNext();) {
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExportToCSVAction.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExportToCSVAction.java
index 42da18095f..39a28d5dba 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExportToCSVAction.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STExportToCSVAction.java
@@ -44,12 +44,12 @@ public class STExportToCSVAction extends Action {
* the stViewer to export
*/
public STExportToCSVAction(AbstractSTViewer stViewer) {
- super(STDataViewersMessages.exportToCSVAction_title,
- STDataViewersImages
- .getImageDescriptor(STDataViewersImages.IMG_EXPORT));
+ super(STDataViewersMessages.exportToCSVAction_title,
+ STDataViewersImages
+ .getImageDescriptor(STDataViewersImages.IMG_EXPORT));
- this.stViewer = stViewer;
- this.exporter = new STDataViewersCSVExporter(stViewer);
+ this.stViewer = stViewer;
+ this.exporter = new STDataViewersCSVExporter(stViewer);
}
/*
@@ -58,13 +58,13 @@ public class STExportToCSVAction extends Action {
* @see org.eclipse.jface.action.Action#run()
*/
@Override
- public void run() {
+ public void run() {
STDataViewersExportToCSVDialog dialog = new STDataViewersExportToCSVDialog(stViewer.getViewer().getControl()
.getShell(), exporter);
if (dialog.open() == Window.OK) {
Job exportToCSVJob = new Job("Export to CSV") {
@Override
- public IStatus run(IProgressMonitor monitor) {
+ public IStatus run(IProgressMonitor monitor) {
exporter.export(monitor);
return Status.OK_STATUS;
}
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STHideShowColAction.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STHideShowColAction.java
index 2602b30ce7..c62223eb4c 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STHideShowColAction.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/actions/STHideShowColAction.java
@@ -30,10 +30,10 @@ public class STHideShowColAction extends Action {
* @param stViewer The AbstractSTViewer to create the action for.
*/
public STHideShowColAction(AbstractSTViewer stViewer) {
- super(STDataViewersMessages.hideshowAction_title, STDataViewersImages
- .getImageDescriptor(STDataViewersImages.IMG_EDIT_PROPERTIES));
- this.stViewer = stViewer;
- setEnabled(true);
+ super(STDataViewersMessages.hideshowAction_title, STDataViewersImages
+ .getImageDescriptor(STDataViewersImages.IMG_EDIT_PROPERTIES));
+ this.stViewer = stViewer;
+ setEnabled(true);
}
@Override
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersExportToCSVDialog.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersExportToCSVDialog.java
index 8f5e470786..562691f31e 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersExportToCSVDialog.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersExportToCSVDialog.java
@@ -84,19 +84,19 @@ public class STDataViewersExportToCSVDialog extends Dialog {
private ModifyListener updatePreviewModifyListener = new ModifyListener() {
@Override
- public void modifyText(ModifyEvent e) {
+ public void modifyText(ModifyEvent e) {
updatePreview();
}
};
private SelectionListener updatePreviewSelectionListener = new SelectionListener() {
@Override
- public void widgetDefaultSelected(SelectionEvent e) {
+ public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
updatePreview();
}
};
@@ -174,7 +174,7 @@ public class STDataViewersExportToCSVDialog extends Dialog {
browseOutputButton.setText("File System...");
browseOutputButton.addSelectionListener(new SelectionAdapter() {
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
handleBrowse();
}
});
@@ -185,7 +185,7 @@ public class STDataViewersExportToCSVDialog extends Dialog {
browseOutputInWorkspaceButton.setText("Workspace...");
browseOutputInWorkspaceButton.addSelectionListener(new SelectionAdapter() {
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
handleBrowseWorkspace();
}
});
@@ -240,12 +240,12 @@ public class STDataViewersExportToCSVDialog extends Dialog {
exportTreePrefixButton.addSelectionListener(updatePreviewSelectionListener);
exportTreePrefixButton.addSelectionListener(new SelectionListener() {
@Override
- public void widgetDefaultSelected(SelectionEvent e) {
+ public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
boolean enabled = exportTreePrefixButton.getSelection();
enableTreePrefixText(enabled);
}
@@ -349,12 +349,12 @@ public class STDataViewersExportToCSVDialog extends Dialog {
restoreDefaults.setText("Restore Defaults");
restoreDefaults.addSelectionListener(new SelectionListener() {
@Override
- public void widgetDefaultSelected(SelectionEvent e) {
+ public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
restoreDefaults();
}
});
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersHideShowColumnsDialog.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersHideShowColumnsDialog.java
index 77bd44eb54..f9b53c55fe 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersHideShowColumnsDialog.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersHideShowColumnsDialog.java
@@ -60,13 +60,13 @@ public class STDataViewersHideShowColumnsDialog extends Dialog {
}
@Override
- protected void configureShell(Shell newShell) {
+ protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(STDataViewersMessages.hideshowDialog_title);
}
@Override
- protected Control createDialogArea(Composite parent) {
+ protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
GridData layoutData = new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1);
composite.setLayoutData(layoutData);
@@ -84,12 +84,12 @@ public class STDataViewersHideShowColumnsDialog extends Dialog {
selectAllButton.setText(STDataViewersMessages.selectAll_text);
selectAllButton.addSelectionListener(new SelectionListener() {
@Override
- public void widgetDefaultSelected(SelectionEvent e) {
+ public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
dirty = true;
checkButtonsTable.setAllChecked(true);
}
@@ -101,12 +101,12 @@ public class STDataViewersHideShowColumnsDialog extends Dialog {
deselectAllButton.setText(STDataViewersMessages.deselectAll_text);
deselectAllButton.addSelectionListener(new SelectionListener() {
@Override
- public void widgetDefaultSelected(SelectionEvent e) {
+ public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
dirty = true;
checkButtonsTable.setAllChecked(false);
}
@@ -132,7 +132,7 @@ public class STDataViewersHideShowColumnsDialog extends Dialog {
private ICheckStateListener checkStateListener = new ICheckStateListener() {
@Override
- public void checkStateChanged(CheckStateChangedEvent event) {
+ public void checkStateChanged(CheckStateChangedEvent event) {
dirty = true;
}
};
@@ -158,7 +158,7 @@ public class STDataViewersHideShowColumnsDialog extends Dialog {
tableViewer.setContentProvider(new IStructuredContentProvider() {
@Override
- public Object[] getElements(Object inputElement) {
+ public Object[] getElements(Object inputElement) {
if (inputElement instanceof Item[]) {
Item[] columns = (Item[]) inputElement;
int[] order = stViewer.getColumnOrder();
@@ -175,17 +175,17 @@ public class STDataViewersHideShowColumnsDialog extends Dialog {
}
@Override
- public void dispose() {
+ public void dispose() {
}
@Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
});
tableViewer.setLabelProvider(new LabelProvider() {
@Override
- public String getText(Object element) {
+ public String getText(Object element) {
if (element instanceof Item) {
Item column = (Item) element;
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersSortDialog.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersSortDialog.java
index 7ee272315f..baff09a163 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersSortDialog.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/dialogs/STDataViewersSortDialog.java
@@ -66,7 +66,7 @@ public class STDataViewersSortDialog extends TrayDialog {
* (non-Javadoc) Method declared on Window.
*/
@Override
- protected void configureShell(Shell newShell) {
+ protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(STDataViewersMessages.sortDialog_title);
}
@@ -75,7 +75,7 @@ public class STDataViewersSortDialog extends TrayDialog {
* (non-Javadoc) Method declared on Dialog.
*/
@Override
- protected Control createDialogArea(Composite parent) {
+ protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
if (sorter == null) {
return composite;
@@ -128,7 +128,7 @@ public class STDataViewersSortDialog extends TrayDialog {
ascendingButtons[i].setText(getAscendingText(i));
ascendingButtons[i].addSelectionListener(new SelectionAdapter() {
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
markDirty();
}
});
@@ -136,7 +136,7 @@ public class STDataViewersSortDialog extends TrayDialog {
descendingButtons[i].setText(getDescendingText(i));
descendingButtons[i].addSelectionListener(new SelectionAdapter() {
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
markDirty();
}
});
@@ -144,7 +144,7 @@ public class STDataViewersSortDialog extends TrayDialog {
if (i < priorityCombos.length - 1) {
priorityCombos[i].addSelectionListener(new SelectionAdapter() {
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
List<String> allItems = new ArrayList<>(Arrays.asList(priorityCombos[index].getItems()));
computeSelectionItems(index, allItems);
markDirty();
@@ -179,7 +179,7 @@ public class STDataViewersSortDialog extends TrayDialog {
} else {
priorityCombos[i].addSelectionListener(new SelectionAdapter() {
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
markDirty();
}
});
@@ -242,7 +242,7 @@ public class STDataViewersSortDialog extends TrayDialog {
setButtonSize(defaultsButton, new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.FILL_HORIZONTAL));
defaultsButton.addSelectionListener(new SelectionAdapter() {
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
restoreDefaults();
markDirty();
}
@@ -295,7 +295,7 @@ public class STDataViewersSortDialog extends TrayDialog {
}
@Override
- protected void okPressed() {
+ protected void okPressed() {
if (isDirty()) {
outerfor: for (int i = priorityCombos.length - 1; i >= 0; i--) {
Combo combo = priorityCombos[i];
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STColumnSizeListener.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STColumnSizeListener.java
index b8e63c2cbe..ae2fb5a36c 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STColumnSizeListener.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STColumnSizeListener.java
@@ -24,7 +24,7 @@ public class STColumnSizeListener implements Listener {
}
@Override
- public void handleEvent(Event event) {
+ public void handleEvent(Event event) {
if (hideshowMng != null) {
Item column = (Item) event.widget;
AbstractSTViewer stViewer = hideshowMng.getSTViewer();
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STDisposeListener.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STDisposeListener.java
index 4407321280..7b59006f27 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STDisposeListener.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STDisposeListener.java
@@ -22,7 +22,7 @@ public class STDisposeListener implements DisposeListener {
}
@Override
- public void widgetDisposed(DisposeEvent e) {
+ public void widgetDisposed(DisposeEvent e) {
stViewer.saveState();
}
diff --git a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STHeaderListener.java b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STHeaderListener.java
index cbcbac4dc7..0ae96f340d 100644
--- a/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STHeaderListener.java
+++ b/profiling/org.eclipse.linuxtools.dataviewers/src/org/eclipse/linuxtools/dataviewers/listeners/STHeaderListener.java
@@ -30,12 +30,12 @@ public class STHeaderListener implements SelectionListener {
}
@Override
- public void widgetDefaultSelected(SelectionEvent e) {
+ public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
@Override
- public void widgetSelected(SelectionEvent e) {
+ public void widgetSelected(SelectionEvent e) {
final Item column = (Item) e.widget;
final ISTDataViewersField field = (ISTDataViewersField) column.getData();
resortTable(column, field);
@@ -59,7 +59,7 @@ public class STHeaderListener implements SelectionListener {
BusyIndicator.showWhile(null, new Runnable() {
@Override
- public void run() {
+ public void run() {
stViewer.getViewer().refresh();
stViewer.updateDirectionIndicator(column);
}
diff --git a/profiling/org.eclipse.linuxtools.profiling-feature/feature.xml b/profiling/org.eclipse.linuxtools.profiling-feature/feature.xml
index ddc632cb8e..8dfc1ce0f3 100644
--- a/profiling/org.eclipse.linuxtools.profiling-feature/feature.xml
+++ b/profiling/org.eclipse.linuxtools.profiling-feature/feature.xml
@@ -66,13 +66,13 @@
download-size="0"
install-size="0"
version="0.0.0"/>
-
+
<plugin
id="org.eclipse.linuxtools.tools.launch.core"
download-size="0"
install-size="0"
version="0.0.0"/>
-
+
<plugin
id="org.eclipse.linuxtools.tools.launch.ui"
download-size="0"
diff --git a/profiling/org.eclipse.linuxtools.profiling-feature/pom.xml b/profiling/org.eclipse.linuxtools.profiling-feature/pom.xml
index 30fecae7f2..682b5e31b7 100644
--- a/profiling/org.eclipse.linuxtools.profiling-feature/pom.xml
+++ b/profiling/org.eclipse.linuxtools.profiling-feature/pom.xml
@@ -22,7 +22,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools Profiling Framework Feature</name>
-
+
<build>
<plugins>
<plugin>
diff --git a/profiling/org.eclipse.linuxtools.profiling.docs/build-helper.xml b/profiling/org.eclipse.linuxtools.profiling.docs/build-helper.xml
index 9b6c6a449f..fc43286b4c 100644
--- a/profiling/org.eclipse.linuxtools.profiling.docs/build-helper.xml
+++ b/profiling/org.eclipse.linuxtools.profiling.docs/build-helper.xml
@@ -5,7 +5,7 @@
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-
+
Contributors:
Red Hat - initial API and implementation
-->
@@ -14,57 +14,57 @@
Generate Eclipse help content for the Linux Tools profiling user guide
</description>
- <property name="help.doc.url.base" value="http://wiki.eclipse.org"/>
+ <property name="help.doc.url.base" value="http://wiki.eclipse.org"/>
+
+ <path id="wikitext.tasks.classpath">
+ <!-- Replace dir with the dir you have wikitext installed into.-->
+ <fileset dir="/notnfs/jjohnstn/eclipse-4.2/eclipse/plugins">
+ <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
+ </fileset>
+ </path>
- <path id="wikitext.tasks.classpath">
- <!-- Replace dir with the dir you have wikitext installed into.-->
- <fileset dir="/notnfs/jjohnstn/eclipse-4.2/eclipse/plugins">
- <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
- </fileset>
- </path>
-
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
- <target name="all" description="Generate Eclipse help content for the Linux Tools profiling user guide">
- <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="Profiling Framework User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
+ <target name="all" description="Generate Eclipse help content for the Linux Tools profiling user guide">
+ <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="Profiling Framework User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
- <path name="Linux_Tools_Project/Profiling/User_Guide" title="Profiling Framework User Guide" generateToc="false" />
- <stylesheet url="book.css" />
- <pageAppendum>
+ <path name="Linux_Tools_Project/Profiling/User_Guide" title="Profiling Framework User Guide" generateToc="false" />
+ <stylesheet url="book.css" />
+ <pageAppendum>
= Updating This Document =
-
-This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
+
+This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
http://wiki.eclipse.org/Linux_Tools_Project/Profiling/User_Guide
</pageAppendum>
- </mediawiki-to-eclipse-help>
- <antcall target="test" />
- </target>
+ </mediawiki-to-eclipse-help>
+ <antcall target="test" />
+ </target>
- <target name="test" description="verify that all of the HTML files are well-formed XML">
- <echo level="info">
+ <target name="test" description="verify that all of the HTML files are well-formed XML">
+ <echo level="info">
Validating help content XML and HTML files: The Eclipse help system expects well-formed XML
-
+
If validation fails it is because either:
-
+
* the userguide source code is poorly formed, or
* the WikiText MediaWiki parser has a bug
-
+
Problems with userguide source are usually caused by improper use of HTML markup in the MediaWiki source,
or inadvertently starting a line with a space character (in MediaWiki this starts a preformatted block)
- </echo>
+ </echo>
- <!--
- Don't bother with DTD validation: we only care if the files are well-formed.
- We therefore provide an empty DTD
- -->
- <echo file="tmp/__empty.dtd" message="" />
- <xmlvalidate lenient="true">
- <fileset dir="Linux_Tools_Project">
- <include name="**/*.html" />
- </fileset>
- <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
- </xmlvalidate>
- <delete dir="tmp"/>
- </target>
+ <!--
+ Don't bother with DTD validation: we only care if the files are well-formed.
+ We therefore provide an empty DTD
+ -->
+ <echo file="tmp/__empty.dtd" message="" />
+ <xmlvalidate lenient="true">
+ <fileset dir="Linux_Tools_Project">
+ <include name="**/*.html" />
+ </fileset>
+ <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
+ </xmlvalidate>
+ <delete dir="tmp"/>
+ </target>
</project>
diff --git a/profiling/org.eclipse.linuxtools.profiling.docs/toc.xml b/profiling/org.eclipse.linuxtools.profiling.docs/toc.xml
index a30183ca99..24fbc5f34b 100644
--- a/profiling/org.eclipse.linuxtools.profiling.docs/toc.xml
+++ b/profiling/org.eclipse.linuxtools.profiling.docs/toc.xml
@@ -1,9 +1,9 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/Profiling/User_Guide/User-Guide.html" label="Profiling Framework User Guide">
- <topic href="Linux_Tools_Project/Profiling/User_Guide/User-Guide.html" label="Profiling Framework User Guide">
- <topic href="Linux_Tools_Project/Profiling/User_Guide/User-Guide.html" label="Overview"></topic>
- <topic href="Linux_Tools_Project/Profiling/User_Guide/Profiling-Categories.html" label="Profiling Categories"></topic>
- <topic href="Linux_Tools_Project/Profiling/User_Guide/Profiling-Configurations.html" label="Profiling Configurations"></topic>
- <topic href="Linux_Tools_Project/Profiling/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
- </topic>
+ <topic href="Linux_Tools_Project/Profiling/User_Guide/User-Guide.html" label="Profiling Framework User Guide">
+ <topic href="Linux_Tools_Project/Profiling/User_Guide/User-Guide.html" label="Overview"></topic>
+ <topic href="Linux_Tools_Project/Profiling/User_Guide/Profiling-Categories.html" label="Profiling Categories"></topic>
+ <topic href="Linux_Tools_Project/Profiling/User_Guide/Profiling-Configurations.html" label="Profiling Configurations"></topic>
+ <topic href="Linux_Tools_Project/Profiling/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
+ </topic>
</toc> \ No newline at end of file
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch.ui.rdt.proxy/src/org/eclipse/linuxtools/internal/profiling/launch/ui/rdt/proxy/Messages.java b/profiling/org.eclipse.linuxtools.profiling.launch.ui.rdt.proxy/src/org/eclipse/linuxtools/internal/profiling/launch/ui/rdt/proxy/Messages.java
index a8bb1d51a3..4d5fff1b31 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch.ui.rdt.proxy/src/org/eclipse/linuxtools/internal/profiling/launch/ui/rdt/proxy/Messages.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch.ui.rdt.proxy/src/org/eclipse/linuxtools/internal/profiling/launch/ui/rdt/proxy/Messages.java
@@ -3,14 +3,14 @@ package org.eclipse.linuxtools.internal.profiling.launch.ui.rdt.proxy;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.profiling.launch.ui.rdt.proxy.messages"; //$NON-NLS-1$
- public static String RDTResourceSelectorProxy_unsupported_resourceType;
- public static String RDTResourceSelectorProxy_URI_syntax_error;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.profiling.launch.ui.rdt.proxy.messages"; //$NON-NLS-1$
+ public static String RDTResourceSelectorProxy_unsupported_resourceType;
+ public static String RDTResourceSelectorProxy_URI_syntax_error;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/plugin.xml b/profiling/org.eclipse.linuxtools.profiling.launch/plugin.xml
index 2d9f4dff75..d67e348a6c 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/plugin.xml
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/plugin.xml
@@ -32,11 +32,11 @@
modes="linuxtools"
path="/linuxtools/category">
<class class="org.eclipse.linuxtools.internal.profiling.launch.provider.launch.ProviderLaunchShortcut">
- <parameter
+ <parameter
name="type"
value="timing"/>
- <parameter
- name="configurationId"
+ <parameter
+ name="configurationId"
value="org.eclipse.linuxtools.profiling.provider.TimingLaunchConfigurationType"/>
</class>
<contextualLaunch>
@@ -84,10 +84,10 @@
id="org.eclipse.linuxtools.profiling.provider.TimingLaunchConfigurationTabGroup"
type="org.eclipse.linuxtools.profiling.provider.TimingLaunchConfigurationType">
<class class="org.eclipse.linuxtools.internal.profiling.launch.provider.ProviderLaunchConfigurationTabGroup">
- <parameter
+ <parameter
name="type"
value="timing"/>
- <parameter
+ <parameter
name="name"
value="Timing"/>
</class>
@@ -112,7 +112,7 @@
id="org.eclipse.linuxtools.profiling.provider.TimingPreferencePage"
name="%page.name.0">
<class class="org.eclipse.linuxtools.internal.profiling.launch.provider.AbstractProviderPreferencesPage">
- <parameter
+ <parameter
name="type"
value="timing"/>
</class>
@@ -129,11 +129,11 @@
modes="linuxtools"
path="/linuxtools/category">
<class class="org.eclipse.linuxtools.internal.profiling.launch.provider.launch.ProviderLaunchShortcut">
- <parameter
+ <parameter
name="type"
value="memory"/>
- <parameter
- name="configurationId"
+ <parameter
+ name="configurationId"
value="org.eclipse.linuxtools.profiling.provider.MemoryLaunchConfigurationType"/>
</class>
<contextualLaunch>
@@ -181,10 +181,10 @@
id="org.eclipse.linuxtools.profiling.provider.MemoryLaunchConfigurationTabGroup"
type="org.eclipse.linuxtools.profiling.provider.MemoryLaunchConfigurationType">
<class class="org.eclipse.linuxtools.internal.profiling.launch.provider.ProviderLaunchConfigurationTabGroup">
- <parameter
+ <parameter
name="type"
value="memory"/>
- <parameter
+ <parameter
name="name"
value="Memory"/>
</class>
@@ -209,7 +209,7 @@
id="org.eclipse.linuxtools.profiling.provider.MemoryPreferencePage"
name="%page.name.1">
<class class="org.eclipse.linuxtools.internal.profiling.launch.provider.AbstractProviderPreferencesPage">
- <parameter
+ <parameter
name="type"
value="memory"/>
</class>
@@ -226,11 +226,11 @@
modes="linuxtools"
path="/linuxtools/category">
<class class="org.eclipse.linuxtools.internal.profiling.launch.provider.launch.ProviderLaunchShortcut">
- <parameter
+ <parameter
name="type"
value="coverage"/>
- <parameter
- name="configurationId"
+ <parameter
+ name="configurationId"
value="org.eclipse.linuxtools.profiling.provider.CoverageLaunchConfigurationType"/>
</class>
<contextualLaunch>
@@ -278,10 +278,10 @@
id="org.eclipse.linuxtools.profiling.provider.CoverageLaunchConfigurationTabGroup"
type="org.eclipse.linuxtools.profiling.provider.CoverageLaunchConfigurationType">
<class class="org.eclipse.linuxtools.internal.profiling.launch.provider.ProviderLaunchConfigurationTabGroup">
- <parameter
+ <parameter
name="type"
value="coverage"/>
- <parameter
+ <parameter
name="name"
value="Coverage"/>
</class>
@@ -306,7 +306,7 @@
id="org.eclipse.linuxtools.profiling.provider.CoveragePreferencePage"
name="%page.name.2">
<class class="org.eclipse.linuxtools.internal.profiling.launch.provider.AbstractProviderPreferencesPage">
- <parameter
+ <parameter
name="type"
value="coverage"/>
</class>
@@ -522,6 +522,6 @@
<configurationType
id="org.eclipse.cdt.launch.applicationLaunchType">
</configurationType>
- </shortcut>
+ </shortcut>
</extension>
</plugin>
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/AbstractProfilingOptionsTab.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/AbstractProfilingOptionsTab.java
index 938e708331..62f899ff8d 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/AbstractProfilingOptionsTab.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/AbstractProfilingOptionsTab.java
@@ -44,402 +44,402 @@ import org.eclipse.swt.widgets.Composite;
*/
public abstract class AbstractProfilingOptionsTab extends AbstractLaunchConfigurationTab {
- private String type;
- private String name;
- private String id;
- private Composite top;
- private Combo providerCombo;
- private AbstractLaunchConfigurationTab[] tabs;
- private ILaunchConfiguration initial;
- private Map<String, String> comboItems;
- private CTabFolder tabgroup;
- protected Image img;
-
- // if tabs are being initialized do not call performApply()
- private Map<String, Boolean> initialized = new HashMap<> ();
-
- /**
- * Get list of profiling providers for the user to choose from.
- *
- * @return Map of provider ids and provider tool names
- */
- protected abstract Map<String, String> getProviders();
-
- @Override
- public void createControl(Composite parent) {
- top = new Composite(parent, SWT.NONE);
- setControl(top);
- top.setLayout(new GridLayout(1, true));
-
- providerCombo = new Combo(top, SWT.READ_ONLY);
- comboItems = getProviders();
- Set<String> providerNames = comboItems.keySet();
- providerCombo.setItems(providerNames.toArray(new String[0]));
-
- tabgroup = new CTabFolder(top, SWT.NONE);
- tabgroup.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true,
- true));
-
- providerCombo.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String curProviderId = comboItems.get(providerCombo.getText());
- loadTabGroupItems(tabgroup, curProviderId);
- initializeFrom(initial);
- // Since we are calling initializeFrom manually, we have to
- // update the launch configuration dialog manually to ensure
- // initial validation on the configuration.
- updateLaunchConfigurationDialog();
- top.layout();
- }
- });
- }
-
- /**
- * Get the default provider id to use if one is not set for the configuration.
- *
- * @return default provider id
- */
- protected abstract String getDefaultProviderId();
-
- private void loadTabGroupItems(CTabFolder tabgroup, String curProviderId) {
- // dispose of old tabs and their state
- for (CTabItem item : tabgroup.getItems()) {
- item.dispose();
- }
- setErrorMessage(null);
- initialized.clear();
-
- ProfileLaunchConfigurationTabGroup tabGroupConfig;
-
- if (curProviderId == null || curProviderId.isEmpty()) {
- curProviderId = getDefaultProviderId();
- }
-
- // starting initialization of this tab's controls
- initialized.put(curProviderId, false);
-
- tabGroupConfig = ProviderFramework.getTabGroupProviderFromId(curProviderId);
- if (tabGroupConfig == null) {
- String profilingToolName = null;
- try {
- profilingToolName = initial.getAttribute(ProviderProfileConstants.PROVIDER_CONFIG_TOOLNAME_ATT, (String)null);
- } catch (CoreException e) {
- // do nothing
- }
- if (profilingToolName == null) {
- setErrorMessage(NLS.bind(Messages.ProfilingTab_specified_providerid_not_installed, curProviderId));
- } else {
- setErrorMessage(NLS.bind(Messages.ProfilingTab_specified_profiler_not_installed, profilingToolName));
- }
- return;
- }
- tabs = tabGroupConfig.getProfileTabs();
- setProvider(curProviderId);
-
- // Show provider name in combo.
- int itemIndex = getComboItemIndexFromId(curProviderId);
- providerCombo.select(itemIndex);
-
- // Set name of configuration.
- setConfigurationName(providerCombo.getText());
-
- // create the tab item, and load the specified tab inside
- for (ILaunchConfigurationTab tab : tabs) {
- tab.setLaunchConfigurationDialog(getLaunchConfigurationDialog());
- CTabItem item = new CTabItem(tabgroup, SWT.NONE);
- item.setText(tab.getName());
- item.setImage(tab.getImage());
-
- tab.createControl(tabgroup);
- item.setControl(tab.getControl());
- tabgroup.setSelection(0);
- }
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
- if (providerCombo != null && !providerCombo.getText().isEmpty()) {
- for (AbstractLaunchConfigurationTab tab : tabs) {
- tab.setDefaults(configuration);
- }
- }
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration configuration) {
- /**
- * First time the configuration is selected.
- *
- * This is a cheap way to get access to the launch configuration. Our
- * tabs are loaded dynamically, so the tab group doesn't "know" about
- * them. We get access to this launch configuration to ensure that we
- * can properly load the widgets the first time.
- */
-
- // update current configuration (initial) with configuration being
- // passed in
- initial = configuration;
-
-
- // check if there exists a launch provider id in the configuration
- if (initial != null) {
- try {
- String providerId = initial.getAttribute(
- ProviderProfileConstants.PROVIDER_CONFIG_ATT, (String)null);
- // load provider corresponding to specified ids
- loadTabGroupItems(tabgroup, providerId);
- } catch (CoreException e) {
- // continue, initialize tabs
- }
- }
- if (tabs != null) {
- for (AbstractLaunchConfigurationTab tab : tabs) {
- tab.initializeFrom(configuration);
- }
- }
-
- // finished initialization
- initialized.put(getProviderId(), true);
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
- // make sure tabs are not null, and the tab's controls have been
- // initialized.
-
- Boolean isInitialized = initialized.get(getProviderId());
- isInitialized = (isInitialized != null) ? isInitialized : false;
-
- if (tabs != null && isInitialized) {
- for (AbstractLaunchConfigurationTab tab : tabs) {
- tab.performApply(configuration);
- }
- }
- }
-
- /**
- * Set the provider attribute in the specified configuration.
- *
- * @param configuration a configuration
- */
- private void setProvider(String providerId) {
- try {
- ILaunchConfigurationWorkingCopy wc = initial.getWorkingCopy();
- wc.setAttribute(ProviderProfileConstants.PROVIDER_CONFIG_ATT,
- providerId);
- initial = wc.doSave();
- } catch (CoreException e1) {
- e1.printStackTrace();
- }
- }
-
- /**
- * Set name of the launch configuration.
- *
- * @param newToolName String tool name to be appended to configuration name,
- */
- protected void setConfigurationName(String newToolName) {
- try {
- String currentToolName = initial.getAttribute(
- ProviderProfileConstants.PROVIDER_CONFIG_TOOLNAME_ATT, ""); //$NON-NLS-1$
-
- // Append the new tool name as long as the current and new tool
- // names are different.
- if (newToolName != null && !newToolName.isEmpty()
- && !currentToolName.equals(newToolName)) {
-
- String projectName = initial.getAttribute(
- ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
-
- // String of the form <project name> [<tool name>].
- String newConfigurationName = ProviderLaunchShortcut
- .generateProviderConfigurationName(projectName,
- newToolName);
-
- // Unique name of the form <project name> [<tool name>]{(<number>)}.
- String newUniqueToolName = getLaunchManager()
- .generateLaunchConfigurationName(newConfigurationName);
-
- // Save changes in current configuration.
- ILaunchConfigurationWorkingCopy wc = initial.getWorkingCopy();
- wc.rename(newUniqueToolName);
- wc.setAttribute(
- ProviderProfileConstants.PROVIDER_CONFIG_TOOLNAME_ATT,
- newToolName);
- initial = wc.doSave();
-
- // Set name field in launch configuration dialog to avoid the
- // new configuration name from being overwritten.
- getLaunchConfigurationDialog().setName(newUniqueToolName);
- }
- } catch (CoreException e) {
- // If unable to set the name, leave the original name as is.
- }
- }
-
- /**
- * Get the provider ID for the provider of the currently loaded
- * configuration.
- *
- * @return the provider ID or an empty string if the configuration
- * has no provider ID defined.
- */
- private String getProviderId() {
- try {
- return initial.getAttribute(
- ProviderProfileConstants.PROVIDER_CONFIG_ATT, ""); //$NON-NLS-1$
- } catch (CoreException e) {
- return ""; //$NON-NLS-1$
- }
- }
-
- /**
- * Get Combo item name from specified id
- *
- * @param id provider id
- * @return name of item, <code>null</code> if no entry found with given id.
- */
- private String getComboItemNameFromId(String id) {
- for (Entry<String, String> entry : comboItems.entrySet()) {
- if (id.equals(entry.getValue())) {
- return entry.getKey();
- }
- }
- return null;
- }
-
- /**
- * Get index of specific name in the combo items list
- *
- * @param name name of item
- * @return index of given name, -1 if it not found
- */
- private int getItemIndex(Combo combo, String name) {
- int itemCount = combo.getItemCount();
- for (int i = 0; i < itemCount; i++) {
- if (combo.getItem(i).equals(name)) {
- return i;
- }
- }
- return -1;
- }
-
- /**
- * Get index of specific id in the provider combo items list
- *
- * @param id
- * @return index of given id in provider combo items list, -1 if it not found.
- */
- private int getComboItemIndexFromId(String id) {
- String providerName = getComboItemNameFromId(id);
- return getItemIndex(providerCombo, providerName);
- }
-
- @Override
- public boolean isValid(ILaunchConfiguration config) {
- String provider;
- try {
- provider = config.getAttribute(
- ProviderProfileConstants.PROVIDER_CONFIG_ATT, ""); //$NON-NLS-1$
- } catch (CoreException e) {
- setErrorMessage(e.getMessage());
- return false;
- }
- if (provider.isEmpty()) {
- setErrorMessage(Messages.ProfilingTab_providerid_not_found);
- return false;
- }
-
- Boolean isInitialized = initialized.get(getProviderId());
-
- if (isInitialized) {
- // Tabs should not be null after initialization.
- if (tabs == null) {
- return false;
- }
-
- // Validate tab configurations of underlying tool.
- for (AbstractLaunchConfigurationTab tab : tabs) {
- if (!tab.isValid(config)) {
- return false;
- }
- }
- }
- return true;
- }
-
- /**
- * Get name of profiling type that used for this tab.
- *
- * @return String profiling name.
- */
- @Override
- public String getName() {
- return name;
- }
-
- /**
- * Set the name for this tab.
- *
- * @param name
- */
- protected void setName(String name) {
- this.name = name;
- }
-
- @Override
- public String getId() {
- return id;
- }
-
- /**
- * Set the id for this tab.
- *
- * @param id
- */
- protected void setId(String id) {
- this.id = id;
- }
-
- /**
- * Get profiling type of the configuration.
- *
- * @return String profiling type this plug-in supports.
- */
- protected String getProfilingType() {
- return type;
- }
-
- /**
- * Set profiling type of configuration.
- *
- * @param type
- */
- protected void setProfilingType(String type) {
- this.type = type;
- }
-
- @Override
- public Image getImage() {
- return img;
- }
-
- /**
- * Set the image for this tab.
- *
- * @param img
- */
- public void setImage(Image img) {
- this.img = img;
- }
-
- @Override
- public void dispose() {
- if (img != null) {
- img.dispose();
- }
- super.dispose();
- }
+ private String type;
+ private String name;
+ private String id;
+ private Composite top;
+ private Combo providerCombo;
+ private AbstractLaunchConfigurationTab[] tabs;
+ private ILaunchConfiguration initial;
+ private Map<String, String> comboItems;
+ private CTabFolder tabgroup;
+ protected Image img;
+
+ // if tabs are being initialized do not call performApply()
+ private Map<String, Boolean> initialized = new HashMap<> ();
+
+ /**
+ * Get list of profiling providers for the user to choose from.
+ *
+ * @return Map of provider ids and provider tool names
+ */
+ protected abstract Map<String, String> getProviders();
+
+ @Override
+ public void createControl(Composite parent) {
+ top = new Composite(parent, SWT.NONE);
+ setControl(top);
+ top.setLayout(new GridLayout(1, true));
+
+ providerCombo = new Combo(top, SWT.READ_ONLY);
+ comboItems = getProviders();
+ Set<String> providerNames = comboItems.keySet();
+ providerCombo.setItems(providerNames.toArray(new String[0]));
+
+ tabgroup = new CTabFolder(top, SWT.NONE);
+ tabgroup.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true,
+ true));
+
+ providerCombo.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ String curProviderId = comboItems.get(providerCombo.getText());
+ loadTabGroupItems(tabgroup, curProviderId);
+ initializeFrom(initial);
+ // Since we are calling initializeFrom manually, we have to
+ // update the launch configuration dialog manually to ensure
+ // initial validation on the configuration.
+ updateLaunchConfigurationDialog();
+ top.layout();
+ }
+ });
+ }
+
+ /**
+ * Get the default provider id to use if one is not set for the configuration.
+ *
+ * @return default provider id
+ */
+ protected abstract String getDefaultProviderId();
+
+ private void loadTabGroupItems(CTabFolder tabgroup, String curProviderId) {
+ // dispose of old tabs and their state
+ for (CTabItem item : tabgroup.getItems()) {
+ item.dispose();
+ }
+ setErrorMessage(null);
+ initialized.clear();
+
+ ProfileLaunchConfigurationTabGroup tabGroupConfig;
+
+ if (curProviderId == null || curProviderId.isEmpty()) {
+ curProviderId = getDefaultProviderId();
+ }
+
+ // starting initialization of this tab's controls
+ initialized.put(curProviderId, false);
+
+ tabGroupConfig = ProviderFramework.getTabGroupProviderFromId(curProviderId);
+ if (tabGroupConfig == null) {
+ String profilingToolName = null;
+ try {
+ profilingToolName = initial.getAttribute(ProviderProfileConstants.PROVIDER_CONFIG_TOOLNAME_ATT, (String)null);
+ } catch (CoreException e) {
+ // do nothing
+ }
+ if (profilingToolName == null) {
+ setErrorMessage(NLS.bind(Messages.ProfilingTab_specified_providerid_not_installed, curProviderId));
+ } else {
+ setErrorMessage(NLS.bind(Messages.ProfilingTab_specified_profiler_not_installed, profilingToolName));
+ }
+ return;
+ }
+ tabs = tabGroupConfig.getProfileTabs();
+ setProvider(curProviderId);
+
+ // Show provider name in combo.
+ int itemIndex = getComboItemIndexFromId(curProviderId);
+ providerCombo.select(itemIndex);
+
+ // Set name of configuration.
+ setConfigurationName(providerCombo.getText());
+
+ // create the tab item, and load the specified tab inside
+ for (ILaunchConfigurationTab tab : tabs) {
+ tab.setLaunchConfigurationDialog(getLaunchConfigurationDialog());
+ CTabItem item = new CTabItem(tabgroup, SWT.NONE);
+ item.setText(tab.getName());
+ item.setImage(tab.getImage());
+
+ tab.createControl(tabgroup);
+ item.setControl(tab.getControl());
+ tabgroup.setSelection(0);
+ }
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
+ if (providerCombo != null && !providerCombo.getText().isEmpty()) {
+ for (AbstractLaunchConfigurationTab tab : tabs) {
+ tab.setDefaults(configuration);
+ }
+ }
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration configuration) {
+ /**
+ * First time the configuration is selected.
+ *
+ * This is a cheap way to get access to the launch configuration. Our
+ * tabs are loaded dynamically, so the tab group doesn't "know" about
+ * them. We get access to this launch configuration to ensure that we
+ * can properly load the widgets the first time.
+ */
+
+ // update current configuration (initial) with configuration being
+ // passed in
+ initial = configuration;
+
+
+ // check if there exists a launch provider id in the configuration
+ if (initial != null) {
+ try {
+ String providerId = initial.getAttribute(
+ ProviderProfileConstants.PROVIDER_CONFIG_ATT, (String)null);
+ // load provider corresponding to specified ids
+ loadTabGroupItems(tabgroup, providerId);
+ } catch (CoreException e) {
+ // continue, initialize tabs
+ }
+ }
+ if (tabs != null) {
+ for (AbstractLaunchConfigurationTab tab : tabs) {
+ tab.initializeFrom(configuration);
+ }
+ }
+
+ // finished initialization
+ initialized.put(getProviderId(), true);
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy configuration) {
+ // make sure tabs are not null, and the tab's controls have been
+ // initialized.
+
+ Boolean isInitialized = initialized.get(getProviderId());
+ isInitialized = (isInitialized != null) ? isInitialized : false;
+
+ if (tabs != null && isInitialized) {
+ for (AbstractLaunchConfigurationTab tab : tabs) {
+ tab.performApply(configuration);
+ }
+ }
+ }
+
+ /**
+ * Set the provider attribute in the specified configuration.
+ *
+ * @param configuration a configuration
+ */
+ private void setProvider(String providerId) {
+ try {
+ ILaunchConfigurationWorkingCopy wc = initial.getWorkingCopy();
+ wc.setAttribute(ProviderProfileConstants.PROVIDER_CONFIG_ATT,
+ providerId);
+ initial = wc.doSave();
+ } catch (CoreException e1) {
+ e1.printStackTrace();
+ }
+ }
+
+ /**
+ * Set name of the launch configuration.
+ *
+ * @param newToolName String tool name to be appended to configuration name,
+ */
+ protected void setConfigurationName(String newToolName) {
+ try {
+ String currentToolName = initial.getAttribute(
+ ProviderProfileConstants.PROVIDER_CONFIG_TOOLNAME_ATT, ""); //$NON-NLS-1$
+
+ // Append the new tool name as long as the current and new tool
+ // names are different.
+ if (newToolName != null && !newToolName.isEmpty()
+ && !currentToolName.equals(newToolName)) {
+
+ String projectName = initial.getAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
+
+ // String of the form <project name> [<tool name>].
+ String newConfigurationName = ProviderLaunchShortcut
+ .generateProviderConfigurationName(projectName,
+ newToolName);
+
+ // Unique name of the form <project name> [<tool name>]{(<number>)}.
+ String newUniqueToolName = getLaunchManager()
+ .generateLaunchConfigurationName(newConfigurationName);
+
+ // Save changes in current configuration.
+ ILaunchConfigurationWorkingCopy wc = initial.getWorkingCopy();
+ wc.rename(newUniqueToolName);
+ wc.setAttribute(
+ ProviderProfileConstants.PROVIDER_CONFIG_TOOLNAME_ATT,
+ newToolName);
+ initial = wc.doSave();
+
+ // Set name field in launch configuration dialog to avoid the
+ // new configuration name from being overwritten.
+ getLaunchConfigurationDialog().setName(newUniqueToolName);
+ }
+ } catch (CoreException e) {
+ // If unable to set the name, leave the original name as is.
+ }
+ }
+
+ /**
+ * Get the provider ID for the provider of the currently loaded
+ * configuration.
+ *
+ * @return the provider ID or an empty string if the configuration
+ * has no provider ID defined.
+ */
+ private String getProviderId() {
+ try {
+ return initial.getAttribute(
+ ProviderProfileConstants.PROVIDER_CONFIG_ATT, ""); //$NON-NLS-1$
+ } catch (CoreException e) {
+ return ""; //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Get Combo item name from specified id
+ *
+ * @param id provider id
+ * @return name of item, <code>null</code> if no entry found with given id.
+ */
+ private String getComboItemNameFromId(String id) {
+ for (Entry<String, String> entry : comboItems.entrySet()) {
+ if (id.equals(entry.getValue())) {
+ return entry.getKey();
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Get index of specific name in the combo items list
+ *
+ * @param name name of item
+ * @return index of given name, -1 if it not found
+ */
+ private int getItemIndex(Combo combo, String name) {
+ int itemCount = combo.getItemCount();
+ for (int i = 0; i < itemCount; i++) {
+ if (combo.getItem(i).equals(name)) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * Get index of specific id in the provider combo items list
+ *
+ * @param id
+ * @return index of given id in provider combo items list, -1 if it not found.
+ */
+ private int getComboItemIndexFromId(String id) {
+ String providerName = getComboItemNameFromId(id);
+ return getItemIndex(providerCombo, providerName);
+ }
+
+ @Override
+ public boolean isValid(ILaunchConfiguration config) {
+ String provider;
+ try {
+ provider = config.getAttribute(
+ ProviderProfileConstants.PROVIDER_CONFIG_ATT, ""); //$NON-NLS-1$
+ } catch (CoreException e) {
+ setErrorMessage(e.getMessage());
+ return false;
+ }
+ if (provider.isEmpty()) {
+ setErrorMessage(Messages.ProfilingTab_providerid_not_found);
+ return false;
+ }
+
+ Boolean isInitialized = initialized.get(getProviderId());
+
+ if (isInitialized) {
+ // Tabs should not be null after initialization.
+ if (tabs == null) {
+ return false;
+ }
+
+ // Validate tab configurations of underlying tool.
+ for (AbstractLaunchConfigurationTab tab : tabs) {
+ if (!tab.isValid(config)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Get name of profiling type that used for this tab.
+ *
+ * @return String profiling name.
+ */
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Set the name for this tab.
+ *
+ * @param name
+ */
+ protected void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String getId() {
+ return id;
+ }
+
+ /**
+ * Set the id for this tab.
+ *
+ * @param id
+ */
+ protected void setId(String id) {
+ this.id = id;
+ }
+
+ /**
+ * Get profiling type of the configuration.
+ *
+ * @return String profiling type this plug-in supports.
+ */
+ protected String getProfilingType() {
+ return type;
+ }
+
+ /**
+ * Set profiling type of configuration.
+ *
+ * @param type
+ */
+ protected void setProfilingType(String type) {
+ this.type = type;
+ }
+
+ @Override
+ public Image getImage() {
+ return img;
+ }
+
+ /**
+ * Set the image for this tab.
+ *
+ * @param img
+ */
+ public void setImage(Image img) {
+ this.img = img;
+ }
+
+ @Override
+ public void dispose() {
+ if (img != null) {
+ img.dispose();
+ }
+ super.dispose();
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/CApplicationLaunchShortcut.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/CApplicationLaunchShortcut.java
index 8c6213a566..50b83ab96f 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/CApplicationLaunchShortcut.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/CApplicationLaunchShortcut.java
@@ -26,67 +26,67 @@ import org.eclipse.ui.IEditorPart;
*/
public class CApplicationLaunchShortcut implements ILaunchShortcut2 {
- private static final String CDT_LAUNCH_SHORTCUT_ID = "org.eclipse.cdt.debug.ui.localCShortcut"; //$NON-NLS-1$
- private ILaunchShortcut2 proxy;
+ private static final String CDT_LAUNCH_SHORTCUT_ID = "org.eclipse.cdt.debug.ui.localCShortcut"; //$NON-NLS-1$
+ private ILaunchShortcut2 proxy;
- private ILaunchShortcut2 getProxy() {
- if (proxy == null) {
- // Get a proxy to CDT's CApplicationLaunchShortcut class which is internal
- // This plug-in has a dependency on org.eclipe.cdt.debug.ui so this extension is expected to be found.
- IExtensionPoint extPoint =
- Platform.getExtensionRegistry().getExtensionPoint("org.eclipse.debug.ui.launchShortcuts"); //$NON-NLS-1$
- IConfigurationElement[] configs = extPoint.getConfigurationElements();
- for (IConfigurationElement config : configs) {
- Object obj = null;
- if (config.getName().equals("shortcut")) { //$NON-NLS-1$
- String id = config.getAttribute("id"); //$NON-NLS-1$
- if (id.equals(CDT_LAUNCH_SHORTCUT_ID)) {
- try {
- obj = config.createExecutableExtension("class"); //$NON-NLS-1$
- } catch (CoreException e) {
- ProfileLaunchPlugin.log(e);
- }
- if (obj instanceof ILaunchShortcut2) {
- proxy = (ILaunchShortcut2)obj;
- break;
- }
- }
- }
- if (proxy != null)
- break;
- }
- }
- return proxy;
- }
+ private ILaunchShortcut2 getProxy() {
+ if (proxy == null) {
+ // Get a proxy to CDT's CApplicationLaunchShortcut class which is internal
+ // This plug-in has a dependency on org.eclipe.cdt.debug.ui so this extension is expected to be found.
+ IExtensionPoint extPoint =
+ Platform.getExtensionRegistry().getExtensionPoint("org.eclipse.debug.ui.launchShortcuts"); //$NON-NLS-1$
+ IConfigurationElement[] configs = extPoint.getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ Object obj = null;
+ if (config.getName().equals("shortcut")) { //$NON-NLS-1$
+ String id = config.getAttribute("id"); //$NON-NLS-1$
+ if (id.equals(CDT_LAUNCH_SHORTCUT_ID)) {
+ try {
+ obj = config.createExecutableExtension("class"); //$NON-NLS-1$
+ } catch (CoreException e) {
+ ProfileLaunchPlugin.log(e);
+ }
+ if (obj instanceof ILaunchShortcut2) {
+ proxy = (ILaunchShortcut2)obj;
+ break;
+ }
+ }
+ }
+ if (proxy != null)
+ break;
+ }
+ }
+ return proxy;
+ }
- @Override
- public void launch(ISelection selection, String mode) {
- getProxy().launch(selection, mode);
- }
+ @Override
+ public void launch(ISelection selection, String mode) {
+ getProxy().launch(selection, mode);
+ }
- @Override
- public void launch(IEditorPart editor, String mode) {
- getProxy().launch(editor, mode);
- }
+ @Override
+ public void launch(IEditorPart editor, String mode) {
+ getProxy().launch(editor, mode);
+ }
- @Override
- public ILaunchConfiguration[] getLaunchConfigurations(ISelection selection) {
- return getProxy().getLaunchConfigurations(selection);
- }
+ @Override
+ public ILaunchConfiguration[] getLaunchConfigurations(ISelection selection) {
+ return getProxy().getLaunchConfigurations(selection);
+ }
- @Override
- public ILaunchConfiguration[] getLaunchConfigurations(IEditorPart editorpart) {
- return getProxy().getLaunchConfigurations(editorpart);
- }
+ @Override
+ public ILaunchConfiguration[] getLaunchConfigurations(IEditorPart editorpart) {
+ return getProxy().getLaunchConfigurations(editorpart);
+ }
- @Override
- public IResource getLaunchableResource(ISelection selection) {
- return getProxy().getLaunchableResource(selection);
- }
+ @Override
+ public IResource getLaunchableResource(ISelection selection) {
+ return getProxy().getLaunchableResource(selection);
+ }
- @Override
- public IResource getLaunchableResource(IEditorPart editorpart) {
- return getProxy().getLaunchableResource(editorpart);
- }
+ @Override
+ public IResource getLaunchableResource(IEditorPart editorpart) {
+ return getProxy().getLaunchableResource(editorpart);
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/CProfilingOptionsTab.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/CProfilingOptionsTab.java
index c0970bddbf..21835ce876 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/CProfilingOptionsTab.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/CProfilingOptionsTab.java
@@ -24,56 +24,56 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
*/
public class CProfilingOptionsTab extends AbstractProfilingOptionsTab {
- String defaultType;
+ String defaultType;
- public static final String TAB_ID = "org.eclipse.linuxtools.profiling.launch.profileApplicationLaunch.profilingTab"; //$NON-NLS-1$
+ public static final String TAB_ID = "org.eclipse.linuxtools.profiling.launch.profileApplicationLaunch.profilingTab"; //$NON-NLS-1$
- /**
- * ProviderOptionsTab constructor.
- *
- */
- public CProfilingOptionsTab() {
- setName(Messages.ProfilingTabName);
- setId(TAB_ID);
- }
+ /**
+ * ProviderOptionsTab constructor.
+ *
+ */
+ public CProfilingOptionsTab() {
+ setName(Messages.ProfilingTabName);
+ setId(TAB_ID);
+ }
- @Override
- protected SortedMap<String, String> getProviders() {
- return ProviderFramework.getAllProviderNames();
- }
+ @Override
+ protected SortedMap<String, String> getProviders() {
+ return ProviderFramework.getAllProviderNames();
+ }
- @Override
- protected String getDefaultProviderId() {
- // get the id of a provider
- if (defaultType == null) {
- String[] categories = ProviderFramework.getProviderCategories();
- if (categories.length == 0) {
- setErrorMessage(Messages.ProfilingTab_no_profilers_installed);
- return ""; //$NON-NLS-1$
- }
- for (String category : categories) {
- // Give precedence to timing category if present
- if (category.equals("timing")){ //$NON-NLS-1$
- defaultType = "timing"; //$NON-NLS-1$
- }
- }
- // if default category still not set, take first one found
- if (defaultType == null)
- defaultType = categories[0];
- }
- return ProviderFramework.getProviderIdToRun(null, defaultType);
- }
+ @Override
+ protected String getDefaultProviderId() {
+ // get the id of a provider
+ if (defaultType == null) {
+ String[] categories = ProviderFramework.getProviderCategories();
+ if (categories.length == 0) {
+ setErrorMessage(Messages.ProfilingTab_no_profilers_installed);
+ return ""; //$NON-NLS-1$
+ }
+ for (String category : categories) {
+ // Give precedence to timing category if present
+ if (category.equals("timing")){ //$NON-NLS-1$
+ defaultType = "timing"; //$NON-NLS-1$
+ }
+ }
+ // if default category still not set, take first one found
+ if (defaultType == null)
+ defaultType = categories[0];
+ }
+ return ProviderFramework.getProviderIdToRun(null, defaultType);
+ }
- @Override
- protected void setConfigurationName(String newToolName) {
- // do nothing
- }
+ @Override
+ protected void setConfigurationName(String newToolName) {
+ // do nothing
+ }
- @Override
- public Image getImage() {
- if (img == null)
- img = AbstractUIPlugin.imageDescriptorFromPlugin(ProfileLaunchPlugin.PLUGIN_ID,
- "icons/time_obj.gif").createImage(); //$NON-NLS-1$
- return img;
- }
+ @Override
+ public Image getImage() {
+ if (img == null)
+ img = AbstractUIPlugin.imageDescriptorFromPlugin(ProfileLaunchPlugin.PLUGIN_ID,
+ "icons/time_obj.gif").createImage(); //$NON-NLS-1$
+ return img;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/LocalFileProxy.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/LocalFileProxy.java
index dbef0f1722..2ab12781b3 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/LocalFileProxy.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/LocalFileProxy.java
@@ -21,44 +21,44 @@ import org.eclipse.linuxtools.profiling.launch.IRemoteFileProxy;
public class LocalFileProxy implements IRemoteFileProxy {
- URI workingDirURI;
+ URI workingDirURI;
- public LocalFileProxy(URI uri) {
- workingDirURI=uri;
- }
+ public LocalFileProxy(URI uri) {
+ workingDirURI=uri;
+ }
- @Override
- public URI toURI(IPath path) {
- return path.toFile().toURI();
- }
+ @Override
+ public URI toURI(IPath path) {
+ return path.toFile().toURI();
+ }
- @Override
- public URI toURI(String path) {
- try {
- return new URI(path);
- } catch (URISyntaxException e) {
- return null;
- }
- }
+ @Override
+ public URI toURI(String path) {
+ try {
+ return new URI(path);
+ } catch (URISyntaxException e) {
+ return null;
+ }
+ }
- @Override
- public String toPath(URI uri) {
- return uri.getPath();
- }
+ @Override
+ public String toPath(URI uri) {
+ return uri.getPath();
+ }
- @Override
- public String getDirectorySeparator() {
- return System.getProperty("file.separator"); //$NON-NLS-1$
- }
+ @Override
+ public String getDirectorySeparator() {
+ return System.getProperty("file.separator"); //$NON-NLS-1$
+ }
- @Override
- public IFileStore getResource(String path) {
- return EFS.getLocalFileSystem().getStore(new Path(path));
- }
+ @Override
+ public IFileStore getResource(String path) {
+ return EFS.getLocalFileSystem().getStore(new Path(path));
+ }
- @Override
- public URI getWorkingDir() {
- return workingDirURI;
- }
+ @Override
+ public URI getWorkingDir() {
+ return workingDirURI;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/LocalLauncher.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/LocalLauncher.java
index 792b6c616a..cd78b56a30 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/LocalLauncher.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/LocalLauncher.java
@@ -24,44 +24,44 @@ import org.eclipse.linuxtools.profiling.launch.IRemoteCommandLauncher;
public class LocalLauncher implements IRemoteCommandLauncher {
- private CommandLauncher launcher;
+ private CommandLauncher launcher;
- public LocalLauncher() {
- launcher = new CommandLauncher();
- }
+ public LocalLauncher() {
+ launcher = new CommandLauncher();
+ }
- @Override
- public Process execute(IPath commandPath, String[] args, String[] env,
- IPath changeToDirectory, IProgressMonitor monitor)
- throws CoreException {
- launcher.showCommand(true);
- return launcher.execute(commandPath, args, env, changeToDirectory, monitor);
- }
+ @Override
+ public Process execute(IPath commandPath, String[] args, String[] env,
+ IPath changeToDirectory, IProgressMonitor monitor)
+ throws CoreException {
+ launcher.showCommand(true);
+ return launcher.execute(commandPath, args, env, changeToDirectory, monitor);
+ }
- @Override
- public Process execute(IPath commandPath, String[] args, String[] env,
- IPath changeToDirectory, IProgressMonitor monitor, PTY pty) {
- String [] mergedCommand = new String [args.length + 1];
- System.arraycopy(args, 0, mergedCommand, 1, args.length);
- mergedCommand[0] = commandPath.toOSString();
- Process p = null;
- try {
- p = ProcessFactory.getFactory().exec(mergedCommand, env, changeToDirectory.toFile(), pty);
- } catch (IOException e) {
- CCorePlugin.log(e);
- }
- return p;
- }
+ @Override
+ public Process execute(IPath commandPath, String[] args, String[] env,
+ IPath changeToDirectory, IProgressMonitor monitor, PTY pty) {
+ String [] mergedCommand = new String [args.length + 1];
+ System.arraycopy(args, 0, mergedCommand, 1, args.length);
+ mergedCommand[0] = commandPath.toOSString();
+ Process p = null;
+ try {
+ p = ProcessFactory.getFactory().exec(mergedCommand, env, changeToDirectory.toFile(), pty);
+ } catch (IOException e) {
+ CCorePlugin.log(e);
+ }
+ return p;
+ }
- @Override
- public int waitAndRead(OutputStream output, OutputStream err,
- IProgressMonitor monitor) {
- return launcher.waitAndRead(output, err, monitor);
- }
+ @Override
+ public int waitAndRead(OutputStream output, OutputStream err,
+ IProgressMonitor monitor) {
+ return launcher.waitAndRead(output, err, monitor);
+ }
- @Override
- public String getErrorMessage() {
- return launcher.getErrorMessage();
- }
+ @Override
+ public String getErrorMessage() {
+ return launcher.getErrorMessage();
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/Messages.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/Messages.java
index 4027ee5513..c447203996 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/Messages.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/Messages.java
@@ -7,35 +7,35 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.profiling.launch;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.profiling.launch.messages"; //$NON-NLS-1$
- public static String RemoteProxyManager_unrecognized_scheme;
- public static String ProfilingTabName;
- public static String ProfilingTab_no_profilers_installed;
- public static String ProfilingTab_specified_providerid_not_installed;
- public static String ProfilingTab_specified_profiler_not_installed;
- public static String ProfilingTab_providerid_not_found;
- public static String ProfileLaunchShortcut_Binaries;
- public static String ProfileLaunchShortcut_Binary_not_found;
- public static String ProfileLaunchShortcut_Choose_a_launch_configuration;
- public static String ProfileLaunchShortcut_Choose_a_local_application;
- public static String ProfileLaunchShortcut_Launch_Configuration_Selection;
- public static String ProfileLaunchShortcut_Looking_for_executables;
- public static String ProfileLaunchShortcut_no_project_selected;
- public static String ProfileLaunchShortcut_Profile;
- public static String ProfileLaunchShortcut_Qualifier;
- public static String ProfileLaunchShortcut_Launcher;
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.profiling.launch.messages"; //$NON-NLS-1$
+ public static String RemoteProxyManager_unrecognized_scheme;
+ public static String ProfilingTabName;
+ public static String ProfilingTab_no_profilers_installed;
+ public static String ProfilingTab_specified_providerid_not_installed;
+ public static String ProfilingTab_specified_profiler_not_installed;
+ public static String ProfilingTab_providerid_not_found;
+ public static String ProfileLaunchShortcut_Binaries;
+ public static String ProfileLaunchShortcut_Binary_not_found;
+ public static String ProfileLaunchShortcut_Choose_a_launch_configuration;
+ public static String ProfileLaunchShortcut_Choose_a_local_application;
+ public static String ProfileLaunchShortcut_Launch_Configuration_Selection;
+ public static String ProfileLaunchShortcut_Looking_for_executables;
+ public static String ProfileLaunchShortcut_no_project_selected;
+ public static String ProfileLaunchShortcut_Profile;
+ public static String ProfileLaunchShortcut_Qualifier;
+ public static String ProfileLaunchShortcut_Launcher;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/ProfileContextualLaunchAction.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/ProfileContextualLaunchAction.java
index b443f4936b..7829bc8ae7 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/ProfileContextualLaunchAction.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/ProfileContextualLaunchAction.java
@@ -14,7 +14,7 @@ import org.eclipse.debug.ui.actions.ContextualLaunchAction;
public class ProfileContextualLaunchAction extends ContextualLaunchAction {
- public ProfileContextualLaunchAction() {
- super(ProfileLaunchPlugin.LAUNCH_MODE);
- }
+ public ProfileContextualLaunchAction() {
+ super(ProfileLaunchPlugin.LAUNCH_MODE);
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/ProfileLaunchPlugin.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/ProfileLaunchPlugin.java
index 197475a675..042423fbba 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/ProfileLaunchPlugin.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/ProfileLaunchPlugin.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.profiling.launch;
import org.eclipse.core.runtime.IStatus;
@@ -19,118 +19,118 @@ import org.osgi.framework.BundleContext;
public class ProfileLaunchPlugin extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.profiling.launch"; //$NON-NLS-1$
-
- // The shared instance
- private static ProfileLaunchPlugin plugin;
-
- // The launch mode this plug-in supports
- public static final String LAUNCH_MODE = "linuxtools"; //$NON-NLS-1$
-
-
- /**
- * The constructor
- */
- public ProfileLaunchPlugin() {
- }
-
- /**
- * Convenience method which returns the unique identifier of this plugin.
- * @since 1.1
- */
- public static String getUniqueIdentifier() {
- if (getDefault() == null) {
- // If the default instance is not yet initialized,
- // return a static identifier. This identifier must
- // match the plugin id defined in plugin.xml
- return PLUGIN_ID;
- }
- return getDefault().getBundle().getSymbolicName();
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static ProfileLaunchPlugin getDefault() {
- return plugin;
- }
-
- public static Shell getActiveWorkbenchShell() {
- IWorkbenchWindow window = getDefault().getWorkbench().getActiveWorkbenchWindow();
- if (window != null) {
- return window.getShell();
- }
- return null;
- }
-
- public static Shell getShell() {
- if (getActiveWorkbenchShell() != null) {
- return getActiveWorkbenchShell();
- }
- IWorkbenchWindow[] windows = getDefault().getWorkbench().getWorkbenchWindows();
- return windows[0].getShell();
- }
-
- /**
- * Logs the specified status with this plug-in's log.
- *
- * @param status
- * status to log
- * @since 1.1
- */
- public static void log(IStatus status) {
- getDefault().getLog().log(status);
- }
- /**
- * Logs an internal error with the specified message.
- *
- * @param message
- * the error message to log
- * @since 1.1
- */
- public static void logErrorMessage(String message) {
- log(new Status(IStatus.ERROR, getUniqueIdentifier(), IStatus.ERROR, message, null));
- }
-
- /**
- * Logs an internal error with the specified throwable
- *
- * @param e
- * the exception to be logged
- * @since 1.1
- */
- public static void log(Throwable e) {
- log(new Status(IStatus.ERROR, getUniqueIdentifier(), IStatus.ERROR, e.getMessage(), e));
- }
-
- public static void log(int status, String msg, Throwable e) {
- plugin.getLog().log(new Status(status, PLUGIN_ID, IStatus.OK, msg, e));
- }
-
- public static void log(int status, String msg) {
- log(status, msg, null);
- }
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.profiling.launch"; //$NON-NLS-1$
+
+ // The shared instance
+ private static ProfileLaunchPlugin plugin;
+
+ // The launch mode this plug-in supports
+ public static final String LAUNCH_MODE = "linuxtools"; //$NON-NLS-1$
+
+
+ /**
+ * The constructor
+ */
+ public ProfileLaunchPlugin() {
+ }
+
+ /**
+ * Convenience method which returns the unique identifier of this plugin.
+ * @since 1.1
+ */
+ public static String getUniqueIdentifier() {
+ if (getDefault() == null) {
+ // If the default instance is not yet initialized,
+ // return a static identifier. This identifier must
+ // match the plugin id defined in plugin.xml
+ return PLUGIN_ID;
+ }
+ return getDefault().getBundle().getSymbolicName();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static ProfileLaunchPlugin getDefault() {
+ return plugin;
+ }
+
+ public static Shell getActiveWorkbenchShell() {
+ IWorkbenchWindow window = getDefault().getWorkbench().getActiveWorkbenchWindow();
+ if (window != null) {
+ return window.getShell();
+ }
+ return null;
+ }
+
+ public static Shell getShell() {
+ if (getActiveWorkbenchShell() != null) {
+ return getActiveWorkbenchShell();
+ }
+ IWorkbenchWindow[] windows = getDefault().getWorkbench().getWorkbenchWindows();
+ return windows[0].getShell();
+ }
+
+ /**
+ * Logs the specified status with this plug-in's log.
+ *
+ * @param status
+ * status to log
+ * @since 1.1
+ */
+ public static void log(IStatus status) {
+ getDefault().getLog().log(status);
+ }
+ /**
+ * Logs an internal error with the specified message.
+ *
+ * @param message
+ * the error message to log
+ * @since 1.1
+ */
+ public static void logErrorMessage(String message) {
+ log(new Status(IStatus.ERROR, getUniqueIdentifier(), IStatus.ERROR, message, null));
+ }
+
+ /**
+ * Logs an internal error with the specified throwable
+ *
+ * @param e
+ * the exception to be logged
+ * @since 1.1
+ */
+ public static void log(Throwable e) {
+ log(new Status(IStatus.ERROR, getUniqueIdentifier(), IStatus.ERROR, e.getMessage(), e));
+ }
+
+ public static void log(int status, String msg, Throwable e) {
+ plugin.getLog().log(new Status(status, PLUGIN_ID, IStatus.OK, msg, e));
+ }
+
+ public static void log(int status, String msg) {
+ log(status, msg, null);
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/AbstractProviderPreferencesPage.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/AbstractProviderPreferencesPage.java
index fd45fce659..d069d33515 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/AbstractProviderPreferencesPage.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/AbstractProviderPreferencesPage.java
@@ -30,127 +30,127 @@ import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
public class AbstractProviderPreferencesPage extends
- FieldEditorPreferencePage implements IWorkbenchPreferencePage, IExecutableExtension {
-
- // Launch provider extension point tool information attribute
- private static final String PROVIDER_ATT_INFO = "information"; //$NON-NLS-1$
-
- // Launch provider extension point tool description attribute
- private static final String PROVIDER_ATT_DESC = "description"; //$NON-NLS-1$
-
- // Profiling type
- private String type;
-
- @Override
- public void setInitializationData(IConfigurationElement config,
- String propertyName, Object data) {
- Hashtable<String, String> parameters = (Hashtable<String, String>) data;
- String profilingType = parameters
- .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY);
-
- if (profilingType == null) {
- profilingType = ""; //$NON-NLS-1$
- }
-
- setProfilingType(profilingType);
- }
-
- public AbstractProviderPreferencesPage() {
- super(GRID);
- }
-
- @Override
- public void init(IWorkbench workbench) {
- final IPreferenceStore store = new ScopedPreferenceStore(
- ConfigurationScope.INSTANCE, ProviderProfileConstants.PLUGIN_ID);
- setPreferenceStore(store);
- }
-
- public void initializeDefaultPreferences() {
- super.performDefaults();
- String providerId = ProviderFramework
- .getHighestProviderId(type);
- ConfigurationScope.INSTANCE.getNode(ProviderProfileConstants.PLUGIN_ID)
- .put(ProviderProfileConstants.PREFS_KEY + type, providerId);
-
- }
-
- @Override
- protected Control createContents(Composite parent) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, getHelpContextId());
- return super.createContents(parent);
- }
-
- @Override
- protected void createFieldEditors() {
- String providerId = ProviderFramework.getHighestProviderId(type);
-
- if (providerId != null) {
- getPreferenceStore().setDefault(
- ProviderProfileConstants.PREFS_KEY + type, providerId);
- }
-
- HashMap<String, String> map = ProviderFramework
- .getProviderNamesForType(type);
- // 2d array containing launch provider names on the first column and
- // corresponding id's on the second.
- String[][] providerList = new String[map.size()][2];
- int i = 0;
- for (Entry<String, String> entry : map.entrySet()) {
- String toolId = entry.getValue();
- String toolDescription = ProviderFramework.getToolInformationFromId(toolId, PROVIDER_ATT_DESC);
- String toolName = entry.getKey();
-
- // Append tool description to tool name if available.
- if (toolDescription != null && !toolDescription.equals("")) { //$NON-NLS-1$
- toolName = toolName + " " + "[" + toolDescription + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- providerList[i][0] = toolName;
- providerList[i][1] = toolId;
- i++;
- }
-
- // Create basic field editor.
- RadioGroupFieldEditor editor = new RadioGroupFieldEditor(
- ProviderProfileConstants.PREFS_KEY + type,
- Messages.ProviderPreferencesPage_1, 1, providerList,
- getFieldEditorParent(), true);
- editor.setPreferenceStore(getPreferenceStore());
- addField(editor);
-
- Composite radioBoxControl = editor
- .getRadioBoxControl(getFieldEditorParent());
- Control[] providerOptions = radioBoxControl.getChildren();
-
- // Set tool tip text on field editors.
- for (Control control : providerOptions) {
- // Get tool specific information from provider id.
- String curProviderId = (String) control.getData();
- // Set tool tip description text.
- String toolDescription = ProviderFramework.getToolInformationFromId(curProviderId,
- PROVIDER_ATT_INFO);
- if (toolDescription != null && !toolDescription.equals("")) { //$NON-NLS-1$
- control.setToolTipText(toolDescription);
- }
- }
- }
-
- /**
- * Return the help context id to use if the help button is pushed.
- *
- * @return the help context id
- */
- private String getHelpContextId() {
- return ProviderProfileConstants.PLUGIN_ID + ".profiling_categories"; //$NON-NLS-1$
- }
-
- /**
- * Set profiling type.
- *
- * @param profilingType String profiling type.
- */
- private void setProfilingType(String profilingType) {
- type = profilingType;
- }
+ FieldEditorPreferencePage implements IWorkbenchPreferencePage, IExecutableExtension {
+
+ // Launch provider extension point tool information attribute
+ private static final String PROVIDER_ATT_INFO = "information"; //$NON-NLS-1$
+
+ // Launch provider extension point tool description attribute
+ private static final String PROVIDER_ATT_DESC = "description"; //$NON-NLS-1$
+
+ // Profiling type
+ private String type;
+
+ @Override
+ public void setInitializationData(IConfigurationElement config,
+ String propertyName, Object data) {
+ Hashtable<String, String> parameters = (Hashtable<String, String>) data;
+ String profilingType = parameters
+ .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY);
+
+ if (profilingType == null) {
+ profilingType = ""; //$NON-NLS-1$
+ }
+
+ setProfilingType(profilingType);
+ }
+
+ public AbstractProviderPreferencesPage() {
+ super(GRID);
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ final IPreferenceStore store = new ScopedPreferenceStore(
+ ConfigurationScope.INSTANCE, ProviderProfileConstants.PLUGIN_ID);
+ setPreferenceStore(store);
+ }
+
+ public void initializeDefaultPreferences() {
+ super.performDefaults();
+ String providerId = ProviderFramework
+ .getHighestProviderId(type);
+ ConfigurationScope.INSTANCE.getNode(ProviderProfileConstants.PLUGIN_ID)
+ .put(ProviderProfileConstants.PREFS_KEY + type, providerId);
+
+ }
+
+ @Override
+ protected Control createContents(Composite parent) {
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, getHelpContextId());
+ return super.createContents(parent);
+ }
+
+ @Override
+ protected void createFieldEditors() {
+ String providerId = ProviderFramework.getHighestProviderId(type);
+
+ if (providerId != null) {
+ getPreferenceStore().setDefault(
+ ProviderProfileConstants.PREFS_KEY + type, providerId);
+ }
+
+ HashMap<String, String> map = ProviderFramework
+ .getProviderNamesForType(type);
+ // 2d array containing launch provider names on the first column and
+ // corresponding id's on the second.
+ String[][] providerList = new String[map.size()][2];
+ int i = 0;
+ for (Entry<String, String> entry : map.entrySet()) {
+ String toolId = entry.getValue();
+ String toolDescription = ProviderFramework.getToolInformationFromId(toolId, PROVIDER_ATT_DESC);
+ String toolName = entry.getKey();
+
+ // Append tool description to tool name if available.
+ if (toolDescription != null && !toolDescription.equals("")) { //$NON-NLS-1$
+ toolName = toolName + " " + "[" + toolDescription + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ providerList[i][0] = toolName;
+ providerList[i][1] = toolId;
+ i++;
+ }
+
+ // Create basic field editor.
+ RadioGroupFieldEditor editor = new RadioGroupFieldEditor(
+ ProviderProfileConstants.PREFS_KEY + type,
+ Messages.ProviderPreferencesPage_1, 1, providerList,
+ getFieldEditorParent(), true);
+ editor.setPreferenceStore(getPreferenceStore());
+ addField(editor);
+
+ Composite radioBoxControl = editor
+ .getRadioBoxControl(getFieldEditorParent());
+ Control[] providerOptions = radioBoxControl.getChildren();
+
+ // Set tool tip text on field editors.
+ for (Control control : providerOptions) {
+ // Get tool specific information from provider id.
+ String curProviderId = (String) control.getData();
+ // Set tool tip description text.
+ String toolDescription = ProviderFramework.getToolInformationFromId(curProviderId,
+ PROVIDER_ATT_INFO);
+ if (toolDescription != null && !toolDescription.equals("")) { //$NON-NLS-1$
+ control.setToolTipText(toolDescription);
+ }
+ }
+ }
+
+ /**
+ * Return the help context id to use if the help button is pushed.
+ *
+ * @return the help context id
+ */
+ private String getHelpContextId() {
+ return ProviderProfileConstants.PLUGIN_ID + ".profiling_categories"; //$NON-NLS-1$
+ }
+
+ /**
+ * Set profiling type.
+ *
+ * @param profilingType String profiling type.
+ */
+ private void setProfilingType(String profilingType) {
+ type = profilingType;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/AbstractProviderPropertyTab.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/AbstractProviderPropertyTab.java
index 1397e930a8..bbb8730c19 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/AbstractProviderPropertyTab.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/AbstractProviderPropertyTab.java
@@ -40,98 +40,98 @@ import org.eclipse.ui.preferences.ScopedPreferenceStore;
public abstract class AbstractProviderPropertyTab extends AbstractCPropertyTab {
- protected abstract String getType();
- protected abstract String getPrefPageId();
-
- // Launch provider extension point tool information attribute
- private static final String PROVIDER_ATT_INFO = "information"; //$NON-NLS-1$
-
- // Launch provider extension point tool description attribute
- private static final String PROVIDER_ATT_DESC = "description"; //$NON-NLS-1$
-
- private Link fLink;
- private Button useProjectSetting;
- private ScopedPreferenceStore preferenceStore;
- private Group projectSettingsGroup;
- private Button[] radioButtons;
- private String value;
-
- @Override
- protected void createControls(final Composite parent) {
- super.createControls(parent);
-
- usercomp.setLayout(new GridLayout(2, true));
-
- // Get the property provider (project, file, folder) and fine the project.
- IResource resource = (IResource)page.getElement().getAdapter(IResource.class);
- IProject project = resource.getProject();
-
- // Create the preference store to use
- ProjectScope ps = new ProjectScope(project);
- ScopedPreferenceStore scoped = new ScopedPreferenceStore(ps, ProviderProfileConstants.PLUGIN_ID);
- scoped.setSearchContexts(new IScopeContext[] { ps, InstanceScope.INSTANCE });
- setPreferenceStore(scoped);
-
- getPreferenceStore().setDefault(ProviderProfileConstants.USE_PROJECT_SETTINGS + getType(), false);
-
- useProjectSetting = new Button(usercomp, SWT.CHECK);
- useProjectSetting.setText(Messages.UseProjectSetting_0);
- useProjectSetting.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false, 1, 1));
- useProjectSetting.setSelection(getPreferenceStore().getBoolean(ProviderProfileConstants.USE_PROJECT_SETTINGS + getType()));
- useProjectSetting.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateOptionsEnable();
- }
- });
-
- String highestProviderId = ProviderFramework.getHighestProviderId(getType());
- if (highestProviderId != null) {
- getPreferenceStore().setDefault(ProviderProfileConstants.PREFS_KEY + getType(), highestProviderId);
- } else {
- useProjectSetting.setEnabled(false);
- }
-
- fLink= new Link(usercomp, SWT.NULL);
- fLink.setText(Messages.PreferenceLink_0);
- fLink.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, false, 1, 1));
- fLink.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(parent.getShell(), getPrefPageId(), null, null).open();
- }
- });
-
-
- HashMap<String, String> map = ProviderFramework
- .getProviderNamesForType(getType());
- // 2d array containing launch provider names on the first column and
- // corresponding id's on the second.
- String[][] providerList = new String[map.size()][2];
- int i = 0;
- for (Entry<String, String> entry : map.entrySet()) {
- String toolId = entry.getValue();
- String toolDescription = ProviderFramework.getToolInformationFromId(toolId, PROVIDER_ATT_DESC);
- String toolName = entry.getKey();
-
- // Append tool description to tool name if available.
- if (toolDescription != null && !toolDescription.isEmpty()) {
- toolName = toolName + " " + "[" + toolDescription + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- providerList[i][0] = toolName;
- providerList[i][1] = toolId;
- i++;
- }
-
- projectSettingsGroup = new Group(usercomp, SWT.NONE);
- projectSettingsGroup.setFont(parent.getFont());
- projectSettingsGroup.setText(Messages.ProviderPreferencesPage_1);
- projectSettingsGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
- GridLayout layout = new GridLayout();
- layout.horizontalSpacing = 8;
- layout.numColumns = 1;
- projectSettingsGroup.setLayout(layout);
+ protected abstract String getType();
+ protected abstract String getPrefPageId();
+
+ // Launch provider extension point tool information attribute
+ private static final String PROVIDER_ATT_INFO = "information"; //$NON-NLS-1$
+
+ // Launch provider extension point tool description attribute
+ private static final String PROVIDER_ATT_DESC = "description"; //$NON-NLS-1$
+
+ private Link fLink;
+ private Button useProjectSetting;
+ private ScopedPreferenceStore preferenceStore;
+ private Group projectSettingsGroup;
+ private Button[] radioButtons;
+ private String value;
+
+ @Override
+ protected void createControls(final Composite parent) {
+ super.createControls(parent);
+
+ usercomp.setLayout(new GridLayout(2, true));
+
+ // Get the property provider (project, file, folder) and fine the project.
+ IResource resource = (IResource)page.getElement().getAdapter(IResource.class);
+ IProject project = resource.getProject();
+
+ // Create the preference store to use
+ ProjectScope ps = new ProjectScope(project);
+ ScopedPreferenceStore scoped = new ScopedPreferenceStore(ps, ProviderProfileConstants.PLUGIN_ID);
+ scoped.setSearchContexts(new IScopeContext[] { ps, InstanceScope.INSTANCE });
+ setPreferenceStore(scoped);
+
+ getPreferenceStore().setDefault(ProviderProfileConstants.USE_PROJECT_SETTINGS + getType(), false);
+
+ useProjectSetting = new Button(usercomp, SWT.CHECK);
+ useProjectSetting.setText(Messages.UseProjectSetting_0);
+ useProjectSetting.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, false, 1, 1));
+ useProjectSetting.setSelection(getPreferenceStore().getBoolean(ProviderProfileConstants.USE_PROJECT_SETTINGS + getType()));
+ useProjectSetting.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateOptionsEnable();
+ }
+ });
+
+ String highestProviderId = ProviderFramework.getHighestProviderId(getType());
+ if (highestProviderId != null) {
+ getPreferenceStore().setDefault(ProviderProfileConstants.PREFS_KEY + getType(), highestProviderId);
+ } else {
+ useProjectSetting.setEnabled(false);
+ }
+
+ fLink= new Link(usercomp, SWT.NULL);
+ fLink.setText(Messages.PreferenceLink_0);
+ fLink.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, true, false, 1, 1));
+ fLink.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ PreferencesUtil.createPreferenceDialogOn(parent.getShell(), getPrefPageId(), null, null).open();
+ }
+ });
+
+
+ HashMap<String, String> map = ProviderFramework
+ .getProviderNamesForType(getType());
+ // 2d array containing launch provider names on the first column and
+ // corresponding id's on the second.
+ String[][] providerList = new String[map.size()][2];
+ int i = 0;
+ for (Entry<String, String> entry : map.entrySet()) {
+ String toolId = entry.getValue();
+ String toolDescription = ProviderFramework.getToolInformationFromId(toolId, PROVIDER_ATT_DESC);
+ String toolName = entry.getKey();
+
+ // Append tool description to tool name if available.
+ if (toolDescription != null && !toolDescription.isEmpty()) {
+ toolName = toolName + " " + "[" + toolDescription + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ providerList[i][0] = toolName;
+ providerList[i][1] = toolId;
+ i++;
+ }
+
+ projectSettingsGroup = new Group(usercomp, SWT.NONE);
+ projectSettingsGroup.setFont(parent.getFont());
+ projectSettingsGroup.setText(Messages.ProviderPreferencesPage_1);
+ projectSettingsGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
+ GridLayout layout = new GridLayout();
+ layout.horizontalSpacing = 8;
+ layout.numColumns = 1;
+ projectSettingsGroup.setLayout(layout);
radioButtons = new Button[map.size()];
for (int j = 0; j < radioButtons.length; j++) {
@@ -139,90 +139,90 @@ public abstract class AbstractProviderPropertyTab extends AbstractCPropertyTab {
radio.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, true, false, 1, 1));
radioButtons[j] = radio;
String[] labelAndValue = providerList[j];
- String curProviderId = labelAndValue[1];
- // Set tool tip description text.
- String toolInfo = ProviderFramework.getToolInformationFromId(curProviderId,
- PROVIDER_ATT_INFO);
- if (toolInfo != null && !toolInfo.isEmpty()) {
- radio.setToolTipText(toolInfo);
- }
- radio.setText(labelAndValue[0]);
+ String curProviderId = labelAndValue[1];
+ // Set tool tip description text.
+ String toolInfo = ProviderFramework.getToolInformationFromId(curProviderId,
+ PROVIDER_ATT_INFO);
+ if (toolInfo != null && !toolInfo.isEmpty()) {
+ radio.setToolTipText(toolInfo);
+ }
+ radio.setText(labelAndValue[0]);
radio.setData(labelAndValue[1]);
radio.setFont(parent.getFont());
radio.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- value = (String) event.widget.getData();
- }
+ @Override
+ public void widgetSelected(SelectionEvent event) {
+ value = (String) event.widget.getData();
+ }
});
}
projectSettingsGroup.addDisposeListener(new DisposeListener() {
@Override
- public void widgetDisposed(DisposeEvent event) {
+ public void widgetDisposed(DisposeEvent event) {
projectSettingsGroup = null;
radioButtons = null;
}
});
- updateOptionsEnable();
- updateValue(getPreferenceStore().getString(ProviderProfileConstants.PREFS_KEY + getType()));
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, getHelpContextId());
- }
+ updateOptionsEnable();
+ updateValue(getPreferenceStore().getString(ProviderProfileConstants.PREFS_KEY + getType()));
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, getHelpContextId());
+ }
- private void setButtonsEnabled(boolean value) {
+ private void setButtonsEnabled(boolean value) {
for (int j = 0; j < radioButtons.length; j++) {
- radioButtons[j].setEnabled(value);
+ radioButtons[j].setEnabled(value);
+ }
+ }
+
+ private void updateOptionsEnable() {
+ if (useProjectSetting.getSelection()) {
+ projectSettingsGroup.setEnabled(true);
+ setButtonsEnabled(true);
+ fLink.setVisible(false);
+ } else {
+ setButtonsEnabled(false);
+ projectSettingsGroup.setEnabled(false);
+ fLink.setVisible(true);
+ }
+ }
+
+ @Override
+ protected void performDefaults() {
+ if (useProjectSetting.getSelection()) {
+ updateValue(getPreferenceStore().getDefaultString(ProviderProfileConstants.PREFS_KEY + getType()));
+ }
+ updateOptionsEnable();
+ }
+
+ @Override
+ public void performOK() {
+ getPreferenceStore().setValue(ProviderProfileConstants.USE_PROJECT_SETTINGS + getType(), useProjectSetting.getSelection());
+ getPreferenceStore().setValue(ProviderProfileConstants.PREFS_KEY + getType(), value);
+ try {
+ getPreferenceStore().save();
+ } catch (IOException e) {
+ // do nothing
}
- }
-
- private void updateOptionsEnable() {
- if (useProjectSetting.getSelection()) {
- projectSettingsGroup.setEnabled(true);
- setButtonsEnabled(true);
- fLink.setVisible(false);
- } else {
- setButtonsEnabled(false);
- projectSettingsGroup.setEnabled(false);
- fLink.setVisible(true);
- }
- }
-
- @Override
- protected void performDefaults() {
- if (useProjectSetting.getSelection()) {
- updateValue(getPreferenceStore().getDefaultString(ProviderProfileConstants.PREFS_KEY + getType()));
- }
- updateOptionsEnable();
- }
-
- @Override
- public void performOK() {
- getPreferenceStore().setValue(ProviderProfileConstants.USE_PROJECT_SETTINGS + getType(), useProjectSetting.getSelection());
- getPreferenceStore().setValue(ProviderProfileConstants.PREFS_KEY + getType(), value);
- try {
- getPreferenceStore().save();
- } catch (IOException e) {
- // do nothing
- }
- }
-
- private ScopedPreferenceStore getPreferenceStore() {
- return preferenceStore;
- }
-
- private void setPreferenceStore(ScopedPreferenceStore store) {
- preferenceStore = store;
- }
-
- @Override
- protected void performApply(ICResourceDescription src, ICResourceDescription dst) {
- getPreferenceStore().setValue(ProviderProfileConstants.USE_PROJECT_SETTINGS + getType(), useProjectSetting.getSelection());
- getPreferenceStore().setValue(ProviderProfileConstants.PREFS_KEY + getType(), value);
- try {
- getPreferenceStore().save();
- } catch (IOException e) {
- // do nothing
- }
- }
+ }
+
+ private ScopedPreferenceStore getPreferenceStore() {
+ return preferenceStore;
+ }
+
+ private void setPreferenceStore(ScopedPreferenceStore store) {
+ preferenceStore = store;
+ }
+
+ @Override
+ protected void performApply(ICResourceDescription src, ICResourceDescription dst) {
+ getPreferenceStore().setValue(ProviderProfileConstants.USE_PROJECT_SETTINGS + getType(), useProjectSetting.getSelection());
+ getPreferenceStore().setValue(ProviderProfileConstants.PREFS_KEY + getType(), value);
+ try {
+ getPreferenceStore().save();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
/**
* Select the radio button that conforms to the given value.
@@ -232,8 +232,8 @@ public abstract class AbstractProviderPropertyTab extends AbstractCPropertyTab {
private void updateValue(String selectedValue) {
this.value = selectedValue;
if (radioButtons == null) {
- return;
- }
+ return;
+ }
if (this.value != null) {
boolean found = false;
@@ -247,8 +247,8 @@ public abstract class AbstractProviderPropertyTab extends AbstractCPropertyTab {
radio.setSelection(selection);
}
if (found) {
- return;
- }
+ return;
+ }
}
// We weren't able to find the value. So we select the first
@@ -260,21 +260,21 @@ public abstract class AbstractProviderPropertyTab extends AbstractCPropertyTab {
return;
}
- @Override
- public String getHelpContextId() {
- return ProviderProfileConstants.PLUGIN_ID + ".profiling_categories"; //$NON-NLS-1$
- }
+ @Override
+ public String getHelpContextId() {
+ return ProviderProfileConstants.PLUGIN_ID + ".profiling_categories"; //$NON-NLS-1$
+ }
- // This page can be displayed for project only
- @Override
- public boolean canBeVisible() {
- return page.isForProject() || page.isForPrefs();
- }
+ // This page can be displayed for project only
+ @Override
+ public boolean canBeVisible() {
+ return page.isForProject() || page.isForPrefs();
+ }
- @Override
- protected void updateButtons() {/* Empty block */}
+ @Override
+ protected void updateButtons() {/* Empty block */}
- @Override
- protected void updateData(ICResourceDescription cfg) {/* Empty block */}
+ @Override
+ protected void updateData(ICResourceDescription cfg) {/* Empty block */}
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/CoveragePropertyTab.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/CoveragePropertyTab.java
index cc89a48e5f..a2ce8291ae 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/CoveragePropertyTab.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/CoveragePropertyTab.java
@@ -13,18 +13,18 @@ package org.eclipse.linuxtools.internal.profiling.launch.provider;
public class CoveragePropertyTab extends AbstractProviderPropertyTab {
- public CoveragePropertyTab() {
- super();
- }
+ public CoveragePropertyTab() {
+ super();
+ }
- @Override
- protected String getType() {
- return "coverage"; //$NON-NLS-1$
- }
-
- @Override
- protected String getPrefPageId() {
- return "org.eclipse.linuxtools.profiling.provider.CoveragePreferencePage"; //$NON-NLS-1$
- }
+ @Override
+ protected String getType() {
+ return "coverage"; //$NON-NLS-1$
+ }
+
+ @Override
+ protected String getPrefPageId() {
+ return "org.eclipse.linuxtools.profiling.provider.CoveragePreferencePage"; //$NON-NLS-1$
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/MemoryPropertyTab.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/MemoryPropertyTab.java
index c94e54f9e5..a80d551e99 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/MemoryPropertyTab.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/MemoryPropertyTab.java
@@ -13,19 +13,19 @@ package org.eclipse.linuxtools.internal.profiling.launch.provider;
public class MemoryPropertyTab extends AbstractProviderPropertyTab {
- public MemoryPropertyTab() {
- super();
- }
+ public MemoryPropertyTab() {
+ super();
+ }
- @Override
- protected String getType() {
- return "memory"; //$NON-NLS-01$
- }
-
- @Override
- protected String getPrefPageId() {
- return "org.eclipse.linuxtools.profiling.provider.MemoryPreferencePage"; //$NON-NLS-1$
- }
+ @Override
+ protected String getType() {
+ return "memory"; //$NON-NLS-01$
+ }
+
+ @Override
+ protected String getPrefPageId() {
+ return "org.eclipse.linuxtools.profiling.provider.MemoryPreferencePage"; //$NON-NLS-1$
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProfilingCategoriesPreferencesPage.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProfilingCategoriesPreferencesPage.java
index 2560d23cd8..71ac74af64 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProfilingCategoriesPreferencesPage.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProfilingCategoriesPreferencesPage.java
@@ -20,31 +20,31 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.PlatformUI;
public class ProfilingCategoriesPreferencesPage extends FieldEditorPreferencePage
- implements IWorkbenchPreferencePage {
-
- @Override
- public void init(IWorkbench workbench) {
- setDescription(Messages.ProviderPreferencesPage_2);
- }
-
- @Override
- protected void createFieldEditors() {
- // Content for global profiling provider preferences.
- }
-
- @Override
- protected Control createContents(Composite parent) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, getHelpContextId());
- return super.createContents(parent);
- }
-
- /**
- * Return the help context id to use if the help button is pushed.
- *
- * @return the help context id
- */
- private String getHelpContextId() {
- return ProviderProfileConstants.PLUGIN_ID + ".profiling_categories"; //$NON-NLS-1$
- }
+ implements IWorkbenchPreferencePage {
+
+ @Override
+ public void init(IWorkbench workbench) {
+ setDescription(Messages.ProviderPreferencesPage_2);
+ }
+
+ @Override
+ protected void createFieldEditors() {
+ // Content for global profiling provider preferences.
+ }
+
+ @Override
+ protected Control createContents(Composite parent) {
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, getHelpContextId());
+ return super.createContents(parent);
+ }
+
+ /**
+ * Return the help context id to use if the help button is pushed.
+ *
+ * @return the help context id
+ */
+ private String getHelpContextId() {
+ return ProviderProfileConstants.PLUGIN_ID + ".profiling_categories"; //$NON-NLS-1$
+ }
} \ No newline at end of file
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProfilingPropertyPage.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProfilingPropertyPage.java
index 56384cfb11..8bd2216ce2 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProfilingPropertyPage.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProfilingPropertyPage.java
@@ -14,12 +14,12 @@ import org.eclipse.cdt.ui.newui.AbstractPage;
public class ProfilingPropertyPage extends AbstractPage {
- @Override
- protected boolean showsConfig() { return false; }
-
- @Override
- protected boolean isSingle() {
- return false;
- }
+ @Override
+ protected boolean showsConfig() { return false; }
+
+ @Override
+ protected boolean isSingle() {
+ return false;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderLaunchConfigurationTabGroup.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderLaunchConfigurationTabGroup.java
index 2dfa1404ca..aa9c829813 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderLaunchConfigurationTabGroup.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderLaunchConfigurationTabGroup.java
@@ -19,57 +19,57 @@ import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTabGroup;
public class ProviderLaunchConfigurationTabGroup extends
- ProfileLaunchConfigurationTabGroup implements IExecutableExtension {
+ ProfileLaunchConfigurationTabGroup implements IExecutableExtension {
- // Profiling type.
- private String type;
+ // Profiling type.
+ private String type;
- // Profiling type name to be displayed.
- private String name;
+ // Profiling type name to be displayed.
+ private String name;
- @Override
- public void setInitializationData(IConfigurationElement config,
- String propertyName, Object data) {
- Map<String, String> parameters = (Map<String, String>) data;
- String profilingType = parameters
- .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY);
- String profilingTypeName = parameters
- .get(ProviderProfileConstants.INIT_DATA_NAME_KEY);
+ @Override
+ public void setInitializationData(IConfigurationElement config,
+ String propertyName, Object data) {
+ Map<String, String> parameters = (Map<String, String>) data;
+ String profilingType = parameters
+ .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY);
+ String profilingTypeName = parameters
+ .get(ProviderProfileConstants.INIT_DATA_NAME_KEY);
- if (profilingType == null) {
- profilingType = ""; //$NON-NLS-1$
- }
- if (profilingTypeName == null) {
- profilingTypeName = ""; //$NON-NLS-1$
- }
+ if (profilingType == null) {
+ profilingType = ""; //$NON-NLS-1$
+ }
+ if (profilingTypeName == null) {
+ profilingTypeName = ""; //$NON-NLS-1$
+ }
- setProfilingType(profilingType);
- setProfilingTypeName(profilingTypeName);
- }
+ setProfilingType(profilingType);
+ setProfilingTypeName(profilingTypeName);
+ }
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- ArrayList<AbstractLaunchConfigurationTab> tabs = new ArrayList<>();
- tabs.add(new ProviderOptionsTab(type, name));
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ ArrayList<AbstractLaunchConfigurationTab> tabs = new ArrayList<>();
+ tabs.add(new ProviderOptionsTab(type, name));
- return tabs.toArray(new AbstractLaunchConfigurationTab [] {});
- }
+ return tabs.toArray(new AbstractLaunchConfigurationTab [] {});
+ }
- /**
- * Set profiling type.
- *
- * @param profilingType
- */
- private void setProfilingType(String profilingType) {
- type = profilingType;
- }
+ /**
+ * Set profiling type.
+ *
+ * @param profilingType
+ */
+ private void setProfilingType(String profilingType) {
+ type = profilingType;
+ }
- /**
- * Set profiling type name to be displayed.
- *
- * @param profilingTypeName
- */
- private void setProfilingTypeName(String profilingTypeName) {
- name = profilingTypeName;
- }
+ /**
+ * Set profiling type name to be displayed.
+ *
+ * @param profilingTypeName
+ */
+ private void setProfilingTypeName(String profilingTypeName) {
+ name = profilingTypeName;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderOptionsTab.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderOptionsTab.java
index 505c38e543..83467535ce 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderOptionsTab.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderOptionsTab.java
@@ -17,26 +17,26 @@ import org.eclipse.linuxtools.internal.profiling.launch.provider.launch.Provider
public class ProviderOptionsTab extends AbstractProfilingOptionsTab {
- /**
- * ProviderOptionsTab constructor.
- *
- * @param profilingType String type of profiling this tab will be used for.
- * @param profilingName String name of this tab to be displayed.
- */
- public ProviderOptionsTab(String profilingType, String profilingName) {
- setProfilingType(profilingType);
- setName(profilingName);
- }
-
- @Override
- protected Map<String, String> getProviders() {
- return ProviderFramework.getProviderNamesForType(getProfilingType());
- }
-
- @Override
- protected String getDefaultProviderId() {
- return ProviderFramework.getProviderIdToRun(null, getProfilingType());
- }
-
+ /**
+ * ProviderOptionsTab constructor.
+ *
+ * @param profilingType String type of profiling this tab will be used for.
+ * @param profilingName String name of this tab to be displayed.
+ */
+ public ProviderOptionsTab(String profilingType, String profilingName) {
+ setProfilingType(profilingType);
+ setName(profilingName);
+ }
+
+ @Override
+ protected Map<String, String> getProviders() {
+ return ProviderFramework.getProviderNamesForType(getProfilingType());
+ }
+
+ @Override
+ protected String getDefaultProviderId() {
+ return ProviderFramework.getProviderIdToRun(null, getProfilingType());
+ }
+
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderPreferencesPage.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderPreferencesPage.java
index 953344553e..100694a80d 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderPreferencesPage.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderPreferencesPage.java
@@ -20,31 +20,31 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.PlatformUI;
public class ProviderPreferencesPage extends FieldEditorPreferencePage
- implements IWorkbenchPreferencePage {
-
- @Override
- public void init(IWorkbench workbench) {
- setDescription(Messages.ProviderPreferencesPage_0);
- }
-
- @Override
- protected void createFieldEditors() {
- // Content for global profiling provider preferences.
- }
-
- @Override
- protected Control createContents(Composite parent) {
- PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, getHelpContextId());
- return super.createContents(parent);
- }
-
- /**
- * Return the help context id to use if the help button is pushed.
- *
- * @return the help context id
- */
- private String getHelpContextId() {
- return ProviderProfileConstants.PLUGIN_ID + ".profiling_categories"; //$NON-NLS-1$
- }
+ implements IWorkbenchPreferencePage {
+
+ @Override
+ public void init(IWorkbench workbench) {
+ setDescription(Messages.ProviderPreferencesPage_0);
+ }
+
+ @Override
+ protected void createFieldEditors() {
+ // Content for global profiling provider preferences.
+ }
+
+ @Override
+ protected Control createContents(Composite parent) {
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, getHelpContextId());
+ return super.createContents(parent);
+ }
+
+ /**
+ * Return the help context id to use if the help button is pushed.
+ *
+ * @return the help context id
+ */
+ private String getHelpContextId() {
+ return ProviderProfileConstants.PLUGIN_ID + ".profiling_categories"; //$NON-NLS-1$
+ }
} \ No newline at end of file
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderProfileConstants.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderProfileConstants.java
index 5ea682dd23..bf30d92c01 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderProfileConstants.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/ProviderProfileConstants.java
@@ -15,46 +15,46 @@ package org.eclipse.linuxtools.internal.profiling.launch.provider;
*/
public class ProviderProfileConstants {
- /**
- * The plug-in id.
- */
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.profiling.launch"; //$NON-NLS-1$
-
- /**
- * Profiling preferences key.
- */
- public static final String PREFS_KEY = "provider"; //$NON-NLS-1$
-
- /**
- * Project attribute to indicate project is overriding settings
- */
- public static final String USE_PROJECT_SETTINGS = "use_project"; //$NON-NLS-1$
-
- /**
- * Key to acquire the extension point class parameter containing the
- * profiling type.
- */
- public static final String INIT_DATA_TYPE_KEY = "type"; //$NON-NLS-1$
-
- /**
- * Key to acquire the extension point class parameter containing the name to
- * be used by the options tab.
- */
- public static final String INIT_DATA_NAME_KEY = "name"; //$NON-NLS-1$
-
- /**
- * Key to acquire the extension point class parameter containing the
- * configuration type identifier.
- */
- public static final String INIT_DATA_CONFIG_ID_KEY = "configurationId"; //$NON-NLS-1$
-
- /**
- * Key to acquire the provider launch configuration attribute.
- */
- public static final String PROVIDER_CONFIG_ATT = "provider"; //$NON-NLS-1$
-
- /**
- * Key to acquire the tool name launch configuration attribute.
- */
- public static final String PROVIDER_CONFIG_TOOLNAME_ATT = "toolname"; //$NON-NLS-1$
+ /**
+ * The plug-in id.
+ */
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.profiling.launch"; //$NON-NLS-1$
+
+ /**
+ * Profiling preferences key.
+ */
+ public static final String PREFS_KEY = "provider"; //$NON-NLS-1$
+
+ /**
+ * Project attribute to indicate project is overriding settings
+ */
+ public static final String USE_PROJECT_SETTINGS = "use_project"; //$NON-NLS-1$
+
+ /**
+ * Key to acquire the extension point class parameter containing the
+ * profiling type.
+ */
+ public static final String INIT_DATA_TYPE_KEY = "type"; //$NON-NLS-1$
+
+ /**
+ * Key to acquire the extension point class parameter containing the name to
+ * be used by the options tab.
+ */
+ public static final String INIT_DATA_NAME_KEY = "name"; //$NON-NLS-1$
+
+ /**
+ * Key to acquire the extension point class parameter containing the
+ * configuration type identifier.
+ */
+ public static final String INIT_DATA_CONFIG_ID_KEY = "configurationId"; //$NON-NLS-1$
+
+ /**
+ * Key to acquire the provider launch configuration attribute.
+ */
+ public static final String PROVIDER_CONFIG_ATT = "provider"; //$NON-NLS-1$
+
+ /**
+ * Key to acquire the tool name launch configuration attribute.
+ */
+ public static final String PROVIDER_CONFIG_TOOLNAME_ATT = "toolname"; //$NON-NLS-1$
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/TimingPropertyTab.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/TimingPropertyTab.java
index adebeb4a21..83432fa9d4 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/TimingPropertyTab.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/TimingPropertyTab.java
@@ -13,18 +13,18 @@ package org.eclipse.linuxtools.internal.profiling.launch.provider;
public class TimingPropertyTab extends AbstractProviderPropertyTab {
- public TimingPropertyTab() {
- super();
- }
+ public TimingPropertyTab() {
+ super();
+ }
- @Override
- protected String getType() {
- return "timing"; //$NON-NLS-1$
- }
+ @Override
+ protected String getType() {
+ return "timing"; //$NON-NLS-1$
+ }
- @Override
- protected String getPrefPageId() {
- return "org.eclipse.linuxtools.profiling.provider.TimingPreferencePage"; //$NON-NLS-1$
- }
+ @Override
+ protected String getPrefPageId() {
+ return "org.eclipse.linuxtools.profiling.provider.TimingPreferencePage"; //$NON-NLS-1$
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderFramework.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderFramework.java
index 1756228c40..cf809d2e6a 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderFramework.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderFramework.java
@@ -44,461 +44,461 @@ import org.eclipse.ui.preferences.ScopedPreferenceStore;
*/
public class ProviderFramework {
- /**
- * Get a profiling launch shortcut that provides the specified type of profiling. This
- * looks through extensions of the extension point
- * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code> that have a
- * specific type attribute.
- *
- * @param type A profiling type (eg. memory, snapshot, timing, etc.)
- * @return a profiling launch shortcut that implements <code>ProfileLaunchShortcut</code>
- * and provides the necessary profiling type, or <code>null</code> if none could be found.
- * @since 1.2
- */
- public static ProfileLaunchShortcut getProfilingProvider(String type) {
- ArrayList<IConfigurationElement> configList = getOrderedConfigElements(type);
+ /**
+ * Get a profiling launch shortcut that provides the specified type of profiling. This
+ * looks through extensions of the extension point
+ * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code> that have a
+ * specific type attribute.
+ *
+ * @param type A profiling type (eg. memory, snapshot, timing, etc.)
+ * @return a profiling launch shortcut that implements <code>ProfileLaunchShortcut</code>
+ * and provides the necessary profiling type, or <code>null</code> if none could be found.
+ * @since 1.2
+ */
+ public static ProfileLaunchShortcut getProfilingProvider(String type) {
+ ArrayList<IConfigurationElement> configList = getOrderedConfigElements(type);
- for (IConfigurationElement config : configList) {
- try {
- Object obj = config.createExecutableExtension("shortcut"); //$NON-NLS-1$
- if (obj instanceof ProfileLaunchShortcut) {
- return (ProfileLaunchShortcut) obj;
- }
- } catch (CoreException e) {
- // continue, other configuration may succeed
- }
- }
- return null;
- }
+ for (IConfigurationElement config : configList) {
+ try {
+ Object obj = config.createExecutableExtension("shortcut"); //$NON-NLS-1$
+ if (obj instanceof ProfileLaunchShortcut) {
+ return (ProfileLaunchShortcut) obj;
+ }
+ } catch (CoreException e) {
+ // continue, other configuration may succeed
+ }
+ }
+ return null;
+ }
- /**
- * Get a profiling launch shortcut that is associated with the specified id.
- * This looks through extensions of the extension point
- * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
- * that have a specific id.
- *
- * @param id A unique identifier
- * @return a profiling launch shortcut that implements <code>ProfileLaunchShortcut</code>
- * and provides the necessary profiling type, or <code>null</code> if none could be found.
- * @since 1.2
- */
- public static ProfileLaunchShortcut getLaunchShortcutProviderFromId(
- String id) {
- IConfigurationElement[] configs = getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals("provider")) { //$NON-NLS-1$
- String currentId = config.getAttribute("id"); //$NON-NLS-1$
- String shortcut = config.getAttribute("shortcut"); //$NON-NLS-1$
- if (currentId != null && shortcut != null
- && currentId.equals(id)) {
- try {
- Object obj = config
- .createExecutableExtension("shortcut"); //$NON-NLS-1$
- if (obj instanceof ProfileLaunchShortcut) {
- return (ProfileLaunchShortcut) obj;
- }
- } catch (CoreException e) {
- // continue, perhaps another configuration will succeed
- }
- }
- }
- }
- return null;
- }
+ /**
+ * Get a profiling launch shortcut that is associated with the specified id.
+ * This looks through extensions of the extension point
+ * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
+ * that have a specific id.
+ *
+ * @param id A unique identifier
+ * @return a profiling launch shortcut that implements <code>ProfileLaunchShortcut</code>
+ * and provides the necessary profiling type, or <code>null</code> if none could be found.
+ * @since 1.2
+ */
+ public static ProfileLaunchShortcut getLaunchShortcutProviderFromId(
+ String id) {
+ IConfigurationElement[] configs = getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals("provider")) { //$NON-NLS-1$
+ String currentId = config.getAttribute("id"); //$NON-NLS-1$
+ String shortcut = config.getAttribute("shortcut"); //$NON-NLS-1$
+ if (currentId != null && shortcut != null
+ && currentId.equals(id)) {
+ try {
+ Object obj = config
+ .createExecutableExtension("shortcut"); //$NON-NLS-1$
+ if (obj instanceof ProfileLaunchShortcut) {
+ return (ProfileLaunchShortcut) obj;
+ }
+ } catch (CoreException e) {
+ // continue, perhaps another configuration will succeed
+ }
+ }
+ }
+ }
+ return null;
+ }
- /**
- * Get a launch configuration delegate that is associated with the specified id.
- * This looks through extensions of the extension point
- * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code> that
- * have a specific delegate attribute.
- *
- * @param id a unique identifier
- * @return a launch configuration delegate that implements
- * <code>AbstractCLaunchDelegate</code> , or <code>null</code> if
- * none could be found.
- * @since 1.2
- */
- public static AbstractCLaunchDelegate getConfigurationDelegateFromId(
- String id) {
- IConfigurationElement[] configs = getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals("provider")) { //$NON-NLS-1$
- String currentId = config.getAttribute("id"); //$NON-NLS-1$
- String tabgroup = config.getAttribute("delegate"); //$NON-NLS-1$
- if (currentId != null && tabgroup != null
- && currentId.equals(id)) {
- try {
- Object obj = config
- .createExecutableExtension("delegate"); //$NON-NLS-1$
- if (obj instanceof AbstractCLaunchDelegate) {
- return (AbstractCLaunchDelegate) obj;
- }
- } catch (CoreException e) {
- // continue, perhaps another configuration will succeed
- }
- }
- }
- }
- return null;
- }
+ /**
+ * Get a launch configuration delegate that is associated with the specified id.
+ * This looks through extensions of the extension point
+ * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code> that
+ * have a specific delegate attribute.
+ *
+ * @param id a unique identifier
+ * @return a launch configuration delegate that implements
+ * <code>AbstractCLaunchDelegate</code> , or <code>null</code> if
+ * none could be found.
+ * @since 1.2
+ */
+ public static AbstractCLaunchDelegate getConfigurationDelegateFromId(
+ String id) {
+ IConfigurationElement[] configs = getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals("provider")) { //$NON-NLS-1$
+ String currentId = config.getAttribute("id"); //$NON-NLS-1$
+ String tabgroup = config.getAttribute("delegate"); //$NON-NLS-1$
+ if (currentId != null && tabgroup != null
+ && currentId.equals(id)) {
+ try {
+ Object obj = config
+ .createExecutableExtension("delegate"); //$NON-NLS-1$
+ if (obj instanceof AbstractCLaunchDelegate) {
+ return (AbstractCLaunchDelegate) obj;
+ }
+ } catch (CoreException e) {
+ // continue, perhaps another configuration will succeed
+ }
+ }
+ }
+ }
+ return null;
+ }
- /**
- * Get id of highest priority profiling tabgroup launch configuration that
- * provides the type of profiling. This looks through extensions of the
- * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
- * extension point that have a specific type attribute.
- *
- * @param type A profiling type (eg. memory, snapshot, timing, etc.)
- * @return an id of the profiling launch shortcut that implements
- * <code>ProfileLaunchShortcut</code> and provides the necessary
- * profiling type, or <code>null</code> if none could be found.
- * @since 1.2
- */
- public static String getHighestProviderId(String type) {
- ArrayList<IConfigurationElement> list = getOrderedConfigElements(type);
+ /**
+ * Get id of highest priority profiling tabgroup launch configuration that
+ * provides the type of profiling. This looks through extensions of the
+ * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
+ * extension point that have a specific type attribute.
+ *
+ * @param type A profiling type (eg. memory, snapshot, timing, etc.)
+ * @return an id of the profiling launch shortcut that implements
+ * <code>ProfileLaunchShortcut</code> and provides the necessary
+ * profiling type, or <code>null</code> if none could be found.
+ * @since 1.2
+ */
+ public static String getHighestProviderId(String type) {
+ ArrayList<IConfigurationElement> list = getOrderedConfigElements(type);
- if (list.size() > 0) {
- return list.get(0).getAttribute("id"); //$NON-NLS-1$
- }
- return null;
- }
+ if (list.size() > 0) {
+ return list.get(0).getAttribute("id"); //$NON-NLS-1$
+ }
+ return null;
+ }
- /**
- * Get map of all pairs of names and IDs of the specific provider type. This
- * looks through extensions of the extension point
- * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
- * that have a specific type.
- *
- * @param type A profiling type (eg. memory, snapshot, timing, etc.)
- * @return A <code>HashMap<String, String></code> of all pairs of names and IDs
- * of the specific type.
- * @since 1.2
- */
- public static HashMap<String, String> getProviderNamesForType(String type) {
- HashMap<String, String> ret = new HashMap<>();
- IConfigurationElement[] configs = getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals("provider")) { //$NON-NLS-1$
- String currentId = config.getAttribute("id"); //$NON-NLS-1$
- String currentName = config.getAttribute("name"); //$NON-NLS-1$
- String currentType = config.getAttribute("type"); //$NON-NLS-1$
- if (currentType != null && type != null
- && currentType.equals(type) && currentName != null) {
- ret.put(currentName, currentId);
- }
- }
- }
- return ret;
- }
+ /**
+ * Get map of all pairs of names and IDs of the specific provider type. This
+ * looks through extensions of the extension point
+ * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
+ * that have a specific type.
+ *
+ * @param type A profiling type (eg. memory, snapshot, timing, etc.)
+ * @return A <code>HashMap<String, String></code> of all pairs of names and IDs
+ * of the specific type.
+ * @since 1.2
+ */
+ public static HashMap<String, String> getProviderNamesForType(String type) {
+ HashMap<String, String> ret = new HashMap<>();
+ IConfigurationElement[] configs = getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals("provider")) { //$NON-NLS-1$
+ String currentId = config.getAttribute("id"); //$NON-NLS-1$
+ String currentName = config.getAttribute("name"); //$NON-NLS-1$
+ String currentType = config.getAttribute("type"); //$NON-NLS-1$
+ if (currentType != null && type != null
+ && currentType.equals(type) && currentName != null) {
+ ret.put(currentName, currentId);
+ }
+ }
+ }
+ return ret;
+ }
- /**
- * Get map of all pairs of names and IDs of profiling providers. This
- * looks through extensions of the extension point
- * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>.
- *
- * @return A <code>SortedMap<String, String></code> of all pairs of names and IDs
- * of profiling providers.
- * @since 2.0
- */
- public static SortedMap<String, String> getAllProviderNames() {
- SortedMap<String, String> ret = new TreeMap<>();
- IConfigurationElement[] configs = getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals("provider")) { //$NON-NLS-1$
- String currentId = config.getAttribute("id"); //$NON-NLS-1$
- String currentName = config.getAttribute("name"); //$NON-NLS-1$
- if (currentName != null && currentId != null) {
- ret.put(currentName, currentId);
- }
- }
- }
- return ret;
- }
+ /**
+ * Get map of all pairs of names and IDs of profiling providers. This
+ * looks through extensions of the extension point
+ * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>.
+ *
+ * @return A <code>SortedMap<String, String></code> of all pairs of names and IDs
+ * of profiling providers.
+ * @since 2.0
+ */
+ public static SortedMap<String, String> getAllProviderNames() {
+ SortedMap<String, String> ret = new TreeMap<>();
+ IConfigurationElement[] configs = getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals("provider")) { //$NON-NLS-1$
+ String currentId = config.getAttribute("id"); //$NON-NLS-1$
+ String currentName = config.getAttribute("name"); //$NON-NLS-1$
+ if (currentName != null && currentId != null) {
+ ret.put(currentName, currentId);
+ }
+ }
+ }
+ return ret;
+ }
- /**
- * Get launch providers for a given type and order them with regards to highest priority first.
- *
- * @param type
- * @return array of launch provider configuration elements in prioritized order
- * @since 1.2
- */
- public static ArrayList<IConfigurationElement> getOrderedConfigElements(String type) {
- IConfigurationElement[] configs = getConfigurationElements();
- ArrayList<IConfigurationElement> configList = new ArrayList<>();
+ /**
+ * Get launch providers for a given type and order them with regards to highest priority first.
+ *
+ * @param type
+ * @return array of launch provider configuration elements in prioritized order
+ * @since 1.2
+ */
+ public static ArrayList<IConfigurationElement> getOrderedConfigElements(String type) {
+ IConfigurationElement[] configs = getConfigurationElements();
+ ArrayList<IConfigurationElement> configList = new ArrayList<>();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals("provider")) { //$NON-NLS-1$
- String currentType = config.getAttribute("type"); //$NON-NLS-1$
- if (currentType != null && currentType.equals(type)) {
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals("provider")) { //$NON-NLS-1$
+ String currentType = config.getAttribute("type"); //$NON-NLS-1$
+ if (currentType != null && currentType.equals(type)) {
- String priority = config.getAttribute("priority"); //$NON-NLS-1$
- if (priority != null) {
- try {
- Integer.parseInt(priority);
- configList.add(config);
- } catch (NumberFormatException e) {
- // continue
- }
- }
- }
- }
- }
+ String priority = config.getAttribute("priority"); //$NON-NLS-1$
+ if (priority != null) {
+ try {
+ Integer.parseInt(priority);
+ configList.add(config);
+ } catch (NumberFormatException e) {
+ // continue
+ }
+ }
+ }
+ }
+ }
- Collections.sort(configList, new Comparator<IConfigurationElement>() {
- @Override
- public int compare(IConfigurationElement c1,
- IConfigurationElement c2) {
- int p1, p2;
- // If priority is not an int or is < 0, corresponding config has
- // lowest priority.
- try {
- p1 = Integer.parseInt(c1.getAttribute("priority")); //$NON-NLS-1$
- if (p1 <= 0) {
- return 1;
- }
- } catch (NumberFormatException e) {
- return 1;
- }
- try {
- p2 = Integer.parseInt(c2.getAttribute("priority")); //$NON-NLS-1$
- if (p2 <= 0) {
- return -1;
- }
- } catch (NumberFormatException e) {
- return -1;
- }
- return p1 < p2 ? -1 : 1;
- }
- });
- return configList;
- }
+ Collections.sort(configList, new Comparator<IConfigurationElement>() {
+ @Override
+ public int compare(IConfigurationElement c1,
+ IConfigurationElement c2) {
+ int p1, p2;
+ // If priority is not an int or is < 0, corresponding config has
+ // lowest priority.
+ try {
+ p1 = Integer.parseInt(c1.getAttribute("priority")); //$NON-NLS-1$
+ if (p1 <= 0) {
+ return 1;
+ }
+ } catch (NumberFormatException e) {
+ return 1;
+ }
+ try {
+ p2 = Integer.parseInt(c2.getAttribute("priority")); //$NON-NLS-1$
+ if (p2 <= 0) {
+ return -1;
+ }
+ } catch (NumberFormatException e) {
+ return -1;
+ }
+ return p1 < p2 ? -1 : 1;
+ }
+ });
+ return configList;
+ }
- /**
- * Helper method to return the list of extensions that contribute the the
- * provider framework.
- * @return All extensions that contribute to the provider framework.
- */
- private static IConfigurationElement [] getConfigurationElements () {
- IExtensionPoint extPoint = Platform.getExtensionRegistry()
- .getExtensionPoint(ProfileLaunchPlugin.PLUGIN_ID, "launchProvider"); //$NON-NLS-1$
- return extPoint.getConfigurationElements();
- }
+ /**
+ * Helper method to return the list of extensions that contribute the the
+ * provider framework.
+ * @return All extensions that contribute to the provider framework.
+ */
+ private static IConfigurationElement [] getConfigurationElements () {
+ IExtensionPoint extPoint = Platform.getExtensionRegistry()
+ .getExtensionPoint(ProfileLaunchPlugin.PLUGIN_ID, "launchProvider"); //$NON-NLS-1$
+ return extPoint.getConfigurationElements();
+ }
- /**
- * Get name of tool with plug-in id <code>id</code>. This looks through
- * extensions of the
- * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
- * extensions point.
- *
- * @since 2.0
- */
- public static String getProviderToolNameFromId(String id) {
- IConfigurationElement[] configs = getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals("provider")) { //$NON-NLS-1$
- String currentId = config.getAttribute("id"); //$NON-NLS-1$
- if (currentId != null && currentId.equals(id)) {
- return config.getAttribute("name"); //$NON-NLS-1$
- }
- }
- }
- return null;
- }
+ /**
+ * Get name of tool with plug-in id <code>id</code>. This looks through
+ * extensions of the
+ * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
+ * extensions point.
+ *
+ * @since 2.0
+ */
+ public static String getProviderToolNameFromId(String id) {
+ IConfigurationElement[] configs = getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals("provider")) { //$NON-NLS-1$
+ String currentId = config.getAttribute("id"); //$NON-NLS-1$
+ if (currentId != null && currentId.equals(id)) {
+ return config.getAttribute("name"); //$NON-NLS-1$
+ }
+ }
+ }
+ return null;
+ }
- /**
- * Get content of attribute <code>attribute</code> from the launch provider
- * with id <code>toolId</code>.
- *
- * @param toolId String unique id of the tool.
- * @return String description of tool.
- * @since 2.0
- */
- public static String getToolInformationFromId(String toolId,
- String attribute) {
- IConfigurationElement[] configs = getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals("provider")) { //$NON-NLS-1$
- String currentId = config.getAttribute("id"); //$NON-NLS-1$
- String currentToolDescription = config.getAttribute(attribute);
- if (currentId != null && currentToolDescription != null
- && currentId.equals(toolId)) {
- return currentToolDescription;
- }
- }
- }
- return null;
- }
+ /**
+ * Get content of attribute <code>attribute</code> from the launch provider
+ * with id <code>toolId</code>.
+ *
+ * @param toolId String unique id of the tool.
+ * @return String description of tool.
+ * @since 2.0
+ */
+ public static String getToolInformationFromId(String toolId,
+ String attribute) {
+ IConfigurationElement[] configs = getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals("provider")) { //$NON-NLS-1$
+ String currentId = config.getAttribute("id"); //$NON-NLS-1$
+ String currentToolDescription = config.getAttribute(attribute);
+ if (currentId != null && currentToolDescription != null
+ && currentId.equals(toolId)) {
+ return currentToolDescription;
+ }
+ }
+ }
+ return null;
+ }
- /**
- * Get a profiling tab that provides the specified type of profiling. This
- * looks through extensions of the extension point
- * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code> that have a
- * specific type attribute.
- *
- * @param type A profiling type (eg. memory, snapshot, timing, etc.)
- * @return a tab that implements <code>ProfileLaunchConfigurationTabGroup</code>
- * and provides the necessary profiling type, or <code>null</code> if none could be found.
- * @since 2.0
- */
- public static ProfileLaunchConfigurationTabGroup getTabGroupProvider(String type) {
- IConfigurationElement[] configs = getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals("provider")) { //$NON-NLS-1$
- String currentType = config.getAttribute("type"); //$NON-NLS-1$
- String shortcut = config.getAttribute("tabgroup"); //$NON-NLS-1$
- if (currentType != null && shortcut != null
- && currentType.equals(type)) {
- try {
- Object obj = config
- .createExecutableExtension("tabgroup"); //$NON-NLS-1$
- if (obj instanceof ProfileLaunchConfigurationTabGroup) {
- return (ProfileLaunchConfigurationTabGroup) obj;
- }
- } catch (CoreException e) {
- // continue, perhaps another configuration will succeed
- }
- }
- }
- }
- return null;
- }
+ /**
+ * Get a profiling tab that provides the specified type of profiling. This
+ * looks through extensions of the extension point
+ * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code> that have a
+ * specific type attribute.
+ *
+ * @param type A profiling type (eg. memory, snapshot, timing, etc.)
+ * @return a tab that implements <code>ProfileLaunchConfigurationTabGroup</code>
+ * and provides the necessary profiling type, or <code>null</code> if none could be found.
+ * @since 2.0
+ */
+ public static ProfileLaunchConfigurationTabGroup getTabGroupProvider(String type) {
+ IConfigurationElement[] configs = getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals("provider")) { //$NON-NLS-1$
+ String currentType = config.getAttribute("type"); //$NON-NLS-1$
+ String shortcut = config.getAttribute("tabgroup"); //$NON-NLS-1$
+ if (currentType != null && shortcut != null
+ && currentType.equals(type)) {
+ try {
+ Object obj = config
+ .createExecutableExtension("tabgroup"); //$NON-NLS-1$
+ if (obj instanceof ProfileLaunchConfigurationTabGroup) {
+ return (ProfileLaunchConfigurationTabGroup) obj;
+ }
+ } catch (CoreException e) {
+ // continue, perhaps another configuration will succeed
+ }
+ }
+ }
+ }
+ return null;
+ }
- /**
- * Get a profiling tab that is associated with the specified id.
- * This looks through extensions of the extension point
- * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code> that have a
- * specific id.
- *
- * @param id A unique identifier
- * @return a tab that implements <code>ProfileLaunchConfigurationTabGroup</code>
- * and provides the necessary profiling type, or <code>null</code> if none could be found.
- * @since 2.0
- */
- public static ProfileLaunchConfigurationTabGroup getTabGroupProviderFromId(
- String id) {
- IConfigurationElement[] configs = getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals("provider")) { //$NON-NLS-1$
- String currentId = config.getAttribute("id"); //$NON-NLS-1$
- String tabgroup = config.getAttribute("tabgroup"); //$NON-NLS-1$
- if (currentId != null && tabgroup != null
- && currentId.equals(id)) {
- try {
- Object obj = config
- .createExecutableExtension("tabgroup"); //$NON-NLS-1$
- if (obj instanceof ProfileLaunchConfigurationTabGroup) {
- return (ProfileLaunchConfigurationTabGroup) obj;
- }
- } catch (CoreException e) {
- // continue, perhaps another configuration will succeed
- }
- }
- }
- }
- return null;
- }
+ /**
+ * Get a profiling tab that is associated with the specified id.
+ * This looks through extensions of the extension point
+ * <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code> that have a
+ * specific id.
+ *
+ * @param id A unique identifier
+ * @return a tab that implements <code>ProfileLaunchConfigurationTabGroup</code>
+ * and provides the necessary profiling type, or <code>null</code> if none could be found.
+ * @since 2.0
+ */
+ public static ProfileLaunchConfigurationTabGroup getTabGroupProviderFromId(
+ String id) {
+ IConfigurationElement[] configs = getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals("provider")) { //$NON-NLS-1$
+ String currentId = config.getAttribute("id"); //$NON-NLS-1$
+ String tabgroup = config.getAttribute("tabgroup"); //$NON-NLS-1$
+ if (currentId != null && tabgroup != null
+ && currentId.equals(id)) {
+ try {
+ Object obj = config
+ .createExecutableExtension("tabgroup"); //$NON-NLS-1$
+ if (obj instanceof ProfileLaunchConfigurationTabGroup) {
+ return (ProfileLaunchConfigurationTabGroup) obj;
+ }
+ } catch (CoreException e) {
+ // continue, perhaps another configuration will succeed
+ }
+ }
+ }
+ }
+ return null;
+ }
- /**
- * Get all IDs of the specific type. This looks through extensions of
- * the extension point <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
- * that have a specific type.
- *
- * @param type A profiling type (eg. memory, snapshot, timing, etc.)
- * @return A <code>String []</code> of all IDs of the specific type.
- * @since 2.0
- */
- public static String[] getProviderIdsForType(String type) {
- ArrayList<String> ret = new ArrayList<> ();
- IConfigurationElement[] configs = getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals("provider")) { //$NON-NLS-1$
- String currentId = config.getAttribute("id"); //$NON-NLS-1$
- String currentType = config.getAttribute("type"); //$NON-NLS-1$
- if (currentType != null && type != null
- && currentType.equals(type)) {
- ret.add(currentId);
- }
- }
- }
- return ret.toArray(new String [] {});
- }
+ /**
+ * Get all IDs of the specific type. This looks through extensions of
+ * the extension point <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
+ * that have a specific type.
+ *
+ * @param type A profiling type (eg. memory, snapshot, timing, etc.)
+ * @return A <code>String []</code> of all IDs of the specific type.
+ * @since 2.0
+ */
+ public static String[] getProviderIdsForType(String type) {
+ ArrayList<String> ret = new ArrayList<> ();
+ IConfigurationElement[] configs = getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals("provider")) { //$NON-NLS-1$
+ String currentId = config.getAttribute("id"); //$NON-NLS-1$
+ String currentType = config.getAttribute("type"); //$NON-NLS-1$
+ if (currentType != null && type != null
+ && currentType.equals(type)) {
+ ret.add(currentId);
+ }
+ }
+ }
+ return ret.toArray(new String [] {});
+ }
- /**
- * Get all the profiling categories. This looks through extensions of
- * the extension point <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
- * and stores the different categories found.
- *
- * @return A <code>String []</code> of all profiling categories.
- * @since 2.0
- */
- public static String[] getProviderCategories() {
- Set<String> ret = new TreeSet<> ();
- IConfigurationElement[] configs = getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals("provider")) { //$NON-NLS-1$
- String currentType = config.getAttribute("type"); //$NON-NLS-1$
- if (currentType != null) {
- ret.add(currentType);
- }
- }
- }
- return ret.toArray(new String [] {});
- }
+ /**
+ * Get all the profiling categories. This looks through extensions of
+ * the extension point <code>org.eclipse.linuxtools.profiling.launch.launchProvider</code>
+ * and stores the different categories found.
+ *
+ * @return A <code>String []</code> of all profiling categories.
+ * @since 2.0
+ */
+ public static String[] getProviderCategories() {
+ Set<String> ret = new TreeSet<> ();
+ IConfigurationElement[] configs = getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals("provider")) { //$NON-NLS-1$
+ String currentType = config.getAttribute("type"); //$NON-NLS-1$
+ if (currentType != null) {
+ ret.add(currentType);
+ }
+ }
+ }
+ return ret.toArray(new String [] {});
+ }
- /**
- * Get a provider id to run for the given profiling type.
- *
- * This first checks for a provider in the project properties if the project
- * can be found and has indicated that project preferences are to override
- * the workspace preferences. If no project is obtainable or the project
- * has not indicated override, then it looks at provider preferences. If these
- * are not set or the specified preference points to a non-installed provider,
- * it will look for the provider with the highest priority for the specified type.
- * If this fails, it will look for the default provider.
- *
- * @param type a profiling type
- * @return a provider id that contributes to the specified type
- * @since 2.0
- */
+ /**
+ * Get a provider id to run for the given profiling type.
+ *
+ * This first checks for a provider in the project properties if the project
+ * can be found and has indicated that project preferences are to override
+ * the workspace preferences. If no project is obtainable or the project
+ * has not indicated override, then it looks at provider preferences. If these
+ * are not set or the specified preference points to a non-installed provider,
+ * it will look for the provider with the highest priority for the specified type.
+ * If this fails, it will look for the default provider.
+ *
+ * @param type a profiling type
+ * @return a provider id that contributes to the specified type
+ * @since 2.0
+ */
- public static String getProviderIdToRun(ILaunchConfigurationWorkingCopy wc, String type) {
- String providerId = null;
- // Look for a project first
- if (wc != null) {
- try {
- IResource[] resources = wc.getMappedResources();
- if(resources != null){
- for (int i = 0; i < resources.length; ++i) {
- IResource resource = resources[i];
- if (resource instanceof IProject) {
- IProject project = (IProject)resource;
- ScopedPreferenceStore store = new ScopedPreferenceStore(new ProjectScope(project),
- ProviderProfileConstants.PLUGIN_ID);
- boolean use_project_settings = store.getBoolean(ProviderProfileConstants.USE_PROJECT_SETTINGS + type);
- if (use_project_settings) {
- String provider = store.getString(ProviderProfileConstants.PREFS_KEY + type);
- if (!provider.isEmpty())
- providerId = provider;
- }
- }
- }
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- // if no providerId specified for project, get one from the preferences
- if (providerId == null) {
- // Look in the preferences for a provider
- providerId = ConfigurationScope.INSTANCE.getNode(
- ProviderProfileConstants.PLUGIN_ID).get(
- ProviderProfileConstants.PREFS_KEY + type, ""); //$NON-NLS-1$
- if (providerId.isEmpty() || getConfigurationDelegateFromId(providerId) == null) {
- // Get highest priority provider
- providerId = getHighestProviderId(type);
- }
- }
- return providerId;
- }
+ public static String getProviderIdToRun(ILaunchConfigurationWorkingCopy wc, String type) {
+ String providerId = null;
+ // Look for a project first
+ if (wc != null) {
+ try {
+ IResource[] resources = wc.getMappedResources();
+ if(resources != null){
+ for (int i = 0; i < resources.length; ++i) {
+ IResource resource = resources[i];
+ if (resource instanceof IProject) {
+ IProject project = (IProject)resource;
+ ScopedPreferenceStore store = new ScopedPreferenceStore(new ProjectScope(project),
+ ProviderProfileConstants.PLUGIN_ID);
+ boolean use_project_settings = store.getBoolean(ProviderProfileConstants.USE_PROJECT_SETTINGS + type);
+ if (use_project_settings) {
+ String provider = store.getString(ProviderProfileConstants.PREFS_KEY + type);
+ if (!provider.isEmpty())
+ providerId = provider;
+ }
+ }
+ }
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ // if no providerId specified for project, get one from the preferences
+ if (providerId == null) {
+ // Look in the preferences for a provider
+ providerId = ConfigurationScope.INSTANCE.getNode(
+ ProviderProfileConstants.PLUGIN_ID).get(
+ ProviderProfileConstants.PREFS_KEY + type, ""); //$NON-NLS-1$
+ if (providerId.isEmpty() || getConfigurationDelegateFromId(providerId) == null) {
+ // Get highest priority provider
+ providerId = getHighestProviderId(type);
+ }
+ }
+ return providerId;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderLaunchConfigurationDelegate.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderLaunchConfigurationDelegate.java
index e5df520970..84b0aad719 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderLaunchConfigurationDelegate.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderLaunchConfigurationDelegate.java
@@ -27,87 +27,87 @@ import org.eclipse.osgi.util.NLS;
public class ProviderLaunchConfigurationDelegate extends AbstractCLaunchDelegate {
- @Override
- public void launch(ILaunchConfiguration config, String mode,
- ILaunch launch, IProgressMonitor monitor) throws CoreException {
+ @Override
+ public void launch(ILaunchConfiguration config, String mode,
+ ILaunch launch, IProgressMonitor monitor) throws CoreException {
- if (config != null) {
- // get provider id from configuration.
- String providerId = config.getAttribute(
- ProviderProfileConstants.PROVIDER_CONFIG_ATT, ""); //$NON-NLS-1$
- String providerToolName = config.getAttribute(
- ProviderProfileConstants.PROVIDER_CONFIG_TOOLNAME_ATT, ""); //$NON-NLS-1$
+ if (config != null) {
+ // get provider id from configuration.
+ String providerId = config.getAttribute(
+ ProviderProfileConstants.PROVIDER_CONFIG_ATT, ""); //$NON-NLS-1$
+ String providerToolName = config.getAttribute(
+ ProviderProfileConstants.PROVIDER_CONFIG_TOOLNAME_ATT, ""); //$NON-NLS-1$
- if (providerId == null || providerId.isEmpty()) {
- String cProjectName = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, ""); //$NON-NLS-1$
- if (cProjectName != null && !cProjectName.isEmpty()) {
- // We have a previously created C/C++ run/debug configuration and now Linux Tools
- // profiling framework has been added. Find a suitable default provider id to use
- // and perform initialization prior to profiling.
- String defaultType = null;
- String[] categories = ProviderFramework.getProviderCategories();
- if (categories.length == 0) {
- infoDialog(Messages.ProviderNoProfilers_title_0, Messages.ProviderNoProfilers_msg_0);
- return;
- }
- for (String category : categories) {
- // Give precedence to timing category if present
- if (category.equals("timing")) { //$NON-NLS-1$
- defaultType = "timing"; //$NON-NLS-1$
- }
- }
- // if default category still not set, take first one found
- if (defaultType == null)
- defaultType = categories[0];
- providerId = ProviderFramework.getProviderIdToRun(null, defaultType);
- ProfileLaunchConfigurationTabGroup tabGroupConfig =
- ProviderFramework.getTabGroupProviderFromId(providerId);
- if (tabGroupConfig == null) {
- infoDialog(Messages.ProviderNoProfilers_title_0, Messages.ProviderNoProfilers_msg_0);
- return;
- }
- AbstractLaunchConfigurationTab[] tabs = tabGroupConfig.getProfileTabs();
+ if (providerId == null || providerId.isEmpty()) {
+ String cProjectName = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, ""); //$NON-NLS-1$
+ if (cProjectName != null && !cProjectName.isEmpty()) {
+ // We have a previously created C/C++ run/debug configuration and now Linux Tools
+ // profiling framework has been added. Find a suitable default provider id to use
+ // and perform initialization prior to profiling.
+ String defaultType = null;
+ String[] categories = ProviderFramework.getProviderCategories();
+ if (categories.length == 0) {
+ infoDialog(Messages.ProviderNoProfilers_title_0, Messages.ProviderNoProfilers_msg_0);
+ return;
+ }
+ for (String category : categories) {
+ // Give precedence to timing category if present
+ if (category.equals("timing")) { //$NON-NLS-1$
+ defaultType = "timing"; //$NON-NLS-1$
+ }
+ }
+ // if default category still not set, take first one found
+ if (defaultType == null)
+ defaultType = categories[0];
+ providerId = ProviderFramework.getProviderIdToRun(null, defaultType);
+ ProfileLaunchConfigurationTabGroup tabGroupConfig =
+ ProviderFramework.getTabGroupProviderFromId(providerId);
+ if (tabGroupConfig == null) {
+ infoDialog(Messages.ProviderNoProfilers_title_0, Messages.ProviderNoProfilers_msg_0);
+ return;
+ }
+ AbstractLaunchConfigurationTab[] tabs = tabGroupConfig.getProfileTabs();
- // Set up defaults according to profiling tabs. We must use a working copy
- // to do this which we save at the end to the original copy.
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- for (ILaunchConfigurationTab tab : tabs) {
- tab.setDefaults(wc);
- }
- config = wc.doSave();
- }
+ // Set up defaults according to profiling tabs. We must use a working copy
+ // to do this which we save at the end to the original copy.
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ for (ILaunchConfigurationTab tab : tabs) {
+ tab.setDefaults(wc);
+ }
+ config = wc.doSave();
+ }
- }
+ }
- // get delegate associated with provider id.
- AbstractCLaunchDelegate delegate = ProviderFramework
- .getConfigurationDelegateFromId(providerId);
+ // get delegate associated with provider id.
+ AbstractCLaunchDelegate delegate = ProviderFramework
+ .getConfigurationDelegateFromId(providerId);
- // launch delegate
- if (delegate != null) {
- delegate.launch(config, mode, launch, monitor);
- } else {
- String message = providerToolName.isEmpty() ?
- NLS.bind(Messages.ProviderProfilerMissing_msg_0, providerId)
- : NLS.bind(Messages.ProviderProfilerMissing_msg_1, providerToolName);
- infoDialog(Messages.ProviderProfilerMissing_title_0, message);
- }
- }
- }
+ // launch delegate
+ if (delegate != null) {
+ delegate.launch(config, mode, launch, monitor);
+ } else {
+ String message = providerToolName.isEmpty() ?
+ NLS.bind(Messages.ProviderProfilerMissing_msg_0, providerId)
+ : NLS.bind(Messages.ProviderProfilerMissing_msg_1, providerToolName);
+ infoDialog(Messages.ProviderProfilerMissing_title_0, message);
+ }
+ }
+ }
- // Display an information dialog to denote there are no profiling plug-ins installed.
- private void infoDialog(final String title, final String message) {
- ProfileLaunchPlugin.getShell().getDisplay().asyncExec( new Runnable() {
- @Override
- public void run() {
- MessageDialog.openInformation(ProfileLaunchPlugin.getShell(), title, message);
- }
- });
- }
+ // Display an information dialog to denote there are no profiling plug-ins installed.
+ private void infoDialog(final String title, final String message) {
+ ProfileLaunchPlugin.getShell().getDisplay().asyncExec( new Runnable() {
+ @Override
+ public void run() {
+ MessageDialog.openInformation(ProfileLaunchPlugin.getShell(), title, message);
+ }
+ });
+ }
- @Override
- protected String getPluginID() {
- return ProviderProfileConstants.PLUGIN_ID;
- }
+ @Override
+ protected String getPluginID() {
+ return ProviderProfileConstants.PLUGIN_ID;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderLaunchShortcut.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderLaunchShortcut.java
index c5bbef619d..2b2242f912 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderLaunchShortcut.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/internal/profiling/launch/provider/launch/ProviderLaunchShortcut.java
@@ -34,271 +34,271 @@ import org.eclipse.swt.widgets.MessageBox;
public class ProviderLaunchShortcut extends ProfileLaunchShortcut implements IExecutableExtension {
- // Profiling type.
- private String type;
-
- // Launch configuration type id.
- private String launchConfigId;
-
- @Override
- public void setInitializationData(IConfigurationElement config,
- String propertyName, Object data) {
- Map<String, String> parameters = (Map<String, String>) data;
- String profilingType = parameters
- .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY);
- String configId = parameters
- .get(ProviderProfileConstants.INIT_DATA_CONFIG_ID_KEY);
-
- if (profilingType == null) {
- profilingType = ""; //$NON-NLS-1$
- }
- if (configId == null) {
- configId = ""; //$NON-NLS-1$
- }
-
- setLaunchConfigID(configId);
- setProfilingType(profilingType);
- }
-
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(getLaunchConfigID());
- }
-
- @Override
- protected ILaunchConfiguration findLaunchConfiguration(IBinary bin, String mode) {
-
- // create a default launch configuration based on the shortcut
- ILaunchConfiguration config = createConfiguration(bin, false);
-
- String providerId = null;
- try {
- providerId = ProviderFramework.getProviderIdToRun(config.getWorkingCopy(), type);
- } catch (CoreException e1) {
- e1.printStackTrace();
- }
-
- // check that there exists a provider for the given profiling type
- if (providerId == null) {
- handleFail(Messages.ProviderLaunchShortcut_0 + " " + type); //$NON-NLS-1$
- return null;
- }
-
- // true if a configuration exists for current project and program
- boolean existsConfigForProject = false;
-
- // true if a configuration exists for current project, program and
- // the default provider
- boolean existsConfigForTool = false;
-
- try {
- String projectName = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
- String programName = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, ""); //$NON-NLS-1$
- ILaunchConfiguration[] configs = getLaunchManager().getLaunchConfigurations(getLaunchConfigType());
-
- for(ILaunchConfiguration currConfig : configs){
- String curProjectName = currConfig.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
- String curProgramName = currConfig.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, ""); //$NON-NLS-1$
-
- // check that current configuration belongs to the current project/program
- if(curProjectName.equals(projectName) && curProgramName.equals(programName)){
- existsConfigForProject = true;
- String curProviderId = currConfig.getAttribute(ProviderProfileConstants.PROVIDER_CONFIG_ATT, ""); //$NON-NLS-1$
-
- // check that current configuration has the same provider as the provider to run.
- if(curProviderId.equals(providerId)){
- existsConfigForTool = true;
- break;
- }
- }
- }
- } catch (CoreException e) {
- // a configuration might be corrupted, skip prompting logic
- // and fall back to default behavior
- existsConfigForProject = true;
- existsConfigForTool = true;
- }
-
- // automatically create a configuration if there are none available for
- // the current project/program
- if (!existsConfigForProject) {
- createConfiguration(bin);
- } else if (!existsConfigForTool) {
- String provider = ProviderFramework
- .getProviderToolNameFromId(providerId);
-
- String profileType = Character.toUpperCase(type.charAt(0))
- + type.substring(1);
-
- // prompt message
- String promptMsg = MessageFormat.format(
- Messages.ProviderLaunchConfigurationPrompt_0,
- (Object[]) new String[] { profileType, provider });
-
- MessageBox prompt = new MessageBox(getActiveWorkbenchShell(),
- SWT.ICON_QUESTION | SWT.YES | SWT.NO);
- prompt.setMessage(promptMsg);
-
- // prompt user for configuration creation
- if (prompt.open() == SWT.YES) {
- return createConfiguration(bin);
- }
- }
- return super.findLaunchConfiguration(bin, mode);
- }
-
- @Override
- protected void setDefaultProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
-
- // acquire a provider id to run.
- final String providerId = ProviderFramework.getProviderIdToRun(wc, getProfilingType());
-
- // get tool name from id.
- final String providerToolName = ProviderFramework.getProviderToolNameFromId(providerId);
-
- // get tab group associated with provider id.
- final ProfileLaunchConfigurationTabGroup tabgroup = ProviderFramework.getTabGroupProviderFromId(providerId);
-
- /**
- * Certain tabs' setDefaults(ILaunchConfigurationWorkingCopy) may
- * require a launch configuration dialog. Eg. CMainTab generates
- * a name for the configuration based on generateName in setDefaults()
- * so we can create a temporary launch configuration dialog here. With
- * the exception of generateName(String), the other methods do not
- * get called.
- */
- ILaunchConfigurationDialog dialog = new ILaunchConfigurationDialog() {
-
- @Override
- public void run(boolean fork, boolean cancelable,
- IRunnableWithProgress runnable) {
- throw new UnsupportedOperationException ();
- }
-
- @Override
- public void updateMessage() {
- throw new UnsupportedOperationException ();
- }
-
- @Override
- public void updateButtons() {
- throw new UnsupportedOperationException ();
- }
-
- @Override
- public void setName(String name) {
- throw new UnsupportedOperationException ();
- }
-
- @Override
- public void setActiveTab(int index) {
- throw new UnsupportedOperationException ();
- }
-
- @Override
- public void setActiveTab(ILaunchConfigurationTab tab) {
- throw new UnsupportedOperationException ();
- }
-
- @Override
- public ILaunchConfigurationTab[] getTabs() {
- return null;
- }
-
- @Override
- public String getMode() {
- return null;
- }
-
- @Override
- public ILaunchConfigurationTab getActiveTab() {
- return null;
- }
-
- @Override
- public String generateName(String name) {
- if (name == null) {
- name = ""; //$NON-NLS-1$
- }
- String providerConfigutationName = generateProviderConfigurationName(name, providerToolName);
- return getLaunchManager().generateLaunchConfigurationName(providerConfigutationName);
- }
- };
-
- tabgroup.createTabs(dialog , "profile"); //$NON-NLS-1$
-
- // set configuration to match default attributes for all tabs.
- for (ILaunchConfigurationTab tab : tabgroup.getTabs()) {
- tab.setLaunchConfigurationDialog(dialog);
- tab.setDefaults(wc);
- }
-
- // get configuration shortcut associated with provider id.
- ProfileLaunchShortcut shortcut= ProviderFramework.getLaunchShortcutProviderFromId(providerId);
- // set attributes related to the specific profiling shortcut configuration.
- shortcut.setDefaultProfileLaunchShortcutAttributes(wc);
-
- wc.setAttribute(ProviderProfileConstants.PROVIDER_CONFIG_ATT,
- providerId);
-
- // set tool name in configuration.
- wc.setAttribute(ProviderProfileConstants.PROVIDER_CONFIG_TOOLNAME_ATT, providerToolName);
-
- /**
- * To avoid renaming an already renamed launch configuration, we can
- * check the expected format of the name using regular expressions and
- * skip on matches.
- */
- String curConfigName = wc.getName();
- Pattern configNamePattern = Pattern.compile(".+\\s\\[.+\\](\\s\\(\\d+\\))?$"); //$NON-NLS-1$
- Matcher match = configNamePattern.matcher(curConfigName);
- if (!match.find()) {
- wc.rename(dialog.generateName(curConfigName));
- }
- }
-
- /**
- * Get name of profiling type that used for this tab.
- *
- * @param profilingType The type of profiling.
- */
- private void setProfilingType(String profilingType) {
- type = profilingType;
- }
- /**
- * Set launch configuration type id.
- *
- * @param configId String configuration type id.
- */
- private void setLaunchConfigID(String configId) {
- launchConfigId = configId;
- }
-
- /**
- * Get profiling type of this plug-in.
- *
- * @return String profiling type this plug-in supports.
- */
- private String getLaunchConfigID() {
- return launchConfigId;
- }
-
- public String getProfilingType() {
- return type;
- }
-
- /**
- * Generate a string that can be used as a name for a provider launch configuration.
- * It combines <code>configName</code> and <code>toolName</code> into a String of
- * consistent format: <configuration name> [<tool name>].
- *
- * @param configName
- * @param toolName
- * @return String tool name appended to original configuration name.
- * @since 1.2
- */
- public static String generateProviderConfigurationName(String configName, String toolName){
- return configName + " " + "[" + toolName + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
+ // Profiling type.
+ private String type;
+
+ // Launch configuration type id.
+ private String launchConfigId;
+
+ @Override
+ public void setInitializationData(IConfigurationElement config,
+ String propertyName, Object data) {
+ Map<String, String> parameters = (Map<String, String>) data;
+ String profilingType = parameters
+ .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY);
+ String configId = parameters
+ .get(ProviderProfileConstants.INIT_DATA_CONFIG_ID_KEY);
+
+ if (profilingType == null) {
+ profilingType = ""; //$NON-NLS-1$
+ }
+ if (configId == null) {
+ configId = ""; //$NON-NLS-1$
+ }
+
+ setLaunchConfigID(configId);
+ setProfilingType(profilingType);
+ }
+
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(getLaunchConfigID());
+ }
+
+ @Override
+ protected ILaunchConfiguration findLaunchConfiguration(IBinary bin, String mode) {
+
+ // create a default launch configuration based on the shortcut
+ ILaunchConfiguration config = createConfiguration(bin, false);
+
+ String providerId = null;
+ try {
+ providerId = ProviderFramework.getProviderIdToRun(config.getWorkingCopy(), type);
+ } catch (CoreException e1) {
+ e1.printStackTrace();
+ }
+
+ // check that there exists a provider for the given profiling type
+ if (providerId == null) {
+ handleFail(Messages.ProviderLaunchShortcut_0 + " " + type); //$NON-NLS-1$
+ return null;
+ }
+
+ // true if a configuration exists for current project and program
+ boolean existsConfigForProject = false;
+
+ // true if a configuration exists for current project, program and
+ // the default provider
+ boolean existsConfigForTool = false;
+
+ try {
+ String projectName = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
+ String programName = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, ""); //$NON-NLS-1$
+ ILaunchConfiguration[] configs = getLaunchManager().getLaunchConfigurations(getLaunchConfigType());
+
+ for(ILaunchConfiguration currConfig : configs){
+ String curProjectName = currConfig.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
+ String curProgramName = currConfig.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, ""); //$NON-NLS-1$
+
+ // check that current configuration belongs to the current project/program
+ if(curProjectName.equals(projectName) && curProgramName.equals(programName)){
+ existsConfigForProject = true;
+ String curProviderId = currConfig.getAttribute(ProviderProfileConstants.PROVIDER_CONFIG_ATT, ""); //$NON-NLS-1$
+
+ // check that current configuration has the same provider as the provider to run.
+ if(curProviderId.equals(providerId)){
+ existsConfigForTool = true;
+ break;
+ }
+ }
+ }
+ } catch (CoreException e) {
+ // a configuration might be corrupted, skip prompting logic
+ // and fall back to default behavior
+ existsConfigForProject = true;
+ existsConfigForTool = true;
+ }
+
+ // automatically create a configuration if there are none available for
+ // the current project/program
+ if (!existsConfigForProject) {
+ createConfiguration(bin);
+ } else if (!existsConfigForTool) {
+ String provider = ProviderFramework
+ .getProviderToolNameFromId(providerId);
+
+ String profileType = Character.toUpperCase(type.charAt(0))
+ + type.substring(1);
+
+ // prompt message
+ String promptMsg = MessageFormat.format(
+ Messages.ProviderLaunchConfigurationPrompt_0,
+ (Object[]) new String[] { profileType, provider });
+
+ MessageBox prompt = new MessageBox(getActiveWorkbenchShell(),
+ SWT.ICON_QUESTION | SWT.YES | SWT.NO);
+ prompt.setMessage(promptMsg);
+
+ // prompt user for configuration creation
+ if (prompt.open() == SWT.YES) {
+ return createConfiguration(bin);
+ }
+ }
+ return super.findLaunchConfiguration(bin, mode);
+ }
+
+ @Override
+ protected void setDefaultProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+
+ // acquire a provider id to run.
+ final String providerId = ProviderFramework.getProviderIdToRun(wc, getProfilingType());
+
+ // get tool name from id.
+ final String providerToolName = ProviderFramework.getProviderToolNameFromId(providerId);
+
+ // get tab group associated with provider id.
+ final ProfileLaunchConfigurationTabGroup tabgroup = ProviderFramework.getTabGroupProviderFromId(providerId);
+
+ /**
+ * Certain tabs' setDefaults(ILaunchConfigurationWorkingCopy) may
+ * require a launch configuration dialog. Eg. CMainTab generates
+ * a name for the configuration based on generateName in setDefaults()
+ * so we can create a temporary launch configuration dialog here. With
+ * the exception of generateName(String), the other methods do not
+ * get called.
+ */
+ ILaunchConfigurationDialog dialog = new ILaunchConfigurationDialog() {
+
+ @Override
+ public void run(boolean fork, boolean cancelable,
+ IRunnableWithProgress runnable) {
+ throw new UnsupportedOperationException ();
+ }
+
+ @Override
+ public void updateMessage() {
+ throw new UnsupportedOperationException ();
+ }
+
+ @Override
+ public void updateButtons() {
+ throw new UnsupportedOperationException ();
+ }
+
+ @Override
+ public void setName(String name) {
+ throw new UnsupportedOperationException ();
+ }
+
+ @Override
+ public void setActiveTab(int index) {
+ throw new UnsupportedOperationException ();
+ }
+
+ @Override
+ public void setActiveTab(ILaunchConfigurationTab tab) {
+ throw new UnsupportedOperationException ();
+ }
+
+ @Override
+ public ILaunchConfigurationTab[] getTabs() {
+ return null;
+ }
+
+ @Override
+ public String getMode() {
+ return null;
+ }
+
+ @Override
+ public ILaunchConfigurationTab getActiveTab() {
+ return null;
+ }
+
+ @Override
+ public String generateName(String name) {
+ if (name == null) {
+ name = ""; //$NON-NLS-1$
+ }
+ String providerConfigutationName = generateProviderConfigurationName(name, providerToolName);
+ return getLaunchManager().generateLaunchConfigurationName(providerConfigutationName);
+ }
+ };
+
+ tabgroup.createTabs(dialog , "profile"); //$NON-NLS-1$
+
+ // set configuration to match default attributes for all tabs.
+ for (ILaunchConfigurationTab tab : tabgroup.getTabs()) {
+ tab.setLaunchConfigurationDialog(dialog);
+ tab.setDefaults(wc);
+ }
+
+ // get configuration shortcut associated with provider id.
+ ProfileLaunchShortcut shortcut= ProviderFramework.getLaunchShortcutProviderFromId(providerId);
+ // set attributes related to the specific profiling shortcut configuration.
+ shortcut.setDefaultProfileLaunchShortcutAttributes(wc);
+
+ wc.setAttribute(ProviderProfileConstants.PROVIDER_CONFIG_ATT,
+ providerId);
+
+ // set tool name in configuration.
+ wc.setAttribute(ProviderProfileConstants.PROVIDER_CONFIG_TOOLNAME_ATT, providerToolName);
+
+ /**
+ * To avoid renaming an already renamed launch configuration, we can
+ * check the expected format of the name using regular expressions and
+ * skip on matches.
+ */
+ String curConfigName = wc.getName();
+ Pattern configNamePattern = Pattern.compile(".+\\s\\[.+\\](\\s\\(\\d+\\))?$"); //$NON-NLS-1$
+ Matcher match = configNamePattern.matcher(curConfigName);
+ if (!match.find()) {
+ wc.rename(dialog.generateName(curConfigName));
+ }
+ }
+
+ /**
+ * Get name of profiling type that used for this tab.
+ *
+ * @param profilingType The type of profiling.
+ */
+ private void setProfilingType(String profilingType) {
+ type = profilingType;
+ }
+ /**
+ * Set launch configuration type id.
+ *
+ * @param configId String configuration type id.
+ */
+ private void setLaunchConfigID(String configId) {
+ launchConfigId = configId;
+ }
+
+ /**
+ * Get profiling type of this plug-in.
+ *
+ * @return String profiling type this plug-in supports.
+ */
+ private String getLaunchConfigID() {
+ return launchConfigId;
+ }
+
+ public String getProfilingType() {
+ return type;
+ }
+
+ /**
+ * Generate a string that can be used as a name for a provider launch configuration.
+ * It combines <code>configName</code> and <code>toolName</code> into a String of
+ * consistent format: <configuration name> [<tool name>].
+ *
+ * @param configName
+ * @param toolName
+ * @return String tool name appended to original configuration name.
+ * @since 1.2
+ */
+ public static String generateProviderConfigurationName(String configName, String toolName){
+ return configName + " " + "[" + toolName + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ConfigUtils.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ConfigUtils.java
index 264c62aff7..8df78b6cef 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ConfigUtils.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ConfigUtils.java
@@ -14,102 +14,102 @@ import org.eclipse.debug.core.ILaunchConfiguration;
*/
public class ConfigUtils {
- private final static String EMPTY_STRING = ""; //$NON-NLS-1$
-
- private ILaunchConfiguration config;
-
- public ConfigUtils(ILaunchConfiguration config) {
- this.config = config;
- }
-
- /**
- * Get if the executable shall be copied to remote target before launch.
- *
- * @return To copy executable or not.
- * @throws CoreException
- */
- public boolean getCopyExecutable() throws CoreException {
- return config.getAttribute(
- RemoteProxyCMainTab.ATTR_ENABLE_COPY_FROM_EXE, false);
- }
-
- /**
- * Get the absolute path of the executable to copy from. If the executable is
- * on a remote machine, this is the path to the executable on that machine.
- * @return The path to the executable.
- *
- * @throws CoreException
- */
- public String getCopyFromExecutablePath()
- throws CoreException {
- return config.getAttribute(
- RemoteProxyCMainTab.ATTR_COPY_FROM_EXE_NAME, EMPTY_STRING);
- }
-
- /**
- * Get the absolute path of the executable to launch. If the executable is
- * on a remote machine, this is the path to the executable on that machine.
- * @return The path to the executable to launch.
- *
- * @throws CoreException
- */
- public String getExecutablePath()
- throws CoreException {
- return config.getAttribute(
- ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, EMPTY_STRING);
- }
-
- /**
- * Get the working directory path for the application launch
- *
- * @return The working directory.
- * @throws CoreException
- * @since 5.0
- */
- public String getWorkingDirectory() throws CoreException {
- String workingDirectory = config.getAttribute(
- RemoteProxyCMainTab.ATTR_REMOTE_WORKING_DIRECTORY_NAME, EMPTY_STRING);
- if (workingDirectory.length() == 0)
- return null;
- URI workingDirectoryURI;
- try {
- workingDirectoryURI = new URI(workingDirectory);
- } catch (URISyntaxException e) {
- // Just treat it as unusable.
- return null;
- }
- return workingDirectoryURI.getPath();
- }
-
- /**
- * Get the IProject object from the project name.
- *
- * @param project
- * name of the project
- * @return IProject resource
- */
- public static IProject getProject(String project) {
- return ResourcesPlugin.getWorkspace().getRoot().getProject(project);
- }
-
- public IProject getProject() throws CoreException {
+ private final static String EMPTY_STRING = ""; //$NON-NLS-1$
+
+ private ILaunchConfiguration config;
+
+ public ConfigUtils(ILaunchConfiguration config) {
+ this.config = config;
+ }
+
+ /**
+ * Get if the executable shall be copied to remote target before launch.
+ *
+ * @return To copy executable or not.
+ * @throws CoreException
+ */
+ public boolean getCopyExecutable() throws CoreException {
+ return config.getAttribute(
+ RemoteProxyCMainTab.ATTR_ENABLE_COPY_FROM_EXE, false);
+ }
+
+ /**
+ * Get the absolute path of the executable to copy from. If the executable is
+ * on a remote machine, this is the path to the executable on that machine.
+ * @return The path to the executable.
+ *
+ * @throws CoreException
+ */
+ public String getCopyFromExecutablePath()
+ throws CoreException {
+ return config.getAttribute(
+ RemoteProxyCMainTab.ATTR_COPY_FROM_EXE_NAME, EMPTY_STRING);
+ }
+
+ /**
+ * Get the absolute path of the executable to launch. If the executable is
+ * on a remote machine, this is the path to the executable on that machine.
+ * @return The path to the executable to launch.
+ *
+ * @throws CoreException
+ */
+ public String getExecutablePath()
+ throws CoreException {
+ return config.getAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, EMPTY_STRING);
+ }
+
+ /**
+ * Get the working directory path for the application launch
+ *
+ * @return The working directory.
+ * @throws CoreException
+ * @since 5.0
+ */
+ public String getWorkingDirectory() throws CoreException {
+ String workingDirectory = config.getAttribute(
+ RemoteProxyCMainTab.ATTR_REMOTE_WORKING_DIRECTORY_NAME, EMPTY_STRING);
+ if (workingDirectory.length() == 0)
+ return null;
+ URI workingDirectoryURI;
+ try {
+ workingDirectoryURI = new URI(workingDirectory);
+ } catch (URISyntaxException e) {
+ // Just treat it as unusable.
+ return null;
+ }
+ return workingDirectoryURI.getPath();
+ }
+
+ /**
+ * Get the IProject object from the project name.
+ *
+ * @param project
+ * name of the project
+ * @return IProject resource
+ */
+ public static IProject getProject(String project) {
+ return ResourcesPlugin.getWorkspace().getRoot().getProject(project);
+ }
+
+ public IProject getProject() throws CoreException {
return getProject(getProjectName());
}
- /**
- * Get the name of the project
- *
- * @return The name of the project.
- * @throws CoreException
- */
- public String getProjectName() throws CoreException {
- return getProjectName(config);
- }
-
- public static String getProjectName(ILaunchConfiguration configuration)
- throws CoreException {
- return configuration.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String) null);
- }
+ /**
+ * Get the name of the project
+ *
+ * @return The name of the project.
+ * @throws CoreException
+ */
+ public String getProjectName() throws CoreException {
+ return getProjectName(config);
+ }
+
+ public static String getProjectName(ILaunchConfiguration configuration)
+ throws CoreException {
+ return configuration.getAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String) null);
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteCommandLauncher.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteCommandLauncher.java
index c30e3b6ed1..b92a62686e 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteCommandLauncher.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteCommandLauncher.java
@@ -18,17 +18,17 @@ import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
public interface IRemoteCommandLauncher {
-
- int OK = 0;
- int COMMAND_CANCELED = 1;
- int ILLEGAL_COMMAND = -1;
-
- Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, IProgressMonitor monitor) throws CoreException;
- /**
- * @since 3.0
- */
- Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, IProgressMonitor monitor, PTY pty) throws CoreException;
- int waitAndRead(OutputStream output, OutputStream err, IProgressMonitor monitor);
- String getErrorMessage();
-
+
+ int OK = 0;
+ int COMMAND_CANCELED = 1;
+ int ILLEGAL_COMMAND = -1;
+
+ Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, IProgressMonitor monitor) throws CoreException;
+ /**
+ * @since 3.0
+ */
+ Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, IProgressMonitor monitor, PTY pty) throws CoreException;
+ int waitAndRead(OutputStream output, OutputStream err, IProgressMonitor monitor);
+ String getErrorMessage();
+
} \ No newline at end of file
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteFileProxy.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteFileProxy.java
index 7ecedeb990..fe842b6ba6 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteFileProxy.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteFileProxy.java
@@ -17,15 +17,15 @@ import org.eclipse.core.runtime.IPath;
public interface IRemoteFileProxy {
- URI toURI(IPath path);
- URI toURI(String path);
- String toPath(URI uri);
- String getDirectorySeparator();
- IFileStore getResource(String path);
- /**
- * @return Returns the working directory.
- * @since 2.0
- */
- URI getWorkingDir();
+ URI toURI(IPath path);
+ URI toURI(String path);
+ String toPath(URI uri);
+ String getDirectorySeparator();
+ IFileStore getResource(String path);
+ /**
+ * @return Returns the working directory.
+ * @since 2.0
+ */
+ URI getWorkingDir();
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteProxyManager.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteProxyManager.java
index 3e7dd4a27f..abd23f59b8 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteProxyManager.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/IRemoteProxyManager.java
@@ -16,13 +16,13 @@ import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
public interface IRemoteProxyManager {
- String EXTENSION_POINT_ID = "RemoteProxyManager"; //$NON-NLS-1$
- String MANAGER_NAME = "manager"; //$NON-NLS-1$
- String SCHEME_ID = "scheme"; //$NON-NLS-1$
- IRemoteFileProxy getFileProxy(IProject project) throws CoreException;
- IRemoteFileProxy getFileProxy(URI uri) throws CoreException;
- IRemoteCommandLauncher getLauncher(IProject project) throws CoreException;
- IRemoteCommandLauncher getLauncher(URI uri) throws CoreException;
- String getOS(IProject project) throws CoreException;
- String getOS(URI uri) throws CoreException;
+ String EXTENSION_POINT_ID = "RemoteProxyManager"; //$NON-NLS-1$
+ String MANAGER_NAME = "manager"; //$NON-NLS-1$
+ String SCHEME_ID = "scheme"; //$NON-NLS-1$
+ IRemoteFileProxy getFileProxy(IProject project) throws CoreException;
+ IRemoteFileProxy getFileProxy(URI uri) throws CoreException;
+ IRemoteCommandLauncher getLauncher(IProject project) throws CoreException;
+ IRemoteCommandLauncher getLauncher(URI uri) throws CoreException;
+ String getOS(IProject project) throws CoreException;
+ String getOS(URI uri) throws CoreException;
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/PlaceHolderLaunchConfigurationTabGroup.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/PlaceHolderLaunchConfigurationTabGroup.java
index 4c08a5c253..1efa5cc8ab 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/PlaceHolderLaunchConfigurationTabGroup.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/PlaceHolderLaunchConfigurationTabGroup.java
@@ -26,8 +26,8 @@ public class PlaceHolderLaunchConfigurationTabGroup extends AbstractLaunchConfig
/* (non-Javadoc)
* @see org.eclipse.debug.ui.ILaunchConfigurationTabGroup#createTabs(org.eclipse.debug.ui.ILaunchConfigurationDialog, java.lang.String)
*/
- @Override
- public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
+ @Override
+ public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
setTabs(new ILaunchConfigurationTab[0]);
}
} \ No newline at end of file
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchConfigurationTabGroup.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchConfigurationTabGroup.java
index c0be60b72f..923109012f 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchConfigurationTabGroup.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchConfigurationTabGroup.java
@@ -24,21 +24,21 @@ import org.eclipse.debug.ui.sourcelookup.SourceLookupTab;
public abstract class ProfileLaunchConfigurationTabGroup extends AbstractLaunchConfigurationTabGroup {
- @Override
- public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
- ArrayList<AbstractLaunchConfigurationTab> tabs = new ArrayList<>();
- tabs.add(new CMainTab());
- tabs.add(new CArgumentsTab());
+ @Override
+ public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
+ ArrayList<AbstractLaunchConfigurationTab> tabs = new ArrayList<>();
+ tabs.add(new CMainTab());
+ tabs.add(new CArgumentsTab());
- tabs.addAll(Arrays.asList(getProfileTabs()));
+ tabs.addAll(Arrays.asList(getProfileTabs()));
- tabs.add(new EnvironmentTab());
- tabs.add(new SourceLookupTab());
- tabs.add(new CommonTab());
+ tabs.add(new EnvironmentTab());
+ tabs.add(new SourceLookupTab());
+ tabs.add(new CommonTab());
- setTabs(tabs.toArray(new AbstractLaunchConfigurationTab[tabs.size()]));
- }
+ setTabs(tabs.toArray(new AbstractLaunchConfigurationTab[tabs.size()]));
+ }
- public abstract AbstractLaunchConfigurationTab[] getProfileTabs();
+ public abstract AbstractLaunchConfigurationTab[] getProfileTabs();
} \ No newline at end of file
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchShortcut.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchShortcut.java
index 12a2f760f9..b15e277c7f 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchShortcut.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchShortcut.java
@@ -54,287 +54,287 @@ import org.eclipse.ui.dialogs.TwoPaneElementSelector;
public abstract class ProfileLaunchShortcut implements ILaunchShortcut {
- @Override
- public void launch(IEditorPart editor, String mode) {
- searchAndLaunch(new Object[] { editor.getEditorInput() }, mode);
- }
+ @Override
+ public void launch(IEditorPart editor, String mode) {
+ searchAndLaunch(new Object[] { editor.getEditorInput() }, mode);
+ }
- @Override
- public void launch(ISelection selection, String mode) {
- if (selection instanceof IStructuredSelection) {
- searchAndLaunch(((IStructuredSelection) selection).toArray(), mode);
- }
- }
+ @Override
+ public void launch(ISelection selection, String mode) {
+ if (selection instanceof IStructuredSelection) {
+ searchAndLaunch(((IStructuredSelection) selection).toArray(), mode);
+ }
+ }
- public void launch(IBinary bin, String mode) {
- ILaunchConfiguration config = findLaunchConfiguration(bin, mode);
- if (config != null) {
- DebugUITools.launch(config, mode);
- }
- }
+ public void launch(IBinary bin, String mode) {
+ ILaunchConfiguration config = findLaunchConfiguration(bin, mode);
+ if (config != null) {
+ DebugUITools.launch(config, mode);
+ }
+ }
- /**
- * Locate a configuration to relaunch for the given type. If one cannot be found, create one.
- *
- * @return a re-useable config or <code>null</code> if none
- */
- protected ILaunchConfiguration findLaunchConfiguration(IBinary bin, String mode) {
- ILaunchConfiguration configuration = null;
- ILaunchConfigurationType configType = getLaunchConfigType();
- List<ILaunchConfiguration> candidateConfigs = Collections.emptyList();
- try {
- ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(configType);
- candidateConfigs = new ArrayList<>(configs.length);
- for (int i = 0; i < configs.length; i++) {
- ILaunchConfiguration config = configs[i];
- IPath programPath = CDebugUtils.getProgramPath(config);
- String projectName = CDebugUtils.getProjectName(config);
- IPath binPath = bin.getResource().getProjectRelativePath();
- if (programPath != null && programPath.equals(binPath)) {
- if (projectName != null && projectName.equals(bin.getCProject().getProject().getName())) {
- candidateConfigs.add(config);
- }
- }
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
+ /**
+ * Locate a configuration to relaunch for the given type. If one cannot be found, create one.
+ *
+ * @return a re-useable config or <code>null</code> if none
+ */
+ protected ILaunchConfiguration findLaunchConfiguration(IBinary bin, String mode) {
+ ILaunchConfiguration configuration = null;
+ ILaunchConfigurationType configType = getLaunchConfigType();
+ List<ILaunchConfiguration> candidateConfigs = Collections.emptyList();
+ try {
+ ILaunchConfiguration[] configs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations(configType);
+ candidateConfigs = new ArrayList<>(configs.length);
+ for (int i = 0; i < configs.length; i++) {
+ ILaunchConfiguration config = configs[i];
+ IPath programPath = CDebugUtils.getProgramPath(config);
+ String projectName = CDebugUtils.getProjectName(config);
+ IPath binPath = bin.getResource().getProjectRelativePath();
+ if (programPath != null && programPath.equals(binPath)) {
+ if (projectName != null && projectName.equals(bin.getCProject().getProject().getName())) {
+ candidateConfigs.add(config);
+ }
+ }
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
- // If there are no existing configs associated with the IBinary, create one.
- // If there is exactly one config associated with the IBinary, return it.
- // Otherwise, if there is more than one config associated with the IBinary, prompt the
- // user to choose one.
- int candidateCount = candidateConfigs.size();
- if (candidateCount < 1) {
- configuration = createConfiguration(bin);
- } else if (candidateCount == 1) {
- configuration = candidateConfigs.get(0);
- } else {
- // Prompt the user to choose a config. A null result means the user
- // cancelled the dialog, in which case this method returns null,
- // since cancelling the dialog should also cancel launching anything.
- configuration = chooseConfiguration(candidateConfigs, mode);
- }
- return configuration;
- }
+ // If there are no existing configs associated with the IBinary, create one.
+ // If there is exactly one config associated with the IBinary, return it.
+ // Otherwise, if there is more than one config associated with the IBinary, prompt the
+ // user to choose one.
+ int candidateCount = candidateConfigs.size();
+ if (candidateCount < 1) {
+ configuration = createConfiguration(bin);
+ } else if (candidateCount == 1) {
+ configuration = candidateConfigs.get(0);
+ } else {
+ // Prompt the user to choose a config. A null result means the user
+ // cancelled the dialog, in which case this method returns null,
+ // since cancelling the dialog should also cancel launching anything.
+ configuration = chooseConfiguration(candidateConfigs, mode);
+ }
+ return configuration;
+ }
- /**
- * Can return <code>getLaunchManager().getLaunchConfigurationType(String ID)</code>.
- * This String will be used to identify your configuration type to Eclipse, and should
- * be unique.
- *
- * @return The launch configuration type.
- */
- protected abstract ILaunchConfigurationType getLaunchConfigType();
+ /**
+ * Can return <code>getLaunchManager().getLaunchConfigurationType(String ID)</code>.
+ * This String will be used to identify your configuration type to Eclipse, and should
+ * be unique.
+ *
+ * @return The launch configuration type.
+ */
+ protected abstract ILaunchConfigurationType getLaunchConfigType();
- protected abstract void setDefaultProfileAttributes(ILaunchConfigurationWorkingCopy wc) throws CoreException;
+ protected abstract void setDefaultProfileAttributes(ILaunchConfigurationWorkingCopy wc) throws CoreException;
- /**
- * Set default attributes for the given configuration.
- *
- * @param wc
- * @since 1.2
- */
- public void setDefaultProfileLaunchShortcutAttributes(ILaunchConfigurationWorkingCopy wc){
- try {
- setDefaultProfileAttributes(wc);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
+ /**
+ * Set default attributes for the given configuration.
+ *
+ * @param wc
+ * @since 1.2
+ */
+ public void setDefaultProfileLaunchShortcutAttributes(ILaunchConfigurationWorkingCopy wc){
+ try {
+ setDefaultProfileAttributes(wc);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
- protected ILaunchConfiguration createConfiguration(IBinary bin) {
- return createConfiguration(bin, true);
- }
+ protected ILaunchConfiguration createConfiguration(IBinary bin) {
+ return createConfiguration(bin, true);
+ }
- /**
- * Create a launch configuration based on a binary, and optionally
- * save it to the underlying resource.
- *
- * @param bin a representation of a binary
- * @param save true if the configuration should be saved to the
- * underlying resource, and false if it should not be saved.
- * @return a launch configuration generated for the binary.
- * @since 1.2
- */
- protected ILaunchConfiguration createConfiguration(IBinary bin, boolean save) {
- ILaunchConfiguration config = null;
- try {
- String projectName = bin.getResource().getProjectRelativePath().toString();
- ILaunchConfigurationType configType = getLaunchConfigType();
- ILaunchConfigurationWorkingCopy wc = configType.newInstance(null, getLaunchManager().generateLaunchConfigurationName(bin.getElementName()));
+ /**
+ * Create a launch configuration based on a binary, and optionally
+ * save it to the underlying resource.
+ *
+ * @param bin a representation of a binary
+ * @param save true if the configuration should be saved to the
+ * underlying resource, and false if it should not be saved.
+ * @return a launch configuration generated for the binary.
+ * @since 1.2
+ */
+ protected ILaunchConfiguration createConfiguration(IBinary bin, boolean save) {
+ ILaunchConfiguration config = null;
+ try {
+ String projectName = bin.getResource().getProjectRelativePath().toString();
+ ILaunchConfigurationType configType = getLaunchConfigType();
+ ILaunchConfigurationWorkingCopy wc = configType.newInstance(null, getLaunchManager().generateLaunchConfigurationName(bin.getElementName()));
- wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, projectName);
- wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, bin.getCProject().getElementName());
- wc.setMappedResources(new IResource[] {bin.getResource(), bin.getResource().getProject()});
- wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, (String) null);
+ wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, projectName);
+ wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, bin.getCProject().getElementName());
+ wc.setMappedResources(new IResource[] {bin.getResource(), bin.getResource().getProject()});
+ wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, (String) null);
- setDefaultProfileAttributes(wc);
+ setDefaultProfileAttributes(wc);
- if (save){
- config = wc.doSave();
- } else {
- config = wc;
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- return config;
- }
+ if (save){
+ config = wc.doSave();
+ } else {
+ config = wc;
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ return config;
+ }
- protected ILaunchManager getLaunchManager() {
- return DebugPlugin.getDefault().getLaunchManager();
- }
+ protected ILaunchManager getLaunchManager() {
+ return DebugPlugin.getDefault().getLaunchManager();
+ }
- /**
- * Method searchAndLaunch.
- * @param objects
- * @param mode
- */
- private void searchAndLaunch(final Object[] elements, String mode) {
- if (elements != null && elements.length > 0) {
- IBinary bin = null;
- if (elements.length == 1 && elements[0] instanceof IBinary) {
- bin = (IBinary) elements[0];
- } else {
- final List<IBinary> results = new ArrayList<>();
- ProgressMonitorDialog dialog = new ProgressMonitorDialog(getActiveWorkbenchShell());
- IRunnableWithProgress runnable = new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor pm) throws InterruptedException {
- int nElements = elements.length;
- pm.beginTask(Messages.ProfileLaunchShortcut_Looking_for_executables, nElements);
- try {
- IProgressMonitor sub = new SubProgressMonitor(pm, 1);
- for (int i = 0; i < nElements; i++) {
- if (elements[i] instanceof IAdaptable) {
- IResource r = (IResource) ((IAdaptable) elements[i]).getAdapter(IResource.class);
- if (r != null) {
- ICProject cproject = CoreModel.getDefault().create(r.getProject());
- if (cproject != null) {
- try {
- IBinary[] bins = cproject.getBinaryContainer().getBinaries();
+ /**
+ * Method searchAndLaunch.
+ * @param objects
+ * @param mode
+ */
+ private void searchAndLaunch(final Object[] elements, String mode) {
+ if (elements != null && elements.length > 0) {
+ IBinary bin = null;
+ if (elements.length == 1 && elements[0] instanceof IBinary) {
+ bin = (IBinary) elements[0];
+ } else {
+ final List<IBinary> results = new ArrayList<>();
+ ProgressMonitorDialog dialog = new ProgressMonitorDialog(getActiveWorkbenchShell());
+ IRunnableWithProgress runnable = new IRunnableWithProgress() {
+ @Override
+ public void run(IProgressMonitor pm) throws InterruptedException {
+ int nElements = elements.length;
+ pm.beginTask(Messages.ProfileLaunchShortcut_Looking_for_executables, nElements);
+ try {
+ IProgressMonitor sub = new SubProgressMonitor(pm, 1);
+ for (int i = 0; i < nElements; i++) {
+ if (elements[i] instanceof IAdaptable) {
+ IResource r = (IResource) ((IAdaptable) elements[i]).getAdapter(IResource.class);
+ if (r != null) {
+ ICProject cproject = CoreModel.getDefault().create(r.getProject());
+ if (cproject != null) {
+ try {
+ IBinary[] bins = cproject.getBinaryContainer().getBinaries();
- for (int j = 0; j < bins.length; j++) {
- if (bins[j].isExecutable()) {
- results.add(bins[j]);
- }
- }
- } catch (CModelException e) {
- // TODO should this be simply ignored ?
- }
- }
- }
- }
- if (pm.isCanceled()) {
- throw new InterruptedException();
- }
- sub.done();
- }
- } finally {
- pm.done();
- }
- }
- };
- try {
- dialog.run(true, true, runnable);
- } catch (InterruptedException e) {
- return;
- } catch (InvocationTargetException e) {
- handleFail(e.getMessage());
- return;
- }
- int count = results.size();
- if (count == 0) {
- handleFail(Messages.ProfileLaunchShortcut_Binary_not_found);
- } else if (count > 1) {
- bin = chooseBinary(results, mode);
- } else {
- bin = results.get(0);
- }
- }
- if (bin != null) {
- launch(bin, mode);
- }
- } else {
- handleFail(Messages.ProfileLaunchShortcut_no_project_selected);
- }
- }
+ for (int j = 0; j < bins.length; j++) {
+ if (bins[j].isExecutable()) {
+ results.add(bins[j]);
+ }
+ }
+ } catch (CModelException e) {
+ // TODO should this be simply ignored ?
+ }
+ }
+ }
+ }
+ if (pm.isCanceled()) {
+ throw new InterruptedException();
+ }
+ sub.done();
+ }
+ } finally {
+ pm.done();
+ }
+ }
+ };
+ try {
+ dialog.run(true, true, runnable);
+ } catch (InterruptedException e) {
+ return;
+ } catch (InvocationTargetException e) {
+ handleFail(e.getMessage());
+ return;
+ }
+ int count = results.size();
+ if (count == 0) {
+ handleFail(Messages.ProfileLaunchShortcut_Binary_not_found);
+ } else if (count > 1) {
+ bin = chooseBinary(results, mode);
+ } else {
+ bin = results.get(0);
+ }
+ }
+ if (bin != null) {
+ launch(bin, mode);
+ }
+ } else {
+ handleFail(Messages.ProfileLaunchShortcut_no_project_selected);
+ }
+ }
- protected void handleFail(String message) {
- MessageDialog.openError(getActiveWorkbenchShell(), Messages.ProfileLaunchShortcut_Launcher, message);
- }
+ protected void handleFail(String message) {
+ MessageDialog.openError(getActiveWorkbenchShell(), Messages.ProfileLaunchShortcut_Launcher, message);
+ }
- /**
- * Prompts the user to select a binary
- *
- * @return the selected binary or <code>null</code> if none.
- */
- protected IBinary chooseBinary(List<IBinary> binList, String mode) {
- ILabelProvider programLabelProvider = new CElementLabelProvider() {
- @Override
- public String getText(Object element) {
- if (element instanceof IBinary) {
- IBinary bin = (IBinary)element;
- StringBuffer name = new StringBuffer();
- name.append(bin.getPath().lastSegment());
- return name.toString();
- }
- return super.getText(element);
- }
- };
+ /**
+ * Prompts the user to select a binary
+ *
+ * @return the selected binary or <code>null</code> if none.
+ */
+ protected IBinary chooseBinary(List<IBinary> binList, String mode) {
+ ILabelProvider programLabelProvider = new CElementLabelProvider() {
+ @Override
+ public String getText(Object element) {
+ if (element instanceof IBinary) {
+ IBinary bin = (IBinary)element;
+ StringBuffer name = new StringBuffer();
+ name.append(bin.getPath().lastSegment());
+ return name.toString();
+ }
+ return super.getText(element);
+ }
+ };
- ILabelProvider qualifierLabelProvider = new CElementLabelProvider() {
- @Override
- public String getText(Object element) {
- if (element instanceof IBinary) {
- IBinary bin = (IBinary)element;
- StringBuffer name = new StringBuffer();
- name.append(bin.getCPU() + (bin.isLittleEndian() ? "le" : "be")); //$NON-NLS-1$ //$NON-NLS-2$
- name.append(" - "); //$NON-NLS-1$
- name.append(bin.getPath().toString());
- return name.toString();
- }
- return super.getText(element);
- }
- };
+ ILabelProvider qualifierLabelProvider = new CElementLabelProvider() {
+ @Override
+ public String getText(Object element) {
+ if (element instanceof IBinary) {
+ IBinary bin = (IBinary)element;
+ StringBuffer name = new StringBuffer();
+ name.append(bin.getCPU() + (bin.isLittleEndian() ? "le" : "be")); //$NON-NLS-1$ //$NON-NLS-2$
+ name.append(" - "); //$NON-NLS-1$
+ name.append(bin.getPath().toString());
+ return name.toString();
+ }
+ return super.getText(element);
+ }
+ };
- TwoPaneElementSelector dialog = new TwoPaneElementSelector(getActiveWorkbenchShell(), programLabelProvider, qualifierLabelProvider);
- dialog.setElements(binList.toArray());
- dialog.setTitle(Messages.ProfileLaunchShortcut_Profile);
- dialog.setMessage(Messages.ProfileLaunchShortcut_Choose_a_local_application);
- dialog.setUpperListLabel(Messages.ProfileLaunchShortcut_Binaries);
- dialog.setLowerListLabel(Messages.ProfileLaunchShortcut_Qualifier);
- dialog.setMultipleSelection(false);
- if (dialog.open() == Window.OK) {
- return (IBinary) dialog.getFirstResult();
- }
+ TwoPaneElementSelector dialog = new TwoPaneElementSelector(getActiveWorkbenchShell(), programLabelProvider, qualifierLabelProvider);
+ dialog.setElements(binList.toArray());
+ dialog.setTitle(Messages.ProfileLaunchShortcut_Profile);
+ dialog.setMessage(Messages.ProfileLaunchShortcut_Choose_a_local_application);
+ dialog.setUpperListLabel(Messages.ProfileLaunchShortcut_Binaries);
+ dialog.setLowerListLabel(Messages.ProfileLaunchShortcut_Qualifier);
+ dialog.setMultipleSelection(false);
+ if (dialog.open() == Window.OK) {
+ return (IBinary) dialog.getFirstResult();
+ }
- return null;
- }
+ return null;
+ }
- /**
- * Show a selection dialog that allows the user to choose one of the specified
- * launch configurations. Return the chosen config, or <code>null</code> if the
- * user cancelled the dialog.
- */
- protected ILaunchConfiguration chooseConfiguration(List<ILaunchConfiguration> configList, String mode) {
- IDebugModelPresentation labelProvider = DebugUITools.newDebugModelPresentation();
- ElementListSelectionDialog dialog = new ElementListSelectionDialog(getActiveWorkbenchShell(), labelProvider);
- dialog.setElements(configList.toArray());
- dialog.setTitle(Messages.ProfileLaunchShortcut_Launch_Configuration_Selection);
- dialog.setMessage(Messages.ProfileLaunchShortcut_Choose_a_launch_configuration);
- dialog.setMultipleSelection(false);
- int result = dialog.open();
- labelProvider.dispose();
- if (result == Window.OK) {
- return (ILaunchConfiguration) dialog.getFirstResult();
- }
- return null;
- }
+ /**
+ * Show a selection dialog that allows the user to choose one of the specified
+ * launch configurations. Return the chosen config, or <code>null</code> if the
+ * user cancelled the dialog.
+ */
+ protected ILaunchConfiguration chooseConfiguration(List<ILaunchConfiguration> configList, String mode) {
+ IDebugModelPresentation labelProvider = DebugUITools.newDebugModelPresentation();
+ ElementListSelectionDialog dialog = new ElementListSelectionDialog(getActiveWorkbenchShell(), labelProvider);
+ dialog.setElements(configList.toArray());
+ dialog.setTitle(Messages.ProfileLaunchShortcut_Launch_Configuration_Selection);
+ dialog.setMessage(Messages.ProfileLaunchShortcut_Choose_a_launch_configuration);
+ dialog.setMultipleSelection(false);
+ int result = dialog.open();
+ labelProvider.dispose();
+ if (result == Window.OK) {
+ return (ILaunchConfiguration) dialog.getFirstResult();
+ }
+ return null;
+ }
- protected Shell getActiveWorkbenchShell() {
- return ProfileLaunchPlugin.getActiveWorkbenchShell();
- }
+ protected Shell getActiveWorkbenchShell() {
+ return ProfileLaunchPlugin.getActiveWorkbenchShell();
+ }
} \ No newline at end of file
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProxyLaunchMessages.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProxyLaunchMessages.java
index 2e7102316e..3f031eba34 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProxyLaunchMessages.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProxyLaunchMessages.java
@@ -17,39 +17,39 @@ import org.eclipse.osgi.util.NLS;
*/
public class ProxyLaunchMessages extends NLS {
- public ProxyLaunchMessages() {
- }
-
- public static String connection_of_copy_from_exe_cannot_be_opened;
- public static String uri_of_copy_from_exe_is_invalid;
- public static String copy_from_exe_is_not_specified;
- public static String copy_from_exe_does_not_exist;
- public static String error_accessing_copy_from_exe;
- public static String copy_from_exe_does_not_have_execution_rights;
- public static String scheme_error_in_copy_from_exe;
-
- public static String connection_of_executable_cannot_be_opened;
- public static String uri_of_executable_is_invalid;
- public static String executable_is_not_specified;
- public static String executable_does_not_exist;
- public static String error_accessing_executable;
- public static String executable_does_not_have_execution_rights;
- public static String scheme_error_in_executable;
-
- public static String connection_of_working_directory_cannot_be_opened;
- public static String uri_of_working_directory_is_invalid;
- public static String working_directory_does_not_exist;
- public static String error_accessing_working_directory;
- public static String working_directory_is_not_a_directory;
- public static String scheme_error_in_working_directory;
-
- public static String scheme_of_working_directory_and_program_do_not_match;
- public static String connection_of_working_directory_and_program_do_not_match;
-
- static {
- // Load message values from bundle file
- NLS.initializeMessages(ProxyLaunchMessages.class.getCanonicalName(),
- ProxyLaunchMessages.class);
- }
+ public ProxyLaunchMessages() {
+ }
+
+ public static String connection_of_copy_from_exe_cannot_be_opened;
+ public static String uri_of_copy_from_exe_is_invalid;
+ public static String copy_from_exe_is_not_specified;
+ public static String copy_from_exe_does_not_exist;
+ public static String error_accessing_copy_from_exe;
+ public static String copy_from_exe_does_not_have_execution_rights;
+ public static String scheme_error_in_copy_from_exe;
+
+ public static String connection_of_executable_cannot_be_opened;
+ public static String uri_of_executable_is_invalid;
+ public static String executable_is_not_specified;
+ public static String executable_does_not_exist;
+ public static String error_accessing_executable;
+ public static String executable_does_not_have_execution_rights;
+ public static String scheme_error_in_executable;
+
+ public static String connection_of_working_directory_cannot_be_opened;
+ public static String uri_of_working_directory_is_invalid;
+ public static String working_directory_does_not_exist;
+ public static String error_accessing_working_directory;
+ public static String working_directory_is_not_a_directory;
+ public static String scheme_error_in_working_directory;
+
+ public static String scheme_of_working_directory_and_program_do_not_match;
+ public static String connection_of_working_directory_and_program_do_not_match;
+
+ static {
+ // Load message values from bundle file
+ NLS.initializeMessages(ProxyLaunchMessages.class.getCanonicalName(),
+ ProxyLaunchMessages.class);
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteConnection.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteConnection.java
index 9ec3f78c08..cc3100e779 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteConnection.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteConnection.java
@@ -33,183 +33,183 @@ import org.eclipse.core.runtime.SubMonitor;
*/
public class RemoteConnection {
- private IRemoteFileProxy rmtFileProxy;
-
- public RemoteConnection(URI uri)
- throws RemoteConnectionException {
- try {
- IRemoteProxyManager rmtProxyMgr = RemoteProxyManager.getInstance();
- rmtFileProxy = rmtProxyMgr.getFileProxy(uri);
- } catch (CoreException e) {
- throw new RemoteConnectionException(
- RemoteMessages.RemoteConnection_failed, e);
- }
- }
-
- /**
- * Copy a data from a path (can be a file or directory) from the remote host
- * to the local host.
- *
- * @param remotePath
- * @param localPath
- * @param monitor
- * @throws CoreException
- */
- private void copyFileFromRemoteHost(String remotePath, String localPath,
- IProgressMonitor monitor)
- throws CoreException {
- SubMonitor progress = SubMonitor.convert(monitor, 15);
- try {
- IFileSystem localFS = EFS.getLocalFileSystem();
- IFileStore localFile = localFS.getStore(Path.fromOSString(localPath));
- IFileStore rmtFile = rmtFileProxy.getResource(remotePath);
- rmtFile.copy(localFile, EFS.OVERWRITE, progress);
- } finally {
- if (monitor != null) {
- monitor.done();
- }
- }
- }
-
- /***
- * Upload files to remote target directory. This method is recursive. If a
- * local directory is specified as the input, then all folders and files are
- * uploaded to the remote target directory. The remote target directory must
- * exist prior to calling this method or else failure will occur.
- *
- * A RemoteConnectionException is thrown on any failure condition.
- *
- * @param localPath
- * - the local path to file
- * @param remotePath
- * - the remote path
- * @param monitor
- * - progress monitor
- * @throws RemoteConnectionException
- */
- public void upload(IPath localPath, IPath remotePath,
- IProgressMonitor monitor) throws RemoteConnectionException {
- try {
- copyFileToRemoteHost(localPath.toOSString(),
- remotePath.toOSString(), monitor);
- } catch (CoreException e) {
- throw new RemoteConnectionException(e.getLocalizedMessage(), e);
- }
- }
-
- /**
- * Create a folder on the remote system. A RemoteConnectionException is
- * thrown if any failure occurs.
- *
- * @param remoteFolderPath
- * - path of the remote folder to create
- * @param monitor
- * - progress monitor
- * @throws RemoteConnectionException
- */
- public void createFolder(IPath remoteFolderPath, IProgressMonitor monitor)
- throws RemoteConnectionException {
- IFileStore remoteFolder = rmtFileProxy.getResource(remoteFolderPath.toString());
- try {
- remoteFolder.mkdir(0, new NullProgressMonitor());
- } catch (CoreException e) {
- throw new RemoteConnectionException(e.getLocalizedMessage(), e);
- }
- }
-
- /**
- * Break up a buffer from ConsoleOutputStream and return it as an array
- * of lines
- * @param buffer typically from ConsoleOutputStream object's readBuffer() method
- * @return array of lines as Strings with no line terminators
- */
- public static String[] getLines(String buffer) /* throws RemoteConnectionException */ {
- // Count the number of newlines in the buffer.
- int numLines = 0;
-
- for (char c : buffer.toCharArray()) {
- if (c == '\n') {
- numLines++;
- }
- }
- String lines[] = new String[numLines];
-
- int line = 0;
- int startOfString = 0;
- for (int endOfString = 0; endOfString < buffer.length(); endOfString++) {
- if (buffer.charAt(endOfString) == '\n') {
- lines[line++] = new String(buffer.toCharArray(), startOfString, endOfString
- - startOfString);
- startOfString = endOfString + 1;
- }
- }
- return lines;
- }
-
- /**
- * Remote delete function. This method is recursive. If a remote directory
- * is specified, the remote directory and all its contents are removed. A
- * RemoteConnectionException is thrown if failure occurs for any reason.
- *
- * @param remotePath
- * - the remote path of the file or folder to be deleted
- * @param monitor
- * - progress monitor
- * @throws RemoteConnectionException
- */
- public void delete(IPath remotePath, IProgressMonitor monitor)
- throws RemoteConnectionException {
- try {
- IFileStore remoteFile = rmtFileProxy.getResource(
- remotePath.toString());
- remoteFile.delete(0, monitor);
- } catch (CoreException e) {
- throw new RemoteConnectionException(e.getLocalizedMessage(), e);
- }
- }
-
- /**
- * Download a file or folder from a remote system. The method is recursive.
- * If a remote folder is specified, all the contents of the folder are
- * downloaded, including folders, and placed under the directory specified
- * by the localPath variable. It is assumed that any remote non-binary file
- * is UTF-8. A RemoteConnectionException is thrown if any failure occurs.
- *
- * @param remotePath
- * - path to remote file or folder
- * @param localPath
- * - local directory target
- * @param monitor
- * - progress monitor
- * @throws RemoteConnectionException
- */
- public void download(IPath remotePath, IPath localPath,
- IProgressMonitor monitor) throws RemoteConnectionException {
- try {
- copyFileFromRemoteHost(remotePath.toString(), localPath.toString(),
- monitor);
- } catch (CoreException e) {
- throw new RemoteConnectionException(e.getLocalizedMessage(), e);
- }
- }
-
- private void copyFileToRemoteHost(String localPath, String remotePath,
- IProgressMonitor monitor) throws CoreException {
- SubMonitor progress = SubMonitor.convert(monitor, 15);
- try {
- IFileSystem localFS = EFS.getLocalFileSystem();
- IFileStore localFile = localFS.getStore(Path.fromOSString(localPath));
- IFileStore rmtFile = rmtFileProxy.getResource(remotePath);
- localFile.copy(rmtFile, EFS.OVERWRITE, progress);
- } finally {
- if (monitor != null) {
- monitor.done();
- }
- }
- }
-
- public IRemoteFileProxy getRmtFileProxy() {
- return rmtFileProxy;
- }
+ private IRemoteFileProxy rmtFileProxy;
+
+ public RemoteConnection(URI uri)
+ throws RemoteConnectionException {
+ try {
+ IRemoteProxyManager rmtProxyMgr = RemoteProxyManager.getInstance();
+ rmtFileProxy = rmtProxyMgr.getFileProxy(uri);
+ } catch (CoreException e) {
+ throw new RemoteConnectionException(
+ RemoteMessages.RemoteConnection_failed, e);
+ }
+ }
+
+ /**
+ * Copy a data from a path (can be a file or directory) from the remote host
+ * to the local host.
+ *
+ * @param remotePath
+ * @param localPath
+ * @param monitor
+ * @throws CoreException
+ */
+ private void copyFileFromRemoteHost(String remotePath, String localPath,
+ IProgressMonitor monitor)
+ throws CoreException {
+ SubMonitor progress = SubMonitor.convert(monitor, 15);
+ try {
+ IFileSystem localFS = EFS.getLocalFileSystem();
+ IFileStore localFile = localFS.getStore(Path.fromOSString(localPath));
+ IFileStore rmtFile = rmtFileProxy.getResource(remotePath);
+ rmtFile.copy(localFile, EFS.OVERWRITE, progress);
+ } finally {
+ if (monitor != null) {
+ monitor.done();
+ }
+ }
+ }
+
+ /***
+ * Upload files to remote target directory. This method is recursive. If a
+ * local directory is specified as the input, then all folders and files are
+ * uploaded to the remote target directory. The remote target directory must
+ * exist prior to calling this method or else failure will occur.
+ *
+ * A RemoteConnectionException is thrown on any failure condition.
+ *
+ * @param localPath
+ * - the local path to file
+ * @param remotePath
+ * - the remote path
+ * @param monitor
+ * - progress monitor
+ * @throws RemoteConnectionException
+ */
+ public void upload(IPath localPath, IPath remotePath,
+ IProgressMonitor monitor) throws RemoteConnectionException {
+ try {
+ copyFileToRemoteHost(localPath.toOSString(),
+ remotePath.toOSString(), monitor);
+ } catch (CoreException e) {
+ throw new RemoteConnectionException(e.getLocalizedMessage(), e);
+ }
+ }
+
+ /**
+ * Create a folder on the remote system. A RemoteConnectionException is
+ * thrown if any failure occurs.
+ *
+ * @param remoteFolderPath
+ * - path of the remote folder to create
+ * @param monitor
+ * - progress monitor
+ * @throws RemoteConnectionException
+ */
+ public void createFolder(IPath remoteFolderPath, IProgressMonitor monitor)
+ throws RemoteConnectionException {
+ IFileStore remoteFolder = rmtFileProxy.getResource(remoteFolderPath.toString());
+ try {
+ remoteFolder.mkdir(0, new NullProgressMonitor());
+ } catch (CoreException e) {
+ throw new RemoteConnectionException(e.getLocalizedMessage(), e);
+ }
+ }
+
+ /**
+ * Break up a buffer from ConsoleOutputStream and return it as an array
+ * of lines
+ * @param buffer typically from ConsoleOutputStream object's readBuffer() method
+ * @return array of lines as Strings with no line terminators
+ */
+ public static String[] getLines(String buffer) /* throws RemoteConnectionException */ {
+ // Count the number of newlines in the buffer.
+ int numLines = 0;
+
+ for (char c : buffer.toCharArray()) {
+ if (c == '\n') {
+ numLines++;
+ }
+ }
+ String lines[] = new String[numLines];
+
+ int line = 0;
+ int startOfString = 0;
+ for (int endOfString = 0; endOfString < buffer.length(); endOfString++) {
+ if (buffer.charAt(endOfString) == '\n') {
+ lines[line++] = new String(buffer.toCharArray(), startOfString, endOfString
+ - startOfString);
+ startOfString = endOfString + 1;
+ }
+ }
+ return lines;
+ }
+
+ /**
+ * Remote delete function. This method is recursive. If a remote directory
+ * is specified, the remote directory and all its contents are removed. A
+ * RemoteConnectionException is thrown if failure occurs for any reason.
+ *
+ * @param remotePath
+ * - the remote path of the file or folder to be deleted
+ * @param monitor
+ * - progress monitor
+ * @throws RemoteConnectionException
+ */
+ public void delete(IPath remotePath, IProgressMonitor monitor)
+ throws RemoteConnectionException {
+ try {
+ IFileStore remoteFile = rmtFileProxy.getResource(
+ remotePath.toString());
+ remoteFile.delete(0, monitor);
+ } catch (CoreException e) {
+ throw new RemoteConnectionException(e.getLocalizedMessage(), e);
+ }
+ }
+
+ /**
+ * Download a file or folder from a remote system. The method is recursive.
+ * If a remote folder is specified, all the contents of the folder are
+ * downloaded, including folders, and placed under the directory specified
+ * by the localPath variable. It is assumed that any remote non-binary file
+ * is UTF-8. A RemoteConnectionException is thrown if any failure occurs.
+ *
+ * @param remotePath
+ * - path to remote file or folder
+ * @param localPath
+ * - local directory target
+ * @param monitor
+ * - progress monitor
+ * @throws RemoteConnectionException
+ */
+ public void download(IPath remotePath, IPath localPath,
+ IProgressMonitor monitor) throws RemoteConnectionException {
+ try {
+ copyFileFromRemoteHost(remotePath.toString(), localPath.toString(),
+ monitor);
+ } catch (CoreException e) {
+ throw new RemoteConnectionException(e.getLocalizedMessage(), e);
+ }
+ }
+
+ private void copyFileToRemoteHost(String localPath, String remotePath,
+ IProgressMonitor monitor) throws CoreException {
+ SubMonitor progress = SubMonitor.convert(monitor, 15);
+ try {
+ IFileSystem localFS = EFS.getLocalFileSystem();
+ IFileStore localFile = localFS.getStore(Path.fromOSString(localPath));
+ IFileStore rmtFile = rmtFileProxy.getResource(remotePath);
+ localFile.copy(rmtFile, EFS.OVERWRITE, progress);
+ } finally {
+ if (monitor != null) {
+ monitor.done();
+ }
+ }
+ }
+
+ public IRemoteFileProxy getRmtFileProxy() {
+ return rmtFileProxy;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteConnectionException.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteConnectionException.java
index 19fe04d9f9..3894c0370f 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteConnectionException.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteConnectionException.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Red Hat Inc. - Initial implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.profiling.launch;
import org.eclipse.core.runtime.CoreException;
@@ -21,10 +21,10 @@ import org.eclipse.linuxtools.internal.profiling.launch.ProfileLaunchPlugin;
*/
public class RemoteConnectionException extends CoreException {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- public RemoteConnectionException(String message, Throwable t) {
- super(new Status(IStatus.ERROR, ProfileLaunchPlugin.PLUGIN_ID, message, t));
- }
+ public RemoteConnectionException(String message, Throwable t) {
+ super(new Status(IStatus.ERROR, ProfileLaunchPlugin.PLUGIN_ID, message, t));
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteEnvProxyManager.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteEnvProxyManager.java
index dbefd732cf..d93e042698 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteEnvProxyManager.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteEnvProxyManager.java
@@ -25,25 +25,25 @@ import org.eclipse.core.runtime.CoreException;
*/
public class RemoteEnvProxyManager extends RemoteProxyManager implements IRemoteEnvProxyManager {
- @Override
- public Map<String, String> getEnv(IProject project) throws CoreException {
- String scheme = mapping.getSchemeFromNature(project);
- if (scheme!=null) {
- IRemoteEnvProxyManager manager = (IRemoteEnvProxyManager) getRemoteManager(scheme);
- return manager.getEnv(project);
- }
- URI projectURI = project.getLocationURI();
- return getEnv(projectURI);
- }
+ @Override
+ public Map<String, String> getEnv(IProject project) throws CoreException {
+ String scheme = mapping.getSchemeFromNature(project);
+ if (scheme!=null) {
+ IRemoteEnvProxyManager manager = (IRemoteEnvProxyManager) getRemoteManager(scheme);
+ return manager.getEnv(project);
+ }
+ URI projectURI = project.getLocationURI();
+ return getEnv(projectURI);
+ }
- @Override
- public Map<String, String> getEnv(URI uri) throws CoreException {
- String scheme = uri.getScheme();
- if (scheme != null && !scheme.equals(LOCALSCHEME)){
- IRemoteEnvProxyManager manager = (IRemoteEnvProxyManager) getRemoteManager(scheme);
- return manager.getEnv(uri);
- }
- return System.getenv();
- }
+ @Override
+ public Map<String, String> getEnv(URI uri) throws CoreException {
+ String scheme = uri.getScheme();
+ if (scheme != null && !scheme.equals(LOCALSCHEME)){
+ IRemoteEnvProxyManager manager = (IRemoteEnvProxyManager) getRemoteManager(scheme);
+ return manager.getEnv(uri);
+ }
+ return System.getenv();
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteMessages.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteMessages.java
index 04881d19cf..e2b841a04c 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteMessages.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteMessages.java
@@ -8,7 +8,7 @@
* Contributors:
* Elliott Baron <ebaron@fedoraproject.org> - initial API and implementation
* Red Hat Inc. - modified to be shared by remote tools
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.profiling.launch;
import org.eclipse.osgi.util.NLS;
@@ -17,13 +17,13 @@ import org.eclipse.osgi.util.NLS;
* @since 1.1
*/
public class RemoteMessages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.profiling.launch.remoteMessages"; //$NON-NLS-1$
- public static String RemoteConnection_failed;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, RemoteMessages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.profiling.launch.remoteMessages"; //$NON-NLS-1$
+ public static String RemoteConnection_failed;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, RemoteMessages.class);
+ }
- private RemoteMessages() {
- }
+ private RemoteMessages() {
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyCMainTab.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyCMainTab.java
index 9983535b83..429503b6b2 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyCMainTab.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyCMainTab.java
@@ -8,8 +8,8 @@
* Contributors:
* QNX Software Systems - initial API and implementation
* Ken Ryall (Nokia) - bug 178731
- * IBM Corporation
- * Sergey Prigogin (Google)
+ * IBM Corporation
+ * Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.linuxtools.profiling.launch;
@@ -75,1085 +75,1085 @@ import org.eclipse.ui.dialogs.TwoPaneElementSelector;
@SuppressWarnings("restriction")
public class RemoteProxyCMainTab extends CAbstractMainTab {
- /**
- * Tab identifier used for ordering of tabs added using the
- * <code>org.eclipse.debug.ui.launchConfigurationTabs</code> extension
- * point.
- *
- * @since 6.0
- */
- public static final String TAB_ID = "org.eclipse.linuxtools.profiling.launch.RemoteProxyCMainTab"; //$NON-NLS-1$
-
- private final boolean fWantsTerminalOption;
- protected Button fTerminalButton;
-
- protected ResourceSelectorWidget exeSelector;
-
- protected Text copyFromExeText;
- protected Button enableCopyFromExeButton;
- protected ResourceSelectorWidget copyFromExeSelector;
- protected Label toLabel;
- protected String fPreviouslyCheckedCopyFromExe;
- protected boolean fPreviouslyCheckedCopyFromExeIsValid;
- protected String fPreviouslyCheckedCopyFromExeErrorMsg;
-
- protected Text workingDirText;
- protected String fPreviouslyCheckedWorkingDir;
- protected boolean fPreviouslyCheckedWorkingDirIsValid;
- protected String fPreviouslyCheckedWorkingDirErrorMsg;
- protected ResourceSelectorWidget workingDirSelector;
-
- private final boolean dontCheckProgram;
- private final boolean fSpecifyCoreFile;
-
- public static final int WANTS_TERMINAL = 1;
- public static final int DONT_CHECK_PROGRAM = 2;
- /** @since 6.0 */
- public static final int SPECIFY_CORE_FILE = 4;
-
- public static final String ATTR_REMOTE_WORKING_DIRECTORY_NAME = "REMOTE_WORKING_DIRECTORY_NAME"; //$NON-NLS-1$
- public static final String ATTR_COPY_FROM_EXE_NAME = "COPY_FROM_EXE_NAME"; //$NON-NLS-1$
- public static final String ATTR_ENABLE_COPY_FROM_EXE = "ENABLE_COPY_FROM_EXE"; //$NON-NLS-1$
-
- public RemoteProxyCMainTab() {
- this(WANTS_TERMINAL);
- }
-
- public RemoteProxyCMainTab(boolean terminalOption) {
- this(terminalOption ? WANTS_TERMINAL : 0);
- }
-
- public RemoteProxyCMainTab(int flags) {
- fWantsTerminalOption = (flags & WANTS_TERMINAL) != 0;
- dontCheckProgram = (flags & DONT_CHECK_PROGRAM) != 0;
- fSpecifyCoreFile = (flags & SPECIFY_CORE_FILE) != 0;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.debug.ui.ILaunchConfigurationTab#createControl(org.eclipse
- * .swt.widgets.Composite)
- */
- @Override
- public void createControl(Composite parent) {
- Composite comp = new Composite(parent, SWT.NONE);
- setControl(comp);
-
- ProfileLaunchPlugin
- .getDefault()
- .getWorkbench()
- .getHelpSystem()
- .setHelp(
- getControl(),
- ICDTLaunchHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_MAIN_TAB);
-
- GridLayout topLayout = new GridLayout();
- comp.setLayout(topLayout);
-
- createVerticalSpacer(comp, 1);
- createCopyFromExeGroup(comp, 1);
- createExeFileGroup(comp, 1);
- createWorkingDirGroup(comp, 1);
- createProjectGroup(comp, 1);
- createBuildOptionGroup(comp, 1);
- createVerticalSpacer(comp, 1);
- if (fSpecifyCoreFile) {
- createCoreFileGroup(comp, 1);
- }
- if (wantsTerminalOption() /* && ProcessFactory.supportesTerminal() */) {
- createTerminalOption(comp, 1);
- }
- }
-
- protected boolean wantsTerminalOption() {
- return fWantsTerminalOption;
- }
-
- protected void createTerminalOption(Composite parent, int colSpan) {
- Composite mainComp = new Composite(parent, SWT.NONE);
- GridLayout mainLayout = new GridLayout();
- mainLayout.numColumns = 1;
- mainLayout.marginHeight = 0;
- mainLayout.marginWidth = 0;
- mainComp.setLayout(mainLayout);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = colSpan;
- mainComp.setLayoutData(gd);
-
- fTerminalButton = createCheckButton(mainComp,
- LaunchMessages.CMainTab_UseTerminal);
- fTerminalButton.addSelectionListener(new SelectionAdapter() {
-
- @Override
- public void widgetSelected(SelectionEvent evt) {
- updateLaunchConfigurationDialog();
- }
- });
- fTerminalButton.setEnabled(PTY.isSupported());
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(org.eclipse
- * .debug.core.ILaunchConfiguration)
- */
- @Override
- public void initializeFrom(ILaunchConfiguration config) {
- filterPlatform = getPlatform(config);
- updateProjectFromConfig(config);
- updateCopyFromExeFromConfig(config);
- updateProgramFromConfig(config);
- updateWorkingDirFromConfig(config);
- updateCoreFromConfig(config);
- updateBuildOptionFromConfig(config);
- updateTerminalFromConfig(config);
- }
-
- protected void updateTerminalFromConfig(ILaunchConfiguration config) {
- if (fTerminalButton != null) {
- boolean useTerminal = true;
- try {
- useTerminal = config.getAttribute(
- ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL,
- ICDTLaunchConfigurationConstants.USE_TERMINAL_DEFAULT);
- } catch (CoreException e) {
- ProfileLaunchPlugin.log(e);
- }
- fTerminalButton.setSelection(useTerminal);
- }
- }
-
- /** @since 6.0 */
- protected void updateCoreFromConfig(ILaunchConfiguration config) {
- if (fCoreText != null) {
- String coreName = EMPTY_STRING;
- try {
- coreName = config.getAttribute(
- ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH,
- EMPTY_STRING);
- } catch (CoreException ce) {
- ProfileLaunchPlugin.log(ce);
- }
- fCoreText.setText(coreName);
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(org.eclipse
- * .debug.core.ILaunchConfigurationWorkingCopy)
- */
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy config) {
- super.performApply(config);
- ICProject cProject = this.getCProject();
- if (cProject != null && cProject.exists()) {
- config.setMappedResources(new IResource[] { cProject.getProject() });
- } else {
- // the user typed in a non-existent project name. Ensure that
- // won't be suppressed from the dialog. This matches JDT behaviour
- config.setMappedResources(null);
- }
- config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- fProjText.getText());
- if (enableCopyFromExeButton != null) {
- config.setAttribute(
- ATTR_ENABLE_COPY_FROM_EXE,
- enableCopyFromExeButton.getSelection());
- }
- if (copyFromExeText != null) {
- config.setAttribute(
- ATTR_COPY_FROM_EXE_NAME,
- copyFromExeText.getText());
- }
- if (fProgText != null) {
- config.setAttribute(
- ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
- fProgText.getText());
- }
- if (workingDirText != null) {
- config.setAttribute(
- ATTR_REMOTE_WORKING_DIRECTORY_NAME,
- workingDirText.getText());
- }
- if (fCoreText != null) {
- config.setAttribute(
- ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH,
- fCoreText.getText());
- }
- if (fTerminalButton != null) {
- config.setAttribute(
- ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL,
- fTerminalButton.getSelection());
- }
- }
-
- /**
- * Show a dialog that lists all main types
- */
- @Override
- protected void handleSearchButtonSelected() {
- if (getCProject() == null) {
- MessageDialog
- .openInformation(
- getShell(),
- LaunchMessages.CMainTab_Project_required,
- LaunchMessages.CMainTab_Enter_project_before_searching_for_program);
- return;
- }
-
- ILabelProvider programLabelProvider = new CElementLabelProvider() {
-
- @Override
- public String getText(Object element) {
- if (element instanceof IBinary) {
- IBinary bin = (IBinary) element;
- StringBuffer name = new StringBuffer();
- name.append(bin.getPath().lastSegment());
- return name.toString();
- }
- return super.getText(element);
- }
-
- @Override
- public Image getImage(Object element) {
- if (!(element instanceof ICElement)) {
- return super.getImage(element);
- }
- ICElement celement = (ICElement) element;
-
- if (celement.getElementType() == ICElement.C_BINARY) {
- IBinary belement = (IBinary) celement;
- if (belement.isExecutable()) {
- return DebugUITools
- .getImage(IDebugUIConstants.IMG_ACT_RUN);
- }
- }
-
- return super.getImage(element);
- }
- };
-
- ILabelProvider qualifierLabelProvider = new CElementLabelProvider() {
-
- @Override
- public String getText(Object element) {
- if (element instanceof IBinary) {
- IBinary bin = (IBinary) element;
- StringBuffer name = new StringBuffer();
- name.append(bin.getCPU()
- + (bin.isLittleEndian() ? "le" : "be")); //$NON-NLS-1$ //$NON-NLS-2$
- name.append(" - "); //$NON-NLS-1$
- name.append(bin.getPath().toString());
- return name.toString();
- }
- return super.getText(element);
- }
- };
-
- TwoPaneElementSelector dialog = new TwoPaneElementSelector(getShell(),
- programLabelProvider, qualifierLabelProvider);
- dialog.setElements(getBinaryFiles(getCProject()));
- dialog.setMessage(LaunchMessages.CMainTab_Choose_program_to_run);
- dialog.setTitle(LaunchMessages.CMainTab_Program_Selection);
- dialog.setUpperListLabel(LaunchMessages.Launch_common_BinariesColon);
- dialog.setLowerListLabel(LaunchMessages.Launch_common_QualifierColon);
- dialog.setMultipleSelection(false);
- // dialog.set
- if (dialog.open() == Window.OK) {
- IBinary binary = (IBinary) dialog.getFirstResult();
- fProgText.setText(binary.getResource().getProjectRelativePath()
- .toString());
- }
- }
-
- /**
- * @since 6.0
- */
- @Override
- protected void createProjectGroup(Composite parent, int colSpan) {
- Composite projComp = new Composite(parent, SWT.NONE);
- GridLayout projLayout = new GridLayout();
- projLayout.numColumns = 2;
- projLayout.marginHeight = 0;
- projLayout.marginWidth = 0;
- projComp.setLayout(projLayout);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = colSpan;
- projComp.setLayoutData(gd);
-
- fProjLabel = new Label(projComp, SWT.NONE);
- fProjLabel.setText(LaunchMessages.CMainTab_ProjectColon);
- gd = new GridData();
- gd.horizontalSpan = 2;
- fProjLabel.setLayoutData(gd);
-
- fProjText = new Text(projComp, SWT.SINGLE | SWT.BORDER);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- fProjText.setLayoutData(gd);
- fProjText.addModifyListener(new ModifyListener() {
-
- @Override
- public void modifyText(ModifyEvent evt) {
- // if project changes, invalidate program name cache
- fPreviouslyCheckedProgram = null;
-
- updateBuildConfigCombo(""); //$NON-NLS-1$
- updateLaunchConfigurationDialog();
- }
- });
-
- fProjButton = createPushButton(projComp,
- LaunchMessages.Launch_common_Browse_1, null);
- fProjButton.addSelectionListener(new SelectionAdapter() {
-
- @Override
- public void widgetSelected(SelectionEvent evt) {
- handleProjectButtonSelected();
- updateLaunchConfigurationDialog();
- }
- });
- }
-
- @Override
- protected void updateProgramFromConfig(ILaunchConfiguration config) {
- super.updateProgramFromConfig(config);
- if(fProgText.getText().equals(EMPTY_STRING)){
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- if(this.fProjText != null){
- IProject project = root.getProject(this.fProjText.getText());
- if(project != null){
- fProgText.setText(project.getLocationURI().toString());
- }
- }
- }
- }
-
- protected void updateCopyFromExeFromConfig(ILaunchConfiguration config) {
- if (copyFromExeText != null) {
- String workingDir = EMPTY_STRING;
- try {
- workingDir = config.getAttribute(ATTR_COPY_FROM_EXE_NAME, EMPTY_STRING);
- } catch (CoreException ce) {
- ProfileLaunchPlugin.log(ce);
- }
- copyFromExeText.setText(workingDir);
- }
- if (enableCopyFromExeButton != null) {
- boolean enableCopyFromExe = false;
- try {
- enableCopyFromExe = config.getAttribute(ATTR_ENABLE_COPY_FROM_EXE, false);
- } catch (CoreException ce) {
- ProfileLaunchPlugin.log(ce);
- }
- setEnableCopyFromSection(enableCopyFromExe);
- }
- }
-
- private void setEnableCopyFromSection(boolean enable) {
- // setSelection will be redundant if called from a listener
- enableCopyFromExeButton.setSelection(enable);
- copyFromExeSelector.setEnabled(enable);
- toLabel.setEnabled(enable);
- }
-
- protected void createCopyFromExeGroup(Composite parent, int colSpan) {
- Composite mainComp = new Composite(parent, SWT.NONE);
- GridLayout mainLayout = new GridLayout();
- mainLayout.numColumns = 1;
- mainLayout.marginHeight = 0;
- mainLayout.marginWidth = 0;
- mainComp.setLayout(mainLayout);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = colSpan;
- mainComp.setLayoutData(gd);
-
- enableCopyFromExeButton = createCheckButton(mainComp, "Copy C/C++ executable from:");
- copyFromExeSelector = new ResourceSelectorWidget(mainComp,
- ResourceSelectorWidget.ResourceType.FILE,
- 2, "C/C++ executable origin", null); //$NON-NLS-1$
- toLabel = new Label(mainComp, SWT.NONE);
- toLabel.setText("To:");
-
- // The "copy from" check box is initially off, the selector and "To:" label
- // are disabled.
- copyFromExeSelector.setEnabled(false);
- enableCopyFromExeButton.setSelection(false);
-
- toLabel.setEnabled(false);
-
- enableCopyFromExeButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- boolean copyEnabled = enableCopyFromExeButton.getSelection();
- setEnableCopyFromSection(copyEnabled);
- updateLaunchConfigurationDialog();
- }
- });
-
- copyFromExeText = copyFromExeSelector.getURIText();
- copyFromExeText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent evt) {
- updateLaunchConfigurationDialog();
- }
- });
- }
-
-
- protected void createExeFileGroup(Composite parent, int colSpan) {
- Composite mainComp = new Composite(parent, SWT.NONE);
- GridLayout mainLayout = new GridLayout();
- mainLayout.numColumns = 1;
- mainLayout.marginHeight = 0;
- mainLayout.marginWidth = 0;
- mainComp.setLayout(mainLayout);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = colSpan;
- mainComp.setLayoutData(gd);
- exeSelector = new ResourceSelectorWidget(mainComp,
- ResourceSelectorWidget.ResourceType.FILE,
- 2, "C/C++ executable", null); //$NON-NLS-1$
- fProgText = exeSelector.getURIText();
- fProgText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent evt) {
- updateLaunchConfigurationDialog();
- }
- });
- }
-
- protected void updateWorkingDirFromConfig(ILaunchConfiguration config) {
- if (workingDirText != null) {
- String projectDir = EMPTY_STRING;
- try {
- projectDir = config.getAttribute(ATTR_REMOTE_WORKING_DIRECTORY_NAME, EMPTY_STRING);
- } catch (CoreException ce) {
- ProfileLaunchPlugin.log(ce);
- }
-
- if (projectDir.equals(EMPTY_STRING)){
- if(this.fProjText != null){
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IProject project = root.getProject(this.fProjText.getText());
- try {
- projectDir = RemoteProxyManager.getInstance().getRemoteProjectLocation(project);
- } catch (CoreException e) {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory);
- }
- }
- }
- workingDirText.setText(projectDir);
- }
- }
-
- protected void createWorkingDirGroup(Composite parent, int colSpan) {
- Composite mainComp = new Composite(parent, SWT.NONE);
- GridLayout mainLayout = new GridLayout();
- mainLayout.numColumns = 1;
- mainLayout.marginHeight = 0;
- mainLayout.marginWidth = 0;
- mainComp.setLayout(mainLayout);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = colSpan;
- mainComp.setLayoutData(gd);
- ResourceSelectorWidget workingDirSelector = new ResourceSelectorWidget(mainComp,
- ResourceSelectorWidget.ResourceType.DIRECTORY,
- 2, "Working directory", null); //$NON-NLS-1$
- workingDirText = workingDirSelector.getURIText();
- workingDirText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent evt) {
- updateLaunchConfigurationDialog();
- }
- });
- }
-
- private boolean checkCopyFromExe(ILaunchConfiguration config, IProject project) {
- if (!enableCopyFromExeButton.getSelection()) {
- setErrorMessage(null);
- return true;
- }
-
- String name = copyFromExeText.getText().trim();
- if (name.length() == 0) {
- setErrorMessage(ProxyLaunchMessages.copy_from_exe_is_not_specified);
- return false;
- }
- // Avoid constantly checking the binary if nothing relevant has
- // changed (binary or project name). See bug 277663.
- if (name.equals(fPreviouslyCheckedCopyFromExe)) {
- if (fPreviouslyCheckedCopyFromExeErrorMsg != null) {
- setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg);
- }
- return fPreviouslyCheckedCopyFromExeIsValid;
- }
- fPreviouslyCheckedCopyFromExe = name;
- fPreviouslyCheckedCopyFromExeIsValid = true; // we'll flip this below if
- // not true
- fPreviouslyCheckedCopyFromExeErrorMsg = null; // we'll set this below if
- // there's an error
- IPath exePath;
- URI exeURI = null;
- boolean passed = false;
-
- try {
- exeURI = new URI(name);
- String exePathStr = exeURI.getPath();
- if (exePathStr == null) {
- setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.uri_of_copy_from_exe_is_invalid);
- fPreviouslyCheckedCopyFromExeIsValid = false;
- return false;
- }
- exePath = Path.fromOSString(exeURI.getPath());
- if (!exePath.isAbsolute() && exeURI != null && !exeURI.isAbsolute()) {
- URI projectURI = project.getLocationURI();
- exeURI = new URI(projectURI.getScheme(),
- projectURI.getAuthority(), projectURI.getRawPath() + '/'
- + exePath.toString(), EMPTY_STRING);
- }
- if (exeURI != null) {
- passed = true;
- }
- } catch (URISyntaxException e) {
- setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.uri_of_copy_from_exe_is_invalid);
- fPreviouslyCheckedCopyFromExeIsValid = false;
- return false;
- }
-
- if (!passed) {
- setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.copy_from_exe_does_not_exist);
- fPreviouslyCheckedCopyFromExeIsValid = false;
- return false;
- }
-
- passed = false;
- try {
- IRemoteFileProxy exeFileProxy;
- exeFileProxy = RemoteProxyManager.getInstance().getFileProxy(exeURI);
- if (exeFileProxy != null) {
- String exeFilePath = exeURI.getPath();
- IFileStore exeFS = exeFileProxy
- .getResource(exeFilePath);
- if (exeFS != null) {
- IFileInfo exeFI = exeFS.fetchInfo();
- if (exeFI != null) {
- if (exeFI.exists()) {
- if (exeFI.getAttribute(EFS.ATTRIBUTE_EXECUTABLE) &&
- !exeFI.isDirectory()) {
- passed = true;
- } else {
- setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.copy_from_exe_does_not_have_execution_rights);
- }
- } else {
- setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.copy_from_exe_does_not_exist);
- }
- } else {
- setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.error_accessing_copy_from_exe);
- }
- } else {
- setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.error_accessing_copy_from_exe);
- }
- } else {
- setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.scheme_error_in_copy_from_exe);
- }
- } catch (CoreException e) {
- setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.connection_of_copy_from_exe_cannot_be_opened);
- }
- if (!passed) {
- fPreviouslyCheckedCopyFromExeIsValid = false;
- return false;
- }
- setErrorMessage(null);
- return true;
- }
-
-
- private boolean checkProgram(ILaunchConfiguration config, IProject project) {
- String name = fProgText.getText().trim();
- if (name.length() == 0) {
- setErrorMessage(ProxyLaunchMessages.executable_is_not_specified);
- return false;
- }
- // Avoid constantly checking the binary if nothing relevant has
- // changed (binary or project name). See bug 277663.
- if (name.equals(fPreviouslyCheckedProgram)) {
- if (fPreviouslyCheckedProgramErrorMsg != null) {
- setErrorMessage(fPreviouslyCheckedProgramErrorMsg);
- }
- return fPreviouslyCheckedProgramIsValid;
- }
- fPreviouslyCheckedProgram = name;
- fPreviouslyCheckedProgramIsValid = true; // we'll flip this below if
- // not true
- fPreviouslyCheckedProgramErrorMsg = null; // we'll set this below if
- // there's an error
- IPath exePath;
- URI exeURI = null;
- boolean passed = false;
-
- try {
- exeURI = new URI(name);
- String exePathStr = exeURI.getPath();
- if (exePathStr == null) {
- setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.uri_of_executable_is_invalid);
- fPreviouslyCheckedProgramIsValid = false;
- return false;
- }
-
- exePath = Path.fromOSString(exeURI.getPath());
- if (!exePath.isAbsolute() && exeURI != null && !exeURI.isAbsolute()) {
- URI projectURI = project.getLocationURI();
- exeURI = new URI(projectURI.getScheme(),
- projectURI.getAuthority(), projectURI.getRawPath() + '/'
- + exePath.toString(), EMPTY_STRING);
- }
- if (exeURI != null) {
- passed = true;
- }
- } catch (URISyntaxException e) {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.uri_of_executable_is_invalid);
- fPreviouslyCheckedProgramIsValid = false;
- return false;
- }
-
- if (!passed) {
- setErrorMessage(fPreviouslyCheckedProgramErrorMsg = LaunchMessages.CMainTab_Program_does_not_exist);
- fPreviouslyCheckedProgramIsValid = false;
- return false;
- }
-
- passed = false;
- try {
- IRemoteFileProxy exeFileProxy;
- exeFileProxy = RemoteProxyManager.getInstance().getFileProxy(exeURI);
- if (exeFileProxy != null) {
- String exeFilePath = exeURI.getPath();
- IFileStore exeFS = exeFileProxy
- .getResource(exeFilePath);
- if (exeFS != null) {
- IFileInfo exeFI = exeFS.fetchInfo();
- if (exeFI != null) {
- if (dontCheckProgram || enableCopyFromExeButton.getSelection()) {
- // The program may not exist yet if we are copying it.
- passed = true;
- } else {
- if (exeFI.exists()) {
- if (exeFI.getAttribute(EFS.ATTRIBUTE_EXECUTABLE) &&
- !exeFI.isDirectory()) {
- passed = true;
- } else {
- setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.executable_does_not_have_execution_rights);
- }
- } else {
- setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.executable_does_not_exist);
- }
- }
- } else {
- setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.error_accessing_executable);
- }
- } else {
- setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.error_accessing_executable);
- }
- } else {
- setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.scheme_error_in_executable);
- }
- } catch (CoreException e) {
- setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.connection_of_executable_cannot_be_opened);
- }
- if (!passed) {
- fPreviouslyCheckedProgramIsValid = false;
- return false;
- }
- setErrorMessage(null);
- return true;
- }
-
- private boolean checkWorkingDir(ILaunchConfiguration config, IProject project) {
- String name = workingDirText.getText().trim();
- if (name.length() == 0) {
- return true; // an empty working directory means, "use the default"
- }
- // Avoid constantly checking the working dir if nothing relevant has
- // changed (project).
- if (name.equals(fPreviouslyCheckedWorkingDir)) {
- if (fPreviouslyCheckedWorkingDirErrorMsg != null) {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg);
- }
- return fPreviouslyCheckedWorkingDirIsValid;
- }
- fPreviouslyCheckedWorkingDir = name;
- fPreviouslyCheckedWorkingDirIsValid = true; // we'll flip this below if
- // not true
- fPreviouslyCheckedWorkingDirErrorMsg = null; // we'll set this below if
- // there's an error
- IPath wdPath;
- URI wdURI = null;
- boolean passed = false;
-
- try {
- wdURI = new URI(name);
- String wdPathStr = wdURI.getPath();
- if (wdPathStr == null) {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.uri_of_working_directory_is_invalid);
- fPreviouslyCheckedWorkingDirIsValid = false;
- return false;
- }
-
- wdPath = Path.fromOSString(wdURI.getPath());
- if (!wdPath.isAbsolute() && wdURI != null && !wdURI.isAbsolute()) {
- URI projectURI = project.getLocationURI();
- wdURI = new URI(projectURI.getScheme(),
- projectURI.getAuthority(), projectURI.getRawPath() + '/'
- + wdPath.toString(), EMPTY_STRING);
- }
- if (wdURI != null) {
- passed = true;
- }
- } catch (URISyntaxException e) {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.uri_of_working_directory_is_invalid);
- fPreviouslyCheckedWorkingDirIsValid = false;
- return false;
- }
-
- if (!passed) {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.working_directory_does_not_exist);
- fPreviouslyCheckedWorkingDirIsValid = false;
- return false;
- }
-
- passed = false;
- IRemoteFileProxy wdFileProxy;
- try {
- wdFileProxy = RemoteProxyManager.getInstance().getFileProxy(wdURI);
- if (wdFileProxy != null) {
- IFileStore wdFS = wdFileProxy
- .getResource(wdURI.getPath());
- if (wdFS != null) {
- IFileInfo wdFI = wdFS.fetchInfo();
- if (wdFI != null) {
- if (wdFI.exists()) {
- if (wdFI.isDirectory()) {
- passed = true;
- } else {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.working_directory_is_not_a_directory);
- }
- } else {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.working_directory_does_not_exist);
- }
- } else {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory);
- }
- } else {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory);
- }
- } else {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.scheme_error_in_working_directory);
- }
- } catch (CoreException e) {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.connection_of_working_directory_cannot_be_opened);
- }
-
- if (!passed) {
- fPreviouslyCheckedWorkingDirIsValid = false;
- return false;
- }
- setErrorMessage(null);
- return true;
- }
-
- /**
- * Compare two strings as equal or not, but allow for one or both of
- * the strings to be null. If both are null, they are treated as equal.
- * If one is null and the other isn't, they are considered unequal. If
- * they are both non-null, the result is the same as the
- * String.equals() method.
- * @param s1 First string to compare.
- * @param s2 Second string to compare.
- * @return Return true if equal, false otherwise.
- */
- private static boolean equal(String s1, String s2) {
- if (s1 == null && s2 == null)
- return true;
- if (s1 == null || s2 == null)
- return false;
- return s1.equals(s2);
- }
-
- /**
- * Check to see if the Executable's location has the same scheme and host name as
- * the working directory. If not, this is an error.
- * @param config
- * @param project
- * @return true if they are compatible, and false if not compatible.
- */
- private boolean checkCompatibility(ILaunchConfiguration config, IProject project) {
- String wdName = workingDirText.getText().trim();
- String progName = fProgText.getText().trim();
- URI wdURI;
- URI progURI;
-
- try {
- wdURI = new URI(wdName);
- progURI = new URI(progName);
- } catch (URISyntaxException e) {
- // this will have been dealt with by previous checks of the Program and Working
- // directory
- System.err.println("internal error. URI syntax error in working directory or program");
- return false;
- }
- {
- String wdScheme = wdURI.getScheme();
- String progScheme = progURI.getScheme();
- if (wdScheme == null && progScheme == null) {
- // local filesystem. No further tests are needed.
- setErrorMessage(null);
- return true;
-
- }
- if (!equal(wdScheme, progScheme)) {
- setErrorMessage(ProxyLaunchMessages.scheme_of_working_directory_and_program_do_not_match);
- return false;
- }
- }
- {
- String wdAuth = wdURI.getAuthority();
- String progAuth = progURI.getAuthority();
- if (!equal(wdAuth, progAuth)) {
- setErrorMessage(ProxyLaunchMessages.connection_of_working_directory_and_program_do_not_match);
- return false;
- }
- }
- {
- String wdQuery = wdURI.getQuery();
- String progQuery = progURI.getQuery();
- if (!equal(wdQuery, progQuery)) {
- setErrorMessage(ProxyLaunchMessages.connection_of_working_directory_and_program_do_not_match);
- return false;
- }
- }
- setErrorMessage(null);
- return true;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.debug.ui.ILaunchConfigurationTab#isValid(org.eclipse.debug
- * .core.ILaunchConfiguration)
- */
- @Override
- public boolean isValid(ILaunchConfiguration config) {
- IProject project;
-
- this.setErrorMessage(null);
- setMessage(null);
-
- String name = fProjText.getText().trim();
- if (name.length() == 0) {
- setErrorMessage(LaunchMessages.CMainTab_Project_not_specified);
- return false;
- }
- project = ResourcesPlugin.getWorkspace().getRoot().getProject(name);
- if (!project.exists()) {
- setErrorMessage(LaunchMessages.Launch_common_Project_does_not_exist);
- return false;
- }
- if (!project.isOpen()) {
- setErrorMessage(LaunchMessages.CMainTab_Project_must_be_opened);
- return false;
- }
-
- if (!checkCopyFromExe(config, project))
- return false;
-
- if (!checkProgram(config, project))
- return false;
-
- if (!checkWorkingDir(config, project))
- return false;
-
- if (!checkCompatibility(config, project))
- return false;
-
- if (fCoreText != null) {
- String coreName = fCoreText.getText().trim();
- // We accept an empty string. This should trigger a prompt to the
- // user
- // This allows to re-use the launch, with a different core file.
- if (!coreName.equals(EMPTY_STRING)) {
- if (coreName.equals(".") || coreName.equals("..")) { //$NON-NLS-1$ //$NON-NLS-2$
- setErrorMessage(LaunchMessages.CMainTab_Core_does_not_exist);
- return false;
- }
- IPath corePath = new Path(coreName);
- if (!corePath.toFile().exists()) {
- setErrorMessage(LaunchMessages.CMainTab_Core_does_not_exist);
- return false;
- }
- }
- }
- return true;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(org.eclipse.
- * debug.core.ILaunchConfigurationWorkingCopy)
- */
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy config) {
- // We set empty attributes for project & program so that when one config
- // is
- // compared to another, the existence of empty attributes doesn't cause
- // an
- // incorrect result (the performApply() method can result in empty
- // values
- // for these attributes being set on a config if there is nothing in the
- // corresponding text boxes)
- // plus getContext will use this to base context from if set.
- config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- EMPTY_STRING);
- config.setAttribute(
- ICDTLaunchConfigurationConstants.ATTR_PROJECT_BUILD_CONFIG_ID,
- EMPTY_STRING);
- config.setAttribute(
- ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH,
- EMPTY_STRING);
-
- // Set the auto choose build configuration to true for new
- // configurations.
- // Existing configurations created before this setting was introduced
- // will have this disabled.
- config.setAttribute(
- ICDTLaunchConfigurationConstants.ATTR_PROJECT_BUILD_CONFIG_AUTO,
- true);
-
- ICElement cElement = null;
- cElement = getContext(config, getPlatform(config));
- if (cElement != null) {
- initializeCProject(cElement, config);
- initializeProgramName(cElement, config);
- } else {
- // don't want to remember the interim value from before
- config.setMappedResources(null);
- }
- if (wantsTerminalOption()) {
- config.setAttribute(
- ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL,
- ICDTLaunchConfigurationConstants.USE_TERMINAL_DEFAULT);
- }
- }
-
- /**
- * Set the program name attributes on the working copy based on the
- * ICElement
- */
- protected void initializeProgramName(ICElement cElement,
- ILaunchConfigurationWorkingCopy config) {
- boolean renamed = false;
-
- if (!(cElement instanceof IBinary)) {
- cElement = cElement.getCProject();
- }
-
- if (cElement instanceof ICProject) {
- IProject project = cElement.getCProject().getProject();
- String name = project.getName();
- ICProjectDescription projDes = CCorePlugin.getDefault()
- .getProjectDescription(project);
- if (projDes != null) {
- String buildConfigName = projDes.getActiveConfiguration()
- .getName();
- // Bug 234951
- name = NLS.bind(LaunchMessages.CMainTab_Configuration_name,
- name, buildConfigName);
- }
- name = getLaunchConfigurationDialog().generateName(name);
- config.rename(name);
- renamed = true;
- }
-
- IBinary binary = null;
- if (cElement instanceof ICProject) {
- IBinary[] bins = getBinaryFiles((ICProject) cElement);
- if (bins != null && bins.length == 1) {
- binary = bins[0];
- }
- } else if (cElement instanceof IBinary) {
- binary = (IBinary) cElement;
- }
-
- String projectDir = EMPTY_STRING;
- IProject project = null;
- try {
- project = ConfigUtils.getProject(ConfigUtils.getProjectName(config));
- } catch (CoreException e) {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory);
- }
- if(project != null){
- try {
- projectDir = RemoteProxyManager.getInstance().getRemoteProjectLocation(project);
- } catch (CoreException e) {
- setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory);
- }
- }
-
- String path = EMPTY_STRING;
- if (binary != null) {
- path = binary.getResource().getProjectRelativePath().toOSString();
- if (!renamed) {
- String name = binary.getElementName();
- int index = name.lastIndexOf('.');
- if (index > 0) {
- name = name.substring(0, index);
- }
- name = getLaunchConfigurationDialog().generateName(name);
- config.rename(name);
- renamed = true;
- }
- }
- config.setAttribute(
- ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, projectDir + IPath.SEPARATOR + path);
-
- if (!renamed) {
- String name = getLaunchConfigurationDialog().generateName(
- cElement.getCProject().getElementName());
- config.rename(name);
- }
- }
-
- @Override
- public String getId() {
- return TAB_ID;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName()
- */
- @Override
- public String getName() {
- return LaunchMessages.CMainTab_Main;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage()
- */
- @Override
- public Image getImage() {
- return LaunchImages.get(LaunchImages.IMG_VIEW_MAIN_TAB);
- }
+ /**
+ * Tab identifier used for ordering of tabs added using the
+ * <code>org.eclipse.debug.ui.launchConfigurationTabs</code> extension
+ * point.
+ *
+ * @since 6.0
+ */
+ public static final String TAB_ID = "org.eclipse.linuxtools.profiling.launch.RemoteProxyCMainTab"; //$NON-NLS-1$
+
+ private final boolean fWantsTerminalOption;
+ protected Button fTerminalButton;
+
+ protected ResourceSelectorWidget exeSelector;
+
+ protected Text copyFromExeText;
+ protected Button enableCopyFromExeButton;
+ protected ResourceSelectorWidget copyFromExeSelector;
+ protected Label toLabel;
+ protected String fPreviouslyCheckedCopyFromExe;
+ protected boolean fPreviouslyCheckedCopyFromExeIsValid;
+ protected String fPreviouslyCheckedCopyFromExeErrorMsg;
+
+ protected Text workingDirText;
+ protected String fPreviouslyCheckedWorkingDir;
+ protected boolean fPreviouslyCheckedWorkingDirIsValid;
+ protected String fPreviouslyCheckedWorkingDirErrorMsg;
+ protected ResourceSelectorWidget workingDirSelector;
+
+ private final boolean dontCheckProgram;
+ private final boolean fSpecifyCoreFile;
+
+ public static final int WANTS_TERMINAL = 1;
+ public static final int DONT_CHECK_PROGRAM = 2;
+ /** @since 6.0 */
+ public static final int SPECIFY_CORE_FILE = 4;
+
+ public static final String ATTR_REMOTE_WORKING_DIRECTORY_NAME = "REMOTE_WORKING_DIRECTORY_NAME"; //$NON-NLS-1$
+ public static final String ATTR_COPY_FROM_EXE_NAME = "COPY_FROM_EXE_NAME"; //$NON-NLS-1$
+ public static final String ATTR_ENABLE_COPY_FROM_EXE = "ENABLE_COPY_FROM_EXE"; //$NON-NLS-1$
+
+ public RemoteProxyCMainTab() {
+ this(WANTS_TERMINAL);
+ }
+
+ public RemoteProxyCMainTab(boolean terminalOption) {
+ this(terminalOption ? WANTS_TERMINAL : 0);
+ }
+
+ public RemoteProxyCMainTab(int flags) {
+ fWantsTerminalOption = (flags & WANTS_TERMINAL) != 0;
+ dontCheckProgram = (flags & DONT_CHECK_PROGRAM) != 0;
+ fSpecifyCoreFile = (flags & SPECIFY_CORE_FILE) != 0;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.debug.ui.ILaunchConfigurationTab#createControl(org.eclipse
+ * .swt.widgets.Composite)
+ */
+ @Override
+ public void createControl(Composite parent) {
+ Composite comp = new Composite(parent, SWT.NONE);
+ setControl(comp);
+
+ ProfileLaunchPlugin
+ .getDefault()
+ .getWorkbench()
+ .getHelpSystem()
+ .setHelp(
+ getControl(),
+ ICDTLaunchHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_MAIN_TAB);
+
+ GridLayout topLayout = new GridLayout();
+ comp.setLayout(topLayout);
+
+ createVerticalSpacer(comp, 1);
+ createCopyFromExeGroup(comp, 1);
+ createExeFileGroup(comp, 1);
+ createWorkingDirGroup(comp, 1);
+ createProjectGroup(comp, 1);
+ createBuildOptionGroup(comp, 1);
+ createVerticalSpacer(comp, 1);
+ if (fSpecifyCoreFile) {
+ createCoreFileGroup(comp, 1);
+ }
+ if (wantsTerminalOption() /* && ProcessFactory.supportesTerminal() */) {
+ createTerminalOption(comp, 1);
+ }
+ }
+
+ protected boolean wantsTerminalOption() {
+ return fWantsTerminalOption;
+ }
+
+ protected void createTerminalOption(Composite parent, int colSpan) {
+ Composite mainComp = new Composite(parent, SWT.NONE);
+ GridLayout mainLayout = new GridLayout();
+ mainLayout.numColumns = 1;
+ mainLayout.marginHeight = 0;
+ mainLayout.marginWidth = 0;
+ mainComp.setLayout(mainLayout);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = colSpan;
+ mainComp.setLayoutData(gd);
+
+ fTerminalButton = createCheckButton(mainComp,
+ LaunchMessages.CMainTab_UseTerminal);
+ fTerminalButton.addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent evt) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+ fTerminalButton.setEnabled(PTY.isSupported());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(org.eclipse
+ * .debug.core.ILaunchConfiguration)
+ */
+ @Override
+ public void initializeFrom(ILaunchConfiguration config) {
+ filterPlatform = getPlatform(config);
+ updateProjectFromConfig(config);
+ updateCopyFromExeFromConfig(config);
+ updateProgramFromConfig(config);
+ updateWorkingDirFromConfig(config);
+ updateCoreFromConfig(config);
+ updateBuildOptionFromConfig(config);
+ updateTerminalFromConfig(config);
+ }
+
+ protected void updateTerminalFromConfig(ILaunchConfiguration config) {
+ if (fTerminalButton != null) {
+ boolean useTerminal = true;
+ try {
+ useTerminal = config.getAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL,
+ ICDTLaunchConfigurationConstants.USE_TERMINAL_DEFAULT);
+ } catch (CoreException e) {
+ ProfileLaunchPlugin.log(e);
+ }
+ fTerminalButton.setSelection(useTerminal);
+ }
+ }
+
+ /** @since 6.0 */
+ protected void updateCoreFromConfig(ILaunchConfiguration config) {
+ if (fCoreText != null) {
+ String coreName = EMPTY_STRING;
+ try {
+ coreName = config.getAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH,
+ EMPTY_STRING);
+ } catch (CoreException ce) {
+ ProfileLaunchPlugin.log(ce);
+ }
+ fCoreText.setText(coreName);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(org.eclipse
+ * .debug.core.ILaunchConfigurationWorkingCopy)
+ */
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy config) {
+ super.performApply(config);
+ ICProject cProject = this.getCProject();
+ if (cProject != null && cProject.exists()) {
+ config.setMappedResources(new IResource[] { cProject.getProject() });
+ } else {
+ // the user typed in a non-existent project name. Ensure that
+ // won't be suppressed from the dialog. This matches JDT behaviour
+ config.setMappedResources(null);
+ }
+ config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME,
+ fProjText.getText());
+ if (enableCopyFromExeButton != null) {
+ config.setAttribute(
+ ATTR_ENABLE_COPY_FROM_EXE,
+ enableCopyFromExeButton.getSelection());
+ }
+ if (copyFromExeText != null) {
+ config.setAttribute(
+ ATTR_COPY_FROM_EXE_NAME,
+ copyFromExeText.getText());
+ }
+ if (fProgText != null) {
+ config.setAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
+ fProgText.getText());
+ }
+ if (workingDirText != null) {
+ config.setAttribute(
+ ATTR_REMOTE_WORKING_DIRECTORY_NAME,
+ workingDirText.getText());
+ }
+ if (fCoreText != null) {
+ config.setAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH,
+ fCoreText.getText());
+ }
+ if (fTerminalButton != null) {
+ config.setAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL,
+ fTerminalButton.getSelection());
+ }
+ }
+
+ /**
+ * Show a dialog that lists all main types
+ */
+ @Override
+ protected void handleSearchButtonSelected() {
+ if (getCProject() == null) {
+ MessageDialog
+ .openInformation(
+ getShell(),
+ LaunchMessages.CMainTab_Project_required,
+ LaunchMessages.CMainTab_Enter_project_before_searching_for_program);
+ return;
+ }
+
+ ILabelProvider programLabelProvider = new CElementLabelProvider() {
+
+ @Override
+ public String getText(Object element) {
+ if (element instanceof IBinary) {
+ IBinary bin = (IBinary) element;
+ StringBuffer name = new StringBuffer();
+ name.append(bin.getPath().lastSegment());
+ return name.toString();
+ }
+ return super.getText(element);
+ }
+
+ @Override
+ public Image getImage(Object element) {
+ if (!(element instanceof ICElement)) {
+ return super.getImage(element);
+ }
+ ICElement celement = (ICElement) element;
+
+ if (celement.getElementType() == ICElement.C_BINARY) {
+ IBinary belement = (IBinary) celement;
+ if (belement.isExecutable()) {
+ return DebugUITools
+ .getImage(IDebugUIConstants.IMG_ACT_RUN);
+ }
+ }
+
+ return super.getImage(element);
+ }
+ };
+
+ ILabelProvider qualifierLabelProvider = new CElementLabelProvider() {
+
+ @Override
+ public String getText(Object element) {
+ if (element instanceof IBinary) {
+ IBinary bin = (IBinary) element;
+ StringBuffer name = new StringBuffer();
+ name.append(bin.getCPU()
+ + (bin.isLittleEndian() ? "le" : "be")); //$NON-NLS-1$ //$NON-NLS-2$
+ name.append(" - "); //$NON-NLS-1$
+ name.append(bin.getPath().toString());
+ return name.toString();
+ }
+ return super.getText(element);
+ }
+ };
+
+ TwoPaneElementSelector dialog = new TwoPaneElementSelector(getShell(),
+ programLabelProvider, qualifierLabelProvider);
+ dialog.setElements(getBinaryFiles(getCProject()));
+ dialog.setMessage(LaunchMessages.CMainTab_Choose_program_to_run);
+ dialog.setTitle(LaunchMessages.CMainTab_Program_Selection);
+ dialog.setUpperListLabel(LaunchMessages.Launch_common_BinariesColon);
+ dialog.setLowerListLabel(LaunchMessages.Launch_common_QualifierColon);
+ dialog.setMultipleSelection(false);
+ // dialog.set
+ if (dialog.open() == Window.OK) {
+ IBinary binary = (IBinary) dialog.getFirstResult();
+ fProgText.setText(binary.getResource().getProjectRelativePath()
+ .toString());
+ }
+ }
+
+ /**
+ * @since 6.0
+ */
+ @Override
+ protected void createProjectGroup(Composite parent, int colSpan) {
+ Composite projComp = new Composite(parent, SWT.NONE);
+ GridLayout projLayout = new GridLayout();
+ projLayout.numColumns = 2;
+ projLayout.marginHeight = 0;
+ projLayout.marginWidth = 0;
+ projComp.setLayout(projLayout);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = colSpan;
+ projComp.setLayoutData(gd);
+
+ fProjLabel = new Label(projComp, SWT.NONE);
+ fProjLabel.setText(LaunchMessages.CMainTab_ProjectColon);
+ gd = new GridData();
+ gd.horizontalSpan = 2;
+ fProjLabel.setLayoutData(gd);
+
+ fProjText = new Text(projComp, SWT.SINGLE | SWT.BORDER);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ fProjText.setLayoutData(gd);
+ fProjText.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent evt) {
+ // if project changes, invalidate program name cache
+ fPreviouslyCheckedProgram = null;
+
+ updateBuildConfigCombo(""); //$NON-NLS-1$
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ fProjButton = createPushButton(projComp,
+ LaunchMessages.Launch_common_Browse_1, null);
+ fProjButton.addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent evt) {
+ handleProjectButtonSelected();
+ updateLaunchConfigurationDialog();
+ }
+ });
+ }
+
+ @Override
+ protected void updateProgramFromConfig(ILaunchConfiguration config) {
+ super.updateProgramFromConfig(config);
+ if(fProgText.getText().equals(EMPTY_STRING)){
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ if(this.fProjText != null){
+ IProject project = root.getProject(this.fProjText.getText());
+ if(project != null){
+ fProgText.setText(project.getLocationURI().toString());
+ }
+ }
+ }
+ }
+
+ protected void updateCopyFromExeFromConfig(ILaunchConfiguration config) {
+ if (copyFromExeText != null) {
+ String workingDir = EMPTY_STRING;
+ try {
+ workingDir = config.getAttribute(ATTR_COPY_FROM_EXE_NAME, EMPTY_STRING);
+ } catch (CoreException ce) {
+ ProfileLaunchPlugin.log(ce);
+ }
+ copyFromExeText.setText(workingDir);
+ }
+ if (enableCopyFromExeButton != null) {
+ boolean enableCopyFromExe = false;
+ try {
+ enableCopyFromExe = config.getAttribute(ATTR_ENABLE_COPY_FROM_EXE, false);
+ } catch (CoreException ce) {
+ ProfileLaunchPlugin.log(ce);
+ }
+ setEnableCopyFromSection(enableCopyFromExe);
+ }
+ }
+
+ private void setEnableCopyFromSection(boolean enable) {
+ // setSelection will be redundant if called from a listener
+ enableCopyFromExeButton.setSelection(enable);
+ copyFromExeSelector.setEnabled(enable);
+ toLabel.setEnabled(enable);
+ }
+
+ protected void createCopyFromExeGroup(Composite parent, int colSpan) {
+ Composite mainComp = new Composite(parent, SWT.NONE);
+ GridLayout mainLayout = new GridLayout();
+ mainLayout.numColumns = 1;
+ mainLayout.marginHeight = 0;
+ mainLayout.marginWidth = 0;
+ mainComp.setLayout(mainLayout);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = colSpan;
+ mainComp.setLayoutData(gd);
+
+ enableCopyFromExeButton = createCheckButton(mainComp, "Copy C/C++ executable from:");
+ copyFromExeSelector = new ResourceSelectorWidget(mainComp,
+ ResourceSelectorWidget.ResourceType.FILE,
+ 2, "C/C++ executable origin", null); //$NON-NLS-1$
+ toLabel = new Label(mainComp, SWT.NONE);
+ toLabel.setText("To:");
+
+ // The "copy from" check box is initially off, the selector and "To:" label
+ // are disabled.
+ copyFromExeSelector.setEnabled(false);
+ enableCopyFromExeButton.setSelection(false);
+
+ toLabel.setEnabled(false);
+
+ enableCopyFromExeButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ boolean copyEnabled = enableCopyFromExeButton.getSelection();
+ setEnableCopyFromSection(copyEnabled);
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ copyFromExeText = copyFromExeSelector.getURIText();
+ copyFromExeText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent evt) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+ }
+
+
+ protected void createExeFileGroup(Composite parent, int colSpan) {
+ Composite mainComp = new Composite(parent, SWT.NONE);
+ GridLayout mainLayout = new GridLayout();
+ mainLayout.numColumns = 1;
+ mainLayout.marginHeight = 0;
+ mainLayout.marginWidth = 0;
+ mainComp.setLayout(mainLayout);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = colSpan;
+ mainComp.setLayoutData(gd);
+ exeSelector = new ResourceSelectorWidget(mainComp,
+ ResourceSelectorWidget.ResourceType.FILE,
+ 2, "C/C++ executable", null); //$NON-NLS-1$
+ fProgText = exeSelector.getURIText();
+ fProgText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent evt) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+ }
+
+ protected void updateWorkingDirFromConfig(ILaunchConfiguration config) {
+ if (workingDirText != null) {
+ String projectDir = EMPTY_STRING;
+ try {
+ projectDir = config.getAttribute(ATTR_REMOTE_WORKING_DIRECTORY_NAME, EMPTY_STRING);
+ } catch (CoreException ce) {
+ ProfileLaunchPlugin.log(ce);
+ }
+
+ if (projectDir.equals(EMPTY_STRING)){
+ if(this.fProjText != null){
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ IProject project = root.getProject(this.fProjText.getText());
+ try {
+ projectDir = RemoteProxyManager.getInstance().getRemoteProjectLocation(project);
+ } catch (CoreException e) {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory);
+ }
+ }
+ }
+ workingDirText.setText(projectDir);
+ }
+ }
+
+ protected void createWorkingDirGroup(Composite parent, int colSpan) {
+ Composite mainComp = new Composite(parent, SWT.NONE);
+ GridLayout mainLayout = new GridLayout();
+ mainLayout.numColumns = 1;
+ mainLayout.marginHeight = 0;
+ mainLayout.marginWidth = 0;
+ mainComp.setLayout(mainLayout);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = colSpan;
+ mainComp.setLayoutData(gd);
+ ResourceSelectorWidget workingDirSelector = new ResourceSelectorWidget(mainComp,
+ ResourceSelectorWidget.ResourceType.DIRECTORY,
+ 2, "Working directory", null); //$NON-NLS-1$
+ workingDirText = workingDirSelector.getURIText();
+ workingDirText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent evt) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+ }
+
+ private boolean checkCopyFromExe(ILaunchConfiguration config, IProject project) {
+ if (!enableCopyFromExeButton.getSelection()) {
+ setErrorMessage(null);
+ return true;
+ }
+
+ String name = copyFromExeText.getText().trim();
+ if (name.length() == 0) {
+ setErrorMessage(ProxyLaunchMessages.copy_from_exe_is_not_specified);
+ return false;
+ }
+ // Avoid constantly checking the binary if nothing relevant has
+ // changed (binary or project name). See bug 277663.
+ if (name.equals(fPreviouslyCheckedCopyFromExe)) {
+ if (fPreviouslyCheckedCopyFromExeErrorMsg != null) {
+ setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg);
+ }
+ return fPreviouslyCheckedCopyFromExeIsValid;
+ }
+ fPreviouslyCheckedCopyFromExe = name;
+ fPreviouslyCheckedCopyFromExeIsValid = true; // we'll flip this below if
+ // not true
+ fPreviouslyCheckedCopyFromExeErrorMsg = null; // we'll set this below if
+ // there's an error
+ IPath exePath;
+ URI exeURI = null;
+ boolean passed = false;
+
+ try {
+ exeURI = new URI(name);
+ String exePathStr = exeURI.getPath();
+ if (exePathStr == null) {
+ setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.uri_of_copy_from_exe_is_invalid);
+ fPreviouslyCheckedCopyFromExeIsValid = false;
+ return false;
+ }
+ exePath = Path.fromOSString(exeURI.getPath());
+ if (!exePath.isAbsolute() && exeURI != null && !exeURI.isAbsolute()) {
+ URI projectURI = project.getLocationURI();
+ exeURI = new URI(projectURI.getScheme(),
+ projectURI.getAuthority(), projectURI.getRawPath() + '/'
+ + exePath.toString(), EMPTY_STRING);
+ }
+ if (exeURI != null) {
+ passed = true;
+ }
+ } catch (URISyntaxException e) {
+ setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.uri_of_copy_from_exe_is_invalid);
+ fPreviouslyCheckedCopyFromExeIsValid = false;
+ return false;
+ }
+
+ if (!passed) {
+ setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.copy_from_exe_does_not_exist);
+ fPreviouslyCheckedCopyFromExeIsValid = false;
+ return false;
+ }
+
+ passed = false;
+ try {
+ IRemoteFileProxy exeFileProxy;
+ exeFileProxy = RemoteProxyManager.getInstance().getFileProxy(exeURI);
+ if (exeFileProxy != null) {
+ String exeFilePath = exeURI.getPath();
+ IFileStore exeFS = exeFileProxy
+ .getResource(exeFilePath);
+ if (exeFS != null) {
+ IFileInfo exeFI = exeFS.fetchInfo();
+ if (exeFI != null) {
+ if (exeFI.exists()) {
+ if (exeFI.getAttribute(EFS.ATTRIBUTE_EXECUTABLE) &&
+ !exeFI.isDirectory()) {
+ passed = true;
+ } else {
+ setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.copy_from_exe_does_not_have_execution_rights);
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.copy_from_exe_does_not_exist);
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.error_accessing_copy_from_exe);
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.error_accessing_copy_from_exe);
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.scheme_error_in_copy_from_exe);
+ }
+ } catch (CoreException e) {
+ setErrorMessage(fPreviouslyCheckedCopyFromExeErrorMsg = ProxyLaunchMessages.connection_of_copy_from_exe_cannot_be_opened);
+ }
+ if (!passed) {
+ fPreviouslyCheckedCopyFromExeIsValid = false;
+ return false;
+ }
+ setErrorMessage(null);
+ return true;
+ }
+
+
+ private boolean checkProgram(ILaunchConfiguration config, IProject project) {
+ String name = fProgText.getText().trim();
+ if (name.length() == 0) {
+ setErrorMessage(ProxyLaunchMessages.executable_is_not_specified);
+ return false;
+ }
+ // Avoid constantly checking the binary if nothing relevant has
+ // changed (binary or project name). See bug 277663.
+ if (name.equals(fPreviouslyCheckedProgram)) {
+ if (fPreviouslyCheckedProgramErrorMsg != null) {
+ setErrorMessage(fPreviouslyCheckedProgramErrorMsg);
+ }
+ return fPreviouslyCheckedProgramIsValid;
+ }
+ fPreviouslyCheckedProgram = name;
+ fPreviouslyCheckedProgramIsValid = true; // we'll flip this below if
+ // not true
+ fPreviouslyCheckedProgramErrorMsg = null; // we'll set this below if
+ // there's an error
+ IPath exePath;
+ URI exeURI = null;
+ boolean passed = false;
+
+ try {
+ exeURI = new URI(name);
+ String exePathStr = exeURI.getPath();
+ if (exePathStr == null) {
+ setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.uri_of_executable_is_invalid);
+ fPreviouslyCheckedProgramIsValid = false;
+ return false;
+ }
+
+ exePath = Path.fromOSString(exeURI.getPath());
+ if (!exePath.isAbsolute() && exeURI != null && !exeURI.isAbsolute()) {
+ URI projectURI = project.getLocationURI();
+ exeURI = new URI(projectURI.getScheme(),
+ projectURI.getAuthority(), projectURI.getRawPath() + '/'
+ + exePath.toString(), EMPTY_STRING);
+ }
+ if (exeURI != null) {
+ passed = true;
+ }
+ } catch (URISyntaxException e) {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.uri_of_executable_is_invalid);
+ fPreviouslyCheckedProgramIsValid = false;
+ return false;
+ }
+
+ if (!passed) {
+ setErrorMessage(fPreviouslyCheckedProgramErrorMsg = LaunchMessages.CMainTab_Program_does_not_exist);
+ fPreviouslyCheckedProgramIsValid = false;
+ return false;
+ }
+
+ passed = false;
+ try {
+ IRemoteFileProxy exeFileProxy;
+ exeFileProxy = RemoteProxyManager.getInstance().getFileProxy(exeURI);
+ if (exeFileProxy != null) {
+ String exeFilePath = exeURI.getPath();
+ IFileStore exeFS = exeFileProxy
+ .getResource(exeFilePath);
+ if (exeFS != null) {
+ IFileInfo exeFI = exeFS.fetchInfo();
+ if (exeFI != null) {
+ if (dontCheckProgram || enableCopyFromExeButton.getSelection()) {
+ // The program may not exist yet if we are copying it.
+ passed = true;
+ } else {
+ if (exeFI.exists()) {
+ if (exeFI.getAttribute(EFS.ATTRIBUTE_EXECUTABLE) &&
+ !exeFI.isDirectory()) {
+ passed = true;
+ } else {
+ setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.executable_does_not_have_execution_rights);
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.executable_does_not_exist);
+ }
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.error_accessing_executable);
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.error_accessing_executable);
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.scheme_error_in_executable);
+ }
+ } catch (CoreException e) {
+ setErrorMessage(fPreviouslyCheckedProgramErrorMsg = ProxyLaunchMessages.connection_of_executable_cannot_be_opened);
+ }
+ if (!passed) {
+ fPreviouslyCheckedProgramIsValid = false;
+ return false;
+ }
+ setErrorMessage(null);
+ return true;
+ }
+
+ private boolean checkWorkingDir(ILaunchConfiguration config, IProject project) {
+ String name = workingDirText.getText().trim();
+ if (name.length() == 0) {
+ return true; // an empty working directory means, "use the default"
+ }
+ // Avoid constantly checking the working dir if nothing relevant has
+ // changed (project).
+ if (name.equals(fPreviouslyCheckedWorkingDir)) {
+ if (fPreviouslyCheckedWorkingDirErrorMsg != null) {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg);
+ }
+ return fPreviouslyCheckedWorkingDirIsValid;
+ }
+ fPreviouslyCheckedWorkingDir = name;
+ fPreviouslyCheckedWorkingDirIsValid = true; // we'll flip this below if
+ // not true
+ fPreviouslyCheckedWorkingDirErrorMsg = null; // we'll set this below if
+ // there's an error
+ IPath wdPath;
+ URI wdURI = null;
+ boolean passed = false;
+
+ try {
+ wdURI = new URI(name);
+ String wdPathStr = wdURI.getPath();
+ if (wdPathStr == null) {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.uri_of_working_directory_is_invalid);
+ fPreviouslyCheckedWorkingDirIsValid = false;
+ return false;
+ }
+
+ wdPath = Path.fromOSString(wdURI.getPath());
+ if (!wdPath.isAbsolute() && wdURI != null && !wdURI.isAbsolute()) {
+ URI projectURI = project.getLocationURI();
+ wdURI = new URI(projectURI.getScheme(),
+ projectURI.getAuthority(), projectURI.getRawPath() + '/'
+ + wdPath.toString(), EMPTY_STRING);
+ }
+ if (wdURI != null) {
+ passed = true;
+ }
+ } catch (URISyntaxException e) {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.uri_of_working_directory_is_invalid);
+ fPreviouslyCheckedWorkingDirIsValid = false;
+ return false;
+ }
+
+ if (!passed) {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.working_directory_does_not_exist);
+ fPreviouslyCheckedWorkingDirIsValid = false;
+ return false;
+ }
+
+ passed = false;
+ IRemoteFileProxy wdFileProxy;
+ try {
+ wdFileProxy = RemoteProxyManager.getInstance().getFileProxy(wdURI);
+ if (wdFileProxy != null) {
+ IFileStore wdFS = wdFileProxy
+ .getResource(wdURI.getPath());
+ if (wdFS != null) {
+ IFileInfo wdFI = wdFS.fetchInfo();
+ if (wdFI != null) {
+ if (wdFI.exists()) {
+ if (wdFI.isDirectory()) {
+ passed = true;
+ } else {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.working_directory_is_not_a_directory);
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.working_directory_does_not_exist);
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory);
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory);
+ }
+ } else {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.scheme_error_in_working_directory);
+ }
+ } catch (CoreException e) {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.connection_of_working_directory_cannot_be_opened);
+ }
+
+ if (!passed) {
+ fPreviouslyCheckedWorkingDirIsValid = false;
+ return false;
+ }
+ setErrorMessage(null);
+ return true;
+ }
+
+ /**
+ * Compare two strings as equal or not, but allow for one or both of
+ * the strings to be null. If both are null, they are treated as equal.
+ * If one is null and the other isn't, they are considered unequal. If
+ * they are both non-null, the result is the same as the
+ * String.equals() method.
+ * @param s1 First string to compare.
+ * @param s2 Second string to compare.
+ * @return Return true if equal, false otherwise.
+ */
+ private static boolean equal(String s1, String s2) {
+ if (s1 == null && s2 == null)
+ return true;
+ if (s1 == null || s2 == null)
+ return false;
+ return s1.equals(s2);
+ }
+
+ /**
+ * Check to see if the Executable's location has the same scheme and host name as
+ * the working directory. If not, this is an error.
+ * @param config
+ * @param project
+ * @return true if they are compatible, and false if not compatible.
+ */
+ private boolean checkCompatibility(ILaunchConfiguration config, IProject project) {
+ String wdName = workingDirText.getText().trim();
+ String progName = fProgText.getText().trim();
+ URI wdURI;
+ URI progURI;
+
+ try {
+ wdURI = new URI(wdName);
+ progURI = new URI(progName);
+ } catch (URISyntaxException e) {
+ // this will have been dealt with by previous checks of the Program and Working
+ // directory
+ System.err.println("internal error. URI syntax error in working directory or program");
+ return false;
+ }
+ {
+ String wdScheme = wdURI.getScheme();
+ String progScheme = progURI.getScheme();
+ if (wdScheme == null && progScheme == null) {
+ // local filesystem. No further tests are needed.
+ setErrorMessage(null);
+ return true;
+
+ }
+ if (!equal(wdScheme, progScheme)) {
+ setErrorMessage(ProxyLaunchMessages.scheme_of_working_directory_and_program_do_not_match);
+ return false;
+ }
+ }
+ {
+ String wdAuth = wdURI.getAuthority();
+ String progAuth = progURI.getAuthority();
+ if (!equal(wdAuth, progAuth)) {
+ setErrorMessage(ProxyLaunchMessages.connection_of_working_directory_and_program_do_not_match);
+ return false;
+ }
+ }
+ {
+ String wdQuery = wdURI.getQuery();
+ String progQuery = progURI.getQuery();
+ if (!equal(wdQuery, progQuery)) {
+ setErrorMessage(ProxyLaunchMessages.connection_of_working_directory_and_program_do_not_match);
+ return false;
+ }
+ }
+ setErrorMessage(null);
+ return true;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.debug.ui.ILaunchConfigurationTab#isValid(org.eclipse.debug
+ * .core.ILaunchConfiguration)
+ */
+ @Override
+ public boolean isValid(ILaunchConfiguration config) {
+ IProject project;
+
+ this.setErrorMessage(null);
+ setMessage(null);
+
+ String name = fProjText.getText().trim();
+ if (name.length() == 0) {
+ setErrorMessage(LaunchMessages.CMainTab_Project_not_specified);
+ return false;
+ }
+ project = ResourcesPlugin.getWorkspace().getRoot().getProject(name);
+ if (!project.exists()) {
+ setErrorMessage(LaunchMessages.Launch_common_Project_does_not_exist);
+ return false;
+ }
+ if (!project.isOpen()) {
+ setErrorMessage(LaunchMessages.CMainTab_Project_must_be_opened);
+ return false;
+ }
+
+ if (!checkCopyFromExe(config, project))
+ return false;
+
+ if (!checkProgram(config, project))
+ return false;
+
+ if (!checkWorkingDir(config, project))
+ return false;
+
+ if (!checkCompatibility(config, project))
+ return false;
+
+ if (fCoreText != null) {
+ String coreName = fCoreText.getText().trim();
+ // We accept an empty string. This should trigger a prompt to the
+ // user
+ // This allows to re-use the launch, with a different core file.
+ if (!coreName.equals(EMPTY_STRING)) {
+ if (coreName.equals(".") || coreName.equals("..")) { //$NON-NLS-1$ //$NON-NLS-2$
+ setErrorMessage(LaunchMessages.CMainTab_Core_does_not_exist);
+ return false;
+ }
+ IPath corePath = new Path(coreName);
+ if (!corePath.toFile().exists()) {
+ setErrorMessage(LaunchMessages.CMainTab_Core_does_not_exist);
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(org.eclipse.
+ * debug.core.ILaunchConfigurationWorkingCopy)
+ */
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy config) {
+ // We set empty attributes for project & program so that when one config
+ // is
+ // compared to another, the existence of empty attributes doesn't cause
+ // an
+ // incorrect result (the performApply() method can result in empty
+ // values
+ // for these attributes being set on a config if there is nothing in the
+ // corresponding text boxes)
+ // plus getContext will use this to base context from if set.
+ config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME,
+ EMPTY_STRING);
+ config.setAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_PROJECT_BUILD_CONFIG_ID,
+ EMPTY_STRING);
+ config.setAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH,
+ EMPTY_STRING);
+
+ // Set the auto choose build configuration to true for new
+ // configurations.
+ // Existing configurations created before this setting was introduced
+ // will have this disabled.
+ config.setAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_PROJECT_BUILD_CONFIG_AUTO,
+ true);
+
+ ICElement cElement = null;
+ cElement = getContext(config, getPlatform(config));
+ if (cElement != null) {
+ initializeCProject(cElement, config);
+ initializeProgramName(cElement, config);
+ } else {
+ // don't want to remember the interim value from before
+ config.setMappedResources(null);
+ }
+ if (wantsTerminalOption()) {
+ config.setAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL,
+ ICDTLaunchConfigurationConstants.USE_TERMINAL_DEFAULT);
+ }
+ }
+
+ /**
+ * Set the program name attributes on the working copy based on the
+ * ICElement
+ */
+ protected void initializeProgramName(ICElement cElement,
+ ILaunchConfigurationWorkingCopy config) {
+ boolean renamed = false;
+
+ if (!(cElement instanceof IBinary)) {
+ cElement = cElement.getCProject();
+ }
+
+ if (cElement instanceof ICProject) {
+ IProject project = cElement.getCProject().getProject();
+ String name = project.getName();
+ ICProjectDescription projDes = CCorePlugin.getDefault()
+ .getProjectDescription(project);
+ if (projDes != null) {
+ String buildConfigName = projDes.getActiveConfiguration()
+ .getName();
+ // Bug 234951
+ name = NLS.bind(LaunchMessages.CMainTab_Configuration_name,
+ name, buildConfigName);
+ }
+ name = getLaunchConfigurationDialog().generateName(name);
+ config.rename(name);
+ renamed = true;
+ }
+
+ IBinary binary = null;
+ if (cElement instanceof ICProject) {
+ IBinary[] bins = getBinaryFiles((ICProject) cElement);
+ if (bins != null && bins.length == 1) {
+ binary = bins[0];
+ }
+ } else if (cElement instanceof IBinary) {
+ binary = (IBinary) cElement;
+ }
+
+ String projectDir = EMPTY_STRING;
+ IProject project = null;
+ try {
+ project = ConfigUtils.getProject(ConfigUtils.getProjectName(config));
+ } catch (CoreException e) {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory);
+ }
+ if(project != null){
+ try {
+ projectDir = RemoteProxyManager.getInstance().getRemoteProjectLocation(project);
+ } catch (CoreException e) {
+ setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory);
+ }
+ }
+
+ String path = EMPTY_STRING;
+ if (binary != null) {
+ path = binary.getResource().getProjectRelativePath().toOSString();
+ if (!renamed) {
+ String name = binary.getElementName();
+ int index = name.lastIndexOf('.');
+ if (index > 0) {
+ name = name.substring(0, index);
+ }
+ name = getLaunchConfigurationDialog().generateName(name);
+ config.rename(name);
+ renamed = true;
+ }
+ }
+ config.setAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, projectDir + IPath.SEPARATOR + path);
+
+ if (!renamed) {
+ String name = getLaunchConfigurationDialog().generateName(
+ cElement.getCProject().getElementName());
+ config.rename(name);
+ }
+ }
+
+ @Override
+ public String getId() {
+ return TAB_ID;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName()
+ */
+ @Override
+ public String getName() {
+ return LaunchMessages.CMainTab_Main;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage()
+ */
+ @Override
+ public Image getImage() {
+ return LaunchImages.get(LaunchImages.IMG_VIEW_MAIN_TAB);
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyManager.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyManager.java
index 1784129c3c..11c58c2f23 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyManager.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyManager.java
@@ -28,155 +28,155 @@ import org.eclipse.linuxtools.internal.profiling.launch.ProfileLaunchPlugin;
public class RemoteProxyManager implements IRemoteProxyManager {
- private static final String EXT_ATTR_CLASS = "class"; //$NON-NLS-1$
- /**
- * @since 2.1
- */
- protected static final String LOCALSCHEME = "file"; //$NON-NLS-1$
-
- private static RemoteProxyManager manager;
- private LocalFileProxy lfp;
- /**
- * @since 2.1
- */
- protected RemoteProxyNatureMapping mapping = new RemoteProxyNatureMapping();
- private Map<String, IRemoteProxyManager> remoteManagers = new HashMap<>();
-
- /**
- * @since 2.1
- */
- protected RemoteProxyManager() {
- // do nothing
- }
-
- public static RemoteProxyManager getInstance() {
- if (manager == null)
- manager = new RemoteProxyManager();
- return manager;
- }
-
- LocalFileProxy getLocalFileProxy(URI uri) {
- if (lfp == null)
- lfp = new LocalFileProxy(uri);
- return lfp;
- }
- /**
- * @since 2.1
- */
- protected IRemoteProxyManager getRemoteManager(String schemeId) throws CoreException {
- IRemoteProxyManager remoteManager = remoteManagers.get(schemeId);
- if (remoteManager == null) {
- IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(ProfileLaunchPlugin.PLUGIN_ID, IRemoteProxyManager.EXTENSION_POINT_ID);
- IConfigurationElement[] infos = extensionPoint.getConfigurationElements();
- for(int i = 0; i < infos.length; i++) {
- IConfigurationElement configurationElement = infos[i];
- if (configurationElement.getName().equals(IRemoteProxyManager.MANAGER_NAME)) {
- if (configurationElement.getAttribute(IRemoteProxyManager.SCHEME_ID).equals(schemeId)) {
- Object obj = configurationElement.createExecutableExtension(EXT_ATTR_CLASS);
- if (obj instanceof IRemoteProxyManager) {
- remoteManager = (IRemoteProxyManager)obj;
- remoteManagers.put(schemeId, remoteManager);
- break;
- }
- }
- }
- }
- }
- return remoteManager;
- }
-
- @Override
- public IRemoteFileProxy getFileProxy(URI uri) throws CoreException {
- String scheme = uri.getScheme();
- if (scheme != null && !scheme.equals(LOCALSCHEME)){
- IRemoteProxyManager manager = getRemoteManager(scheme);
- if (manager != null)
- return manager.getFileProxy(uri);
- else
- throw new CoreException(new Status(IStatus.ERROR, ProfileLaunchPlugin.PLUGIN_ID,
- IStatus.OK, Messages.RemoteProxyManager_unrecognized_scheme + scheme, null));
- }
- return getLocalFileProxy(uri);
- }
-
- @Override
- public IRemoteFileProxy getFileProxy(IProject project) throws CoreException {
- if (project == null) {
- return getLocalFileProxy(null);
- }
- String scheme = mapping.getSchemeFromNature(project);
- if (scheme!=null) {
- IRemoteProxyManager manager = getRemoteManager(scheme);
- if (manager != null)
- return manager.getFileProxy(project);
- }
- URI projectURI = project.getLocationURI();
- return getFileProxy(projectURI);
- }
-
- @Override
- public IRemoteCommandLauncher getLauncher(URI uri) throws CoreException {
- String scheme = uri.getScheme();
- if (scheme != null && !scheme.equals(LOCALSCHEME)){
- IRemoteProxyManager manager = getRemoteManager(scheme);
- if (manager != null)
- return manager.getLauncher(uri);
- }
- return new LocalLauncher();
- }
-
- @Override
- public IRemoteCommandLauncher getLauncher(IProject project) throws CoreException {
- if (project == null){
- return new LocalLauncher();
- }
- String scheme = mapping.getSchemeFromNature(project);
- if (scheme!=null) {
- IRemoteProxyManager manager = getRemoteManager(scheme);
- return manager.getLauncher(project);
- }
- URI projectURI = project.getLocationURI();
- return getLauncher(projectURI);
- }
-
- @Override
- public String getOS(URI uri) throws CoreException {
- String scheme = uri.getScheme();
- if (scheme != null && !scheme.equals(LOCALSCHEME)){
- IRemoteProxyManager manager = getRemoteManager(scheme);
- if (manager != null)
- return manager.getOS(uri);
- }
- return Platform.getOS();
- }
-
- @Override
- public String getOS(IProject project) throws CoreException {
- String scheme = mapping.getSchemeFromNature(project);
- if (scheme!=null) {
- IRemoteProxyManager manager = getRemoteManager(scheme);
- return manager.getOS(project);
- }
- URI projectURI = project.getLocationURI();
- return getOS(projectURI);
- }
-
- /**
- * This method gets the proper remote project location
- * of pure remote and sync projects. Synchronized projects
- * have a cached path and a remote one, and this method
- * returns the remote one.
- * @return string containing the project location
- * @since 2.2
- */
- public String getRemoteProjectLocation(IProject project) throws CoreException {
- if(project != null){
- IRemoteFileProxy remoteFileProxy = null;
- remoteFileProxy = getFileProxy(project);
- URI workingDirURI = remoteFileProxy.getWorkingDir();
- return workingDirURI.toString();
- }
- return null;
- }
+ private static final String EXT_ATTR_CLASS = "class"; //$NON-NLS-1$
+ /**
+ * @since 2.1
+ */
+ protected static final String LOCALSCHEME = "file"; //$NON-NLS-1$
+
+ private static RemoteProxyManager manager;
+ private LocalFileProxy lfp;
+ /**
+ * @since 2.1
+ */
+ protected RemoteProxyNatureMapping mapping = new RemoteProxyNatureMapping();
+ private Map<String, IRemoteProxyManager> remoteManagers = new HashMap<>();
+
+ /**
+ * @since 2.1
+ */
+ protected RemoteProxyManager() {
+ // do nothing
+ }
+
+ public static RemoteProxyManager getInstance() {
+ if (manager == null)
+ manager = new RemoteProxyManager();
+ return manager;
+ }
+
+ LocalFileProxy getLocalFileProxy(URI uri) {
+ if (lfp == null)
+ lfp = new LocalFileProxy(uri);
+ return lfp;
+ }
+ /**
+ * @since 2.1
+ */
+ protected IRemoteProxyManager getRemoteManager(String schemeId) throws CoreException {
+ IRemoteProxyManager remoteManager = remoteManagers.get(schemeId);
+ if (remoteManager == null) {
+ IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(ProfileLaunchPlugin.PLUGIN_ID, IRemoteProxyManager.EXTENSION_POINT_ID);
+ IConfigurationElement[] infos = extensionPoint.getConfigurationElements();
+ for(int i = 0; i < infos.length; i++) {
+ IConfigurationElement configurationElement = infos[i];
+ if (configurationElement.getName().equals(IRemoteProxyManager.MANAGER_NAME)) {
+ if (configurationElement.getAttribute(IRemoteProxyManager.SCHEME_ID).equals(schemeId)) {
+ Object obj = configurationElement.createExecutableExtension(EXT_ATTR_CLASS);
+ if (obj instanceof IRemoteProxyManager) {
+ remoteManager = (IRemoteProxyManager)obj;
+ remoteManagers.put(schemeId, remoteManager);
+ break;
+ }
+ }
+ }
+ }
+ }
+ return remoteManager;
+ }
+
+ @Override
+ public IRemoteFileProxy getFileProxy(URI uri) throws CoreException {
+ String scheme = uri.getScheme();
+ if (scheme != null && !scheme.equals(LOCALSCHEME)){
+ IRemoteProxyManager manager = getRemoteManager(scheme);
+ if (manager != null)
+ return manager.getFileProxy(uri);
+ else
+ throw new CoreException(new Status(IStatus.ERROR, ProfileLaunchPlugin.PLUGIN_ID,
+ IStatus.OK, Messages.RemoteProxyManager_unrecognized_scheme + scheme, null));
+ }
+ return getLocalFileProxy(uri);
+ }
+
+ @Override
+ public IRemoteFileProxy getFileProxy(IProject project) throws CoreException {
+ if (project == null) {
+ return getLocalFileProxy(null);
+ }
+ String scheme = mapping.getSchemeFromNature(project);
+ if (scheme!=null) {
+ IRemoteProxyManager manager = getRemoteManager(scheme);
+ if (manager != null)
+ return manager.getFileProxy(project);
+ }
+ URI projectURI = project.getLocationURI();
+ return getFileProxy(projectURI);
+ }
+
+ @Override
+ public IRemoteCommandLauncher getLauncher(URI uri) throws CoreException {
+ String scheme = uri.getScheme();
+ if (scheme != null && !scheme.equals(LOCALSCHEME)){
+ IRemoteProxyManager manager = getRemoteManager(scheme);
+ if (manager != null)
+ return manager.getLauncher(uri);
+ }
+ return new LocalLauncher();
+ }
+
+ @Override
+ public IRemoteCommandLauncher getLauncher(IProject project) throws CoreException {
+ if (project == null){
+ return new LocalLauncher();
+ }
+ String scheme = mapping.getSchemeFromNature(project);
+ if (scheme!=null) {
+ IRemoteProxyManager manager = getRemoteManager(scheme);
+ return manager.getLauncher(project);
+ }
+ URI projectURI = project.getLocationURI();
+ return getLauncher(projectURI);
+ }
+
+ @Override
+ public String getOS(URI uri) throws CoreException {
+ String scheme = uri.getScheme();
+ if (scheme != null && !scheme.equals(LOCALSCHEME)){
+ IRemoteProxyManager manager = getRemoteManager(scheme);
+ if (manager != null)
+ return manager.getOS(uri);
+ }
+ return Platform.getOS();
+ }
+
+ @Override
+ public String getOS(IProject project) throws CoreException {
+ String scheme = mapping.getSchemeFromNature(project);
+ if (scheme!=null) {
+ IRemoteProxyManager manager = getRemoteManager(scheme);
+ return manager.getOS(project);
+ }
+ URI projectURI = project.getLocationURI();
+ return getOS(projectURI);
+ }
+
+ /**
+ * This method gets the proper remote project location
+ * of pure remote and sync projects. Synchronized projects
+ * have a cached path and a remote one, and this method
+ * returns the remote one.
+ * @return string containing the project location
+ * @since 2.2
+ */
+ public String getRemoteProjectLocation(IProject project) throws CoreException {
+ if(project != null){
+ IRemoteFileProxy remoteFileProxy = null;
+ remoteFileProxy = getFileProxy(project);
+ URI workingDirURI = remoteFileProxy.getWorkingDir();
+ return workingDirURI.toString();
+ }
+ return null;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyNatureMapping.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyNatureMapping.java
index a9b9bd1ee6..ce086808a8 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyNatureMapping.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyNatureMapping.java
@@ -24,28 +24,28 @@ import org.eclipse.linuxtools.internal.profiling.launch.ProfileLaunchPlugin;
*/
public class RemoteProxyNatureMapping {
- private static final String EXTENSION_POINT_ID = "RemoteProxyNatureMapping"; //$NON-NLS-1$
- private static final String MANAGER_NAME = "mapping"; //$NON-NLS-1$
- private static final String NATURE_ID = "nature"; //$NON-NLS-1$
- private static final String SCHEME_ID = "schema"; //$NON-NLS-1$
+ private static final String EXTENSION_POINT_ID = "RemoteProxyNatureMapping"; //$NON-NLS-1$
+ private static final String MANAGER_NAME = "mapping"; //$NON-NLS-1$
+ private static final String NATURE_ID = "nature"; //$NON-NLS-1$
+ private static final String SCHEME_ID = "schema"; //$NON-NLS-1$
- public String getSchemeFromNature(IProject project) throws CoreException {
+ public String getSchemeFromNature(IProject project) throws CoreException {
- IProjectDescription description = project.getDescription();
- String[] natures = description.getNatureIds();
+ IProjectDescription description = project.getDescription();
+ String[] natures = description.getNatureIds();
- IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(ProfileLaunchPlugin.PLUGIN_ID, EXTENSION_POINT_ID);
- IConfigurationElement[] infos = extensionPoint.getConfigurationElements();
- for(int i = 0; i < infos.length; i++) {
- IConfigurationElement configurationElement = infos[i];
- if (configurationElement.getName().equals(MANAGER_NAME)) {
- for (int j=0;j<natures.length;j++) {
- if (configurationElement.getAttribute(NATURE_ID).equals(natures[j])) {
- return configurationElement.getAttribute(SCHEME_ID);
- }
- }
- }
- }
- return null;
- }
+ IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(ProfileLaunchPlugin.PLUGIN_ID, EXTENSION_POINT_ID);
+ IConfigurationElement[] infos = extensionPoint.getConfigurationElements();
+ for(int i = 0; i < infos.length; i++) {
+ IConfigurationElement configurationElement = infos[i];
+ if (configurationElement.getName().equals(MANAGER_NAME)) {
+ for (int j=0;j<natures.length;j++) {
+ if (configurationElement.getAttribute(NATURE_ID).equals(natures[j])) {
+ return configurationElement.getAttribute(SCHEME_ID);
+ }
+ }
+ }
+ }
+ return null;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyProfileLaunchConfigurationTabGroup.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyProfileLaunchConfigurationTabGroup.java
index db97f23337..874cbb97aa 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyProfileLaunchConfigurationTabGroup.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/RemoteProxyProfileLaunchConfigurationTabGroup.java
@@ -8,7 +8,7 @@
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
* Rafael Teixeira <rafaelmt@linux.vnet.ibm.com> - Switched to
- * RemoteProxyCMainTab
+ * RemoteProxyCMainTab
*******************************************************************************/
package org.eclipse.linuxtools.profiling.launch;
@@ -29,21 +29,21 @@ import org.eclipse.debug.ui.sourcelookup.SourceLookupTab;
*/
public abstract class RemoteProxyProfileLaunchConfigurationTabGroup extends AbstractLaunchConfigurationTabGroup {
- @Override
- public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
- ArrayList<AbstractLaunchConfigurationTab> tabs = new ArrayList<>();
- tabs.add(new RemoteProxyCMainTab());
- tabs.add(new CArgumentsTab());
+ @Override
+ public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
+ ArrayList<AbstractLaunchConfigurationTab> tabs = new ArrayList<>();
+ tabs.add(new RemoteProxyCMainTab());
+ tabs.add(new CArgumentsTab());
- tabs.addAll(Arrays.asList(getProfileTabs()));
+ tabs.addAll(Arrays.asList(getProfileTabs()));
- tabs.add(new EnvironmentTab());
- tabs.add(new SourceLookupTab());
- tabs.add(new CommonTab());
+ tabs.add(new EnvironmentTab());
+ tabs.add(new SourceLookupTab());
+ tabs.add(new CommonTab());
- setTabs(tabs.toArray(new AbstractLaunchConfigurationTab[tabs.size()]));
- }
+ setTabs(tabs.toArray(new AbstractLaunchConfigurationTab[tabs.size()]));
+ }
- public abstract AbstractLaunchConfigurationTab[] getProfileTabs();
+ public abstract AbstractLaunchConfigurationTab[] getProfileTabs();
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/FileSystemElement.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/FileSystemElement.java
index ca8e61360c..e3229910b9 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/FileSystemElement.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/FileSystemElement.java
@@ -16,32 +16,32 @@ package org.eclipse.linuxtools.profiling.launch.ui;
*/
public class FileSystemElement {
- private String scheme;
- private String schemeLabel;
- private boolean isDefault;
- private IRemoteResourceSelectorProxy selectorProxy;
-
- public FileSystemElement(String scheme, String schemeLabel, boolean isDefault, IRemoteResourceSelectorProxy selectorProxy) {
- this.schemeLabel = schemeLabel;
- this.scheme = scheme;
- this.isDefault = isDefault;
- this.selectorProxy = selectorProxy;
- }
-
- public String getSchemeLabel() {
- return schemeLabel;
- }
-
- public String getScheme() {
- return scheme;
- }
-
- public boolean getIsDefault() {
- return isDefault;
- }
-
- public IRemoteResourceSelectorProxy getSelectorProxy() {
- return selectorProxy;
- }
+ private String scheme;
+ private String schemeLabel;
+ private boolean isDefault;
+ private IRemoteResourceSelectorProxy selectorProxy;
+
+ public FileSystemElement(String scheme, String schemeLabel, boolean isDefault, IRemoteResourceSelectorProxy selectorProxy) {
+ this.schemeLabel = schemeLabel;
+ this.scheme = scheme;
+ this.isDefault = isDefault;
+ this.selectorProxy = selectorProxy;
+ }
+
+ public String getSchemeLabel() {
+ return schemeLabel;
+ }
+
+ public String getScheme() {
+ return scheme;
+ }
+
+ public boolean getIsDefault() {
+ return isDefault;
+ }
+
+ public IRemoteResourceSelectorProxy getSelectorProxy() {
+ return selectorProxy;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/FileSystemSelectionArea.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/FileSystemSelectionArea.java
index d9bbf57b9b..ca8eef0285 100755
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/FileSystemSelectionArea.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/FileSystemSelectionArea.java
@@ -41,178 +41,178 @@ import org.eclipse.swt.widgets.Label;
*/
public class FileSystemSelectionArea {
- private Label fileSystemTitle;
- private ComboViewer fileSystems;
-
- private static final String EXTENSION_POINT_ID = "RemoteResourceSelectorProxy"; //$NON-NLS-1$
- private static final String RESOURCE_SELECTOR_PROXY_NAME = "resourceSelectorProxy"; //$NON-NLS-1$
- private static final String SCHEME_ID = "scheme"; //$NON-NLS-1$
- private static final String SCHEME_LABEL_ID = "schemeLabel"; //$NON-NLS-1$
- private static final String IS_DEFAULT_ID = "isDefault"; //$NON-NLS-1$
- private static final String EXT_ATTR_CLASS = "class"; //$NON-NLS-1$
-
- private LinkedList<FileSystemElement> fsElements;
-
- /**
- * Create a new instance of the receiver.
- */
- public FileSystemSelectionArea(){
- }
-
- private FileSystemElement[] getSchemes() {
- if (fsElements == null) {
- fsElements = new LinkedList<>();
-
- // Add all of the ones declared by the registry.
- IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(ProfileLaunchPlugin.PLUGIN_ID, EXTENSION_POINT_ID);
- IConfigurationElement[] infos = extensionPoint.getConfigurationElements();
- for (int i = 0; i < infos.length; i++) {
- IConfigurationElement configurationElement = infos[i];
- if (configurationElement.getName().equals(RESOURCE_SELECTOR_PROXY_NAME)) {
- IRemoteResourceSelectorProxy remoteSelector = null;
- try {
- Object obj = configurationElement.createExecutableExtension(EXT_ATTR_CLASS);
- if (obj instanceof IRemoteResourceSelectorProxy) {
- remoteSelector = (IRemoteResourceSelectorProxy)obj;
- }
- } catch (CoreException e) {
- ProfileLaunchPlugin.log(IStatus.ERROR, ResourceSelectorWidgetMessages.FileSystemSelectionArea_exception_while_creating_runnable_class + configurationElement.getAttribute(EXT_ATTR_CLASS), e);
- }
- FileSystemElement element = new FileSystemElement(
- configurationElement.getAttribute(SCHEME_ID),
- configurationElement.getAttribute(SCHEME_LABEL_ID),
- Boolean.valueOf(configurationElement.getAttribute(IS_DEFAULT_ID)),
- remoteSelector);
- fsElements.addLast(element);
- }
- }
- }
- return fsElements.toArray(new FileSystemElement[fsElements.size()]);
- }
-
- /**
- * Create the contents of the receiver in composite.
- * @param composite
- */
- public void createContents(Composite composite) {
-
- fileSystemTitle = new Label(composite, SWT.NONE);
- fileSystemTitle.setText(ResourceSelectorWidgetMessages.fileSystemSelectionText);
- fileSystemTitle.setFont(composite.getFont());
-
- fileSystems = new ComboViewer(composite, SWT.READ_ONLY);
- fileSystems.getControl().setFont(composite.getFont());
-
- fileSystems.setLabelProvider(new LabelProvider() {
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
- */
- @Override
- public String getText(Object element) {
- return ((FileSystemElement)element).getSchemeLabel();
- }
- });
-
- fileSystems.setContentProvider(new IStructuredContentProvider() {
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.IContentProvider#dispose()
- */
- @Override
- public void dispose() {
- // Nothing to do
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
- */
- @Override
- public Object[] getElements(Object inputElement) {
- return getSchemes();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
- * java.lang.Object, java.lang.Object)
- */
- @Override
- public void inputChanged(org.eclipse.jface.viewers.Viewer viewer,
- Object oldInput, Object newInput) {
- // Nothing to do
- }
- });
-
- fileSystems.setInput(this);
- Iterator<FileSystemElement> fsEltItr = fsElements.iterator();
- boolean foundDefault = false;
- while (fsEltItr.hasNext()) {
- FileSystemElement fsElt = fsEltItr.next();
- if (fsElt.getIsDefault()) {
- if (foundDefault) {
- ProfileLaunchPlugin.log(IStatus.WARNING, ResourceSelectorWidgetMessages.FileSystemSelectionArea_found_multiple_default_extensions + fsElt.getScheme());
- // use only the first one we found marked as default
- continue;
- }
- fileSystems.setSelection(new StructuredSelection(fsElt));
- foundDefault = true;
- }
- }
- }
-
- /**
- * Return the selected file system.
- * @return FileSystemElement or <code>null</code> if nothing
- * is selected.
- */
- public FileSystemElement getSelectedFileSystem() {
- ISelection selection = fileSystems.getSelection();
-
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection structured = (IStructuredSelection) selection;
- if (structured.size() == 1) {
- return ((FileSystemElement) structured.getFirstElement());
- }
- }
- return null;
- }
-
- /**
- * Set the filesystem selection combo box to the specified scheme. If the scheme isn't
- * legal, throw a CoreException.
- * @param scheme name of scheme, e.g. "rse"
- */
- public void setSelectedFileSystem(String scheme) throws CoreException {
- Iterator<FileSystemElement> fsEltItr = fsElements.iterator();
- boolean foundMatch = false;
- while (fsEltItr.hasNext()) {
- FileSystemElement fsElt = fsEltItr.next();
- if (fsElt.getScheme().equalsIgnoreCase(scheme)) {
- foundMatch = true;
- fileSystems.setSelection(new StructuredSelection(fsElt));
- break;
- }
- }
- if (!foundMatch) {
- throw new CoreException(new Status(IStatus.ERROR, ProfileLaunchPlugin.PLUGIN_ID, IStatus.OK,
- ResourceSelectorWidgetMessages.FileSystemSelectionArea_unrecognized_scheme + scheme, null));
- }
- }
-
-
- /**
- * Set the enablement state of the widget.
- * @param enabled
- */
- public void setEnabled(boolean enabled) {
- fileSystemTitle.setEnabled(enabled);
- fileSystems.getControl().setEnabled(enabled);
- }
+ private Label fileSystemTitle;
+ private ComboViewer fileSystems;
+
+ private static final String EXTENSION_POINT_ID = "RemoteResourceSelectorProxy"; //$NON-NLS-1$
+ private static final String RESOURCE_SELECTOR_PROXY_NAME = "resourceSelectorProxy"; //$NON-NLS-1$
+ private static final String SCHEME_ID = "scheme"; //$NON-NLS-1$
+ private static final String SCHEME_LABEL_ID = "schemeLabel"; //$NON-NLS-1$
+ private static final String IS_DEFAULT_ID = "isDefault"; //$NON-NLS-1$
+ private static final String EXT_ATTR_CLASS = "class"; //$NON-NLS-1$
+
+ private LinkedList<FileSystemElement> fsElements;
+
+ /**
+ * Create a new instance of the receiver.
+ */
+ public FileSystemSelectionArea(){
+ }
+
+ private FileSystemElement[] getSchemes() {
+ if (fsElements == null) {
+ fsElements = new LinkedList<>();
+
+ // Add all of the ones declared by the registry.
+ IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(ProfileLaunchPlugin.PLUGIN_ID, EXTENSION_POINT_ID);
+ IConfigurationElement[] infos = extensionPoint.getConfigurationElements();
+ for (int i = 0; i < infos.length; i++) {
+ IConfigurationElement configurationElement = infos[i];
+ if (configurationElement.getName().equals(RESOURCE_SELECTOR_PROXY_NAME)) {
+ IRemoteResourceSelectorProxy remoteSelector = null;
+ try {
+ Object obj = configurationElement.createExecutableExtension(EXT_ATTR_CLASS);
+ if (obj instanceof IRemoteResourceSelectorProxy) {
+ remoteSelector = (IRemoteResourceSelectorProxy)obj;
+ }
+ } catch (CoreException e) {
+ ProfileLaunchPlugin.log(IStatus.ERROR, ResourceSelectorWidgetMessages.FileSystemSelectionArea_exception_while_creating_runnable_class + configurationElement.getAttribute(EXT_ATTR_CLASS), e);
+ }
+ FileSystemElement element = new FileSystemElement(
+ configurationElement.getAttribute(SCHEME_ID),
+ configurationElement.getAttribute(SCHEME_LABEL_ID),
+ Boolean.valueOf(configurationElement.getAttribute(IS_DEFAULT_ID)),
+ remoteSelector);
+ fsElements.addLast(element);
+ }
+ }
+ }
+ return fsElements.toArray(new FileSystemElement[fsElements.size()]);
+ }
+
+ /**
+ * Create the contents of the receiver in composite.
+ * @param composite
+ */
+ public void createContents(Composite composite) {
+
+ fileSystemTitle = new Label(composite, SWT.NONE);
+ fileSystemTitle.setText(ResourceSelectorWidgetMessages.fileSystemSelectionText);
+ fileSystemTitle.setFont(composite.getFont());
+
+ fileSystems = new ComboViewer(composite, SWT.READ_ONLY);
+ fileSystems.getControl().setFont(composite.getFont());
+
+ fileSystems.setLabelProvider(new LabelProvider() {
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
+ */
+ @Override
+ public String getText(Object element) {
+ return ((FileSystemElement)element).getSchemeLabel();
+ }
+ });
+
+ fileSystems.setContentProvider(new IStructuredContentProvider() {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.IContentProvider#dispose()
+ */
+ @Override
+ public void dispose() {
+ // Nothing to do
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
+ */
+ @Override
+ public Object[] getElements(Object inputElement) {
+ return getSchemes();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
+ * java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public void inputChanged(org.eclipse.jface.viewers.Viewer viewer,
+ Object oldInput, Object newInput) {
+ // Nothing to do
+ }
+ });
+
+ fileSystems.setInput(this);
+ Iterator<FileSystemElement> fsEltItr = fsElements.iterator();
+ boolean foundDefault = false;
+ while (fsEltItr.hasNext()) {
+ FileSystemElement fsElt = fsEltItr.next();
+ if (fsElt.getIsDefault()) {
+ if (foundDefault) {
+ ProfileLaunchPlugin.log(IStatus.WARNING, ResourceSelectorWidgetMessages.FileSystemSelectionArea_found_multiple_default_extensions + fsElt.getScheme());
+ // use only the first one we found marked as default
+ continue;
+ }
+ fileSystems.setSelection(new StructuredSelection(fsElt));
+ foundDefault = true;
+ }
+ }
+ }
+
+ /**
+ * Return the selected file system.
+ * @return FileSystemElement or <code>null</code> if nothing
+ * is selected.
+ */
+ public FileSystemElement getSelectedFileSystem() {
+ ISelection selection = fileSystems.getSelection();
+
+ if (selection instanceof IStructuredSelection) {
+ IStructuredSelection structured = (IStructuredSelection) selection;
+ if (structured.size() == 1) {
+ return ((FileSystemElement) structured.getFirstElement());
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Set the filesystem selection combo box to the specified scheme. If the scheme isn't
+ * legal, throw a CoreException.
+ * @param scheme name of scheme, e.g. "rse"
+ */
+ public void setSelectedFileSystem(String scheme) throws CoreException {
+ Iterator<FileSystemElement> fsEltItr = fsElements.iterator();
+ boolean foundMatch = false;
+ while (fsEltItr.hasNext()) {
+ FileSystemElement fsElt = fsEltItr.next();
+ if (fsElt.getScheme().equalsIgnoreCase(scheme)) {
+ foundMatch = true;
+ fileSystems.setSelection(new StructuredSelection(fsElt));
+ break;
+ }
+ }
+ if (!foundMatch) {
+ throw new CoreException(new Status(IStatus.ERROR, ProfileLaunchPlugin.PLUGIN_ID, IStatus.OK,
+ ResourceSelectorWidgetMessages.FileSystemSelectionArea_unrecognized_scheme + scheme, null));
+ }
+ }
+
+
+ /**
+ * Set the enablement state of the widget.
+ * @param enabled
+ */
+ public void setEnabled(boolean enabled) {
+ fileSystemTitle.setEnabled(enabled);
+ fileSystems.getControl().setEnabled(enabled);
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/IRemoteResourceSelectorProxy.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/IRemoteResourceSelectorProxy.java
index e635711ce7..6a6fa7ada7 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/IRemoteResourceSelectorProxy.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/IRemoteResourceSelectorProxy.java
@@ -19,6 +19,6 @@ import org.eclipse.swt.widgets.Shell;
* @since 2.0
*/
public interface IRemoteResourceSelectorProxy {
- URI selectFile(String scheme, String initialPath, String prompt, Shell shell);
- URI selectDirectory(String scheme, String initialPath, String prompt, Shell shell);
+ URI selectFile(String scheme, String initialPath, String prompt, Shell shell);
+ URI selectDirectory(String scheme, String initialPath, String prompt, Shell shell);
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/LocalResourceSelectorProxy.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/LocalResourceSelectorProxy.java
index 288292ad21..7f4377da3b 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/LocalResourceSelectorProxy.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/LocalResourceSelectorProxy.java
@@ -24,37 +24,37 @@ import org.eclipse.swt.widgets.Shell;
*/
public class LocalResourceSelectorProxy implements IRemoteResourceSelectorProxy {
- @Override
- public URI selectFile(String scheme, String initialPath, String prompt, Shell shell) {
- FileDialog dialog = new FileDialog(shell, SWT.SHEET);
- dialog.setText(prompt);
- dialog.setFilterPath(initialPath);
- try {
- String path = dialog.open();
- if (path != null)
- return new URI(path);
- else
- return null;
- } catch (URISyntaxException e) {
- return null;
- }
- }
-
- @Override
- public URI selectDirectory(String scheme, String initialPath, String prompt, Shell shell) {
- DirectoryDialog dialog = new DirectoryDialog(shell, SWT.SHEET);
- dialog.setText(prompt);
- dialog.setFilterPath(initialPath);
- try {
- String path = dialog.open();
- if (path != null)
- return new URI(path);
- else
- return null;
- } catch (URISyntaxException e) {
- return null;
- }
-
- }
+ @Override
+ public URI selectFile(String scheme, String initialPath, String prompt, Shell shell) {
+ FileDialog dialog = new FileDialog(shell, SWT.SHEET);
+ dialog.setText(prompt);
+ dialog.setFilterPath(initialPath);
+ try {
+ String path = dialog.open();
+ if (path != null)
+ return new URI(path);
+ else
+ return null;
+ } catch (URISyntaxException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public URI selectDirectory(String scheme, String initialPath, String prompt, Shell shell) {
+ DirectoryDialog dialog = new DirectoryDialog(shell, SWT.SHEET);
+ dialog.setText(prompt);
+ dialog.setFilterPath(initialPath);
+ try {
+ String path = dialog.open();
+ if (path != null)
+ return new URI(path);
+ else
+ return null;
+ } catch (URISyntaxException e) {
+ return null;
+ }
+
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/ResourceSelectorWidget.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/ResourceSelectorWidget.java
index f442f6801b..1d1e7acc4d 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/ResourceSelectorWidget.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/ResourceSelectorWidget.java
@@ -37,199 +37,199 @@ import org.eclipse.swt.widgets.Text;
*/
public class ResourceSelectorWidget {
- public enum ResourceType { FILE, DIRECTORY }
-
- private static String BROWSE_LABEL = ResourceSelectorWidgetMessages.browseLabelText;
-
- private ResourceType resourceType;
- private Group mainComp;
- private String sectionLabelText;
- private Label uriLabel;
- private Text uriField;
- private Button browseButton;
- private FileSystemSelectionArea fileSystemSelectionArea;
-
- /**
- * Open an appropriate directory browser
- */
- private void handleURIBrowseButtonPressed() {
-
- String selectedResource = null;
- String path = getURIText().getText();
- FileSystemElement fileSystem = fileSystemSelectionArea.getSelectedFileSystem();
-
- IRemoteResourceSelectorProxy resourceSelector = fileSystem.getSelectorProxy();
- if (resourceSelector != null) {
- switch (resourceType) {
- case FILE: {
- URI uri = resourceSelector.selectFile(fileSystem.getScheme(), path, ResourceSelectorWidgetMessages.ResourceSelectorWidget_select + sectionLabelText, browseButton.getShell());
- if (uri != null) {
- selectedResource = uri.toString();
- }
- break;
- }
- case DIRECTORY: {
- URI uri = resourceSelector.selectDirectory(fileSystem.getScheme(), path, ResourceSelectorWidgetMessages.ResourceSelectorWidget_select + sectionLabelText, browseButton.getShell());
- if (uri != null) {
- selectedResource = uri.toString();
- }
- break;
- }
- default:
- ProfileLaunchPlugin.log(IStatus.ERROR, ResourceSelectorWidgetMessages.ResourceSelectorWidget_unrecognized_resourceType);
- return;
- }
- } else {
- ProfileLaunchPlugin.log(IStatus.ERROR, ResourceSelectorWidgetMessages.ResourceSelectorWidget_getSelectorProxy_returned_null);
- }
-
- if (selectedResource != null) {
- updateURIField(selectedResource);
- }
- }
-
-
-
- /**
- * Update the filesystem selector, if possible
- *
- * @param newPath
- */
- private void updateFilesystemSelector(String newPath) {
- try {
- URI selectedURI = new URI(newPath);
- String scheme = selectedURI.getScheme();
- try {
- if (scheme == null) {
- fileSystemSelectionArea.setSelectedFileSystem("local"); //$NON-NLS-1$
- } else {
- fileSystemSelectionArea.setSelectedFileSystem(scheme);
- }
- } catch (CoreException e) {
- // Probably an unrecognized scheme. Don't change the setting of
- // the filesystem selector.
- }
- } catch (URISyntaxException e) {
- // This error can be ignored because we just won't set the filesystem selector
- // to a anything
- }
- }
-
- /**
- * Update the URI field based on the selected path.
- *
- * @param selectedPath
- */
- private void updateURIField(String selectedPath) {
- uriField.setText(TextProcessor.process(selectedPath));
- updateFilesystemSelector(selectedPath);
- }
-
- /**
- * Create the file system selection area.
- *
- * @param composite
- */
- private void createFileSystemSelection(Composite composite) {
- fileSystemSelectionArea = new FileSystemSelectionArea();
- fileSystemSelectionArea.createContents(composite);
- }
-
- /**
- * Create the area for user entry.
- *
- * @param composite
- * @param defaultEnabled
- */
- private void createUserEntryArea(Composite composite, String uriLabelText, boolean defaultEnabled) {
- // location label
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- layout.marginHeight = 0;
- layout.marginWidth = 0;
- composite.setLayout(layout);
-
- uriLabel = new Label(composite, SWT.NONE);
- if (uriLabelText != null) {
- uriLabel.setText(uriLabelText);
- } else {
- uriLabel.setText(ResourceSelectorWidgetMessages.uriLabelText);
- }
-
- // project location entry field
- uriField = new Text(composite, SWT.BORDER);
- GridData data = new GridData(GridData.FILL_HORIZONTAL);
-
- data.horizontalSpan = 1;
- uriField.setLayoutData(data);
-
- // create a blank space to align the filesystem selector with the path box.
- new Label(composite, SWT.NONE);
-
- Composite browserComp = new Composite(composite, SWT.NONE);
- FillLayout browserLayout = new FillLayout(SWT.HORIZONTAL);
- browserComp.setLayout(browserLayout);
-
- createFileSystemSelection(browserComp);
-
- // browse button
- browseButton = new Button(browserComp, SWT.PUSH);
- browseButton.setText(BROWSE_LABEL);
- browseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- handleURIBrowseButtonPressed();
- }
- });
-
- uriField.addModifyListener(new ModifyListener() {
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
- */
- @Override
- public void modifyText(ModifyEvent e) {
- updateFilesystemSelector(uriField.getText());
- }
- });
- }
-
- public ResourceSelectorWidget(Composite parent, ResourceType resourceType, int colSpan, String sectionLabelText, String uriLabelText) {
- this.resourceType = resourceType;
- this.sectionLabelText = sectionLabelText;
- mainComp = new Group(parent, SWT.NONE);
- GridLayout mainLayout = new GridLayout();
- mainLayout.numColumns = 5;
- mainLayout.marginHeight = 0;
- mainLayout.marginWidth = 0;
- mainComp.setLayout(mainLayout);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = colSpan;
- mainComp.setLayoutData(gd);
- mainComp.setText(sectionLabelText);
- createUserEntryArea(mainComp, uriLabelText, true);
- }
-
- public void setEnabled(boolean enabled) {
- if (mainComp != null) {
- mainComp.setEnabled(enabled);
- }
- if (uriLabel != null) {
- uriLabel.setEnabled(enabled);
- }
- if (browseButton != null) {
- browseButton.setEnabled(enabled);
- }
- if (uriField != null) {
- uriField.setEnabled(enabled);
- }
- if (fileSystemSelectionArea != null) {
- fileSystemSelectionArea.setEnabled(enabled);
- }
- }
-
- public Text getURIText() {
- return uriField;
- }
+ public enum ResourceType { FILE, DIRECTORY }
+
+ private static String BROWSE_LABEL = ResourceSelectorWidgetMessages.browseLabelText;
+
+ private ResourceType resourceType;
+ private Group mainComp;
+ private String sectionLabelText;
+ private Label uriLabel;
+ private Text uriField;
+ private Button browseButton;
+ private FileSystemSelectionArea fileSystemSelectionArea;
+
+ /**
+ * Open an appropriate directory browser
+ */
+ private void handleURIBrowseButtonPressed() {
+
+ String selectedResource = null;
+ String path = getURIText().getText();
+ FileSystemElement fileSystem = fileSystemSelectionArea.getSelectedFileSystem();
+
+ IRemoteResourceSelectorProxy resourceSelector = fileSystem.getSelectorProxy();
+ if (resourceSelector != null) {
+ switch (resourceType) {
+ case FILE: {
+ URI uri = resourceSelector.selectFile(fileSystem.getScheme(), path, ResourceSelectorWidgetMessages.ResourceSelectorWidget_select + sectionLabelText, browseButton.getShell());
+ if (uri != null) {
+ selectedResource = uri.toString();
+ }
+ break;
+ }
+ case DIRECTORY: {
+ URI uri = resourceSelector.selectDirectory(fileSystem.getScheme(), path, ResourceSelectorWidgetMessages.ResourceSelectorWidget_select + sectionLabelText, browseButton.getShell());
+ if (uri != null) {
+ selectedResource = uri.toString();
+ }
+ break;
+ }
+ default:
+ ProfileLaunchPlugin.log(IStatus.ERROR, ResourceSelectorWidgetMessages.ResourceSelectorWidget_unrecognized_resourceType);
+ return;
+ }
+ } else {
+ ProfileLaunchPlugin.log(IStatus.ERROR, ResourceSelectorWidgetMessages.ResourceSelectorWidget_getSelectorProxy_returned_null);
+ }
+
+ if (selectedResource != null) {
+ updateURIField(selectedResource);
+ }
+ }
+
+
+
+ /**
+ * Update the filesystem selector, if possible
+ *
+ * @param newPath
+ */
+ private void updateFilesystemSelector(String newPath) {
+ try {
+ URI selectedURI = new URI(newPath);
+ String scheme = selectedURI.getScheme();
+ try {
+ if (scheme == null) {
+ fileSystemSelectionArea.setSelectedFileSystem("local"); //$NON-NLS-1$
+ } else {
+ fileSystemSelectionArea.setSelectedFileSystem(scheme);
+ }
+ } catch (CoreException e) {
+ // Probably an unrecognized scheme. Don't change the setting of
+ // the filesystem selector.
+ }
+ } catch (URISyntaxException e) {
+ // This error can be ignored because we just won't set the filesystem selector
+ // to a anything
+ }
+ }
+
+ /**
+ * Update the URI field based on the selected path.
+ *
+ * @param selectedPath
+ */
+ private void updateURIField(String selectedPath) {
+ uriField.setText(TextProcessor.process(selectedPath));
+ updateFilesystemSelector(selectedPath);
+ }
+
+ /**
+ * Create the file system selection area.
+ *
+ * @param composite
+ */
+ private void createFileSystemSelection(Composite composite) {
+ fileSystemSelectionArea = new FileSystemSelectionArea();
+ fileSystemSelectionArea.createContents(composite);
+ }
+
+ /**
+ * Create the area for user entry.
+ *
+ * @param composite
+ * @param defaultEnabled
+ */
+ private void createUserEntryArea(Composite composite, String uriLabelText, boolean defaultEnabled) {
+ // location label
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ layout.marginHeight = 0;
+ layout.marginWidth = 0;
+ composite.setLayout(layout);
+
+ uriLabel = new Label(composite, SWT.NONE);
+ if (uriLabelText != null) {
+ uriLabel.setText(uriLabelText);
+ } else {
+ uriLabel.setText(ResourceSelectorWidgetMessages.uriLabelText);
+ }
+
+ // project location entry field
+ uriField = new Text(composite, SWT.BORDER);
+ GridData data = new GridData(GridData.FILL_HORIZONTAL);
+
+ data.horizontalSpan = 1;
+ uriField.setLayoutData(data);
+
+ // create a blank space to align the filesystem selector with the path box.
+ new Label(composite, SWT.NONE);
+
+ Composite browserComp = new Composite(composite, SWT.NONE);
+ FillLayout browserLayout = new FillLayout(SWT.HORIZONTAL);
+ browserComp.setLayout(browserLayout);
+
+ createFileSystemSelection(browserComp);
+
+ // browse button
+ browseButton = new Button(browserComp, SWT.PUSH);
+ browseButton.setText(BROWSE_LABEL);
+ browseButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent event) {
+ handleURIBrowseButtonPressed();
+ }
+ });
+
+ uriField.addModifyListener(new ModifyListener() {
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
+ */
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateFilesystemSelector(uriField.getText());
+ }
+ });
+ }
+
+ public ResourceSelectorWidget(Composite parent, ResourceType resourceType, int colSpan, String sectionLabelText, String uriLabelText) {
+ this.resourceType = resourceType;
+ this.sectionLabelText = sectionLabelText;
+ mainComp = new Group(parent, SWT.NONE);
+ GridLayout mainLayout = new GridLayout();
+ mainLayout.numColumns = 5;
+ mainLayout.marginHeight = 0;
+ mainLayout.marginWidth = 0;
+ mainComp.setLayout(mainLayout);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = colSpan;
+ mainComp.setLayoutData(gd);
+ mainComp.setText(sectionLabelText);
+ createUserEntryArea(mainComp, uriLabelText, true);
+ }
+
+ public void setEnabled(boolean enabled) {
+ if (mainComp != null) {
+ mainComp.setEnabled(enabled);
+ }
+ if (uriLabel != null) {
+ uriLabel.setEnabled(enabled);
+ }
+ if (browseButton != null) {
+ browseButton.setEnabled(enabled);
+ }
+ if (uriField != null) {
+ uriField.setEnabled(enabled);
+ }
+ if (fileSystemSelectionArea != null) {
+ fileSystemSelectionArea.setEnabled(enabled);
+ }
+ }
+
+ public Text getURIText() {
+ return uriField;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/ResourceSelectorWidgetMessages.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/ResourceSelectorWidgetMessages.java
index 61891aa3e5..e59f32c43b 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/ResourceSelectorWidgetMessages.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ui/ResourceSelectorWidgetMessages.java
@@ -15,27 +15,27 @@ import org.eclipse.osgi.util.NLS;
* @since 2.0
*/
public class ResourceSelectorWidgetMessages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.profiling.launch.ui.messages";//$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.profiling.launch.ui.messages";//$NON-NLS-1$
- public static String uriLabelText;
- public static String browseLabelText;
+ public static String uriLabelText;
+ public static String browseLabelText;
- public static String FileSystemSelectionArea_unrecognized_scheme;
+ public static String FileSystemSelectionArea_unrecognized_scheme;
- public static String FileSystemSelectionArea_exception_while_creating_runnable_class;
+ public static String FileSystemSelectionArea_exception_while_creating_runnable_class;
- public static String FileSystemSelectionArea_found_multiple_default_extensions;
- public static String fileSystemSelectionText;
+ public static String FileSystemSelectionArea_found_multiple_default_extensions;
+ public static String fileSystemSelectionText;
- public static String ResourceSelectorWidget_getSelectorProxy_returned_null;
- public static String ResourceSelectorWidget_invalid_location;
- public static String ResourceSelectorWidget_select;
- public static String ResourceSelectorWidget_unrecognize_resourceType;
- public static String ResourceSelectorWidget_unrecognized_resourceType;
+ public static String ResourceSelectorWidget_getSelectorProxy_returned_null;
+ public static String ResourceSelectorWidget_invalid_location;
+ public static String ResourceSelectorWidget_select;
+ public static String ResourceSelectorWidget_unrecognize_resourceType;
+ public static String ResourceSelectorWidget_unrecognized_resourceType;
- static {
- // load message values from bundle file
- NLS.initializeMessages(BUNDLE_NAME, ResourceSelectorWidgetMessages.class);
- }
+ static {
+ // load message values from bundle file
+ NLS.initializeMessages(BUNDLE_NAME, ResourceSelectorWidgetMessages.class);
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.provider.tests/fragment.xml b/profiling/org.eclipse.linuxtools.profiling.provider.tests/fragment.xml
index 6675d9086a..689b2b7ed0 100644
--- a/profiling/org.eclipse.linuxtools.profiling.provider.tests/fragment.xml
+++ b/profiling/org.eclipse.linuxtools.profiling.provider.tests/fragment.xml
@@ -9,11 +9,11 @@
label="Profile As Stub"
modes="linuxtools">
<class class="org.eclipse.linuxtools.internal.profiling.launch.provider.launch.ProviderLaunchShortcut">
- <parameter
+ <parameter
name="type"
value="stub"/>
- <parameter
- name="configurationId"
+ <parameter
+ name="configurationId"
value="org.eclipse.linuxtools.profiling.stub.launchConfigurationType"/>
</class>
@@ -105,10 +105,10 @@
id="org.eclipse.linuxtools.profiling.stub.launchConfigurationTabGroup"
type="org.eclipse.linuxtools.profiling.stub.launchConfigurationType">
<class class="org.eclipse.linuxtools.internal.profiling.launch.provider.ProviderLaunchConfigurationTabGroup">
- <parameter
+ <parameter
name="type"
value="stub"/>
- <parameter
+ <parameter
name="name"
value="Stub"/>
</class>
diff --git a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/ExtensionPointTest.java b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/ExtensionPointTest.java
index 871828f3e7..bf331e200d 100644
--- a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/ExtensionPointTest.java
+++ b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/ExtensionPointTest.java
@@ -28,53 +28,53 @@ import org.junit.Test;
public class ExtensionPointTest {
- private static final String PROFILING_TYPE = "stub"; //$NON-NLS-1$
- private static final String PLUGIN_ID = "org.eclipse.linuxtools.profiling.provider.stubby"; //$NON-NLS-1$
+ private static final String PROFILING_TYPE = "stub"; //$NON-NLS-1$
+ private static final String PLUGIN_ID = "org.eclipse.linuxtools.profiling.provider.stubby"; //$NON-NLS-1$
- @Test
- public void testId() {
- String highestProviderId = ProviderFramework.getHighestProviderId(PROFILING_TYPE);
- assertEquals(PLUGIN_ID + "1", highestProviderId); //$NON-NLS-1$
+ @Test
+ public void testId() {
+ String highestProviderId = ProviderFramework.getHighestProviderId(PROFILING_TYPE);
+ assertEquals(PLUGIN_ID + "1", highestProviderId); //$NON-NLS-1$
- String[] providerIds = ProviderFramework.getProviderIdsForType(PROFILING_TYPE);
- HashSet<String> set = new HashSet<>(Arrays.asList(providerIds));
- for (int i = 0; i < providerIds.length; i++){
- assertTrue(set.contains(PLUGIN_ID + (i+1)));
- }
- }
+ String[] providerIds = ProviderFramework.getProviderIdsForType(PROFILING_TYPE);
+ HashSet<String> set = new HashSet<>(Arrays.asList(providerIds));
+ for (int i = 0; i < providerIds.length; i++){
+ assertTrue(set.contains(PLUGIN_ID + (i+1)));
+ }
+ }
- @Test
- public void testShortCut () {
- ProfileLaunchShortcut shortcut = ProviderFramework.getLaunchShortcutProviderFromId(PLUGIN_ID + "1"); //$NON-NLS-1$
- ProfileLaunchShortcut shortcut2 = ProviderFramework.getProfilingProvider(PROFILING_TYPE);
+ @Test
+ public void testShortCut () {
+ ProfileLaunchShortcut shortcut = ProviderFramework.getLaunchShortcutProviderFromId(PLUGIN_ID + "1"); //$NON-NLS-1$
+ ProfileLaunchShortcut shortcut2 = ProviderFramework.getProfilingProvider(PROFILING_TYPE);
- assertTrue(shortcut instanceof StubbyLaunchShortcut);
- assertTrue(shortcut2 instanceof StubbyLaunchShortcut);
- }
+ assertTrue(shortcut instanceof StubbyLaunchShortcut);
+ assertTrue(shortcut2 instanceof StubbyLaunchShortcut);
+ }
- @Test
- public void testName () {
- HashMap<String, String> providerNames = ProviderFramework.getProviderNamesForType(PROFILING_TYPE);
- assertEquals(3, providerNames.size());
- for (int i = 1; i <= providerNames.size(); i++){
- assertTrue(providerNames.values().contains(PLUGIN_ID + i));
- assertTrue(providerNames.keySet().contains("Profile As Stubby " + i)); //$NON-NLS-1$
- }
- }
+ @Test
+ public void testName () {
+ HashMap<String, String> providerNames = ProviderFramework.getProviderNamesForType(PROFILING_TYPE);
+ assertEquals(3, providerNames.size());
+ for (int i = 1; i <= providerNames.size(); i++){
+ assertTrue(providerNames.values().contains(PLUGIN_ID + i));
+ assertTrue(providerNames.keySet().contains("Profile As Stubby " + i)); //$NON-NLS-1$
+ }
+ }
- @Test
- public void testDelegate () {
- AbstractCLaunchDelegate delegate = ProviderFramework.getConfigurationDelegateFromId(PLUGIN_ID + "1"); //$NON-NLS-1$
- assertTrue(delegate instanceof StubbyLaunchConfigurationDelegate);
- }
+ @Test
+ public void testDelegate () {
+ AbstractCLaunchDelegate delegate = ProviderFramework.getConfigurationDelegateFromId(PLUGIN_ID + "1"); //$NON-NLS-1$
+ assertTrue(delegate instanceof StubbyLaunchConfigurationDelegate);
+ }
- @Test
- public void testTabGroup () {
- ProfileLaunchConfigurationTabGroup tabgroup = ProviderFramework.getTabGroupProvider(PROFILING_TYPE);
- ProfileLaunchConfigurationTabGroup tabgroup2 = ProviderFramework.getTabGroupProviderFromId(PLUGIN_ID + "1"); //$NON-NLS-1$
+ @Test
+ public void testTabGroup () {
+ ProfileLaunchConfigurationTabGroup tabgroup = ProviderFramework.getTabGroupProvider(PROFILING_TYPE);
+ ProfileLaunchConfigurationTabGroup tabgroup2 = ProviderFramework.getTabGroupProviderFromId(PLUGIN_ID + "1"); //$NON-NLS-1$
- assertTrue(tabgroup instanceof StubbyLaunchConfigurationTabGroup);
- assertTrue(tabgroup2 instanceof StubbyLaunchConfigurationTabGroup);
- }
+ assertTrue(tabgroup instanceof StubbyLaunchConfigurationTabGroup);
+ assertTrue(tabgroup2 instanceof StubbyLaunchConfigurationTabGroup);
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/LaunchTest.java b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/LaunchTest.java
index b7699bb1a7..cbdc7ecfd0 100644
--- a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/LaunchTest.java
+++ b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/LaunchTest.java
@@ -35,140 +35,140 @@ import org.osgi.framework.FrameworkUtil;
public class LaunchTest extends AbstractTest {
- private static final String BIN_NAME = "fibTest"; //$NON-NLS-1$
- private static final String BIN_PATH = "Debug/" + BIN_NAME; //$NON-NLS-1$
- private static final String STUB_ID = "org.eclipse.linuxtools.profiling.stub"; //$NON-NLS-1$
- private static final String LAUNCH_SHORT_EXTPT = "org.eclipse.debug.ui.launchShortcuts"; //$NON-NLS-1$
-
- ProviderLaunchShortcut shortcut;
- String launchConfigTypeId;
-
- @Before
- public void setUp() throws Exception {
- proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()),
- BIN_NAME);
-
- // Set up the shortcut and launch config ID passed in through
- // IExecutableExtension
- IExtensionPoint extPoint = Platform.getExtensionRegistry()
- .getExtensionPoint(LAUNCH_SHORT_EXTPT);
- IConfigurationElement[] configs = extPoint.getConfigurationElements();
- for (IConfigurationElement cfg : configs) {
- if (cfg.getAttribute("id").equals(STUB_ID)) { //$NON-NLS-1$
- shortcut = (ProviderLaunchShortcut) cfg
- .createExecutableExtension("class"); //$NON-NLS-1$
- launchConfigTypeId = cfg.getChildren("class")[0].getChildren("parameter")[1].getAttribute("value"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- }
- }
-
- @After
- public void tearDown() {
- try {
- deleteProject(proj);
- } catch (CoreException e) {
- fail(e.getMessage());
- }
- }
-
- @Test
- public void testIExecutableExtension() {
- IExtensionPoint extPoint = Platform.getExtensionRegistry()
- .getExtensionPoint(LAUNCH_SHORT_EXTPT);
- assertNotNull(extPoint);
-
- IConfigurationElement[] configs = extPoint.getConfigurationElements();
- assertTrue(configs.length > 0);
-
- for (IConfigurationElement cfg : configs) {
- if (cfg.getAttribute("id").equals(STUB_ID)) { //$NON-NLS-1$
- try {
- assertTrue(cfg.createExecutableExtension("class") instanceof ProviderLaunchShortcut); //$NON-NLS-1$
- } catch (CoreException e) {
- fail(e.getMessage());
- }
- assertEquals(cfg.getChildren("class").length, 1); //$NON-NLS-1$
- IConfigurationElement elem = cfg.getChildren("class")[0]; //$NON-NLS-1$
- for (int i = 0; i < 2; i++) {
- assertNotNull(elem.getChildren("parameter")[i].getAttribute("name")); //$NON-NLS-1$ //$NON-NLS-2$
- assertNotNull(elem.getChildren("parameter")[i].getAttribute("value")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- }
- }
- }
-
- @Test
- public void testShortCut() throws CModelException {
- shortcut.launch(proj.getBinaryContainer().getBinaries()[0],
- ILaunchManager.PROFILE_MODE);
- }
-
- @Test
- public void testDefaultProfileShortcutSettings() throws CModelException {
- testShortCut();
-
- try {
- for (ILaunchConfiguration config : getLaunchManager()
- .getLaunchConfigurations()) {
- if (config
- .getAttribute(
- ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
- "").equals(BIN_PATH)) { //$NON-NLS-1$
- if (config.getAttribute("foo", "").equals("bar")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- return;
- }
- }
- }
- } catch (CoreException e) {
- fail(e.getMessage());
- }
- fail();
- }
-
- @Test
- public void testDelegate() throws CoreException {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ProviderLaunchConfigurationDelegate delegate = new ProviderLaunchConfigurationDelegate();
- ILaunch launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
-
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- setProfileAttributes(wc);
-
- delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
- }
-
- @Test
- public void testNoDefaultProfileShortcutSettings() throws CoreException {
- testDelegate();
-
- for (ILaunchConfiguration config : getLaunchManager()
- .getLaunchConfigurations()) {
- if (config
- .getAttribute(
- ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
- "").equals(BIN_PATH)) { //$NON-NLS-1$
- assertNotSame("bar", config.getAttribute("foo", "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- }
- }
-
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager()
- .getLaunchConfigurationType(launchConfigTypeId);
- }
-
- @Override
- protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- // A delegate launch will have this property set, otherwise a shortcut
- // launch will be assumed
- // This is the provider with the highest priority
- wc.setAttribute(ProviderProfileConstants.PROVIDER_CONFIG_ATT,
- "org.eclipse.linuxtools.profiling.provider.stubby1"); //$NON-NLS-1$
- // Make each configuration unique
- wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- String.valueOf(System.currentTimeMillis()));
- }
+ private static final String BIN_NAME = "fibTest"; //$NON-NLS-1$
+ private static final String BIN_PATH = "Debug/" + BIN_NAME; //$NON-NLS-1$
+ private static final String STUB_ID = "org.eclipse.linuxtools.profiling.stub"; //$NON-NLS-1$
+ private static final String LAUNCH_SHORT_EXTPT = "org.eclipse.debug.ui.launchShortcuts"; //$NON-NLS-1$
+
+ ProviderLaunchShortcut shortcut;
+ String launchConfigTypeId;
+
+ @Before
+ public void setUp() throws Exception {
+ proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()),
+ BIN_NAME);
+
+ // Set up the shortcut and launch config ID passed in through
+ // IExecutableExtension
+ IExtensionPoint extPoint = Platform.getExtensionRegistry()
+ .getExtensionPoint(LAUNCH_SHORT_EXTPT);
+ IConfigurationElement[] configs = extPoint.getConfigurationElements();
+ for (IConfigurationElement cfg : configs) {
+ if (cfg.getAttribute("id").equals(STUB_ID)) { //$NON-NLS-1$
+ shortcut = (ProviderLaunchShortcut) cfg
+ .createExecutableExtension("class"); //$NON-NLS-1$
+ launchConfigTypeId = cfg.getChildren("class")[0].getChildren("parameter")[1].getAttribute("value"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ }
+ }
+
+ @After
+ public void tearDown() {
+ try {
+ deleteProject(proj);
+ } catch (CoreException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ @Test
+ public void testIExecutableExtension() {
+ IExtensionPoint extPoint = Platform.getExtensionRegistry()
+ .getExtensionPoint(LAUNCH_SHORT_EXTPT);
+ assertNotNull(extPoint);
+
+ IConfigurationElement[] configs = extPoint.getConfigurationElements();
+ assertTrue(configs.length > 0);
+
+ for (IConfigurationElement cfg : configs) {
+ if (cfg.getAttribute("id").equals(STUB_ID)) { //$NON-NLS-1$
+ try {
+ assertTrue(cfg.createExecutableExtension("class") instanceof ProviderLaunchShortcut); //$NON-NLS-1$
+ } catch (CoreException e) {
+ fail(e.getMessage());
+ }
+ assertEquals(cfg.getChildren("class").length, 1); //$NON-NLS-1$
+ IConfigurationElement elem = cfg.getChildren("class")[0]; //$NON-NLS-1$
+ for (int i = 0; i < 2; i++) {
+ assertNotNull(elem.getChildren("parameter")[i].getAttribute("name")); //$NON-NLS-1$ //$NON-NLS-2$
+ assertNotNull(elem.getChildren("parameter")[i].getAttribute("value")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ }
+ }
+ }
+
+ @Test
+ public void testShortCut() throws CModelException {
+ shortcut.launch(proj.getBinaryContainer().getBinaries()[0],
+ ILaunchManager.PROFILE_MODE);
+ }
+
+ @Test
+ public void testDefaultProfileShortcutSettings() throws CModelException {
+ testShortCut();
+
+ try {
+ for (ILaunchConfiguration config : getLaunchManager()
+ .getLaunchConfigurations()) {
+ if (config
+ .getAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
+ "").equals(BIN_PATH)) { //$NON-NLS-1$
+ if (config.getAttribute("foo", "").equals("bar")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ return;
+ }
+ }
+ }
+ } catch (CoreException e) {
+ fail(e.getMessage());
+ }
+ fail();
+ }
+
+ @Test
+ public void testDelegate() throws CoreException {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ProviderLaunchConfigurationDelegate delegate = new ProviderLaunchConfigurationDelegate();
+ ILaunch launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
+
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ setProfileAttributes(wc);
+
+ delegate.launch(wc, ILaunchManager.PROFILE_MODE, launch, null);
+ }
+
+ @Test
+ public void testNoDefaultProfileShortcutSettings() throws CoreException {
+ testDelegate();
+
+ for (ILaunchConfiguration config : getLaunchManager()
+ .getLaunchConfigurations()) {
+ if (config
+ .getAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
+ "").equals(BIN_PATH)) { //$NON-NLS-1$
+ assertNotSame("bar", config.getAttribute("foo", "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ }
+ }
+
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager()
+ .getLaunchConfigurationType(launchConfigTypeId);
+ }
+
+ @Override
+ protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ // A delegate launch will have this property set, otherwise a shortcut
+ // launch will be assumed
+ // This is the provider with the highest priority
+ wc.setAttribute(ProviderProfileConstants.PROVIDER_CONFIG_ATT,
+ "org.eclipse.linuxtools.profiling.provider.stubby1"); //$NON-NLS-1$
+ // Make each configuration unique
+ wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME,
+ String.valueOf(System.currentTimeMillis()));
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/PreferencesTest.java b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/PreferencesTest.java
index 9c5c929c13..85350a0ae0 100644
--- a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/PreferencesTest.java
+++ b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/PreferencesTest.java
@@ -52,268 +52,268 @@ import org.osgi.framework.FrameworkUtil;
@RunWith(SWTBotJunit4ClassRunner.class)
public class PreferencesTest extends AbstractTest{
- private static final String PROJ_NAME = "fibTest"; //$NON-NLS-1$
- private static final String STUB_TOOLTIP = "tooltip test"; //$NON-NLS-1$
- private static final String STUB_LABEL = "Test Tool [description test]"; //$NON-NLS-1$
- private static final String PROFILING_PREFS_CATEGORY = "Timing"; //$NON-NLS-1$
- private static final String PROFILING_PREFS_TYPE = "timing"; //$NON-NLS-1$
- private static final String[][] PROFILING_PREFS_INFO = {
- { "Coverage", "coverage" }, { "Memory", "memory" },{ "Timing", "timing" } }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-
- private static class NodeAvailableAndSelect extends DefaultCondition {
-
- private SWTBotTree tree;
- private String[] nodes;
-
- /**
- * Wait for a tree node (with a known parent) to become visible, and select it
- * when it does. Note that this wait condition should only be used after having
- * made an attempt to reveal the node.
- * @param tree The SWTBotTree that contains the node to select.
- * @param nodes A list of the names of each node containing the target node.
- */
- NodeAvailableAndSelect(SWTBotTree tree, String ...nodes) {
- this.tree = tree;
- this.nodes = new String[nodes.length];
- System.arraycopy(nodes, 0, this.nodes, 0, nodes.length);
- }
-
- @Override
- public boolean test() {
- try {
- SWTBotTreeItem currentNode = tree.getTreeItem(nodes[0]);
- for (int i = 1, n = nodes.length; i < n; i++) {
- currentNode = currentNode.getNode(nodes[i]);
- }
- currentNode.select();
- return true;
- } catch (WidgetNotFoundException e) {
- return false;
- }
- }
-
- @Override
- public String getFailureMessage() {
- return "Timed out waiting for " + nodes[nodes.length - 1]; //$NON-NLS-1$
- }
- }
-
- @BeforeClass
- public static void setUpWorkbench() throws Exception {
- // Set up is based from from GcovTest{c,CPP}.
-
- SWTWorkbenchBot bot = new SWTWorkbenchBot();
- try {
- bot.viewByTitle("Welcome").close(); //$NON-NLS-1$
- // hide Subclipse Usage stats popup if present/installed
- bot.shell("Subclipse Usage").activate(); //$NON-NLS-1$
- bot.button("Cancel").click(); //$NON-NLS-1$
- } catch (WidgetNotFoundException e) {
- // ignore
- }
-
- // Set C/C++ perspective.
- bot.perspectiveByLabel("C/C++").activate(); //$NON-NLS-1$
- bot.sleep(500);
- for (SWTBotShell sh : bot.shells()) {
- if (sh.getText().startsWith("C/C++")) { //$NON-NLS-1$
- sh.activate();
- bot.sleep(500);
- break;
- }
- }
-
- // Turn off automatic building by default to avoid timing issues
- SWTBotMenu windowsMenu = bot.menu("Window"); //$NON-NLS-1$
- windowsMenu.menu("Preferences").click(); //$NON-NLS-1$
- SWTBotShell shell = bot.shell("Preferences"); //$NON-NLS-1$
- shell.activate();
- bot.text().setText("Workspace"); //$NON-NLS-1$
- bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "General", "Workspace")); //$NON-NLS-1$ //$NON-NLS-2$
- SWTBotCheckBox buildAuto = bot.checkBox("Build automatically"); //$NON-NLS-1$
- if (buildAuto != null && buildAuto.isChecked()) {
- buildAuto.click();
- }
- bot.sleep(1000);
- bot.button("Apply").click(); //$NON-NLS-1$
- bot.button("OK").click(); //$NON-NLS-1$
- bot.waitUntil(shellCloses(shell));
- }
-
- @Test
- public void testDefaultPreferences() {
- for (String[] preferenceInfo : PROFILING_PREFS_INFO) {
- checkDefaultPreference(preferenceInfo[0], preferenceInfo[1]);
- }
- }
-
- @Test
- public void testPreferencesPage() {
- SWTWorkbenchBot bot = new SWTWorkbenchBot();
-
- // Set default tool for "timing" profiling.
- checkDefaultPreference(PROFILING_PREFS_CATEGORY, PROFILING_PREFS_TYPE);
-
- // Open preferences shell.
- SWTBotMenu windowsMenu = bot.menu("Window"); //$NON-NLS-1$
- windowsMenu.menu("Preferences").click(); //$NON-NLS-1$
- SWTBotShell shell = bot.shell("Preferences"); //$NON-NLS-1$
- shell.activate();
-
- // Go to "Profiling Categories" preferences page.
- bot.text().setText(PROFILING_PREFS_CATEGORY);
- bot.waitUntil(new NodeAvailableAndSelect(bot.tree(),
- "C/C++", "Profiling", "Categories", PROFILING_PREFS_CATEGORY)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- // Get name of default tool to deselect.
- String defaultToolId = ProviderFramework.getProviderIdToRun(null, PROFILING_PREFS_TYPE);
- String defaultToolName = ProviderFramework.getToolInformationFromId(defaultToolId , "name"); //$NON-NLS-1$
-
- // Workaround for BZ #344484.
- deselectSelectionByName(defaultToolName, bot);
-
- // Assert specified tool to select is what we expect and select it.
- SWTBotRadio stubRadio = bot.radio(STUB_LABEL);
- assertNotNull(stubRadio);
- assertEquals(STUB_TOOLTIP,stubRadio.getToolTipText());
- stubRadio.click();
-
- bot.button("Apply").click(); //$NON-NLS-1$
- bot.button("OK").click(); //$NON-NLS-1$
- }
-
- @Test
- public void testProfileProject() throws Exception {
- SWTWorkbenchBot bot = new SWTWorkbenchBot();
- proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), PROJ_NAME);
- try {
- testProfileProjectActions(bot);
- } catch (Exception e) {
- throw e;
- } finally {
- deleteProject(proj);
- }
- }
-
- private void testProfileProjectActions(SWTWorkbenchBot bot) throws Exception {
- testPreferencesPage();
-
- // Focus on project explorer view.
- SWTBotView projectExplorer = bot.viewByTitle("Project Explorer"); //$NON-NLS-1$
- projectExplorer.bot().tree().select(PROJ_NAME);
- final Shell shellWidget = bot.activeShell().widget;
-
- // Open profiling configurations dialog
- UIThreadRunnable.asyncExec(new VoidResult() {
- @Override
- public void run() {
- DebugUITools.openLaunchConfigurationDialogOnGroup(shellWidget,
- (StructuredSelection) PlatformUI.getWorkbench().getWorkbenchWindows()[0].
- getSelectionService().getSelection(), "org.eclipse.debug.ui.launchGroup.profilee"); //$NON-NLS-1$
- }
- });
- SWTBotShell shell = bot.shell("Profiling Tools Configurations"); //$NON-NLS-1$
- shell.activate();
-
- // Create new profiling configuration
- SWTBotTree profilingConfigs = bot.tree();
- SWTBotTree perfNode = profilingConfigs.select("Profile Timing"); //$NON-NLS-1$
- perfNode.contextMenu("New").click(); //$NON-NLS-1$
- bot.button("Profile").click(); //$NON-NLS-1$
- bot.waitUntil(Conditions.shellCloses(shell));
-
- // Assert that the expected tool is running.
- SWTBotShell profileShell = bot.shell("Successful profile launch").activate(); //$NON-NLS-1$
- assertNotNull(profileShell);
-
- bot.button("OK").click(); //$NON-NLS-1$
- bot.waitUntil(shellCloses(profileShell));
- }
-
- private static void checkDefaultPreference(String preferenceCategory, String profilingType){
- SWTWorkbenchBot bot = new SWTWorkbenchBot();
-
- // Open preferences shell.
- SWTBotMenu windowsMenu = bot.menu("Window"); //$NON-NLS-1$
- windowsMenu.menu("Preferences").click(); //$NON-NLS-1$
- SWTBotShell shell = bot.shell("Preferences"); //$NON-NLS-1$
- shell.activate();
-
- // Go to specified tree item in "Profiling Categories" preferences page.
- bot.text().setText(preferenceCategory);
- bot.waitUntil(new NodeAvailableAndSelect(bot.tree(),
- "C/C++", "Profiling", "Categories", preferenceCategory)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- // Restore defaults.
- bot.button("Restore Defaults").click(); //$NON-NLS-1$
- bot.button("Apply").click(); //$NON-NLS-1$
-
- // Get information for default tool.
- String defaultToolId = ProviderFramework.getProviderIdToRun(null, profilingType);
- String defaultToolName = ProviderFramework.getToolInformationFromId(defaultToolId , "name"); //$NON-NLS-1$
- String defaultToolInfo = ProviderFramework.getToolInformationFromId(defaultToolId , "information"); //$NON-NLS-1$
- String defaultToolDescription = ProviderFramework.getToolInformationFromId(defaultToolId , "description"); //$NON-NLS-1$
- String defaultToolLabel = defaultToolName + " [" + defaultToolDescription + "]"; //$NON-NLS-1$ //$NON-NLS-2$
-
- // Assert default radio is as expected.
- SWTBotRadio defaultRadio = bot.radio(defaultToolLabel);
- assertNotNull(defaultRadio);
- assertEquals(defaultToolInfo, defaultRadio.getToolTipText());
-
- bot.button("Apply").click(); //$NON-NLS-1$
- bot.button("OK").click(); //$NON-NLS-1$
- }
-
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return null;
- }
-
- @Override
- protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- }
-
- /**
- * Deselect radio button with partial label name.
- *
- * Adapted workaround for BZ #344484:
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=344484#c1
- *
- * @param name partial label of radio button to deselect.
- */
- public static void deselectSelectionByName(final String name, final SWTWorkbenchBot bot) {
- UIThreadRunnable.syncExec(new VoidResult() {
- @Override
- public void run() {
- @SuppressWarnings("unchecked")
- Matcher<Widget> matcher = allOf(widgetOfType(Button.class),
- withStyle(SWT.RADIO, "SWT.RADIO"), //$NON-NLS-1$
- withRegex(name + ".*")); //$NON-NLS-1$
-
- Button b = (Button) bot.widget(matcher); // the current selection
- b.setSelection(false);
- }
- });
- }
-
- /**
- * Click specfied menu item.
- *
- * @param menuItem
- * menu item to click
- */
- public static void click(final MenuItem menuItem) {
- final Event event = new Event();
- event.time = (int) System.currentTimeMillis();
- event.widget = menuItem;
- event.display = menuItem.getDisplay();
- event.type = SWT.Selection;
-
- UIThreadRunnable.asyncExec(menuItem.getDisplay(), new VoidResult() {
- @Override
- public void run() {
- menuItem.notifyListeners(SWT.Selection, event);
- }
- });
- }
+ private static final String PROJ_NAME = "fibTest"; //$NON-NLS-1$
+ private static final String STUB_TOOLTIP = "tooltip test"; //$NON-NLS-1$
+ private static final String STUB_LABEL = "Test Tool [description test]"; //$NON-NLS-1$
+ private static final String PROFILING_PREFS_CATEGORY = "Timing"; //$NON-NLS-1$
+ private static final String PROFILING_PREFS_TYPE = "timing"; //$NON-NLS-1$
+ private static final String[][] PROFILING_PREFS_INFO = {
+ { "Coverage", "coverage" }, { "Memory", "memory" },{ "Timing", "timing" } }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+
+ private static class NodeAvailableAndSelect extends DefaultCondition {
+
+ private SWTBotTree tree;
+ private String[] nodes;
+
+ /**
+ * Wait for a tree node (with a known parent) to become visible, and select it
+ * when it does. Note that this wait condition should only be used after having
+ * made an attempt to reveal the node.
+ * @param tree The SWTBotTree that contains the node to select.
+ * @param nodes A list of the names of each node containing the target node.
+ */
+ NodeAvailableAndSelect(SWTBotTree tree, String ...nodes) {
+ this.tree = tree;
+ this.nodes = new String[nodes.length];
+ System.arraycopy(nodes, 0, this.nodes, 0, nodes.length);
+ }
+
+ @Override
+ public boolean test() {
+ try {
+ SWTBotTreeItem currentNode = tree.getTreeItem(nodes[0]);
+ for (int i = 1, n = nodes.length; i < n; i++) {
+ currentNode = currentNode.getNode(nodes[i]);
+ }
+ currentNode.select();
+ return true;
+ } catch (WidgetNotFoundException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return "Timed out waiting for " + nodes[nodes.length - 1]; //$NON-NLS-1$
+ }
+ }
+
+ @BeforeClass
+ public static void setUpWorkbench() throws Exception {
+ // Set up is based from from GcovTest{c,CPP}.
+
+ SWTWorkbenchBot bot = new SWTWorkbenchBot();
+ try {
+ bot.viewByTitle("Welcome").close(); //$NON-NLS-1$
+ // hide Subclipse Usage stats popup if present/installed
+ bot.shell("Subclipse Usage").activate(); //$NON-NLS-1$
+ bot.button("Cancel").click(); //$NON-NLS-1$
+ } catch (WidgetNotFoundException e) {
+ // ignore
+ }
+
+ // Set C/C++ perspective.
+ bot.perspectiveByLabel("C/C++").activate(); //$NON-NLS-1$
+ bot.sleep(500);
+ for (SWTBotShell sh : bot.shells()) {
+ if (sh.getText().startsWith("C/C++")) { //$NON-NLS-1$
+ sh.activate();
+ bot.sleep(500);
+ break;
+ }
+ }
+
+ // Turn off automatic building by default to avoid timing issues
+ SWTBotMenu windowsMenu = bot.menu("Window"); //$NON-NLS-1$
+ windowsMenu.menu("Preferences").click(); //$NON-NLS-1$
+ SWTBotShell shell = bot.shell("Preferences"); //$NON-NLS-1$
+ shell.activate();
+ bot.text().setText("Workspace"); //$NON-NLS-1$
+ bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "General", "Workspace")); //$NON-NLS-1$ //$NON-NLS-2$
+ SWTBotCheckBox buildAuto = bot.checkBox("Build automatically"); //$NON-NLS-1$
+ if (buildAuto != null && buildAuto.isChecked()) {
+ buildAuto.click();
+ }
+ bot.sleep(1000);
+ bot.button("Apply").click(); //$NON-NLS-1$
+ bot.button("OK").click(); //$NON-NLS-1$
+ bot.waitUntil(shellCloses(shell));
+ }
+
+ @Test
+ public void testDefaultPreferences() {
+ for (String[] preferenceInfo : PROFILING_PREFS_INFO) {
+ checkDefaultPreference(preferenceInfo[0], preferenceInfo[1]);
+ }
+ }
+
+ @Test
+ public void testPreferencesPage() {
+ SWTWorkbenchBot bot = new SWTWorkbenchBot();
+
+ // Set default tool for "timing" profiling.
+ checkDefaultPreference(PROFILING_PREFS_CATEGORY, PROFILING_PREFS_TYPE);
+
+ // Open preferences shell.
+ SWTBotMenu windowsMenu = bot.menu("Window"); //$NON-NLS-1$
+ windowsMenu.menu("Preferences").click(); //$NON-NLS-1$
+ SWTBotShell shell = bot.shell("Preferences"); //$NON-NLS-1$
+ shell.activate();
+
+ // Go to "Profiling Categories" preferences page.
+ bot.text().setText(PROFILING_PREFS_CATEGORY);
+ bot.waitUntil(new NodeAvailableAndSelect(bot.tree(),
+ "C/C++", "Profiling", "Categories", PROFILING_PREFS_CATEGORY)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ // Get name of default tool to deselect.
+ String defaultToolId = ProviderFramework.getProviderIdToRun(null, PROFILING_PREFS_TYPE);
+ String defaultToolName = ProviderFramework.getToolInformationFromId(defaultToolId , "name"); //$NON-NLS-1$
+
+ // Workaround for BZ #344484.
+ deselectSelectionByName(defaultToolName, bot);
+
+ // Assert specified tool to select is what we expect and select it.
+ SWTBotRadio stubRadio = bot.radio(STUB_LABEL);
+ assertNotNull(stubRadio);
+ assertEquals(STUB_TOOLTIP,stubRadio.getToolTipText());
+ stubRadio.click();
+
+ bot.button("Apply").click(); //$NON-NLS-1$
+ bot.button("OK").click(); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testProfileProject() throws Exception {
+ SWTWorkbenchBot bot = new SWTWorkbenchBot();
+ proj = createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), PROJ_NAME);
+ try {
+ testProfileProjectActions(bot);
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ deleteProject(proj);
+ }
+ }
+
+ private void testProfileProjectActions(SWTWorkbenchBot bot) throws Exception {
+ testPreferencesPage();
+
+ // Focus on project explorer view.
+ SWTBotView projectExplorer = bot.viewByTitle("Project Explorer"); //$NON-NLS-1$
+ projectExplorer.bot().tree().select(PROJ_NAME);
+ final Shell shellWidget = bot.activeShell().widget;
+
+ // Open profiling configurations dialog
+ UIThreadRunnable.asyncExec(new VoidResult() {
+ @Override
+ public void run() {
+ DebugUITools.openLaunchConfigurationDialogOnGroup(shellWidget,
+ (StructuredSelection) PlatformUI.getWorkbench().getWorkbenchWindows()[0].
+ getSelectionService().getSelection(), "org.eclipse.debug.ui.launchGroup.profilee"); //$NON-NLS-1$
+ }
+ });
+ SWTBotShell shell = bot.shell("Profiling Tools Configurations"); //$NON-NLS-1$
+ shell.activate();
+
+ // Create new profiling configuration
+ SWTBotTree profilingConfigs = bot.tree();
+ SWTBotTree perfNode = profilingConfigs.select("Profile Timing"); //$NON-NLS-1$
+ perfNode.contextMenu("New").click(); //$NON-NLS-1$
+ bot.button("Profile").click(); //$NON-NLS-1$
+ bot.waitUntil(Conditions.shellCloses(shell));
+
+ // Assert that the expected tool is running.
+ SWTBotShell profileShell = bot.shell("Successful profile launch").activate(); //$NON-NLS-1$
+ assertNotNull(profileShell);
+
+ bot.button("OK").click(); //$NON-NLS-1$
+ bot.waitUntil(shellCloses(profileShell));
+ }
+
+ private static void checkDefaultPreference(String preferenceCategory, String profilingType){
+ SWTWorkbenchBot bot = new SWTWorkbenchBot();
+
+ // Open preferences shell.
+ SWTBotMenu windowsMenu = bot.menu("Window"); //$NON-NLS-1$
+ windowsMenu.menu("Preferences").click(); //$NON-NLS-1$
+ SWTBotShell shell = bot.shell("Preferences"); //$NON-NLS-1$
+ shell.activate();
+
+ // Go to specified tree item in "Profiling Categories" preferences page.
+ bot.text().setText(preferenceCategory);
+ bot.waitUntil(new NodeAvailableAndSelect(bot.tree(),
+ "C/C++", "Profiling", "Categories", preferenceCategory)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ // Restore defaults.
+ bot.button("Restore Defaults").click(); //$NON-NLS-1$
+ bot.button("Apply").click(); //$NON-NLS-1$
+
+ // Get information for default tool.
+ String defaultToolId = ProviderFramework.getProviderIdToRun(null, profilingType);
+ String defaultToolName = ProviderFramework.getToolInformationFromId(defaultToolId , "name"); //$NON-NLS-1$
+ String defaultToolInfo = ProviderFramework.getToolInformationFromId(defaultToolId , "information"); //$NON-NLS-1$
+ String defaultToolDescription = ProviderFramework.getToolInformationFromId(defaultToolId , "description"); //$NON-NLS-1$
+ String defaultToolLabel = defaultToolName + " [" + defaultToolDescription + "]"; //$NON-NLS-1$ //$NON-NLS-2$
+
+ // Assert default radio is as expected.
+ SWTBotRadio defaultRadio = bot.radio(defaultToolLabel);
+ assertNotNull(defaultRadio);
+ assertEquals(defaultToolInfo, defaultRadio.getToolTipText());
+
+ bot.button("Apply").click(); //$NON-NLS-1$
+ bot.button("OK").click(); //$NON-NLS-1$
+ }
+
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return null;
+ }
+
+ @Override
+ protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ }
+
+ /**
+ * Deselect radio button with partial label name.
+ *
+ * Adapted workaround for BZ #344484:
+ * https://bugs.eclipse.org/bugs/show_bug.cgi?id=344484#c1
+ *
+ * @param name partial label of radio button to deselect.
+ */
+ public static void deselectSelectionByName(final String name, final SWTWorkbenchBot bot) {
+ UIThreadRunnable.syncExec(new VoidResult() {
+ @Override
+ public void run() {
+ @SuppressWarnings("unchecked")
+ Matcher<Widget> matcher = allOf(widgetOfType(Button.class),
+ withStyle(SWT.RADIO, "SWT.RADIO"), //$NON-NLS-1$
+ withRegex(name + ".*")); //$NON-NLS-1$
+
+ Button b = (Button) bot.widget(matcher); // the current selection
+ b.setSelection(false);
+ }
+ });
+ }
+
+ /**
+ * Click specfied menu item.
+ *
+ * @param menuItem
+ * menu item to click
+ */
+ public static void click(final MenuItem menuItem) {
+ final Event event = new Event();
+ event.time = (int) System.currentTimeMillis();
+ event.widget = menuItem;
+ event.display = menuItem.getDisplay();
+ event.type = SWT.Selection;
+
+ UIThreadRunnable.asyncExec(menuItem.getDisplay(), new VoidResult() {
+ @Override
+ public void run() {
+ menuItem.notifyListeners(SWT.Selection, event);
+ }
+ });
+ }
} \ No newline at end of file
diff --git a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchConfigurationDelegate.java b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchConfigurationDelegate.java
index 6f62516755..9681a0d588 100644
--- a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchConfigurationDelegate.java
+++ b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchConfigurationDelegate.java
@@ -17,14 +17,14 @@ import org.eclipse.debug.core.ILaunchConfiguration;
public class StubbyLaunchConfigurationDelegate extends AbstractCLaunchDelegate {
- @Override
- public void launch(ILaunchConfiguration configuration, String mode,
- ILaunch launch, IProgressMonitor monitor) {
- }
+ @Override
+ public void launch(ILaunchConfiguration configuration, String mode,
+ ILaunch launch, IProgressMonitor monitor) {
+ }
- @Override
- protected String getPluginID() {
- return null;
- }
+ @Override
+ protected String getPluginID() {
+ return null;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchConfigurationTabGroup.java b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchConfigurationTabGroup.java
index 7ba8ed2f61..aa502ba80f 100644
--- a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchConfigurationTabGroup.java
+++ b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchConfigurationTabGroup.java
@@ -14,11 +14,11 @@ import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTabGroup;
public class StubbyLaunchConfigurationTabGroup extends
- ProfileLaunchConfigurationTabGroup {
+ ProfileLaunchConfigurationTabGroup {
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- return new AbstractLaunchConfigurationTab [] {};
- }
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ return new AbstractLaunchConfigurationTab [] {};
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchShortcut.java b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchShortcut.java
index 3ab0723955..f53fe0b6e4 100644
--- a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchShortcut.java
+++ b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyLaunchShortcut.java
@@ -16,15 +16,15 @@ import org.eclipse.linuxtools.profiling.launch.ProfileLaunchShortcut;
public class StubbyLaunchShortcut extends ProfileLaunchShortcut {
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType("org.eclipse.linuxtools.profiling.stubby.launchConfigurationType"); //$NON-NLS-1$
- }
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType("org.eclipse.linuxtools.profiling.stubby.launchConfigurationType"); //$NON-NLS-1$
+ }
- @Override
- protected void setDefaultProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- // Set this for testing purposes
- wc.setAttribute("foo", "bar"); //$NON-NLS-1$ //$NON-NLS-2$
- }
+ @Override
+ protected void setDefaultProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ // Set this for testing purposes
+ wc.setAttribute("foo", "bar"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyTimingLaunchConfigurationDelegate.java b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyTimingLaunchConfigurationDelegate.java
index 119b9fd163..e6dfa03ff5 100644
--- a/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyTimingLaunchConfigurationDelegate.java
+++ b/profiling/org.eclipse.linuxtools.profiling.provider.tests/src/org/eclipse/linuxtools/profiling/provider/tests/stubby/StubbyTimingLaunchConfigurationDelegate.java
@@ -19,20 +19,20 @@ import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
public class StubbyTimingLaunchConfigurationDelegate extends
- StubbyLaunchConfigurationDelegate {
+ StubbyLaunchConfigurationDelegate {
- @Override
- public void launch(ILaunchConfiguration configuration, String mode,
- ILaunch launch, IProgressMonitor monitor) {
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- IWorkbenchWindow window = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow();
- MessageDialog.openConfirm(window.getShell(),
- "Successful profile launch", //$NON-NLS-1$
- "Successful profile launch"); //$NON-NLS-1$
- }
- });
- }
+ @Override
+ public void launch(ILaunchConfiguration configuration, String mode,
+ ILaunch launch, IProgressMonitor monitor) {
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ IWorkbenchWindow window = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow();
+ MessageDialog.openConfirm(window.getShell(),
+ "Successful profile launch", //$NON-NLS-1$
+ "Successful profile launch"); //$NON-NLS-1$
+ }
+ });
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/internal/profiling/tests/CProjectHelper.java b/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/internal/profiling/tests/CProjectHelper.java
index fda404926c..740696d908 100644
--- a/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/internal/profiling/tests/CProjectHelper.java
+++ b/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/internal/profiling/tests/CProjectHelper.java
@@ -62,311 +62,311 @@ import org.osgi.framework.Bundle;
*/
public class CProjectHelper {
- public final static String PLUGIN_ID = "org.eclipse.linuxtools.profiling.tests"; //$NON-NLS-1$
+ public final static String PLUGIN_ID = "org.eclipse.linuxtools.profiling.tests"; //$NON-NLS-1$
- private final static IOverwriteQuery OVERWRITE_QUERY= new IOverwriteQuery() {
- @Override
- public String queryOverwrite(String file) {
- return ALL;
- }
- };
+ private final static IOverwriteQuery OVERWRITE_QUERY= new IOverwriteQuery() {
+ @Override
+ public String queryOverwrite(String file) {
+ return ALL;
+ }
+ };
- public static ICProject createCProject(final String projectName, String binFolderName) throws CoreException {
- return createCCProject(projectName, binFolderName);
- }
+ public static ICProject createCProject(final String projectName, String binFolderName) throws CoreException {
+ return createCCProject(projectName, binFolderName);
+ }
- /**
- * Creates a ICProject.
- */
- private static ICProject createCProject2(final String projectName, String binFolderName) throws CoreException {
- final IWorkspace ws = ResourcesPlugin.getWorkspace();
- final ICProject newProject[] = new ICProject[1];
- ws.run(new IWorkspaceRunnable() {
+ /**
+ * Creates a ICProject.
+ */
+ private static ICProject createCProject2(final String projectName, String binFolderName) throws CoreException {
+ final IWorkspace ws = ResourcesPlugin.getWorkspace();
+ final ICProject newProject[] = new ICProject[1];
+ ws.run(new IWorkspaceRunnable() {
- @Override
- public void run(IProgressMonitor monitor) throws CoreException {
- IWorkspaceRoot root = ws.getRoot();
- IProject project = root.getProject(projectName);
- if (!project.exists()) {
- project.create(null);
- } else {
- project.refreshLocal(IResource.DEPTH_INFINITE, null);
- }
- if (!project.isOpen()) {
- project.open(null);
- }
- if (!project.hasNature(CProjectNature.C_NATURE_ID)) {
- String projectId = PLUGIN_ID + ".TestProject"; //$NON-NLS-1$
- addNatureToProject(project, CProjectNature.C_NATURE_ID, null);
- CCorePlugin.getDefault().mapCProjectOwner(project, projectId, false);
- }
- addDefaultBinaryParser(project);
- newProject[0] = CCorePlugin.getDefault().getCoreModel().create(project);
- }
- }, null);
+ @Override
+ public void run(IProgressMonitor monitor) throws CoreException {
+ IWorkspaceRoot root = ws.getRoot();
+ IProject project = root.getProject(projectName);
+ if (!project.exists()) {
+ project.create(null);
+ } else {
+ project.refreshLocal(IResource.DEPTH_INFINITE, null);
+ }
+ if (!project.isOpen()) {
+ project.open(null);
+ }
+ if (!project.hasNature(CProjectNature.C_NATURE_ID)) {
+ String projectId = PLUGIN_ID + ".TestProject"; //$NON-NLS-1$
+ addNatureToProject(project, CProjectNature.C_NATURE_ID, null);
+ CCorePlugin.getDefault().mapCProjectOwner(project, projectId, false);
+ }
+ addDefaultBinaryParser(project);
+ newProject[0] = CCorePlugin.getDefault().getCoreModel().create(project);
+ }
+ }, null);
- return newProject[0];
- }
+ return newProject[0];
+ }
- /**
- * Add the default binary parser if no binary parser configured.
- *
- * @param project
- * @throws CoreException
- */
- public static boolean addDefaultBinaryParser(IProject project) throws CoreException {
- ICConfigExtensionReference[] binaryParsers= CCorePlugin.getDefault().getDefaultBinaryParserExtensions(project);
- if (binaryParsers == null || binaryParsers.length == 0) {
- ICProjectDescription desc= CCorePlugin.getDefault().getProjectDescription(project);
- if (desc == null) {
- return false;
- }
+ /**
+ * Add the default binary parser if no binary parser configured.
+ *
+ * @param project
+ * @throws CoreException
+ */
+ public static boolean addDefaultBinaryParser(IProject project) throws CoreException {
+ ICConfigExtensionReference[] binaryParsers= CCorePlugin.getDefault().getDefaultBinaryParserExtensions(project);
+ if (binaryParsers == null || binaryParsers.length == 0) {
+ ICProjectDescription desc= CCorePlugin.getDefault().getProjectDescription(project);
+ if (desc == null) {
+ return false;
+ }
- desc.getDefaultSettingConfiguration().create(CCorePlugin.BINARY_PARSER_UNIQ_ID, CCorePlugin.DEFAULT_BINARY_PARSER_UNIQ_ID);
- CCorePlugin.getDefault().setProjectDescription(project, desc);
- }
- return true;
- }
+ desc.getDefaultSettingConfiguration().create(CCorePlugin.BINARY_PARSER_UNIQ_ID, CCorePlugin.DEFAULT_BINARY_PARSER_UNIQ_ID);
+ CCorePlugin.getDefault().setProjectDescription(project, desc);
+ }
+ return true;
+ }
- private static String getMessage(IStatus status) {
- StringBuffer message = new StringBuffer("[");
- message.append(status.getMessage());
- if (status.isMultiStatus()) {
- IStatus children[] = status.getChildren();
- for( int i = 0; i < children.length; i++) {
- message.append(getMessage(children[i]));
- }
- }
- message.append("]");
- return message.toString();
- }
+ private static String getMessage(IStatus status) {
+ StringBuffer message = new StringBuffer("[");
+ message.append(status.getMessage());
+ if (status.isMultiStatus()) {
+ IStatus children[] = status.getChildren();
+ for( int i = 0; i < children.length; i++) {
+ message.append(getMessage(children[i]));
+ }
+ }
+ message.append("]");
+ return message.toString();
+ }
- public static ICProject createCCProject(final String projectName, final String binFolderName) throws CoreException {
- final IWorkspace ws = ResourcesPlugin.getWorkspace();
- final ICProject newProject[] = new ICProject[1];
- ws.run(new IWorkspaceRunnable() {
+ public static ICProject createCCProject(final String projectName, final String binFolderName) throws CoreException {
+ final IWorkspace ws = ResourcesPlugin.getWorkspace();
+ final ICProject newProject[] = new ICProject[1];
+ ws.run(new IWorkspaceRunnable() {
- @Override
- public void run(IProgressMonitor monitor) throws CoreException {
- ICProject cproject = createCProject2(projectName, binFolderName);
- if (!cproject.getProject().hasNature(CCProjectNature.CC_NATURE_ID)) {
- addNatureToProject(cproject.getProject(), CCProjectNature.CC_NATURE_ID, null);
- }
- newProject[0] = cproject;
- }
- }, null);
- return newProject[0];
- }
+ @Override
+ public void run(IProgressMonitor monitor) throws CoreException {
+ ICProject cproject = createCProject2(projectName, binFolderName);
+ if (!cproject.getProject().hasNature(CCProjectNature.CC_NATURE_ID)) {
+ addNatureToProject(cproject.getProject(), CCProjectNature.CC_NATURE_ID, null);
+ }
+ newProject[0] = cproject;
+ }
+ }, null);
+ return newProject[0];
+ }
- /**
- * Removes a ICProject.
- */
- public static void delete(ICProject cproject) {
- try {
- cproject.getProject().delete(true, true, null);
- } catch (CoreException e) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e1) {
- } finally {
- try {
- System.gc();
- System.runFinalization();
- cproject.getProject().delete(true, true, null);
- } catch (CoreException e2) {
- fail(getMessage(e2.getStatus()));
- }
- }
- }
- }
+ /**
+ * Removes a ICProject.
+ */
+ public static void delete(ICProject cproject) {
+ try {
+ cproject.getProject().delete(true, true, null);
+ } catch (CoreException e) {
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e1) {
+ } finally {
+ try {
+ System.gc();
+ System.runFinalization();
+ cproject.getProject().delete(true, true, null);
+ } catch (CoreException e2) {
+ fail(getMessage(e2.getStatus()));
+ }
+ }
+ }
+ }
- /**
- * Adds a folder container to a ICProject.
- */
- public static ICContainer addCContainer(ICProject cproject, String containerName) throws CoreException {
- IProject project = cproject.getProject();
- ICContainer container = null;
- if (containerName == null || containerName.length() == 0) {
- ICContainer[] conts = cproject.getSourceRoots();
- if (conts.length > 0) {
- container = conts[0];
- }
- } else {
- IFolder folder = project.getFolder(containerName);
- if (!folder.exists()) {
- folder.create(false, true, null);
- }
- container = CoreModel.getDefault().create(folder);
- }
- return container;
- }
+ /**
+ * Adds a folder container to a ICProject.
+ */
+ public static ICContainer addCContainer(ICProject cproject, String containerName) throws CoreException {
+ IProject project = cproject.getProject();
+ ICContainer container = null;
+ if (containerName == null || containerName.length() == 0) {
+ ICContainer[] conts = cproject.getSourceRoots();
+ if (conts.length > 0) {
+ container = conts[0];
+ }
+ } else {
+ IFolder folder = project.getFolder(containerName);
+ if (!folder.exists()) {
+ folder.create(false, true, null);
+ }
+ container = CoreModel.getDefault().create(folder);
+ }
+ return container;
+ }
- /**
- * Adds a folder container to a ICProject and imports all files contained in the given Zip file.
- */
- public static ICContainer addCContainerWithImport(ICProject cproject, String containerName, ZipFile zipFile)
- throws InvocationTargetException, CoreException {
- ICContainer root = addCContainer(cproject, containerName);
- importFilesFromZip(zipFile, root.getPath(), null);
- return root;
- }
+ /**
+ * Adds a folder container to a ICProject and imports all files contained in the given Zip file.
+ */
+ public static ICContainer addCContainerWithImport(ICProject cproject, String containerName, ZipFile zipFile)
+ throws InvocationTargetException, CoreException {
+ ICContainer root = addCContainer(cproject, containerName);
+ importFilesFromZip(zipFile, root.getPath(), null);
+ return root;
+ }
- /**
- * Removes a folder from a ICProject.
- */
- public static void removeCContainer(ICProject cproject, String containerName) throws CoreException {
- IFolder folder = cproject.getProject().getFolder(containerName);
- folder.delete(true, null);
- }
+ /**
+ * Removes a folder from a ICProject.
+ */
+ public static void removeCContainer(ICProject cproject, String containerName) throws CoreException {
+ IFolder folder = cproject.getProject().getFolder(containerName);
+ folder.delete(true, null);
+ }
- /**
- * Attempts to find an archive with the given name in the workspace
- */
- public static IArchive findArchive(ICProject testProject, String name) throws CModelException {
- int x;
- IArchive[] myArchives;
- IArchiveContainer archCont;
- /***************************************************************************************************************************
- * Since ArchiveContainer.getArchives does not wait until all the archives in the project have been parsed before returning
- * the list, we have to do a sync ArchiveContainer.getChildren first to make sure we find all the archives.
- */
- archCont = testProject.getArchiveContainer();
- myArchives = archCont.getArchives();
- if (myArchives.length < 1)
- return (null);
- for (x = 0; x < myArchives.length; x++) {
- if (myArchives[x].getElementName().equals(name))
- return (myArchives[x]);
- }
- return (null);
- }
+ /**
+ * Attempts to find an archive with the given name in the workspace
+ */
+ public static IArchive findArchive(ICProject testProject, String name) throws CModelException {
+ int x;
+ IArchive[] myArchives;
+ IArchiveContainer archCont;
+ /***************************************************************************************************************************
+ * Since ArchiveContainer.getArchives does not wait until all the archives in the project have been parsed before returning
+ * the list, we have to do a sync ArchiveContainer.getChildren first to make sure we find all the archives.
+ */
+ archCont = testProject.getArchiveContainer();
+ myArchives = archCont.getArchives();
+ if (myArchives.length < 1)
+ return (null);
+ for (x = 0; x < myArchives.length; x++) {
+ if (myArchives[x].getElementName().equals(name))
+ return (myArchives[x]);
+ }
+ return (null);
+ }
- /**
- * Attempts to find a binary with the given name in the workspace
- */
- public static IBinary findBinary(ICProject testProject, String name) throws CModelException {
- IBinaryContainer binCont;
- int x;
- IBinary[] myBinaries;
- binCont = testProject.getBinaryContainer();
- myBinaries = binCont.getBinaries();
- if (myBinaries.length < 1)
- return (null);
- for (x = 0; x < myBinaries.length; x++) {
- if (myBinaries[x].getElementName().equals(name))
- return (myBinaries[x]);
- }
- return (null);
- }
+ /**
+ * Attempts to find a binary with the given name in the workspace
+ */
+ public static IBinary findBinary(ICProject testProject, String name) throws CModelException {
+ IBinaryContainer binCont;
+ int x;
+ IBinary[] myBinaries;
+ binCont = testProject.getBinaryContainer();
+ myBinaries = binCont.getBinaries();
+ if (myBinaries.length < 1)
+ return (null);
+ for (x = 0; x < myBinaries.length; x++) {
+ if (myBinaries[x].getElementName().equals(name))
+ return (myBinaries[x]);
+ }
+ return (null);
+ }
- /**
- * Attempts to find an object with the given name in the workspace
- */
- public static IBinary findObject(ICProject testProject, String name) throws CModelException {
- ICElement[] sourceRoots = testProject.getChildren();
- for (int i = 0; i < sourceRoots.length; i++) {
- ISourceRoot root = (ISourceRoot) sourceRoots[i];
- ICElement[] myElements = root.getChildren();
- for (int x = 0; x < myElements.length; x++) {
- if (myElements[x].getElementName().equals(name)) {
- if (myElements[x] instanceof IBinary) {
- return ((IBinary) myElements[x]);
- }
- }
- }
- }
- return null;
- }
+ /**
+ * Attempts to find an object with the given name in the workspace
+ */
+ public static IBinary findObject(ICProject testProject, String name) throws CModelException {
+ ICElement[] sourceRoots = testProject.getChildren();
+ for (int i = 0; i < sourceRoots.length; i++) {
+ ISourceRoot root = (ISourceRoot) sourceRoots[i];
+ ICElement[] myElements = root.getChildren();
+ for (int x = 0; x < myElements.length; x++) {
+ if (myElements[x].getElementName().equals(name)) {
+ if (myElements[x] instanceof IBinary) {
+ return ((IBinary) myElements[x]);
+ }
+ }
+ }
+ }
+ return null;
+ }
- /**
- * Attempts to find a TranslationUnit with the given name in the workspace
- * @throws InterruptedException
- */
- public static ITranslationUnit findTranslationUnit(ICProject testProject, String name) throws CModelException, InterruptedException {
- for (int j=0; j<20; j++) {
- ICElement[] sourceRoots = testProject.getChildren();
- for (int i = 0; i < sourceRoots.length; i++) {
- ISourceRoot root = (ISourceRoot) sourceRoots[i];
- ICElement[] myElements = root.getChildren();
- for (int x = 0; x < myElements.length; x++) {
- if (myElements[x].getElementName().equals(name)) {
- if (myElements[x] instanceof ITranslationUnit) {
- return ((ITranslationUnit) myElements[x]);
- }
- }
- }
- }
- Thread.sleep(100);
- }
- return null;
- }
+ /**
+ * Attempts to find a TranslationUnit with the given name in the workspace
+ * @throws InterruptedException
+ */
+ public static ITranslationUnit findTranslationUnit(ICProject testProject, String name) throws CModelException, InterruptedException {
+ for (int j=0; j<20; j++) {
+ ICElement[] sourceRoots = testProject.getChildren();
+ for (int i = 0; i < sourceRoots.length; i++) {
+ ISourceRoot root = (ISourceRoot) sourceRoots[i];
+ ICElement[] myElements = root.getChildren();
+ for (int x = 0; x < myElements.length; x++) {
+ if (myElements[x].getElementName().equals(name)) {
+ if (myElements[x] instanceof ITranslationUnit) {
+ return ((ITranslationUnit) myElements[x]);
+ }
+ }
+ }
+ }
+ Thread.sleep(100);
+ }
+ return null;
+ }
- /**
- * Attempts to find an element with the given name in the workspace
- */
- public static ICElement findElement(ICProject testProject, String name) throws CModelException {
- ICElement[] sourceRoots = testProject.getChildren();
- for (int i = 0; i < sourceRoots.length; i++) {
- ISourceRoot root = (ISourceRoot) sourceRoots[i];
- ICElement[] myElements = root.getChildren();
- for (int x = 0; x < myElements.length; x++) {
- if (myElements[x].getElementName().equals(name)) {
- return myElements[x];
- }
- }
- }
- return null;
- }
+ /**
+ * Attempts to find an element with the given name in the workspace
+ */
+ public static ICElement findElement(ICProject testProject, String name) throws CModelException {
+ ICElement[] sourceRoots = testProject.getChildren();
+ for (int i = 0; i < sourceRoots.length; i++) {
+ ISourceRoot root = (ISourceRoot) sourceRoots[i];
+ ICElement[] myElements = root.getChildren();
+ for (int x = 0; x < myElements.length; x++) {
+ if (myElements[x].getElementName().equals(name)) {
+ return myElements[x];
+ }
+ }
+ }
+ return null;
+ }
- public static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
- IProjectDescription description = proj.getDescription();
- String[] prevNatures = description.getNatureIds();
- String[] newNatures = new String[prevNatures.length + 1];
- System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
- newNatures[prevNatures.length] = natureId;
- description.setNatureIds(newNatures);
- proj.setDescription(description, monitor);
- }
+ public static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
+ IProjectDescription description = proj.getDescription();
+ String[] prevNatures = description.getNatureIds();
+ String[] newNatures = new String[prevNatures.length + 1];
+ System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
+ newNatures[prevNatures.length] = natureId;
+ description.setNatureIds(newNatures);
+ proj.setDescription(description, monitor);
+ }
- private static void importFilesFromZip(ZipFile srcZipFile, IPath destPath, IProgressMonitor monitor)
- throws InvocationTargetException {
- ZipFileStructureProvider structureProvider = new ZipFileStructureProvider(srcZipFile);
- try {
- ImportOperation op = new ImportOperation(destPath, structureProvider.getRoot(), structureProvider,
- OVERWRITE_QUERY);
- op.run(monitor);
- } catch (InterruptedException e) {
- // should not happen
- }
- }
+ private static void importFilesFromZip(ZipFile srcZipFile, IPath destPath, IProgressMonitor monitor)
+ throws InvocationTargetException {
+ ZipFileStructureProvider structureProvider = new ZipFileStructureProvider(srcZipFile);
+ try {
+ ImportOperation op = new ImportOperation(destPath, structureProvider.getRoot(), structureProvider,
+ OVERWRITE_QUERY);
+ op.run(monitor);
+ } catch (InterruptedException e) {
+ // should not happen
+ }
+ }
- public static void importSourcesFromPlugin(ICProject project, Bundle bundle, String sources) throws CoreException {
- try {
- String baseDir= FileLocator.toFileURL(FileLocator.find(bundle, new Path(sources), null)).getFile();
- ImportOperation importOp = new ImportOperation(project.getProject().getFullPath(),
- new File(baseDir), FileSystemStructureProvider.INSTANCE, OVERWRITE_QUERY);
- importOp.setCreateContainerStructure(false);
- importOp.run(new NullProgressMonitor());
- }
- catch (Exception e) {
- throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, 0, "Import Interrupted", e));
- }
- }
+ public static void importSourcesFromPlugin(ICProject project, Bundle bundle, String sources) throws CoreException {
+ try {
+ String baseDir= FileLocator.toFileURL(FileLocator.find(bundle, new Path(sources), null)).getFile();
+ ImportOperation importOp = new ImportOperation(project.getProject().getFullPath(),
+ new File(baseDir), FileSystemStructureProvider.INSTANCE, OVERWRITE_QUERY);
+ importOp.setCreateContainerStructure(false);
+ importOp.run(new NullProgressMonitor());
+ }
+ catch (Exception e) {
+ throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, 0, "Import Interrupted", e));
+ }
+ }
- /**
- * @return the location of a newly created directory in temporary area.
- * Note that cleanup should be done with {@link ResourceHelper#cleanUp()}.
- * @throws CoreException
- */
- public static File freshDir() throws CoreException {
- IPath folderPath = ResourceHelper.createTemporaryFolder();
- File folder = new File(folderPath.toOSString());
- assertTrue(folder.exists());
- assertTrue(folder.isDirectory());
- assertTrue(folder.canWrite());
+ /**
+ * @return the location of a newly created directory in temporary area.
+ * Note that cleanup should be done with {@link ResourceHelper#cleanUp()}.
+ * @throws CoreException
+ */
+ public static File freshDir() throws CoreException {
+ IPath folderPath = ResourceHelper.createTemporaryFolder();
+ File folder = new File(folderPath.toOSString());
+ assertTrue(folder.exists());
+ assertTrue(folder.isDirectory());
+ assertTrue(folder.canWrite());
- return folder;
- }
+ return folder;
+ }
} \ No newline at end of file
diff --git a/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/internal/profiling/tests/ResourceHelper.java b/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/internal/profiling/tests/ResourceHelper.java
index ded4d9614d..3aca502b36 100644
--- a/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/internal/profiling/tests/ResourceHelper.java
+++ b/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/internal/profiling/tests/ResourceHelper.java
@@ -41,93 +41,93 @@ import org.eclipse.core.runtime.NullProgressMonitor;
*/
public class ResourceHelper {
- private final static IProgressMonitor NULL_MONITOR = new NullProgressMonitor();
- private final static Set<String> externalFilesCreated = new HashSet<>();
- private final static Set<IResource> resourcesCreated = new HashSet<>();
-
-
- /**
- * Creates new folder from workspace root. The folder name
- * can include relative path as a part of the name.
- * Nonexistent parent directories are being created as per {@link File#mkdirs()}.
- * The intention of the method is to create folders which do not belong to any project.
- *
- * @param name - folder name.
- * @return absolute location of the folder on the file system.
- */
- public static IPath createWorkspaceFolder(String name) throws CoreException {
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IPath fullPath = workspaceRoot.getLocation().append(name);
- java.io.File folder = new java.io.File(fullPath.toOSString());
- if (!folder.exists()) {
- boolean result = folder.mkdirs();
- assertTrue(result);
- }
- assertTrue(folder.exists());
-
- externalFilesCreated.add(fullPath.toOSString());
- workspaceRoot.refreshLocal(IResource.DEPTH_INFINITE, NULL_MONITOR);
- return fullPath;
- }
-
- /**
- * Creates new temporary folder with generated name from workspace root.
- *
- * @return absolute location of the folder on the file system.
- */
- public static IPath createTemporaryFolder() throws CoreException {
- return ResourceHelper.createWorkspaceFolder("tmp/"+System.currentTimeMillis()+'.'+UUID.randomUUID());
- }
-
-
- /**
- * Clean-up any files created as part of a unit test.
- * This method removes *all* Workspace IResources and any external
- * files / folders created with the #createWorkspaceFile #createWorkspaceFolder
- * methods in this class
- */
- public static void cleanUp() throws CoreException {
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- root.refreshLocal(IResource.DEPTH_INFINITE, NULL_MONITOR);
-
- // Delete all external files & folders created using ResourceHelper
- for (String loc : externalFilesCreated) {
- File f = new File(loc);
- if (f.exists())
- deleteRecursive(f);
- }
- externalFilesCreated.clear();
-
- // Remove IResources created by this helper
- for (IResource r : resourcesCreated) {
- if (r.exists())
- try {
- r.delete(true, NULL_MONITOR);
- } catch (CoreException e) {
- // Ignore
- }
- }
- resourcesCreated.clear();
- }
-
-
- /**
- * Recursively delete a directory / file
- *
- * For safety this method only deletes files created under the workspace
- *
- * @param file
- */
- private static final void deleteRecursive(File f) throws IllegalArgumentException {
- // Ensure that the file being deleted is a child of the workspace
- // root to prevent anything nasty happening
- if (! f.getAbsolutePath().startsWith(
- ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getAbsolutePath()))
- throw new IllegalArgumentException("File must exist within the workspace!");
-
- if (f.isDirectory())
- for (File f1 : f.listFiles())
- deleteRecursive(f1);
- f.delete();
- }
+ private final static IProgressMonitor NULL_MONITOR = new NullProgressMonitor();
+ private final static Set<String> externalFilesCreated = new HashSet<>();
+ private final static Set<IResource> resourcesCreated = new HashSet<>();
+
+
+ /**
+ * Creates new folder from workspace root. The folder name
+ * can include relative path as a part of the name.
+ * Nonexistent parent directories are being created as per {@link File#mkdirs()}.
+ * The intention of the method is to create folders which do not belong to any project.
+ *
+ * @param name - folder name.
+ * @return absolute location of the folder on the file system.
+ */
+ public static IPath createWorkspaceFolder(String name) throws CoreException {
+ IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
+ IPath fullPath = workspaceRoot.getLocation().append(name);
+ java.io.File folder = new java.io.File(fullPath.toOSString());
+ if (!folder.exists()) {
+ boolean result = folder.mkdirs();
+ assertTrue(result);
+ }
+ assertTrue(folder.exists());
+
+ externalFilesCreated.add(fullPath.toOSString());
+ workspaceRoot.refreshLocal(IResource.DEPTH_INFINITE, NULL_MONITOR);
+ return fullPath;
+ }
+
+ /**
+ * Creates new temporary folder with generated name from workspace root.
+ *
+ * @return absolute location of the folder on the file system.
+ */
+ public static IPath createTemporaryFolder() throws CoreException {
+ return ResourceHelper.createWorkspaceFolder("tmp/"+System.currentTimeMillis()+'.'+UUID.randomUUID());
+ }
+
+
+ /**
+ * Clean-up any files created as part of a unit test.
+ * This method removes *all* Workspace IResources and any external
+ * files / folders created with the #createWorkspaceFile #createWorkspaceFolder
+ * methods in this class
+ */
+ public static void cleanUp() throws CoreException {
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ root.refreshLocal(IResource.DEPTH_INFINITE, NULL_MONITOR);
+
+ // Delete all external files & folders created using ResourceHelper
+ for (String loc : externalFilesCreated) {
+ File f = new File(loc);
+ if (f.exists())
+ deleteRecursive(f);
+ }
+ externalFilesCreated.clear();
+
+ // Remove IResources created by this helper
+ for (IResource r : resourcesCreated) {
+ if (r.exists())
+ try {
+ r.delete(true, NULL_MONITOR);
+ } catch (CoreException e) {
+ // Ignore
+ }
+ }
+ resourcesCreated.clear();
+ }
+
+
+ /**
+ * Recursively delete a directory / file
+ *
+ * For safety this method only deletes files created under the workspace
+ *
+ * @param file
+ */
+ private static final void deleteRecursive(File f) throws IllegalArgumentException {
+ // Ensure that the file being deleted is a child of the workspace
+ // root to prevent anything nasty happening
+ if (! f.getAbsolutePath().startsWith(
+ ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getAbsolutePath()))
+ throw new IllegalArgumentException("File must exist within the workspace!");
+
+ if (f.isDirectory())
+ for (File f1 : f.listFiles())
+ deleteRecursive(f1);
+ f.delete();
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/AbstractRemoteTest.java b/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/AbstractRemoteTest.java
index 73eda18537..3ad6dd4520 100644
--- a/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/AbstractRemoteTest.java
+++ b/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/AbstractRemoteTest.java
@@ -75,221 +75,221 @@ import org.osgi.framework.Bundle;
@SuppressWarnings("restriction")
public abstract class AbstractRemoteTest extends AbstractTest {
- public static final String REMOTE_NATURE_ID = "org.eclipse.ptp.rdt.core.remoteNature"; //$NON-NLS-1$
- public static final String REMOTE_SERVICES = "org.eclipse.ptp.remote.RemoteTools"; //$NON-NLS-1$
- public static final String REMOTE_MAKE_NATURE = "org.eclipse.ptp.rdt.core.remoteMakeNature"; //$NON-NLS-1$
- public static final String REMOTE_MAKE_BUILDER = "org.eclipse.ptp.rdt.core.remoteMakeBuilder"; //$NON-NLS-1$
- public static final String BUILD_SERVICE = "org.eclipse.ptp.rdt.core.BuildService"; //$NON-NLS-1$
- public static final String CINDEX_SERVICE = "org.eclipse.ptp.rdt.core.CIndexingService"; //$NON-NLS-1$
- public static final String RDT_CINDEX_SERVICE = "org.eclipse.ptp.rdt.server.dstore.RemoteToolsCIndexServiceProvider"; //$NON-NLS-1$
- public static final String TOOLCHAIN_ID = "org.eclipse.ptp.rdt.managedbuild.toolchain.gnu.base"; //$NON-NLS-1$
- public static final String PTP_EXE = "org.eclipse.ptp.rdt.managedbuild.target.gnu.exe"; //$NON-NLS-1$
- public static final String DEBUG = "Debug"; //$NON-NLS-1$
- public static final String USERNAME = ""; //$NON-NLS-1$
- private static final String PASSWORD = ""; //$NON-NLS-1$
- // Sets localhost as default connection if no remote host is given
- private static String HOST = "localhost"; //$NON-NLS-1$
- public static String CONNECTION_NAME = "localhost"; //$NON-NLS-1$
- public static final String RESOURCES_DIR = "resources/"; //$NON-NLS-1$
+ public static final String REMOTE_NATURE_ID = "org.eclipse.ptp.rdt.core.remoteNature"; //$NON-NLS-1$
+ public static final String REMOTE_SERVICES = "org.eclipse.ptp.remote.RemoteTools"; //$NON-NLS-1$
+ public static final String REMOTE_MAKE_NATURE = "org.eclipse.ptp.rdt.core.remoteMakeNature"; //$NON-NLS-1$
+ public static final String REMOTE_MAKE_BUILDER = "org.eclipse.ptp.rdt.core.remoteMakeBuilder"; //$NON-NLS-1$
+ public static final String BUILD_SERVICE = "org.eclipse.ptp.rdt.core.BuildService"; //$NON-NLS-1$
+ public static final String CINDEX_SERVICE = "org.eclipse.ptp.rdt.core.CIndexingService"; //$NON-NLS-1$
+ public static final String RDT_CINDEX_SERVICE = "org.eclipse.ptp.rdt.server.dstore.RemoteToolsCIndexServiceProvider"; //$NON-NLS-1$
+ public static final String TOOLCHAIN_ID = "org.eclipse.ptp.rdt.managedbuild.toolchain.gnu.base"; //$NON-NLS-1$
+ public static final String PTP_EXE = "org.eclipse.ptp.rdt.managedbuild.target.gnu.exe"; //$NON-NLS-1$
+ public static final String DEBUG = "Debug"; //$NON-NLS-1$
+ public static final String USERNAME = ""; //$NON-NLS-1$
+ private static final String PASSWORD = ""; //$NON-NLS-1$
+ // Sets localhost as default connection if no remote host is given
+ private static String HOST = "localhost"; //$NON-NLS-1$
+ public static String CONNECTION_NAME = "localhost"; //$NON-NLS-1$
+ public static final String RESOURCES_DIR = "resources/"; //$NON-NLS-1$
- private IRemoteServices fRemoteServices;
- private IRemoteConnectionWorkingCopy fRemoteConnection;
+ private IRemoteServices fRemoteServices;
+ private IRemoteConnectionWorkingCopy fRemoteConnection;
- /**
- * Create a CDT project outside the default workspace.
- *
- * @param bundle The plug-in bundle.
- * @param projname The name of the project.
- * @param absProjectPath Absolute path to the directory to which the project should be mapped
- * outside the workspace.
- * @return A new external CDT project.
- * @throws CoreException
- * @throws URISyntaxException
- * @throws IOException
- * @throws InvocationTargetException
- * @throws InterruptedException
- */
- protected IProject createRemoteExternalProject(Bundle bundle,
- final String projname, final String absProjectPath,
- final String sourceFile) throws CoreException, URISyntaxException, IOException {
+ /**
+ * Create a CDT project outside the default workspace.
+ *
+ * @param bundle The plug-in bundle.
+ * @param projname The name of the project.
+ * @param absProjectPath Absolute path to the directory to which the project should be mapped
+ * outside the workspace.
+ * @return A new external CDT project.
+ * @throws CoreException
+ * @throws URISyntaxException
+ * @throws IOException
+ * @throws InvocationTargetException
+ * @throws InterruptedException
+ */
+ protected IProject createRemoteExternalProject(Bundle bundle,
+ final String projname, final String absProjectPath,
+ final String sourceFile) throws CoreException, URISyntaxException, IOException {
- IProject externalProject;
- // Turn off auto-building
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceDescription wspDesc = workspace.getDescription();
- wspDesc.setAutoBuilding(false);
- workspace.setDescription(wspDesc);
+ IProject externalProject;
+ // Turn off auto-building
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IWorkspaceDescription wspDesc = workspace.getDescription();
+ wspDesc.setAutoBuilding(false);
+ workspace.setDescription(wspDesc);
- // Create external project
- IWorkspaceRoot root = workspace.getRoot();
- externalProject = root.getProject(projname);
- IProjectDescription description = workspace.newProjectDescription(projname);
+ // Create external project
+ IWorkspaceRoot root = workspace.getRoot();
+ externalProject = root.getProject(projname);
+ IProjectDescription description = workspace.newProjectDescription(projname);
- // Get services responsible for handling the remote connection
- fRemoteServices = RemoteServices.getRemoteServices(REMOTE_SERVICES);
- assertNotNull(fRemoteServices);
+ // Get services responsible for handling the remote connection
+ fRemoteServices = RemoteServices.getRemoteServices(REMOTE_SERVICES);
+ assertNotNull(fRemoteServices);
- // Create connection manager
- IRemoteConnectionManager connMgr = fRemoteServices.getConnectionManager();
- assertNotNull(connMgr);
+ // Create connection manager
+ IRemoteConnectionManager connMgr = fRemoteServices.getConnectionManager();
+ assertNotNull(connMgr);
- try {
- // Creates a localhost connection or a remote one if one is
- // specified by createRemoteExternalProjectAndBuild
- fRemoteConnection = connMgr.newConnection(CONNECTION_NAME);
- } catch (RemoteConnectionException e) {
- fail(e.getLocalizedMessage());
- }
- assertNotNull(fRemoteConnection);
- // Sets the connection arguments
- fRemoteConnection.setAddress(HOST);
- fRemoteConnection.setUsername(USERNAME);
- fRemoteConnection.setPassword(PASSWORD);
+ try {
+ // Creates a localhost connection or a remote one if one is
+ // specified by createRemoteExternalProjectAndBuild
+ fRemoteConnection = connMgr.newConnection(CONNECTION_NAME);
+ } catch (RemoteConnectionException e) {
+ fail(e.getLocalizedMessage());
+ }
+ assertNotNull(fRemoteConnection);
+ // Sets the connection arguments
+ fRemoteConnection.setAddress(HOST);
+ fRemoteConnection.setUsername(USERNAME);
+ fRemoteConnection.setPassword(PASSWORD);
- try {
- fRemoteConnection.open(new NullProgressMonitor());
- } catch (RemoteConnectionException e) {
- fail(e.getLocalizedMessage());
- }
- assertTrue(fRemoteConnection.isOpen());
+ try {
+ fRemoteConnection.open(new NullProgressMonitor());
+ } catch (RemoteConnectionException e) {
+ fail(e.getLocalizedMessage());
+ }
+ assertTrue(fRemoteConnection.isOpen());
- // Sets the location of the remote project
- // RDT format is as follows: remotetools://connectionName/directory
- URI fileProjectURL = new URI(absProjectPath);
- description.setLocationURI(fileProjectURL);
- // Creates CDT project
- externalProject = CCorePlugin.getDefault().createCDTProject(
- description, externalProject, new NullProgressMonitor());
- String pathString = EFSExtensionManager.getDefault().getPathFromURI(externalProject.getLocationURI());
- IPath buildPath = Path.fromPortableString(pathString);
- assertNotNull(externalProject);
- assertTrue(externalProject.isOpen());
+ // Sets the location of the remote project
+ // RDT format is as follows: remotetools://connectionName/directory
+ URI fileProjectURL = new URI(absProjectPath);
+ description.setLocationURI(fileProjectURL);
+ // Creates CDT project
+ externalProject = CCorePlugin.getDefault().createCDTProject(
+ description, externalProject, new NullProgressMonitor());
+ String pathString = EFSExtensionManager.getDefault().getPathFromURI(externalProject.getLocationURI());
+ IPath buildPath = Path.fromPortableString(pathString);
+ assertNotNull(externalProject);
+ assertTrue(externalProject.isOpen());
- // Add the necessary natures to the remote project
- CProjectNature.addCNature(externalProject, new NullProgressMonitor());
- CCProjectNature.addCCNature(externalProject, new NullProgressMonitor());
- CProjectNature.addNature(externalProject, AbstractRemoteTest.REMOTE_NATURE_ID, new NullProgressMonitor());
- ManagedCProjectNature.addManagedNature(externalProject, null);
- ScannerConfigNature.addScannerConfigNature(externalProject);
- // Since it is a remote makefile project, add the make nature
- CProjectNature.addNature(externalProject, REMOTE_MAKE_NATURE, new NullProgressMonitor());
- // Creates a service model required by RDT projects
- ServiceModelManager.getInstance().addConfiguration(externalProject, ServiceModelManager.getInstance().newServiceConfiguration(externalProject.getName()));
- ServiceModelManager smm = ServiceModelManager.getInstance();
- // Creates a Service Configuration for this CDT project
- // RDT needs it in order to build the project later
- IServiceConfiguration config = ServiceModelManager.getInstance().newServiceConfiguration(externalProject.getName());
- IService buildService = smm.getService(BUILD_SERVICE);
- IServiceProviderDescriptor descriptor = buildService.getProviderDescriptor(RemoteBuildServiceProvider.ID);
- RemoteBuildServiceProvider rbsp = (RemoteBuildServiceProvider) smm.getServiceProvider(descriptor);
- if (rbsp != null) {
- rbsp.setRemoteToolsConnection(fRemoteConnection);
- config.setServiceProvider(buildService, rbsp);
- }
- IService indexingService = smm.getService(CINDEX_SERVICE);
- descriptor = indexingService.getProviderDescriptor(RDT_CINDEX_SERVICE);
- IRemoteToolsIndexServiceProvider provider = (IRemoteToolsIndexServiceProvider) smm
- .getServiceProvider(descriptor);
- if (provider != null) {
- provider.setConnection(fRemoteConnection);
- config.setServiceProvider(indexingService, provider);
- }
- // Adds the service configuration with the properties defined to the CDT project
- smm.addConfiguration(externalProject, config);
- smm.setActiveConfiguration(externalProject, config);
- smm.saveModelConfiguration();
+ // Add the necessary natures to the remote project
+ CProjectNature.addCNature(externalProject, new NullProgressMonitor());
+ CCProjectNature.addCCNature(externalProject, new NullProgressMonitor());
+ CProjectNature.addNature(externalProject, AbstractRemoteTest.REMOTE_NATURE_ID, new NullProgressMonitor());
+ ManagedCProjectNature.addManagedNature(externalProject, null);
+ ScannerConfigNature.addScannerConfigNature(externalProject);
+ // Since it is a remote makefile project, add the make nature
+ CProjectNature.addNature(externalProject, REMOTE_MAKE_NATURE, new NullProgressMonitor());
+ // Creates a service model required by RDT projects
+ ServiceModelManager.getInstance().addConfiguration(externalProject, ServiceModelManager.getInstance().newServiceConfiguration(externalProject.getName()));
+ ServiceModelManager smm = ServiceModelManager.getInstance();
+ // Creates a Service Configuration for this CDT project
+ // RDT needs it in order to build the project later
+ IServiceConfiguration config = ServiceModelManager.getInstance().newServiceConfiguration(externalProject.getName());
+ IService buildService = smm.getService(BUILD_SERVICE);
+ IServiceProviderDescriptor descriptor = buildService.getProviderDescriptor(RemoteBuildServiceProvider.ID);
+ RemoteBuildServiceProvider rbsp = (RemoteBuildServiceProvider) smm.getServiceProvider(descriptor);
+ if (rbsp != null) {
+ rbsp.setRemoteToolsConnection(fRemoteConnection);
+ config.setServiceProvider(buildService, rbsp);
+ }
+ IService indexingService = smm.getService(CINDEX_SERVICE);
+ descriptor = indexingService.getProviderDescriptor(RDT_CINDEX_SERVICE);
+ IRemoteToolsIndexServiceProvider provider = (IRemoteToolsIndexServiceProvider) smm
+ .getServiceProvider(descriptor);
+ if (provider != null) {
+ provider.setConnection(fRemoteConnection);
+ config.setServiceProvider(indexingService, provider);
+ }
+ // Adds the service configuration with the properties defined to the CDT project
+ smm.addConfiguration(externalProject, config);
+ smm.setActiveConfiguration(externalProject, config);
+ smm.saveModelConfiguration();
- // Adds a description and a configuration the the CDT project
- ICProjectDescriptionManager mngr =
- CoreModel.getDefault().getProjectDescriptionManager();
- ICProjectDescription des = mngr.createProjectDescription(externalProject, false);
- ManagedBuildInfo info = ManagedBuildManager.createBuildInfo(externalProject);
- IProjectType type = ManagedBuildManager.getProjectType(PTP_EXE);
- IToolChain tc = ManagedBuildManager.getExtensionToolChain(TOOLCHAIN_ID); // or get toolChain from UI
- ManagedProject mProj = new ManagedProject(des);
- info.setManagedProject(mProj);
- IConfiguration cfgs[] = type.getConfigurations();
- assertNotNull(cfgs);
- assertTrue(cfgs.length>0);
+ // Adds a description and a configuration the the CDT project
+ ICProjectDescriptionManager mngr =
+ CoreModel.getDefault().getProjectDescriptionManager();
+ ICProjectDescription des = mngr.createProjectDescription(externalProject, false);
+ ManagedBuildInfo info = ManagedBuildManager.createBuildInfo(externalProject);
+ IProjectType type = ManagedBuildManager.getProjectType(PTP_EXE);
+ IToolChain tc = ManagedBuildManager.getExtensionToolChain(TOOLCHAIN_ID); // or get toolChain from UI
+ ManagedProject mProj = new ManagedProject(des);
+ info.setManagedProject(mProj);
+ IConfiguration cfgs[] = type.getConfigurations();
+ assertNotNull(cfgs);
+ assertTrue(cfgs.length>0);
- for (IConfiguration configuration : cfgs) {
- String id = ManagedBuildManager.calculateChildId(configuration.getToolChain().getId(), null);
- Configuration cfg = new Configuration(mProj, (ToolChain) tc, id, DEBUG);
- IBuilder bld = cfg.getEditableBuilder();
- bld = cfg.getEditableBuilder();
- bld.setBuildPath(pathString);
- CConfigurationData configurationData = cfg.getConfigurationData();
- assertNotNull(configurationData);
- des.createConfiguration(ManagedBuildManager.CFG_DATA_PROVIDER_ID, configurationData);
- }
- mngr.setProjectDescription(externalProject, des);
+ for (IConfiguration configuration : cfgs) {
+ String id = ManagedBuildManager.calculateChildId(configuration.getToolChain().getId(), null);
+ Configuration cfg = new Configuration(mProj, (ToolChain) tc, id, DEBUG);
+ IBuilder bld = cfg.getEditableBuilder();
+ bld = cfg.getEditableBuilder();
+ bld.setBuildPath(pathString);
+ CConfigurationData configurationData = cfg.getConfigurationData();
+ assertNotNull(configurationData);
+ des.createConfiguration(ManagedBuildManager.CFG_DATA_PROVIDER_ID, configurationData);
+ }
+ mngr.setProjectDescription(externalProject, des);
- // The source file in the plug-in test package is copied to the specified directory
- final IRemoteFileManager fileManager = fRemoteConnection.getFileManager();
- final IFileStore dstFileStore = fileManager.getResource(pathString);
- IFileSystem fileSystem = EFS.getLocalFileSystem();
- IFileStore srcFileStore = fileSystem.getStore(URI.create(RESOURCES_DIR + projname));
- srcFileStore.copy(dstFileStore, EFS.OVERWRITE , null);
- externalProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
- IFileInfo dstInfo = dstFileStore.fetchInfo();
- assertTrue(dstInfo.exists());
+ // The source file in the plug-in test package is copied to the specified directory
+ final IRemoteFileManager fileManager = fRemoteConnection.getFileManager();
+ final IFileStore dstFileStore = fileManager.getResource(pathString);
+ IFileSystem fileSystem = EFS.getLocalFileSystem();
+ IFileStore srcFileStore = fileSystem.getStore(URI.create(RESOURCES_DIR + projname));
+ srcFileStore.copy(dstFileStore, EFS.OVERWRITE , null);
+ externalProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
+ IFileInfo dstInfo = dstFileStore.fetchInfo();
+ assertTrue(dstInfo.exists());
- RemoteMakeNature.updateProjectDescription(externalProject, RemoteMakeBuilder.REMOTE_MAKE_BUILDER_ID, new NullProgressMonitor());
+ RemoteMakeNature.updateProjectDescription(externalProject, RemoteMakeBuilder.REMOTE_MAKE_BUILDER_ID, new NullProgressMonitor());
- IManagedBuildInfo mbsInfo = ManagedBuildManager.getBuildInfo(externalProject);
- mbsInfo.getDefaultConfiguration().getBuildData().setBuilderCWD(buildPath);
- mbsInfo.setDirty(true);
- ManagedBuildManager.saveBuildInfo(externalProject, true);
+ IManagedBuildInfo mbsInfo = ManagedBuildManager.getBuildInfo(externalProject);
+ mbsInfo.getDefaultConfiguration().getBuildData().setBuilderCWD(buildPath);
+ mbsInfo.setDirty(true);
+ ManagedBuildManager.saveBuildInfo(externalProject, true);
- try {
- // CDT opens the Project with BACKGROUND_REFRESH enabled which causes the
- // refresh manager to refresh the project 200ms later. This Job interferes
- // with the resource change handler firing see: bug 271264
- Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_REFRESH, null);
- } catch (Exception e) {
- // Ignore
- }
- assertTrue(externalProject.isOpen());
+ try {
+ // CDT opens the Project with BACKGROUND_REFRESH enabled which causes the
+ // refresh manager to refresh the project 200ms later. This Job interferes
+ // with the resource change handler firing see: bug 271264
+ Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_REFRESH, null);
+ } catch (Exception e) {
+ // Ignore
+ }
+ assertTrue(externalProject.isOpen());
- // Index the project
- IIndexManager indexMgr = CCorePlugin.getIndexManager();
- indexMgr.joinIndexer(IIndexManager.FOREVER, new NullProgressMonitor());
- return externalProject;
- }
- protected IProject createRemoteExternalProjectAndBuild(Bundle bundle,
- String projname, String absProjectPath, String sourceFile, String host,
- String connectionName) throws CoreException, URISyntaxException, IOException {
- HOST = host;
- CONNECTION_NAME = connectionName;
- IProject proj = createRemoteExternalProject(bundle, projname, absProjectPath, sourceFile);
- buildProject(proj);
- return proj;
- }
+ // Index the project
+ IIndexManager indexMgr = CCorePlugin.getIndexManager();
+ indexMgr.joinIndexer(IIndexManager.FOREVER, new NullProgressMonitor());
+ return externalProject;
+ }
+ protected IProject createRemoteExternalProjectAndBuild(Bundle bundle,
+ String projname, String absProjectPath, String sourceFile, String host,
+ String connectionName) throws CoreException, URISyntaxException, IOException {
+ HOST = host;
+ CONNECTION_NAME = connectionName;
+ IProject proj = createRemoteExternalProject(bundle, projname, absProjectPath, sourceFile);
+ buildProject(proj);
+ return proj;
+ }
- protected IProject createRemoteExternalProjectAndBuild(Bundle bundle,
- String projname, String absProjectPath, String sourceFile) throws CoreException, URISyntaxException, IOException {
- IProject proj = createRemoteExternalProject(bundle, projname, absProjectPath, sourceFile);
- buildProject(proj);
- return proj;
- }
+ protected IProject createRemoteExternalProjectAndBuild(Bundle bundle,
+ String projname, String absProjectPath, String sourceFile) throws CoreException, URISyntaxException, IOException {
+ IProject proj = createRemoteExternalProject(bundle, projname, absProjectPath, sourceFile);
+ buildProject(proj);
+ return proj;
+ }
- protected void deleteResource (String directory) {
- IRemoteServices fRemoteServices;
- IRemoteConnection fRemoteConnection;
- fRemoteServices = RemoteServices.getRemoteServices(REMOTE_SERVICES);
- assertNotNull(fRemoteServices);
+ protected void deleteResource (String directory) {
+ IRemoteServices fRemoteServices;
+ IRemoteConnection fRemoteConnection;
+ fRemoteServices = RemoteServices.getRemoteServices(REMOTE_SERVICES);
+ assertNotNull(fRemoteServices);
- IRemoteConnectionManager connMgr = fRemoteServices.getConnectionManager();
- assertNotNull(connMgr);
- fRemoteConnection = connMgr.getConnection(CONNECTION_NAME);
- final IRemoteFileManager fileManager = fRemoteConnection.getFileManager();
- final IFileStore dstFileStore = fileManager.getResource(directory);
- try {
- dstFileStore.delete(EFS.NONE, null);
- } catch (CoreException e) {
- }
- }
+ IRemoteConnectionManager connMgr = fRemoteServices.getConnectionManager();
+ assertNotNull(connMgr);
+ fRemoteConnection = connMgr.getConnection(CONNECTION_NAME);
+ final IRemoteFileManager fileManager = fRemoteConnection.getFileManager();
+ final IFileStore dstFileStore = fileManager.getResource(directory);
+ try {
+ dstFileStore.delete(EFS.NONE, null);
+ } catch (CoreException e) {
+ }
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/AbstractTest.java b/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/AbstractTest.java
index 4e5a6a2c17..1a84c02fc8 100644
--- a/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/AbstractTest.java
+++ b/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/AbstractTest.java
@@ -67,303 +67,303 @@ import org.osgi.framework.Bundle;
@SuppressWarnings("restriction")
public abstract class AbstractTest {
- private static final String BIN_DIR = "Debug"; //$NON-NLS-1$
- private static final String IMPORTED_SOURCE_FILE = "primeTest.c"; //$NON-NLS-1$
- protected ICProject proj;
-
- protected ILaunchManager getLaunchManager() {
- return DebugPlugin.getDefault().getLaunchManager();
- }
-
- /**
- * Create a CDT project outside the default workspace.
- *
- * @param bundle
- * The plug-in bundle.
- * @param projname
- * The name of the project.
- * @param absProjectPath
- * Absolute path to the directory to which the project should be
- * mapped outside the workspace.
- * @return A new external CDT project.
- * @throws CoreException
- * @throws URISyntaxException
- * @throws IOException
- * @throws InvocationTargetException
- * @throws InterruptedException
- */
- protected IProject createExternalProject(Bundle bundle,
- final String projname, final Path absProjectPath)
- throws CoreException, URISyntaxException, IOException,
- InvocationTargetException, InterruptedException {
-
- IProject externalProject;
- // Turn off auto-building
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceDescription wspDesc = workspace.getDescription();
- wspDesc.setAutoBuilding(false);
- workspace.setDescription(wspDesc);
-
- // Create external project
- IWorkspaceRoot root = workspace.getRoot();
- externalProject = root.getProject(projname);
- IProjectDescription description = workspace
- .newProjectDescription(projname);
- URI fileProjectURL = new URI("file://" + absProjectPath.toString());
- description.setLocationURI(fileProjectURL);
- externalProject = CCorePlugin.getDefault().createCDTProject(
- description, externalProject, new NullProgressMonitor());
- assertNotNull(externalProject);
- externalProject.open(null);
-
- try {
- // CDT opens the Project with BACKGROUND_REFRESH enabled which
- // causes the
- // refresh manager to refresh the project 200ms later. This Job
- // interferes
- // with the resource change handler firing see: bug 271264
- Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_REFRESH, null);
- } catch (Exception e) {
- // Ignore
- }
- assertTrue(externalProject.isOpen());
-
- // Import boiler-plate files which can then be built and profiled
- URL location = FileLocator.find(bundle, new Path(
- "resources/" + projname), null); //$NON-NLS-1$
- File testDir = new File(FileLocator.toFileURL(location).toURI());
- ImportOperation op = new ImportOperation(externalProject.getFullPath(),
- testDir, FileSystemStructureProvider.INSTANCE,
- new IOverwriteQuery() {
- @Override
- public String queryOverwrite(String pathString) {
- return ALL;
- }
- });
- op.setCreateContainerStructure(false);
- op.run(null);
-
- IStatus status = op.getStatus();
- if (!status.isOK()) {
- throw new CoreException(status);
- }
- // Make sure import went well
- assertNotNull(externalProject
- .findMember(new Path(IMPORTED_SOURCE_FILE)));
-
- // Index the project
- IIndexManager indexMgr = CCorePlugin.getIndexManager();
- indexMgr.joinIndexer(IIndexManager.FOREVER, new NullProgressMonitor());
-
- // These natures must be enabled at this point to continue
- assertTrue(externalProject
- .isNatureEnabled(ScannerConfigNature.NATURE_ID));
- assertTrue(externalProject
- .isNatureEnabled(ManagedCProjectNature.MNG_NATURE_ID));
-
- return externalProject;
- }
-
- /**
- * Create and build a project outside the default workspace
- *
- * @param bundle
- * The plug-in bundle.
- * @param projname
- * The name of the project.
- * @param absProjectPath
- * Absolute path to the directory to which the project should be
- * mapped outside the workspace.
- * @return A new external CDT project with binaries built.
- * @throws CoreException
- * @throws URISyntaxException
- * @throws IOException
- * @throws InvocationTargetException
- * @throws InterruptedException
- */
- protected IProject createExternalProjectAndBuild(Bundle bundle,
- String projname, Path absProjectPath) throws CoreException,
- URISyntaxException, InvocationTargetException,
- InterruptedException, IOException {
- IProject proj = createExternalProject(bundle, projname, absProjectPath);
- buildProject(proj);
- return proj;
- }
-
- protected ICProject createProjectAndBuild(Bundle bundle, String projname)
- throws CoreException, URISyntaxException,
- InvocationTargetException, InterruptedException, IOException {
- ICProject proj = createProject(bundle, projname);
- buildProject(proj);
- return proj;
- }
-
- // Wrapper to allow ICProject parameters, since buildProject doesn't really
- // use
- // ICProject specifics.
- protected void buildProject(ICProject project) throws CoreException {
- buildProject(project.getProject());
- }
-
- protected void buildProject(IProject proj) throws CoreException {
- IWorkspace wsp = ResourcesPlugin.getWorkspace();
- final IProject curProject = proj;
- ISchedulingRule rule = wsp.getRuleFactory().buildRule();
- Job buildJob = new Job("project build job") { //$NON-NLS-1$
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- curProject
- .build(IncrementalProjectBuilder.FULL_BUILD, null);
- } catch (CoreException e) {
- fail(e.getStatus().getMessage());
- } catch (OperationCanceledException e) {
- fail(NLS.bind(
- Messages.getString("AbstractTest.Build_cancelled"), curProject.getName(), e.getMessage())); //$NON-NLS-1$
- }
- return Status.OK_STATUS;
- }
- };
- buildJob.setRule(rule);
-
- buildJob.schedule();
-
- try {
- buildJob.join();
- } catch (InterruptedException e) {
- fail(NLS.bind(
- Messages.getString("AbstractTest.Build_interrupted"), curProject.getName(), e.getMessage())); //$NON-NLS-1$
- }
-
- IStatus status = buildJob.getResult();
- if (status.getCode() != IStatus.OK) {
- fail(NLS.bind(
- Messages.getString("AbstractTest.Build_failed"), curProject.getName(), status.getMessage())); //$NON-NLS-1$
- }
-
- IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
- @Override
- public void run(IProgressMonitor monitor) throws CoreException {
- curProject.refreshLocal(IResource.DEPTH_INFINITE, null);
- }
- };
-
- wsp.run(runnable, wsp.getRoot(), IWorkspace.AVOID_UPDATE, null);
- }
-
- protected ICProject createProject(Bundle bundle, String projname)
- throws CoreException, URISyntaxException, IOException,
- InvocationTargetException, InterruptedException {
- // Turn off auto-building
- IWorkspace wsp = ResourcesPlugin.getWorkspace();
- IWorkspaceDescription desc = wsp.getDescription();
- desc.setAutoBuilding(false);
- wsp.setDescription(desc);
-
- ICProject proj = CProjectHelper.createCProject(projname, BIN_DIR);
- URL location = FileLocator.find(bundle, new Path(
- "resources/" + projname), null); //$NON-NLS-1$
- File testDir = new File(FileLocator.toFileURL(location).toURI());
-
- IProject project = proj.getProject();
- // Add these natures before project is imported due to #273079
- ManagedCProjectNature.addManagedNature(project, null);
- ScannerConfigNature.addScannerConfigNature(project);
-
- ImportOperation op = new ImportOperation(project.getFullPath(),
- testDir, FileSystemStructureProvider.INSTANCE,
- new IOverwriteQuery() {
- @Override
- public String queryOverwrite(String pathString) {
- return ALL;
- }
- });
- op.setCreateContainerStructure(false);
- op.run(null);
-
- IStatus status = op.getStatus();
- if (!status.isOK()) {
- throw new CoreException(status);
- }
-
- // Index the project
- IIndexManager indexManager = CCorePlugin.getIndexManager();
- indexManager.reindex(proj);
- indexManager.joinIndexer(IIndexManager.FOREVER,
- new NullProgressMonitor());
-
- // These natures must be enabled at this point to continue
- assertTrue(project.isNatureEnabled(ScannerConfigNature.NATURE_ID));
- assertTrue(project.isNatureEnabled(ManagedCProjectNature.MNG_NATURE_ID));
-
- return proj;
- }
-
- protected void deleteProject(final ICProject cproject) throws CoreException {
- ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
- @Override
- public void run(IProgressMonitor monitor) {
- CProjectHelper.delete(cproject);
- }
- }, null);
- }
-
- protected ILaunchConfiguration createConfiguration(IProject proj)
- throws CoreException {
- String projectName = proj.getName();
- String binPath = "";
-
- ILaunchConfigurationType configType = getLaunchConfigType();
- ILaunchConfigurationWorkingCopy wc = configType
- .newInstance(null, getLaunchManager()
- .generateLaunchConfigurationName(projectName));
-
- if (proj.getLocation() == null) {
- IFileStore fileStore = null;
- try {
- fileStore = EFS.getStore(new URI(proj.getLocationURI()
- + BIN_DIR + IPath.SEPARATOR + projectName));
- } catch (URISyntaxException e) {
- fail(NLS.bind(
- Messages.getString("AbstractTest.No_binary"), projectName)); //$NON-NLS-1$
- }
- if ((fileStore instanceof LocalFile)) {
- fail(NLS.bind(
- Messages.getString("AbstractTest.No_binary"), projectName)); //$NON-NLS-1$
- }
- binPath = EFSExtensionManager.getDefault().getPathFromURI(
- proj.getLocationURI())
- + BIN_DIR + IPath.SEPARATOR + proj.getName();
- } else {
- IResource bin = proj.findMember(new Path(BIN_DIR)
- .append(projectName));
- if (bin == null) {
- fail(NLS.bind(
- Messages.getString("AbstractTest.No_binary"), projectName)); //$NON-NLS-1$
- }
- binPath = bin.getProjectRelativePath().toString();
- wc.setMappedResources(new IResource[] { bin, proj });
- }
-
- wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
- binPath);
- wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- projectName);
- wc.setAttribute(
- ICDTLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY,
- (String) null);
-
- // Make launch run in foreground
- wc.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false);
-
- setProfileAttributes(wc);
-
- return wc.doSave();
- }
-
- protected abstract ILaunchConfigurationType getLaunchConfigType();
-
- protected abstract void setProfileAttributes(
- ILaunchConfigurationWorkingCopy wc) throws CoreException;
+ private static final String BIN_DIR = "Debug"; //$NON-NLS-1$
+ private static final String IMPORTED_SOURCE_FILE = "primeTest.c"; //$NON-NLS-1$
+ protected ICProject proj;
+
+ protected ILaunchManager getLaunchManager() {
+ return DebugPlugin.getDefault().getLaunchManager();
+ }
+
+ /**
+ * Create a CDT project outside the default workspace.
+ *
+ * @param bundle
+ * The plug-in bundle.
+ * @param projname
+ * The name of the project.
+ * @param absProjectPath
+ * Absolute path to the directory to which the project should be
+ * mapped outside the workspace.
+ * @return A new external CDT project.
+ * @throws CoreException
+ * @throws URISyntaxException
+ * @throws IOException
+ * @throws InvocationTargetException
+ * @throws InterruptedException
+ */
+ protected IProject createExternalProject(Bundle bundle,
+ final String projname, final Path absProjectPath)
+ throws CoreException, URISyntaxException, IOException,
+ InvocationTargetException, InterruptedException {
+
+ IProject externalProject;
+ // Turn off auto-building
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IWorkspaceDescription wspDesc = workspace.getDescription();
+ wspDesc.setAutoBuilding(false);
+ workspace.setDescription(wspDesc);
+
+ // Create external project
+ IWorkspaceRoot root = workspace.getRoot();
+ externalProject = root.getProject(projname);
+ IProjectDescription description = workspace
+ .newProjectDescription(projname);
+ URI fileProjectURL = new URI("file://" + absProjectPath.toString());
+ description.setLocationURI(fileProjectURL);
+ externalProject = CCorePlugin.getDefault().createCDTProject(
+ description, externalProject, new NullProgressMonitor());
+ assertNotNull(externalProject);
+ externalProject.open(null);
+
+ try {
+ // CDT opens the Project with BACKGROUND_REFRESH enabled which
+ // causes the
+ // refresh manager to refresh the project 200ms later. This Job
+ // interferes
+ // with the resource change handler firing see: bug 271264
+ Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_REFRESH, null);
+ } catch (Exception e) {
+ // Ignore
+ }
+ assertTrue(externalProject.isOpen());
+
+ // Import boiler-plate files which can then be built and profiled
+ URL location = FileLocator.find(bundle, new Path(
+ "resources/" + projname), null); //$NON-NLS-1$
+ File testDir = new File(FileLocator.toFileURL(location).toURI());
+ ImportOperation op = new ImportOperation(externalProject.getFullPath(),
+ testDir, FileSystemStructureProvider.INSTANCE,
+ new IOverwriteQuery() {
+ @Override
+ public String queryOverwrite(String pathString) {
+ return ALL;
+ }
+ });
+ op.setCreateContainerStructure(false);
+ op.run(null);
+
+ IStatus status = op.getStatus();
+ if (!status.isOK()) {
+ throw new CoreException(status);
+ }
+ // Make sure import went well
+ assertNotNull(externalProject
+ .findMember(new Path(IMPORTED_SOURCE_FILE)));
+
+ // Index the project
+ IIndexManager indexMgr = CCorePlugin.getIndexManager();
+ indexMgr.joinIndexer(IIndexManager.FOREVER, new NullProgressMonitor());
+
+ // These natures must be enabled at this point to continue
+ assertTrue(externalProject
+ .isNatureEnabled(ScannerConfigNature.NATURE_ID));
+ assertTrue(externalProject
+ .isNatureEnabled(ManagedCProjectNature.MNG_NATURE_ID));
+
+ return externalProject;
+ }
+
+ /**
+ * Create and build a project outside the default workspace
+ *
+ * @param bundle
+ * The plug-in bundle.
+ * @param projname
+ * The name of the project.
+ * @param absProjectPath
+ * Absolute path to the directory to which the project should be
+ * mapped outside the workspace.
+ * @return A new external CDT project with binaries built.
+ * @throws CoreException
+ * @throws URISyntaxException
+ * @throws IOException
+ * @throws InvocationTargetException
+ * @throws InterruptedException
+ */
+ protected IProject createExternalProjectAndBuild(Bundle bundle,
+ String projname, Path absProjectPath) throws CoreException,
+ URISyntaxException, InvocationTargetException,
+ InterruptedException, IOException {
+ IProject proj = createExternalProject(bundle, projname, absProjectPath);
+ buildProject(proj);
+ return proj;
+ }
+
+ protected ICProject createProjectAndBuild(Bundle bundle, String projname)
+ throws CoreException, URISyntaxException,
+ InvocationTargetException, InterruptedException, IOException {
+ ICProject proj = createProject(bundle, projname);
+ buildProject(proj);
+ return proj;
+ }
+
+ // Wrapper to allow ICProject parameters, since buildProject doesn't really
+ // use
+ // ICProject specifics.
+ protected void buildProject(ICProject project) throws CoreException {
+ buildProject(project.getProject());
+ }
+
+ protected void buildProject(IProject proj) throws CoreException {
+ IWorkspace wsp = ResourcesPlugin.getWorkspace();
+ final IProject curProject = proj;
+ ISchedulingRule rule = wsp.getRuleFactory().buildRule();
+ Job buildJob = new Job("project build job") { //$NON-NLS-1$
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ curProject
+ .build(IncrementalProjectBuilder.FULL_BUILD, null);
+ } catch (CoreException e) {
+ fail(e.getStatus().getMessage());
+ } catch (OperationCanceledException e) {
+ fail(NLS.bind(
+ Messages.getString("AbstractTest.Build_cancelled"), curProject.getName(), e.getMessage())); //$NON-NLS-1$
+ }
+ return Status.OK_STATUS;
+ }
+ };
+ buildJob.setRule(rule);
+
+ buildJob.schedule();
+
+ try {
+ buildJob.join();
+ } catch (InterruptedException e) {
+ fail(NLS.bind(
+ Messages.getString("AbstractTest.Build_interrupted"), curProject.getName(), e.getMessage())); //$NON-NLS-1$
+ }
+
+ IStatus status = buildJob.getResult();
+ if (status.getCode() != IStatus.OK) {
+ fail(NLS.bind(
+ Messages.getString("AbstractTest.Build_failed"), curProject.getName(), status.getMessage())); //$NON-NLS-1$
+ }
+
+ IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
+ @Override
+ public void run(IProgressMonitor monitor) throws CoreException {
+ curProject.refreshLocal(IResource.DEPTH_INFINITE, null);
+ }
+ };
+
+ wsp.run(runnable, wsp.getRoot(), IWorkspace.AVOID_UPDATE, null);
+ }
+
+ protected ICProject createProject(Bundle bundle, String projname)
+ throws CoreException, URISyntaxException, IOException,
+ InvocationTargetException, InterruptedException {
+ // Turn off auto-building
+ IWorkspace wsp = ResourcesPlugin.getWorkspace();
+ IWorkspaceDescription desc = wsp.getDescription();
+ desc.setAutoBuilding(false);
+ wsp.setDescription(desc);
+
+ ICProject proj = CProjectHelper.createCProject(projname, BIN_DIR);
+ URL location = FileLocator.find(bundle, new Path(
+ "resources/" + projname), null); //$NON-NLS-1$
+ File testDir = new File(FileLocator.toFileURL(location).toURI());
+
+ IProject project = proj.getProject();
+ // Add these natures before project is imported due to #273079
+ ManagedCProjectNature.addManagedNature(project, null);
+ ScannerConfigNature.addScannerConfigNature(project);
+
+ ImportOperation op = new ImportOperation(project.getFullPath(),
+ testDir, FileSystemStructureProvider.INSTANCE,
+ new IOverwriteQuery() {
+ @Override
+ public String queryOverwrite(String pathString) {
+ return ALL;
+ }
+ });
+ op.setCreateContainerStructure(false);
+ op.run(null);
+
+ IStatus status = op.getStatus();
+ if (!status.isOK()) {
+ throw new CoreException(status);
+ }
+
+ // Index the project
+ IIndexManager indexManager = CCorePlugin.getIndexManager();
+ indexManager.reindex(proj);
+ indexManager.joinIndexer(IIndexManager.FOREVER,
+ new NullProgressMonitor());
+
+ // These natures must be enabled at this point to continue
+ assertTrue(project.isNatureEnabled(ScannerConfigNature.NATURE_ID));
+ assertTrue(project.isNatureEnabled(ManagedCProjectNature.MNG_NATURE_ID));
+
+ return proj;
+ }
+
+ protected void deleteProject(final ICProject cproject) throws CoreException {
+ ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
+ @Override
+ public void run(IProgressMonitor monitor) {
+ CProjectHelper.delete(cproject);
+ }
+ }, null);
+ }
+
+ protected ILaunchConfiguration createConfiguration(IProject proj)
+ throws CoreException {
+ String projectName = proj.getName();
+ String binPath = "";
+
+ ILaunchConfigurationType configType = getLaunchConfigType();
+ ILaunchConfigurationWorkingCopy wc = configType
+ .newInstance(null, getLaunchManager()
+ .generateLaunchConfigurationName(projectName));
+
+ if (proj.getLocation() == null) {
+ IFileStore fileStore = null;
+ try {
+ fileStore = EFS.getStore(new URI(proj.getLocationURI()
+ + BIN_DIR + IPath.SEPARATOR + projectName));
+ } catch (URISyntaxException e) {
+ fail(NLS.bind(
+ Messages.getString("AbstractTest.No_binary"), projectName)); //$NON-NLS-1$
+ }
+ if ((fileStore instanceof LocalFile)) {
+ fail(NLS.bind(
+ Messages.getString("AbstractTest.No_binary"), projectName)); //$NON-NLS-1$
+ }
+ binPath = EFSExtensionManager.getDefault().getPathFromURI(
+ proj.getLocationURI())
+ + BIN_DIR + IPath.SEPARATOR + proj.getName();
+ } else {
+ IResource bin = proj.findMember(new Path(BIN_DIR)
+ .append(projectName));
+ if (bin == null) {
+ fail(NLS.bind(
+ Messages.getString("AbstractTest.No_binary"), projectName)); //$NON-NLS-1$
+ }
+ binPath = bin.getProjectRelativePath().toString();
+ wc.setMappedResources(new IResource[] { bin, proj });
+ }
+
+ wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
+ binPath);
+ wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME,
+ projectName);
+ wc.setAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY,
+ (String) null);
+
+ // Make launch run in foreground
+ wc.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false);
+
+ setProfileAttributes(wc);
+
+ return wc.doSave();
+ }
+
+ protected abstract ILaunchConfigurationType getLaunchConfigType();
+
+ protected abstract void setProfileAttributes(
+ ILaunchConfigurationWorkingCopy wc) throws CoreException;
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/Messages.java b/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/Messages.java
index b2c71d7a3f..ad0d055a0e 100644
--- a/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/Messages.java
+++ b/profiling/org.eclipse.linuxtools.profiling.tests/src/org/eclipse/linuxtools/profiling/tests/Messages.java
@@ -14,19 +14,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.profiling.tests.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.profiling.tests.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.profiling.ui.capability/plugin.xml b/profiling/org.eclipse.linuxtools.profiling.ui.capability/plugin.xml
index 813aed111c..29be92321b 100644
--- a/profiling/org.eclipse.linuxtools.profiling.ui.capability/plugin.xml
+++ b/profiling/org.eclipse.linuxtools.profiling.ui.capability/plugin.xml
@@ -1,135 +1,135 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
- <extension point="org.eclipse.ui.activities">
- <category
- name="%category.name"
- id="org.eclipse.linuxtools.activities.category">
- </category>
- <activity
- name="%activity.name.profiling"
- description="%activity.description.profiling"
- id="org.eclipse.linuxtools.profiling.ui.capabilities">
- </activity>
- <activity
- name="%activity.name.general"
- description="%activity.description.general"
- id="org.eclipse.linuxtools.profiling.general.ui.capabilities">
- </activity>
-
- <categoryActivityBinding
+ <extension point="org.eclipse.ui.activities">
+ <category
+ name="%category.name"
+ id="org.eclipse.linuxtools.activities.category">
+ </category>
+ <activity
+ name="%activity.name.profiling"
+ description="%activity.description.profiling"
+ id="org.eclipse.linuxtools.profiling.ui.capabilities">
+ </activity>
+ <activity
+ name="%activity.name.general"
+ description="%activity.description.general"
+ id="org.eclipse.linuxtools.profiling.general.ui.capabilities">
+ </activity>
+
+ <categoryActivityBinding
activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
categoryId="org.eclipse.linuxtools.activities.category"/>
-
+
<categoryActivityBinding
activityId="org.eclipse.linuxtools.profiling.general.ui.capabilities"
categoryId="org.eclipse.linuxtools.activities.category"/>
-
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.profiling\..*/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.profiling/*">
- </activityPatternBinding>
-
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.callgraph\..*/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.callgraph/*">
- </activityPatternBinding>
-
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.oprofile\..*/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.oprofile/*">
- </activityPatternBinding>
-
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.valgrind\..*/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.valgrind/*">
- </activityPatternBinding>
-
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.lttng\..*/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.lttng/*">
- </activityPatternBinding>
-
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.tmf\..*/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.tmf/*">
- </activityPatternBinding>
-
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.gcov\..*/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.gcov/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.dataviewers\..*/*">
- </activityPatternBinding>
-
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.gprof\..*/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.gprof/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.dataviewers/*">
- </activityPatternBinding>
-
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.systemtap\.ui\.graphing.*/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.systemtap\.ui\/dashboard.*/*">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.systemtap\.ui\.ide.*/*">
- </activityPatternBinding>
-
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.general.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.changelog.*/*">
- </activityPatternBinding>
-
- <activityPatternBinding
- activityId="org.eclipse.linuxtools.profiling.general.ui.capabilities"
- pattern="org\.eclipse\.linuxtools\.rpm.*/*">
- </activityPatternBinding>
-
- <defaultEnablement id="org.eclipse.linuxtools.profiling.ui.capabilities"/>
- <defaultEnablement id="org.eclipse.linuxtools.profiling.general.ui.capabilities"/>
-
+
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.profiling\..*/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.profiling/*">
+ </activityPatternBinding>
+
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.callgraph\..*/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.callgraph/*">
+ </activityPatternBinding>
+
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.oprofile\..*/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.oprofile/*">
+ </activityPatternBinding>
+
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.valgrind\..*/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.valgrind/*">
+ </activityPatternBinding>
+
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.lttng\..*/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.lttng/*">
+ </activityPatternBinding>
+
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.tmf\..*/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.tmf/*">
+ </activityPatternBinding>
+
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.gcov\..*/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.gcov/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.dataviewers\..*/*">
+ </activityPatternBinding>
+
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.gprof\..*/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.gprof/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.dataviewers/*">
+ </activityPatternBinding>
+
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.systemtap\.ui\.graphing.*/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.systemtap\.ui\/dashboard.*/*">
+ </activityPatternBinding>
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.systemtap\.ui\.ide.*/*">
+ </activityPatternBinding>
+
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.general.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.changelog.*/*">
+ </activityPatternBinding>
+
+ <activityPatternBinding
+ activityId="org.eclipse.linuxtools.profiling.general.ui.capabilities"
+ pattern="org\.eclipse\.linuxtools\.rpm.*/*">
+ </activityPatternBinding>
+
+ <defaultEnablement id="org.eclipse.linuxtools.profiling.ui.capabilities"/>
+ <defaultEnablement id="org.eclipse.linuxtools.profiling.general.ui.capabilities"/>
+
</extension>
</plugin>
diff --git a/profiling/org.eclipse.linuxtools.profiling.ui/src/org/eclipse/linuxtools/internal/profiling/ui/ProfileUIPlugin.java b/profiling/org.eclipse.linuxtools.profiling.ui/src/org/eclipse/linuxtools/internal/profiling/ui/ProfileUIPlugin.java
index 8f1be48bdb..36ff65775f 100644
--- a/profiling/org.eclipse.linuxtools.profiling.ui/src/org/eclipse/linuxtools/internal/profiling/ui/ProfileUIPlugin.java
+++ b/profiling/org.eclipse.linuxtools.profiling.ui/src/org/eclipse/linuxtools/internal/profiling/ui/ProfileUIPlugin.java
@@ -20,53 +20,53 @@ import org.osgi.framework.BundleContext;
*/
public class ProfileUIPlugin extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.profiling.ui"; //$NON-NLS-1$
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.profiling.ui"; //$NON-NLS-1$
- // The shared instance
- private static ProfileUIPlugin plugin;
-
- /**
- * The constructor
- */
- public ProfileUIPlugin() {
- }
+ // The shared instance
+ private static ProfileUIPlugin plugin;
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
+ /**
+ * The constructor
+ */
+ public ProfileUIPlugin() {
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static ProfileUIPlugin getDefault() {
- return plugin;
- }
-
- public static Shell getActiveWorkbenchShell() {
- IWorkbenchWindow window = getDefault().getWorkbench().getActiveWorkbenchWindow();
- if (window != null) {
- return window.getShell();
- }
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static ProfileUIPlugin getDefault() {
+ return plugin;
+ }
+
+ public static Shell getActiveWorkbenchShell() {
+ IWorkbenchWindow window = getDefault().getWorkbench().getActiveWorkbenchWindow();
+ if (window != null) {
+ return window.getShell();
+ }
+ return null;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/LaunchCoreConstants.java b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/LaunchCoreConstants.java
index 847763aa6d..57303b4a00 100644
--- a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/LaunchCoreConstants.java
+++ b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/LaunchCoreConstants.java
@@ -17,7 +17,7 @@ package org.eclipse.linuxtools.tools.launch.core;
* @since 2.0
*/
public interface LaunchCoreConstants {
- String PLUGIN_ID = "org.eclipse.linuxtools.tools.launch.core"; //$NON-NLS-1$
- String LINUXTOOLS_PATH_NAME = LaunchCoreConstants.PLUGIN_ID + ".LinuxtoolsPath"; //$NON-NLS-1$
- String LINUXTOOLS_PATH_SYSTEM_NAME = LaunchCoreConstants.PLUGIN_ID + ".LinuxtoolsSystemEnvPath"; //$NON-NLS-1$
+ String PLUGIN_ID = "org.eclipse.linuxtools.tools.launch.core"; //$NON-NLS-1$
+ String LINUXTOOLS_PATH_NAME = LaunchCoreConstants.PLUGIN_ID + ".LinuxtoolsPath"; //$NON-NLS-1$
+ String LINUXTOOLS_PATH_SYSTEM_NAME = LaunchCoreConstants.PLUGIN_ID + ".LinuxtoolsSystemEnvPath"; //$NON-NLS-1$
}
diff --git a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/CdtSpawnerProcessFactory.java b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/CdtSpawnerProcessFactory.java
index bd777f9940..fd1872fe76 100644
--- a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/CdtSpawnerProcessFactory.java
+++ b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/CdtSpawnerProcessFactory.java
@@ -27,37 +27,37 @@ import org.eclipse.core.resources.IProject;
* page.
*/
public class CdtSpawnerProcessFactory extends LinuxtoolsProcessFactory {
- private static CdtSpawnerProcessFactory instance = null;
+ private static CdtSpawnerProcessFactory instance = null;
- public static CdtSpawnerProcessFactory getFactory() {
- if (instance == null) {
- instance = new CdtSpawnerProcessFactory();
- }
- return instance;
- }
+ public static CdtSpawnerProcessFactory getFactory() {
+ if (instance == null) {
+ instance = new CdtSpawnerProcessFactory();
+ }
+ return instance;
+ }
- public Process exec(String[] cmdarray, IProject project) throws IOException {
- return exec(cmdarray, null, project);
- }
+ public Process exec(String[] cmdarray, IProject project) throws IOException {
+ return exec(cmdarray, null, project);
+ }
- public Process exec(String[] cmdarray, String[] envp, IProject project) throws IOException {
- envp = updateEnvironment(envp, project);
- return ProcessFactory.getFactory().exec(cmdarray, envp);
- }
+ public Process exec(String[] cmdarray, String[] envp, IProject project) throws IOException {
+ envp = updateEnvironment(envp, project);
+ return ProcessFactory.getFactory().exec(cmdarray, envp);
+ }
- public Process exec(String cmdarray[], String[] envp, File dir, IProject project)
- throws IOException {
- envp = updateEnvironment(envp, project);
- return ProcessFactory.getFactory().exec(cmdarray, envp, dir);
- }
+ public Process exec(String cmdarray[], String[] envp, File dir, IProject project)
+ throws IOException {
+ envp = updateEnvironment(envp, project);
+ return ProcessFactory.getFactory().exec(cmdarray, envp, dir);
+ }
- public Process exec(String cmdarray[], String[] envp, File dir, PTY pty, IProject project)
- throws IOException {
- envp = updateEnvironment(envp, project);
- return ProcessFactory.getFactory().exec(cmdarray, envp, dir, pty);
- }
+ public Process exec(String cmdarray[], String[] envp, File dir, PTY pty, IProject project)
+ throws IOException {
+ envp = updateEnvironment(envp, project);
+ return ProcessFactory.getFactory().exec(cmdarray, envp, dir, pty);
+ }
- /**
+ /**
* Executes a command array using pty
*
* @param cmdarray -- Split a command string on the ' ' character
diff --git a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/LinuxtoolsProcessFactory.java b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/LinuxtoolsProcessFactory.java
index 702cc21e20..eda1fc0508 100644
--- a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/LinuxtoolsProcessFactory.java
+++ b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/LinuxtoolsProcessFactory.java
@@ -23,96 +23,96 @@ import org.eclipse.linuxtools.tools.launch.core.properties.LinuxtoolsPathPropert
* Abstract class with usefull functions for ProcessFactory classes.
*/
public abstract class LinuxtoolsProcessFactory {
- private static final String PATH = "PATH"; //$NON-NLS-1$
- private static final String PATH_EQUAL = "PATH="; //$NON-NLS-1$
- private static final String SEPARATOR = ":"; //$NON-NLS-1$
+ private static final String PATH = "PATH"; //$NON-NLS-1$
+ private static final String PATH_EQUAL = "PATH="; //$NON-NLS-1$
+ private static final String SEPARATOR = ":"; //$NON-NLS-1$
- private String getEnvpPath(String[] envp) {
- for (String env:envp) {
- if (env.startsWith(PATH_EQUAL)) {
- return env.substring(PATH_EQUAL.length());
- }
- }
- return null;
- }
+ private String getEnvpPath(String[] envp) {
+ for (String env:envp) {
+ if (env.startsWith(PATH_EQUAL)) {
+ return env.substring(PATH_EQUAL.length());
+ }
+ }
+ return null;
+ }
- /*
- * Update the environment variables list with the Linux tools path project
- * property, prepending it to the PATH env. Call this function if the
- * command to be run may be in the path selected in 'Linux tools path'
- * project property page.
- * */
- protected String[] updateEnvironment(String[] envp, IProject project) {
- if (project == null) {
- return envp;
- }
- if (envp == null) {
- envp = new String[0];
- }
- String ltPath = LinuxtoolsPathProperty.getInstance().getLinuxtoolsPath(project);
- String envpPath = getEnvpPath(envp);
- String systemPath = null;
- Map<String, String> systemEnvMap = null;
- try {
- systemEnvMap = RemoteEnvProxyManager.class.newInstance().getEnv(project);
- systemPath = systemEnvMap.get(PATH);
- if (systemPath==null) {
- systemPath = System.getenv(PATH);
- }
- } catch (InstantiationException|IllegalAccessException|CoreException e) {
- e.printStackTrace();
- }
- StringBuffer newPath = new StringBuffer();
- newPath.append(PATH_EQUAL);
+ /*
+ * Update the environment variables list with the Linux tools path project
+ * property, prepending it to the PATH env. Call this function if the
+ * command to be run may be in the path selected in 'Linux tools path'
+ * project property page.
+ * */
+ protected String[] updateEnvironment(String[] envp, IProject project) {
+ if (project == null) {
+ return envp;
+ }
+ if (envp == null) {
+ envp = new String[0];
+ }
+ String ltPath = LinuxtoolsPathProperty.getInstance().getLinuxtoolsPath(project);
+ String envpPath = getEnvpPath(envp);
+ String systemPath = null;
+ Map<String, String> systemEnvMap = null;
+ try {
+ systemEnvMap = RemoteEnvProxyManager.class.newInstance().getEnv(project);
+ systemPath = systemEnvMap.get(PATH);
+ if (systemPath==null) {
+ systemPath = System.getenv(PATH);
+ }
+ } catch (InstantiationException|IllegalAccessException|CoreException e) {
+ e.printStackTrace();
+ }
+ StringBuffer newPath = new StringBuffer();
+ newPath.append(PATH_EQUAL);
- if (ltPath != null && !ltPath.isEmpty()) {
- newPath.append(ltPath);
- newPath.append(SEPARATOR);
- }
- if (envpPath != null && !envpPath.isEmpty()) {
- newPath.append(envpPath);
- newPath.append(SEPARATOR);
- }
- if (systemPath != null && !systemPath.isEmpty()) {
- newPath.append(systemPath);
- newPath.append(SEPARATOR);
- }
+ if (ltPath != null && !ltPath.isEmpty()) {
+ newPath.append(ltPath);
+ newPath.append(SEPARATOR);
+ }
+ if (envpPath != null && !envpPath.isEmpty()) {
+ newPath.append(envpPath);
+ newPath.append(SEPARATOR);
+ }
+ if (systemPath != null && !systemPath.isEmpty()) {
+ newPath.append(systemPath);
+ newPath.append(SEPARATOR);
+ }
- if (newPath.length() == PATH_EQUAL.length()) {
- //there is nothing to add
- return envp;
- }
+ if (newPath.length() == PATH_EQUAL.length()) {
+ //there is nothing to add
+ return envp;
+ }
- String[] newEnvp = new String[] {};
+ String[] newEnvp = new String[] {};
- if (envpPath != null) {
- newEnvp = new String[envp.length];
- for (int i = 0; i < envp.length; i++) {
- if (envp[i].startsWith(PATH_EQUAL)) {
- newEnvp[i] = newPath.toString();
- } else {
- newEnvp[i] = envp[i];
- }
- }
- } else if (systemEnvMap != null) {
- Map<String, String> envVars = systemEnvMap;
- Set<String> keySet = envVars.keySet();
- newEnvp = new String[envVars.size()];
+ if (envpPath != null) {
+ newEnvp = new String[envp.length];
+ for (int i = 0; i < envp.length; i++) {
+ if (envp[i].startsWith(PATH_EQUAL)) {
+ newEnvp[i] = newPath.toString();
+ } else {
+ newEnvp[i] = envp[i];
+ }
+ }
+ } else if (systemEnvMap != null) {
+ Map<String, String> envVars = systemEnvMap;
+ Set<String> keySet = envVars.keySet();
+ newEnvp = new String[envVars.size()];
- int i = 0;
- for (String key : keySet) {
- if(key.startsWith(PATH)) {
- if (ltPath!=null) {
- newEnvp[i] = key + "=" + ltPath + SEPARATOR + envVars.get(key); //$NON-NLS-1$
- } else {
- newEnvp[i] = key + "=" + envVars.get(key); //$NON-NLS-1$
- }
- } else {
- newEnvp[i] = key + "=" + envVars.get(key); //$NON-NLS-1$
- }
- i++;
- }
- }
- return newEnvp;
- }
+ int i = 0;
+ for (String key : keySet) {
+ if(key.startsWith(PATH)) {
+ if (ltPath!=null) {
+ newEnvp[i] = key + "=" + ltPath + SEPARATOR + envVars.get(key); //$NON-NLS-1$
+ } else {
+ newEnvp[i] = key + "=" + envVars.get(key); //$NON-NLS-1$
+ }
+ } else {
+ newEnvp[i] = key + "=" + envVars.get(key); //$NON-NLS-1$
+ }
+ i++;
+ }
+ }
+ return newEnvp;
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/RuntimeProcessFactory.java b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/RuntimeProcessFactory.java
index 85ad9567b1..1d4c651f7b 100644
--- a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/RuntimeProcessFactory.java
+++ b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/factory/RuntimeProcessFactory.java
@@ -39,336 +39,336 @@ import org.eclipse.linuxtools.profiling.launch.RemoteProxyManager;
* page.
*/
public class RuntimeProcessFactory extends LinuxtoolsProcessFactory {
- private static RuntimeProcessFactory instance = null;
- private static final String WHICH_CMD = "which"; //$NON-NLS-1$
-
- private String[] tokenizeCommand(String command) {
- StringTokenizer tokenizer = new StringTokenizer(command);
- String[] cmdarray = new String[tokenizer.countTokens()];
- for (int i = 0; tokenizer.hasMoreElements(); i++) {
- cmdarray[i] = tokenizer.nextToken();
- }
-
- return cmdarray;
- }
-
- private String[] fillPathCommand(String[] cmdarray, IProject project) throws IOException {
- cmdarray[0] = whichCommand(cmdarray[0], project);
- return cmdarray;
- }
-
- private String[] fillPathSudoCommand(String[] cmdarray, IProject project) throws IOException {
- cmdarray[1] = whichCommand(cmdarray[1], project);
- return cmdarray;
- }
-
- /**
- * Used to get the full command path. It will look for the command in the
- * system path and in the path selected in 'Linux Tools Path' preference page
- * in the informed project.
- *
- * @param command The desired command
- * @param project The current project. If null, only system path will be
- * used to look for the command.
- * @return The full command path if command was found or the command if
- * command was not found.
- *
- * @since 1.1
- */
- public String whichCommand(String command, IProject project) throws IOException {
- if (project != null) {
- String[] envp = updateEnvironment(null, project);
- try {
- IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project);
- URI whichUri = URI.create(WHICH_CMD);
- IPath whichPath = new Path(proxy.toPath(whichUri));
- IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(project);
- Process pProxy = launcher.execute(whichPath, new String[]{command}, envp, null, new NullProgressMonitor());
- if (pProxy != null) {
-
- String errorLine;
- try (BufferedReader error = new BufferedReader(
- new InputStreamReader(pProxy.getErrorStream()))) {
- if ((errorLine = error.readLine()) != null) {
- throw new IOException(errorLine);
- }
- }
- ArrayList<String> lines = new ArrayList<>();
- try (BufferedReader reader = new BufferedReader(
- new InputStreamReader(pProxy.getInputStream()))) {
- String readLine = reader.readLine();
- while (readLine != null) {
- lines.add(readLine);
- readLine = reader.readLine();
- }
- }
- if (!lines.isEmpty()) {
- if (project.getLocationURI() != null) {
- if (project.getLocationURI().toString()
- .startsWith("rse:")) { //$NON-NLS-1$
- // RSE output
- if (lines.size() > 1) {
- command = lines.get(lines.size() - 2);
- }
- } else {
- // Remotetools output
- command = lines.get(0);
- }
- } else {
- // Local output
- command = lines.get(0);
- }
- }
- }
- } catch (CoreException e) {
- // Failed to call 'which', do nothing
- }
- }
- return command;
- }
-
- /**
- * @return The default instance of the RuntimeProcessFactory.
- */
- public static RuntimeProcessFactory getFactory() {
- if (instance == null) {
- instance = new RuntimeProcessFactory();
- }
- return instance;
- }
-
- /**
- * Execute one command using the path selected in 'Linux Tools Path' preference page
- * in the informed project.
- * @param cmd The desired command
- * @param project The current project. If null, only system path will be
- * used to look for the command.
- * @return The process started by exec.
- */
- public Process exec(String cmd, IProject project) throws IOException {
- return exec(cmd, null, (IFileStore)null, project);
- }
-
- /**
- * Execute one command using the path selected in 'Linux Tools Path' preference page
- * in the informed project.
- * @param cmdarray An array with the command to be executed and its params.
- * @param project The current project. If null, only system path will be
- * used to look for the command.
- * @return The process started by exec.
- */
- public Process exec(String[] cmdarray, IProject project) throws IOException {
- return exec(cmdarray, null, project);
- }
-
- /**
- * Execute one command using the path selected in 'Linux Tools Path' preference page
- * in the informed project.
- * @param cmdarray An array with the command to be executed and its params.
- * @param envp An array with extra enviroment variables to be used when running
- * the command
- * @param project The current project. If null, only system path will be
- * used to look for the command.
- * @return The process started by exec.
- */
- public Process exec(String[] cmdarray, String[] envp, IProject project) throws IOException {
- return exec(cmdarray, envp, (IFileStore)null, project);
- }
-
- /**
- * Execute one command using the path selected in 'Linux Tools Path' preference page
- * in the informed project.
- * @param cmd The desired command
- * @param envp An array with extra enviroment variables to be used when running
- * the command
- * @param project The current project. If null, only system path will be
- * used to look for the command.
- * @return The process started by exec.
- */
- public Process exec(String cmd, String[] envp, IProject project) throws IOException {
- return exec(cmd, envp, (IFileStore)null, project);
- }
-
- /**
- * Execute one command using the path selected in 'Linux Tools Path' preference page
- * in the informed project.
- * @param cmd The desired command
- * @param envp An array with extra enviroment variables to be used when running
- * the command
- * @param dir The directory used as current directory to run the command.
- * @param project The current project. If null, only system path will be
- * used to look for the command.
- * @return The process started by exec.
- *
- * @since 1.1
- */
- private Process exec(String cmd, String[] envp, IFileStore dir, IProject project)
- throws IOException {
- return exec(tokenizeCommand(cmd), envp, dir, project);
- }
-
- /**
- * Execute one command using the path selected in 'Linux Tools Path' preference page
- * in the informed project.
- * @param cmdarray An array with the command to be executed and its params.
- * @param envp An array with extra enviroment variables to be used when running
- * the command
- * @param dir The directory used as current directory to run the command.
- * @param project The current project. If null, only system path will be
- * used to look for the command.
- * @return The process started by exec.
- *
- * @since 1.1
- */
- public Process exec(String cmdarray[], String[] envp, IFileStore dir, IProject project)
- throws IOException {
- return exec(cmdarray, envp, dir, project, null);
- }
-
- /**
- * Execute one command using the path selected in 'Linux Tools Path' preference page
- * in the informed project.
- * @param cmdarray An array with the command to be executed and its params.
- * @param envp An array with extra enviroment variables to be used when running
- * the command
- * @param dir The directory used as current directory to run the command.
- * @param project The current project. If null, only system path will be
- * used to look for the command.
- * @param pty PTY for use with Eclipse Console.
- * @return The process started by exec.
- *
- * @since 2.1
- */
- public Process exec(String cmdarray[], String[] envp, IFileStore dir, IProject project, PTY pty)
- throws IOException {
-
- Process p = null;
- try {
- cmdarray = fillPathCommand(cmdarray, project);
-
- String command = cmdarray[0];
- URI uri = URI.create(command);
-
- IPath changeToDir = null;
- IPath path;
- IRemoteCommandLauncher launcher;
-
- if (project != null) {
- IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project);
- path = new Path(proxy.toPath(uri));
- launcher = RemoteProxyManager.getInstance().getLauncher(project);
- envp = updateEnvironment(envp, project);
- if (dir != null) {
- changeToDir = new Path(proxy.toPath(dir.toURI()));
- }
- } else {
- path = new Path(uri.getPath());
- launcher = RemoteProxyManager.getInstance().getLauncher(uri);
- if (dir != null) {
- changeToDir = new Path(dir.toURI().getPath());
- }
- }
-
-
- List<String> cmdlist = new ArrayList<>(Arrays.asList(cmdarray));
- cmdlist.remove(0);
- cmdlist.toArray(cmdarray);
- cmdarray = cmdlist.toArray(new String[0]);
-
- if (pty == null) {
- p = launcher.execute(path, cmdarray, envp, changeToDir , new NullProgressMonitor());
- } else {
- p = launcher.execute(path, cmdarray, envp, changeToDir , new NullProgressMonitor(), pty);
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
-
- return p;
- }
-
- /**
- * Execute one command, as root, using the path selected in 'Linux Tools Path'
- * preference page in the informed project.
- * @param cmdarray An array with the command to be executed and its params.
- * @param project The current project. If null, only system path will be
- * used to look for the command.
- * @return The process started by sudoExec
- */
- public Process sudoExec(String[] cmdarray, IProject project) throws IOException {
- return sudoExec(cmdarray, null, project);
- }
-
- /**
- * Execute one command, as root, using the path selected in 'Linux Tools Path'
- * preference page in the informed project.
- * @param cmdarray An array with the command to be executed and its params.
- * @param envp An array with extra enviroment variables to be used when running
- * the command
- * @param project The current project. If null, only system path will be
- * used to look for the command.
- * @return The process started by sudoExec
- */
- private Process sudoExec(String[] cmdarray, String[] envp, IProject project) throws IOException {
- return sudoExec(cmdarray, envp, (IFileStore)null, project);
- }
-
- /**
- * Execute one command, as root, using the path selected in 'Linux Tools Path'
- * preference page in the informed project.
- * @param cmdarray An array with the command to be executed and its params.
- * @param envp An array with extra enviroment variables to be used when running
- * the command
- * @param dir The directory used as current directory to run the command.
- * @param project The current project. If null, only system path will be
- * used to look for the command.
- * @return The process started by sudoExec
- *
- * @since 1.1
- */
- private Process sudoExec(String[] cmdarray, String[] envp, IFileStore dir, IProject project) throws IOException {
- URI uri = URI.create("sudo"); //$NON-NLS-1$
-
- List<String> cmdList = Arrays.asList(cmdarray);
- ArrayList<String> cmdArrayList = new ArrayList<>(cmdList);
- cmdArrayList.add(0, "-n"); //$NON-NLS-1$
-
- String[] cmdArraySudo = new String[cmdArrayList.size()];
- cmdArrayList.toArray(cmdArraySudo);
-
- Process p = null;
- try {
- cmdArraySudo = fillPathSudoCommand(cmdArraySudo, project);
- IRemoteCommandLauncher launcher;
- IPath changeToDir = null, path;
- if (project != null) {
- IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project);
- path = new Path(proxy.toPath(uri));
- launcher = RemoteProxyManager.getInstance().getLauncher(project);
- envp = updateEnvironment(envp, project);
-
- if (dir != null) {
- changeToDir = new Path(proxy.toPath(dir.toURI()));
- }
- } else {
- launcher = RemoteProxyManager.getInstance().getLauncher(uri);
- path = new Path(uri.getPath());
- if (dir != null) {
- changeToDir = new Path(dir.toURI().getPath());
- }
- }
-
- List<String> cmdlist = new ArrayList<>(Arrays.asList(cmdArraySudo));
- cmdlist.remove(0);
- cmdlist.toArray(cmdArraySudo);
- cmdArraySudo = cmdlist.toArray(new String[0]);
-
- p = launcher.execute(path, cmdArraySudo, envp, changeToDir , new NullProgressMonitor());
- } catch (CoreException e) {
- e.printStackTrace();
- }
-
- return p;
-
- }
+ private static RuntimeProcessFactory instance = null;
+ private static final String WHICH_CMD = "which"; //$NON-NLS-1$
+
+ private String[] tokenizeCommand(String command) {
+ StringTokenizer tokenizer = new StringTokenizer(command);
+ String[] cmdarray = new String[tokenizer.countTokens()];
+ for (int i = 0; tokenizer.hasMoreElements(); i++) {
+ cmdarray[i] = tokenizer.nextToken();
+ }
+
+ return cmdarray;
+ }
+
+ private String[] fillPathCommand(String[] cmdarray, IProject project) throws IOException {
+ cmdarray[0] = whichCommand(cmdarray[0], project);
+ return cmdarray;
+ }
+
+ private String[] fillPathSudoCommand(String[] cmdarray, IProject project) throws IOException {
+ cmdarray[1] = whichCommand(cmdarray[1], project);
+ return cmdarray;
+ }
+
+ /**
+ * Used to get the full command path. It will look for the command in the
+ * system path and in the path selected in 'Linux Tools Path' preference page
+ * in the informed project.
+ *
+ * @param command The desired command
+ * @param project The current project. If null, only system path will be
+ * used to look for the command.
+ * @return The full command path if command was found or the command if
+ * command was not found.
+ *
+ * @since 1.1
+ */
+ public String whichCommand(String command, IProject project) throws IOException {
+ if (project != null) {
+ String[] envp = updateEnvironment(null, project);
+ try {
+ IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project);
+ URI whichUri = URI.create(WHICH_CMD);
+ IPath whichPath = new Path(proxy.toPath(whichUri));
+ IRemoteCommandLauncher launcher = RemoteProxyManager.getInstance().getLauncher(project);
+ Process pProxy = launcher.execute(whichPath, new String[]{command}, envp, null, new NullProgressMonitor());
+ if (pProxy != null) {
+
+ String errorLine;
+ try (BufferedReader error = new BufferedReader(
+ new InputStreamReader(pProxy.getErrorStream()))) {
+ if ((errorLine = error.readLine()) != null) {
+ throw new IOException(errorLine);
+ }
+ }
+ ArrayList<String> lines = new ArrayList<>();
+ try (BufferedReader reader = new BufferedReader(
+ new InputStreamReader(pProxy.getInputStream()))) {
+ String readLine = reader.readLine();
+ while (readLine != null) {
+ lines.add(readLine);
+ readLine = reader.readLine();
+ }
+ }
+ if (!lines.isEmpty()) {
+ if (project.getLocationURI() != null) {
+ if (project.getLocationURI().toString()
+ .startsWith("rse:")) { //$NON-NLS-1$
+ // RSE output
+ if (lines.size() > 1) {
+ command = lines.get(lines.size() - 2);
+ }
+ } else {
+ // Remotetools output
+ command = lines.get(0);
+ }
+ } else {
+ // Local output
+ command = lines.get(0);
+ }
+ }
+ }
+ } catch (CoreException e) {
+ // Failed to call 'which', do nothing
+ }
+ }
+ return command;
+ }
+
+ /**
+ * @return The default instance of the RuntimeProcessFactory.
+ */
+ public static RuntimeProcessFactory getFactory() {
+ if (instance == null) {
+ instance = new RuntimeProcessFactory();
+ }
+ return instance;
+ }
+
+ /**
+ * Execute one command using the path selected in 'Linux Tools Path' preference page
+ * in the informed project.
+ * @param cmd The desired command
+ * @param project The current project. If null, only system path will be
+ * used to look for the command.
+ * @return The process started by exec.
+ */
+ public Process exec(String cmd, IProject project) throws IOException {
+ return exec(cmd, null, (IFileStore)null, project);
+ }
+
+ /**
+ * Execute one command using the path selected in 'Linux Tools Path' preference page
+ * in the informed project.
+ * @param cmdarray An array with the command to be executed and its params.
+ * @param project The current project. If null, only system path will be
+ * used to look for the command.
+ * @return The process started by exec.
+ */
+ public Process exec(String[] cmdarray, IProject project) throws IOException {
+ return exec(cmdarray, null, project);
+ }
+
+ /**
+ * Execute one command using the path selected in 'Linux Tools Path' preference page
+ * in the informed project.
+ * @param cmdarray An array with the command to be executed and its params.
+ * @param envp An array with extra enviroment variables to be used when running
+ * the command
+ * @param project The current project. If null, only system path will be
+ * used to look for the command.
+ * @return The process started by exec.
+ */
+ public Process exec(String[] cmdarray, String[] envp, IProject project) throws IOException {
+ return exec(cmdarray, envp, (IFileStore)null, project);
+ }
+
+ /**
+ * Execute one command using the path selected in 'Linux Tools Path' preference page
+ * in the informed project.
+ * @param cmd The desired command
+ * @param envp An array with extra enviroment variables to be used when running
+ * the command
+ * @param project The current project. If null, only system path will be
+ * used to look for the command.
+ * @return The process started by exec.
+ */
+ public Process exec(String cmd, String[] envp, IProject project) throws IOException {
+ return exec(cmd, envp, (IFileStore)null, project);
+ }
+
+ /**
+ * Execute one command using the path selected in 'Linux Tools Path' preference page
+ * in the informed project.
+ * @param cmd The desired command
+ * @param envp An array with extra enviroment variables to be used when running
+ * the command
+ * @param dir The directory used as current directory to run the command.
+ * @param project The current project. If null, only system path will be
+ * used to look for the command.
+ * @return The process started by exec.
+ *
+ * @since 1.1
+ */
+ private Process exec(String cmd, String[] envp, IFileStore dir, IProject project)
+ throws IOException {
+ return exec(tokenizeCommand(cmd), envp, dir, project);
+ }
+
+ /**
+ * Execute one command using the path selected in 'Linux Tools Path' preference page
+ * in the informed project.
+ * @param cmdarray An array with the command to be executed and its params.
+ * @param envp An array with extra enviroment variables to be used when running
+ * the command
+ * @param dir The directory used as current directory to run the command.
+ * @param project The current project. If null, only system path will be
+ * used to look for the command.
+ * @return The process started by exec.
+ *
+ * @since 1.1
+ */
+ public Process exec(String cmdarray[], String[] envp, IFileStore dir, IProject project)
+ throws IOException {
+ return exec(cmdarray, envp, dir, project, null);
+ }
+
+ /**
+ * Execute one command using the path selected in 'Linux Tools Path' preference page
+ * in the informed project.
+ * @param cmdarray An array with the command to be executed and its params.
+ * @param envp An array with extra enviroment variables to be used when running
+ * the command
+ * @param dir The directory used as current directory to run the command.
+ * @param project The current project. If null, only system path will be
+ * used to look for the command.
+ * @param pty PTY for use with Eclipse Console.
+ * @return The process started by exec.
+ *
+ * @since 2.1
+ */
+ public Process exec(String cmdarray[], String[] envp, IFileStore dir, IProject project, PTY pty)
+ throws IOException {
+
+ Process p = null;
+ try {
+ cmdarray = fillPathCommand(cmdarray, project);
+
+ String command = cmdarray[0];
+ URI uri = URI.create(command);
+
+ IPath changeToDir = null;
+ IPath path;
+ IRemoteCommandLauncher launcher;
+
+ if (project != null) {
+ IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project);
+ path = new Path(proxy.toPath(uri));
+ launcher = RemoteProxyManager.getInstance().getLauncher(project);
+ envp = updateEnvironment(envp, project);
+ if (dir != null) {
+ changeToDir = new Path(proxy.toPath(dir.toURI()));
+ }
+ } else {
+ path = new Path(uri.getPath());
+ launcher = RemoteProxyManager.getInstance().getLauncher(uri);
+ if (dir != null) {
+ changeToDir = new Path(dir.toURI().getPath());
+ }
+ }
+
+
+ List<String> cmdlist = new ArrayList<>(Arrays.asList(cmdarray));
+ cmdlist.remove(0);
+ cmdlist.toArray(cmdarray);
+ cmdarray = cmdlist.toArray(new String[0]);
+
+ if (pty == null) {
+ p = launcher.execute(path, cmdarray, envp, changeToDir , new NullProgressMonitor());
+ } else {
+ p = launcher.execute(path, cmdarray, envp, changeToDir , new NullProgressMonitor(), pty);
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+
+ return p;
+ }
+
+ /**
+ * Execute one command, as root, using the path selected in 'Linux Tools Path'
+ * preference page in the informed project.
+ * @param cmdarray An array with the command to be executed and its params.
+ * @param project The current project. If null, only system path will be
+ * used to look for the command.
+ * @return The process started by sudoExec
+ */
+ public Process sudoExec(String[] cmdarray, IProject project) throws IOException {
+ return sudoExec(cmdarray, null, project);
+ }
+
+ /**
+ * Execute one command, as root, using the path selected in 'Linux Tools Path'
+ * preference page in the informed project.
+ * @param cmdarray An array with the command to be executed and its params.
+ * @param envp An array with extra enviroment variables to be used when running
+ * the command
+ * @param project The current project. If null, only system path will be
+ * used to look for the command.
+ * @return The process started by sudoExec
+ */
+ private Process sudoExec(String[] cmdarray, String[] envp, IProject project) throws IOException {
+ return sudoExec(cmdarray, envp, (IFileStore)null, project);
+ }
+
+ /**
+ * Execute one command, as root, using the path selected in 'Linux Tools Path'
+ * preference page in the informed project.
+ * @param cmdarray An array with the command to be executed and its params.
+ * @param envp An array with extra enviroment variables to be used when running
+ * the command
+ * @param dir The directory used as current directory to run the command.
+ * @param project The current project. If null, only system path will be
+ * used to look for the command.
+ * @return The process started by sudoExec
+ *
+ * @since 1.1
+ */
+ private Process sudoExec(String[] cmdarray, String[] envp, IFileStore dir, IProject project) throws IOException {
+ URI uri = URI.create("sudo"); //$NON-NLS-1$
+
+ List<String> cmdList = Arrays.asList(cmdarray);
+ ArrayList<String> cmdArrayList = new ArrayList<>(cmdList);
+ cmdArrayList.add(0, "-n"); //$NON-NLS-1$
+
+ String[] cmdArraySudo = new String[cmdArrayList.size()];
+ cmdArrayList.toArray(cmdArraySudo);
+
+ Process p = null;
+ try {
+ cmdArraySudo = fillPathSudoCommand(cmdArraySudo, project);
+ IRemoteCommandLauncher launcher;
+ IPath changeToDir = null, path;
+ if (project != null) {
+ IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(project);
+ path = new Path(proxy.toPath(uri));
+ launcher = RemoteProxyManager.getInstance().getLauncher(project);
+ envp = updateEnvironment(envp, project);
+
+ if (dir != null) {
+ changeToDir = new Path(proxy.toPath(dir.toURI()));
+ }
+ } else {
+ launcher = RemoteProxyManager.getInstance().getLauncher(uri);
+ path = new Path(uri.getPath());
+ if (dir != null) {
+ changeToDir = new Path(dir.toURI().getPath());
+ }
+ }
+
+ List<String> cmdlist = new ArrayList<>(Arrays.asList(cmdArraySudo));
+ cmdlist.remove(0);
+ cmdlist.toArray(cmdArraySudo);
+ cmdArraySudo = cmdlist.toArray(new String[0]);
+
+ p = launcher.execute(path, cmdArraySudo, envp, changeToDir , new NullProgressMonitor());
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+
+ return p;
+
+ }
}
diff --git a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/properties/LinuxtoolsPathProperty.java b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/properties/LinuxtoolsPathProperty.java
index 648e1924dc..60f5bb7240 100644
--- a/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/properties/LinuxtoolsPathProperty.java
+++ b/profiling/org.eclipse.linuxtools.tools.launch.core/src/org/eclipse/linuxtools/tools/launch/core/properties/LinuxtoolsPathProperty.java
@@ -24,94 +24,94 @@ import org.eclipse.ui.preferences.ScopedPreferenceStore;
* This class provides the path to be used to run linux tools commands
*/
public class LinuxtoolsPathProperty {
- private static final String LINUXTOOLS_PATH_EXT_POINT = "LinuxtoolsPathOptions"; //$NON-NLS-1$
- private static final String LINUXTOOLS_PATH_OPTION = "option"; //$NON-NLS-1$
- private static final String LINUXTOOLS_PATH_OPTION_PATH = "path"; //$NON-NLS-1$
- private static final String LINUXTOOLS_PATH_OPTION_DEFAULT = "default"; //$NON-NLS-1$
- private String linuxtoolsPathDefault = ""; //$NON-NLS-1$
- private boolean linuxtoolsPathSystemDefault = true;
- private static LinuxtoolsPathProperty instance = null;
+ private static final String LINUXTOOLS_PATH_EXT_POINT = "LinuxtoolsPathOptions"; //$NON-NLS-1$
+ private static final String LINUXTOOLS_PATH_OPTION = "option"; //$NON-NLS-1$
+ private static final String LINUXTOOLS_PATH_OPTION_PATH = "path"; //$NON-NLS-1$
+ private static final String LINUXTOOLS_PATH_OPTION_DEFAULT = "default"; //$NON-NLS-1$
+ private String linuxtoolsPathDefault = ""; //$NON-NLS-1$
+ private boolean linuxtoolsPathSystemDefault = true;
+ private static LinuxtoolsPathProperty instance = null;
- private void fillLinuxtoolsPath(String path) {
- if (path != null && !path.isEmpty()) {
- linuxtoolsPathSystemDefault = false;
- linuxtoolsPathDefault = path;
- }
- }
+ private void fillLinuxtoolsPath(String path) {
+ if (path != null && !path.isEmpty()) {
+ linuxtoolsPathSystemDefault = false;
+ linuxtoolsPathDefault = path;
+ }
+ }
- private LinuxtoolsPathProperty() {
- IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(LaunchCoreConstants.PLUGIN_ID, LINUXTOOLS_PATH_EXT_POINT);
- if (extPoint != null) {
- IConfigurationElement[] configs = extPoint.getConfigurationElements();
- for (IConfigurationElement config : configs)
- if (config.getName().equals(LINUXTOOLS_PATH_OPTION)) {
- String sdefault = config.getAttribute(LINUXTOOLS_PATH_OPTION_DEFAULT);
- if (sdefault != null && sdefault.equals(Boolean.toString(true))) {
- fillLinuxtoolsPath(config.getAttribute(LINUXTOOLS_PATH_OPTION_PATH));
- break;
- }
- }
- }
- }
+ private LinuxtoolsPathProperty() {
+ IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(LaunchCoreConstants.PLUGIN_ID, LINUXTOOLS_PATH_EXT_POINT);
+ if (extPoint != null) {
+ IConfigurationElement[] configs = extPoint.getConfigurationElements();
+ for (IConfigurationElement config : configs)
+ if (config.getName().equals(LINUXTOOLS_PATH_OPTION)) {
+ String sdefault = config.getAttribute(LINUXTOOLS_PATH_OPTION_DEFAULT);
+ if (sdefault != null && sdefault.equals(Boolean.toString(true))) {
+ fillLinuxtoolsPath(config.getAttribute(LINUXTOOLS_PATH_OPTION_PATH));
+ break;
+ }
+ }
+ }
+ }
- public static LinuxtoolsPathProperty getInstance() {
- if (instance == null) {
- instance = new LinuxtoolsPathProperty();
- }
- return instance;
- }
+ public static LinuxtoolsPathProperty getInstance() {
+ if (instance == null) {
+ instance = new LinuxtoolsPathProperty();
+ }
+ return instance;
+ }
- /*
- * This function will return the selected Linuxtools Path in the
- * 'Linux Tools Path' project properties page.
- * If there is a default path setted by the extension point it should be
- * selected as the default by the tools.launch.ui classes. This function
- * will not care about it.
- *
- * * If the tools.launch.ui is not installed this function should always
- * return "".
- * * If the option 'Use the System env PATH' this function should return ""
- * * If the option 'Prepend string to path' is selected this function
- * should return the value of the selected path.
- */
- public String getLinuxtoolsPath(IProject project) {
- if (project == null) {
- return ""; //$NON-NLS-1$
- }
+ /*
+ * This function will return the selected Linuxtools Path in the
+ * 'Linux Tools Path' project properties page.
+ * If there is a default path setted by the extension point it should be
+ * selected as the default by the tools.launch.ui classes. This function
+ * will not care about it.
+ *
+ * * If the tools.launch.ui is not installed this function should always
+ * return "".
+ * * If the option 'Use the System env PATH' this function should return ""
+ * * If the option 'Prepend string to path' is selected this function
+ * should return the value of the selected path.
+ */
+ public String getLinuxtoolsPath(IProject project) {
+ if (project == null) {
+ return ""; //$NON-NLS-1$
+ }
- ScopedPreferenceStore store = new ScopedPreferenceStore(
- new ProjectScope(project),
- LaunchCoreConstants.PLUGIN_ID);
+ ScopedPreferenceStore store = new ScopedPreferenceStore(
+ new ProjectScope(project),
+ LaunchCoreConstants.PLUGIN_ID);
- //If the value is not stored we use the default
- boolean systemPathSelected;
- if (store.contains(LaunchCoreConstants.LINUXTOOLS_PATH_SYSTEM_NAME)) {
- systemPathSelected = store.getBoolean(LaunchCoreConstants.LINUXTOOLS_PATH_SYSTEM_NAME);
- } else {
- systemPathSelected = getLinuxtoolsPathSystemDefault();
- }
+ //If the value is not stored we use the default
+ boolean systemPathSelected;
+ if (store.contains(LaunchCoreConstants.LINUXTOOLS_PATH_SYSTEM_NAME)) {
+ systemPathSelected = store.getBoolean(LaunchCoreConstants.LINUXTOOLS_PATH_SYSTEM_NAME);
+ } else {
+ systemPathSelected = getLinuxtoolsPathSystemDefault();
+ }
- if (systemPathSelected) {
- return ""; //$NON-NLS-1$
- }
+ if (systemPathSelected) {
+ return ""; //$NON-NLS-1$
+ }
- String path = null;
- if (store.contains(LaunchCoreConstants.LINUXTOOLS_PATH_NAME)) {
- path = store.getString(LaunchCoreConstants.LINUXTOOLS_PATH_NAME);
- }
+ String path = null;
+ if (store.contains(LaunchCoreConstants.LINUXTOOLS_PATH_NAME)) {
+ path = store.getString(LaunchCoreConstants.LINUXTOOLS_PATH_NAME);
+ }
- if (path == null) {
- return getLinuxtoolsPathDefault();
- }
- return path;
- }
+ if (path == null) {
+ return getLinuxtoolsPathDefault();
+ }
+ return path;
+ }
- public String getLinuxtoolsPathDefault() {
- return linuxtoolsPathDefault;
- }
+ public String getLinuxtoolsPathDefault() {
+ return linuxtoolsPathDefault;
+ }
- public boolean getLinuxtoolsPathSystemDefault() {
- return linuxtoolsPathSystemDefault;
- }
+ public boolean getLinuxtoolsPathSystemDefault() {
+ return linuxtoolsPathSystemDefault;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm-feature/feature.xml b/rpm/org.eclipse.linuxtools.rpm-feature/feature.xml
index 2207815f4b..6b501f587e 100644
--- a/rpm/org.eclipse.linuxtools.rpm-feature/feature.xml
+++ b/rpm/org.eclipse.linuxtools.rpm-feature/feature.xml
@@ -5,7 +5,7 @@
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-
+
Contributors:
Red Hat - initial API and implementation
-->
@@ -66,7 +66,7 @@
download-size="0"
install-size="0"
version="0.0.0"/>
-
+
<plugin
id="org.eclipse.linuxtools.rpmstubby"
download-size="0"
diff --git a/rpm/org.eclipse.linuxtools.rpm-feature/pom.xml b/rpm/org.eclipse.linuxtools.rpm-feature/pom.xml
index 694b99f242..454710aa7f 100644
--- a/rpm/org.eclipse.linuxtools.rpm-feature/pom.xml
+++ b/rpm/org.eclipse.linuxtools.rpm-feature/pom.xml
@@ -22,7 +22,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools RPM Tools Feature</name>
-
+
<build>
<plugins>
<plugin>
diff --git a/rpm/org.eclipse.linuxtools.rpm.core.tests/pom.xml b/rpm/org.eclipse.linuxtools.rpm.core.tests/pom.xml
index 40b9fcd94c..21cef8633e 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core.tests/pom.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.core.tests/pom.xml
@@ -36,7 +36,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.rpm.core.tests</testSuite>
<testClass>org.eclipse.linuxtools.rpm.core.tests.AllTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.platform.ide</product>
</configuration>
diff --git a/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/DownloadPrepareSourcesTest.java b/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/DownloadPrepareSourcesTest.java
index ca3cce6ef5..31f35bc061 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/DownloadPrepareSourcesTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/DownloadPrepareSourcesTest.java
@@ -49,248 +49,248 @@ import org.osgi.framework.FrameworkUtil;
*/
public class DownloadPrepareSourcesTest {
- static IWorkspace workspace;
- static IWorkspaceRoot root;
- static NullProgressMonitor monitor;
- String pluginRoot;
- static IProject testProject;
-
- final String file_sep = System.getProperty("file.separator"); //$NON-NLS-1$
-
- /**
- * Prepare the workspace
- *
- * @throws java.lang.Exception
- */
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- workspace = ResourcesPlugin.getWorkspace();
- root = workspace.getRoot();
- monitor = new NullProgressMonitor();
- }
-
- /**
- * Create the test project before starting each test
- *
- * @throws CoreException
- */
- @Before
- public void setUpBeforeTests() throws CoreException {
- testProject = root.getProject("testHelloWorld");
- testProject.create(monitor);
- testProject.open(monitor);
- }
-
- /**
- * If the test project exists, delete it and its contents
- * (used to start clean and fresh for each test case)
- *
- * @throws CoreException
- */
- @After
- public void cleanUpAfterTests() throws CoreException {
- if (testProject != null && testProject.exists()) {
- testProject.delete(true, true, monitor);
- }
- }
-
- /**
- * Testing downloading sources using RPMBuild layout
- *
- * @throws CoreException
- * @throws IOException
- * @throws InterruptedException
- */
- @Test
- public void layoutRPMBuildDownloadSourcesTest() throws CoreException,
- IOException, InterruptedException {
- RPMProject rpmProject = importSrpm(testProject,
- RPMProjectLayout.RPMBUILD);
- assertNotNull(rpmProject);
-
- downloadFile(rpmProject);
-
- checkDownloadedFile(rpmProject, RPMProjectLayout.RPMBUILD);
- }
-
- /**
- * Test downloading sources using FLAT layout
- *
- * @throws CoreException
- * @throws IOException
- * @throws InterruptedException
- */
- @Test
- public void layoutFLATDownloadSourcesTest() throws CoreException,
- IOException, InterruptedException {
- RPMProject rpmProject = importSrpm(testProject, RPMProjectLayout.FLAT);
- assertNotNull(rpmProject);
-
- downloadFile(rpmProject);
-
- checkDownloadedFile(rpmProject, RPMProjectLayout.FLAT);
- }
-
- /**
- * Test preparing sources using RPMBuild layout
- *
- * @throws CoreException
- * @throws IOException
- * @throws InterruptedException
- */
- @Test
- public void layoutRPMBuildPrepareSourcesTest() throws CoreException,
- IOException, InterruptedException {
- RPMProject rpmProject = importSrpm(testProject,
- RPMProjectLayout.RPMBUILD);
- assertNotNull(rpmProject);
-
- downloadFile(rpmProject);
-
- checkDownloadedFile(rpmProject, RPMProjectLayout.RPMBUILD);
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- IStatus is = rpmProject.buildPrep(bos);
- assertTrue(is.isOK());
-
- checkPreparedSources(rpmProject, RPMProjectLayout.RPMBUILD);
- }
-
- /**
- * Test preparing sources using FLAT layout
- *
- * @throws CoreException
- * @throws IOException
- * @throws InterruptedException
- */
- @Test
- public void layoutFLATPrepareSourcesTest() throws CoreException,
- IOException, InterruptedException {
- RPMProject rpmProject = importSrpm(testProject,
- RPMProjectLayout.FLAT);
- assertNotNull(rpmProject);
-
- downloadFile(rpmProject);
-
- checkDownloadedFile(rpmProject, RPMProjectLayout.FLAT);
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- IStatus is = rpmProject.buildPrep(bos);
- assertTrue(is.isOK());
-
- checkPreparedSources(rpmProject, RPMProjectLayout.FLAT);
- }
-
- /**
- * Check if the file was downloaded correctly based on project layout
- *
- * @param project The RPM project
- * @param layout The layout of the RPM project (RPMBuild or FLAT)
- * @throws CoreException
- */
- public void checkDownloadedFile(RPMProject project, RPMProjectLayout layout)
- throws CoreException {
- IContainer sourcesFolder = project.getConfiguration()
- .getSourcesFolder();
- assertNotNull(sourcesFolder);
- switch (layout) {
- case RPMBUILD:
- assertNotNull(sourcesFolder.getParent().findMember("SOURCES"));
- assertEquals(sourcesFolder.members().length, 1);
- // check if the file exists under SOURCES folder
- assertNotNull(sourcesFolder
- .findMember(new Path("hello-2.8.tar.gz")));
- break;
- case FLAT:
- // 4 = "hello-2.8.tar.gz" + ".project" + "hello-2.8-1.fc19.src.rpm" + "hello.spec"
- assertEquals(sourcesFolder.members().length, 4);
- assertNotNull(sourcesFolder
- .findMember(new Path("hello-2.8.tar.gz")));
- break;
- }
- }
-
- /**
- * Check if the source was prepared correctly based on project layout
- *
- * @param project The RPM project
- * @param layout The layout of the RPM project (RPMBuild or FLAT)
- * @throws CoreException
- */
- public void checkPreparedSources(RPMProject project, RPMProjectLayout layout)
- throws CoreException {
- IContainer buildFolder = project.getConfiguration().getBuildFolder();
- IFolder helloBuildFolder = null;
- assertNotNull(buildFolder);
- switch (layout) {
- case RPMBUILD:
- assertNotNull(buildFolder.getParent().findMember("BUILD"));
- assertEquals(buildFolder.members().length, 1);
- // check if the file exists under BUILD folder
- helloBuildFolder = buildFolder.getFolder(new Path("hello-2.8"));
- assertTrue(helloBuildFolder.exists());
- // there should be some stuff within hello-2.8/ folder
- assertTrue(helloBuildFolder.members().length >= 1);
- break;
- case FLAT:
- // 4 = "hello-2.8.tar.gz" + ".project" + "hello-2.8-1.fc19.src.rpm" + "hello.spec" + "hello-2.8/"
- assertEquals(buildFolder.members().length, 5);
- helloBuildFolder = buildFolder.getFolder(new Path("hello-2.8"));
- assertTrue(helloBuildFolder.exists());
- // there should be some stuff within hello-2.8/ folder
- assertTrue(helloBuildFolder.members().length >= 1);
- break;
- }
- }
-
- /**
- * Download and also test if the file was downloaded correctly
- *
- * @param project The RPM project
- * @throws IOException
- * @throws InterruptedException
- */
- public void downloadFile(RPMProject project) throws IOException,
- InterruptedException {
- // connect to the URL
- URL url = new URL("http://ftp.gnu.org/gnu/hello/hello-2.8.tar.gz");
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- assertEquals(connection.getResponseCode(), HttpURLConnection.HTTP_OK);
-
- // download the file
- String filename = "hello-2.8.tar.gz";
- IFile file = project.getConfiguration().getSourcesFolder()
- .getFile(new Path(filename));
- Job downloadJob = new DownloadJob(file, connection);
- downloadJob.setUser(true);
- downloadJob.schedule();
- downloadJob.join();
- assertEquals(downloadJob.getResult(),Status.OK_STATUS);
- }
-
- /**
- * Import the SRPM into the project (make .spec accessible)
- *
- * @param testProject The test project
- * @param layout layout The layout of the RPM project (RPMBuild or FLAT)
- * @return The RPM project
- * @throws CoreException
- * @throws IOException
- */
- private RPMProject importSrpm(IProject testProject, RPMProjectLayout layout)
- throws CoreException, IOException {
- // Instantiate an RPMProject
- RPMProject rpmProject = new RPMProject(testProject, layout);
-
- // Find the test SRPM and install it
- URL url = FileLocator.find(FrameworkUtil
- .getBundle(RPMProjectTest.class), new Path(
- "resources" + file_sep + "srpms" + file_sep + //$NON-NLS-1$ //$NON-NLS-2$
- "hello-2.8-1.fc19.src.rpm"), null);
- File foo = new File(FileLocator.toFileURL(url).getPath());
-
- // import the SRPM into the RPMProject
- rpmProject.importSourceRPM(foo);
- return rpmProject;
- }
+ static IWorkspace workspace;
+ static IWorkspaceRoot root;
+ static NullProgressMonitor monitor;
+ String pluginRoot;
+ static IProject testProject;
+
+ final String file_sep = System.getProperty("file.separator"); //$NON-NLS-1$
+
+ /**
+ * Prepare the workspace
+ *
+ * @throws java.lang.Exception
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ workspace = ResourcesPlugin.getWorkspace();
+ root = workspace.getRoot();
+ monitor = new NullProgressMonitor();
+ }
+
+ /**
+ * Create the test project before starting each test
+ *
+ * @throws CoreException
+ */
+ @Before
+ public void setUpBeforeTests() throws CoreException {
+ testProject = root.getProject("testHelloWorld");
+ testProject.create(monitor);
+ testProject.open(monitor);
+ }
+
+ /**
+ * If the test project exists, delete it and its contents
+ * (used to start clean and fresh for each test case)
+ *
+ * @throws CoreException
+ */
+ @After
+ public void cleanUpAfterTests() throws CoreException {
+ if (testProject != null && testProject.exists()) {
+ testProject.delete(true, true, monitor);
+ }
+ }
+
+ /**
+ * Testing downloading sources using RPMBuild layout
+ *
+ * @throws CoreException
+ * @throws IOException
+ * @throws InterruptedException
+ */
+ @Test
+ public void layoutRPMBuildDownloadSourcesTest() throws CoreException,
+ IOException, InterruptedException {
+ RPMProject rpmProject = importSrpm(testProject,
+ RPMProjectLayout.RPMBUILD);
+ assertNotNull(rpmProject);
+
+ downloadFile(rpmProject);
+
+ checkDownloadedFile(rpmProject, RPMProjectLayout.RPMBUILD);
+ }
+
+ /**
+ * Test downloading sources using FLAT layout
+ *
+ * @throws CoreException
+ * @throws IOException
+ * @throws InterruptedException
+ */
+ @Test
+ public void layoutFLATDownloadSourcesTest() throws CoreException,
+ IOException, InterruptedException {
+ RPMProject rpmProject = importSrpm(testProject, RPMProjectLayout.FLAT);
+ assertNotNull(rpmProject);
+
+ downloadFile(rpmProject);
+
+ checkDownloadedFile(rpmProject, RPMProjectLayout.FLAT);
+ }
+
+ /**
+ * Test preparing sources using RPMBuild layout
+ *
+ * @throws CoreException
+ * @throws IOException
+ * @throws InterruptedException
+ */
+ @Test
+ public void layoutRPMBuildPrepareSourcesTest() throws CoreException,
+ IOException, InterruptedException {
+ RPMProject rpmProject = importSrpm(testProject,
+ RPMProjectLayout.RPMBUILD);
+ assertNotNull(rpmProject);
+
+ downloadFile(rpmProject);
+
+ checkDownloadedFile(rpmProject, RPMProjectLayout.RPMBUILD);
+
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ IStatus is = rpmProject.buildPrep(bos);
+ assertTrue(is.isOK());
+
+ checkPreparedSources(rpmProject, RPMProjectLayout.RPMBUILD);
+ }
+
+ /**
+ * Test preparing sources using FLAT layout
+ *
+ * @throws CoreException
+ * @throws IOException
+ * @throws InterruptedException
+ */
+ @Test
+ public void layoutFLATPrepareSourcesTest() throws CoreException,
+ IOException, InterruptedException {
+ RPMProject rpmProject = importSrpm(testProject,
+ RPMProjectLayout.FLAT);
+ assertNotNull(rpmProject);
+
+ downloadFile(rpmProject);
+
+ checkDownloadedFile(rpmProject, RPMProjectLayout.FLAT);
+
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ IStatus is = rpmProject.buildPrep(bos);
+ assertTrue(is.isOK());
+
+ checkPreparedSources(rpmProject, RPMProjectLayout.FLAT);
+ }
+
+ /**
+ * Check if the file was downloaded correctly based on project layout
+ *
+ * @param project The RPM project
+ * @param layout The layout of the RPM project (RPMBuild or FLAT)
+ * @throws CoreException
+ */
+ public void checkDownloadedFile(RPMProject project, RPMProjectLayout layout)
+ throws CoreException {
+ IContainer sourcesFolder = project.getConfiguration()
+ .getSourcesFolder();
+ assertNotNull(sourcesFolder);
+ switch (layout) {
+ case RPMBUILD:
+ assertNotNull(sourcesFolder.getParent().findMember("SOURCES"));
+ assertEquals(sourcesFolder.members().length, 1);
+ // check if the file exists under SOURCES folder
+ assertNotNull(sourcesFolder
+ .findMember(new Path("hello-2.8.tar.gz")));
+ break;
+ case FLAT:
+ // 4 = "hello-2.8.tar.gz" + ".project" + "hello-2.8-1.fc19.src.rpm" + "hello.spec"
+ assertEquals(sourcesFolder.members().length, 4);
+ assertNotNull(sourcesFolder
+ .findMember(new Path("hello-2.8.tar.gz")));
+ break;
+ }
+ }
+
+ /**
+ * Check if the source was prepared correctly based on project layout
+ *
+ * @param project The RPM project
+ * @param layout The layout of the RPM project (RPMBuild or FLAT)
+ * @throws CoreException
+ */
+ public void checkPreparedSources(RPMProject project, RPMProjectLayout layout)
+ throws CoreException {
+ IContainer buildFolder = project.getConfiguration().getBuildFolder();
+ IFolder helloBuildFolder = null;
+ assertNotNull(buildFolder);
+ switch (layout) {
+ case RPMBUILD:
+ assertNotNull(buildFolder.getParent().findMember("BUILD"));
+ assertEquals(buildFolder.members().length, 1);
+ // check if the file exists under BUILD folder
+ helloBuildFolder = buildFolder.getFolder(new Path("hello-2.8"));
+ assertTrue(helloBuildFolder.exists());
+ // there should be some stuff within hello-2.8/ folder
+ assertTrue(helloBuildFolder.members().length >= 1);
+ break;
+ case FLAT:
+ // 4 = "hello-2.8.tar.gz" + ".project" + "hello-2.8-1.fc19.src.rpm" + "hello.spec" + "hello-2.8/"
+ assertEquals(buildFolder.members().length, 5);
+ helloBuildFolder = buildFolder.getFolder(new Path("hello-2.8"));
+ assertTrue(helloBuildFolder.exists());
+ // there should be some stuff within hello-2.8/ folder
+ assertTrue(helloBuildFolder.members().length >= 1);
+ break;
+ }
+ }
+
+ /**
+ * Download and also test if the file was downloaded correctly
+ *
+ * @param project The RPM project
+ * @throws IOException
+ * @throws InterruptedException
+ */
+ public void downloadFile(RPMProject project) throws IOException,
+ InterruptedException {
+ // connect to the URL
+ URL url = new URL("http://ftp.gnu.org/gnu/hello/hello-2.8.tar.gz");
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+ assertEquals(connection.getResponseCode(), HttpURLConnection.HTTP_OK);
+
+ // download the file
+ String filename = "hello-2.8.tar.gz";
+ IFile file = project.getConfiguration().getSourcesFolder()
+ .getFile(new Path(filename));
+ Job downloadJob = new DownloadJob(file, connection);
+ downloadJob.setUser(true);
+ downloadJob.schedule();
+ downloadJob.join();
+ assertEquals(downloadJob.getResult(),Status.OK_STATUS);
+ }
+
+ /**
+ * Import the SRPM into the project (make .spec accessible)
+ *
+ * @param testProject The test project
+ * @param layout layout The layout of the RPM project (RPMBuild or FLAT)
+ * @return The RPM project
+ * @throws CoreException
+ * @throws IOException
+ */
+ private RPMProject importSrpm(IProject testProject, RPMProjectLayout layout)
+ throws CoreException, IOException {
+ // Instantiate an RPMProject
+ RPMProject rpmProject = new RPMProject(testProject, layout);
+
+ // Find the test SRPM and install it
+ URL url = FileLocator.find(FrameworkUtil
+ .getBundle(RPMProjectTest.class), new Path(
+ "resources" + file_sep + "srpms" + file_sep + //$NON-NLS-1$ //$NON-NLS-2$
+ "hello-2.8-1.fc19.src.rpm"), null);
+ File foo = new File(FileLocator.toFileURL(url).getPath());
+
+ // import the SRPM into the RPMProject
+ rpmProject.importSourceRPM(foo);
+ return rpmProject;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectCreatorTest.java b/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectCreatorTest.java
index 9d4f3a03e6..208f18cd5d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectCreatorTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectCreatorTest.java
@@ -27,34 +27,34 @@ import org.junit.Test;
public class RPMProjectCreatorTest {
- private IProject newProject;
- @After
- public void deleteProject() throws CoreException {
- if (newProject != null && newProject.exists()) {
- newProject.delete(true, new NullProgressMonitor());
- }
- }
+ private IProject newProject;
+ @After
+ public void deleteProject() throws CoreException {
+ if (newProject != null && newProject.exists()) {
+ newProject.delete(true, new NullProgressMonitor());
+ }
+ }
- @Test
- public void createFlat() throws CoreException {
- RPMProjectCreator projectCreator = new RPMProjectCreator(RPMProjectLayout.FLAT);
- newProject = projectCreator.create("flatproject", Platform.getLocation(), new NullProgressMonitor());
- assertNotNull(newProject);
- assertEquals(1, newProject.getDescription().getNatureIds().length);
- assertEquals(IRPMConstants.RPM_NATURE_ID,
- newProject.getDescription().getNatureIds()[0]);
- }
+ @Test
+ public void createFlat() throws CoreException {
+ RPMProjectCreator projectCreator = new RPMProjectCreator(RPMProjectLayout.FLAT);
+ newProject = projectCreator.create("flatproject", Platform.getLocation(), new NullProgressMonitor());
+ assertNotNull(newProject);
+ assertEquals(1, newProject.getDescription().getNatureIds().length);
+ assertEquals(IRPMConstants.RPM_NATURE_ID,
+ newProject.getDescription().getNatureIds()[0]);
+ }
- @Test
- public void createRPMBuild() throws CoreException {
- RPMProjectCreator projectCreator = new RPMProjectCreator();
- newProject = projectCreator.create("rpmbuild", Platform.getLocation(), new NullProgressMonitor());
- assertNotNull(newProject);
- assertEquals(1, newProject.getDescription().getNatureIds().length);
- assertEquals(IRPMConstants.RPM_NATURE_ID,
- newProject.getDescription().getNatureIds()[0]);
- assertTrue(newProject.exists(new Path("SOURCES")));
- assertTrue(newProject.exists(new Path("SPECS")));
- }
+ @Test
+ public void createRPMBuild() throws CoreException {
+ RPMProjectCreator projectCreator = new RPMProjectCreator();
+ newProject = projectCreator.create("rpmbuild", Platform.getLocation(), new NullProgressMonitor());
+ assertNotNull(newProject);
+ assertEquals(1, newProject.getDescription().getNatureIds().length);
+ assertEquals(IRPMConstants.RPM_NATURE_ID,
+ newProject.getDescription().getNatureIds()[0]);
+ assertTrue(newProject.exists(new Path("SOURCES")));
+ assertTrue(newProject.exists(new Path("SPECS")));
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectNatureTest.java b/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectNatureTest.java
index c93d536042..ee5fe636e6 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectNatureTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectNatureTest.java
@@ -26,35 +26,35 @@ import org.junit.Test;
public class RPMProjectNatureTest {
- static IWorkspace workspace;
- static IWorkspaceRoot root;
- static NullProgressMonitor monitor;
+ static IWorkspace workspace;
+ static IWorkspaceRoot root;
+ static NullProgressMonitor monitor;
- @BeforeClass
- public static void setUp() throws Exception {
- IWorkspaceDescription desc;
- workspace = ResourcesPlugin.getWorkspace();
- if (workspace == null) {
- fail("Workspace was not setup");
- }
- root = workspace.getRoot();
- monitor = new NullProgressMonitor();
- if (root == null) {
- fail("Workspace root was not setup");
- }
- desc = workspace.getDescription();
- desc.setAutoBuilding(false);
- workspace.setDescription(desc);
- }
+ @BeforeClass
+ public static void setUp() throws Exception {
+ IWorkspaceDescription desc;
+ workspace = ResourcesPlugin.getWorkspace();
+ if (workspace == null) {
+ fail("Workspace was not setup");
+ }
+ root = workspace.getRoot();
+ monitor = new NullProgressMonitor();
+ if (root == null) {
+ fail("Workspace root was not setup");
+ }
+ desc = workspace.getDescription();
+ desc.setAutoBuilding(false);
+ workspace.setDescription(desc);
+ }
- @Test
- public void testAddRPMProjectNature() throws Exception {
- IProject testProject = root.getProject("testProject");
- testProject.create(monitor);
- testProject.open(monitor);
- RPMProjectNature.addRPMNature(testProject, monitor);
- assertTrue(testProject.hasNature(IRPMConstants.RPM_NATURE_ID));
- testProject.delete(true, false, monitor);
- }
+ @Test
+ public void testAddRPMProjectNature() throws Exception {
+ IProject testProject = root.getProject("testProject");
+ testProject.create(monitor);
+ testProject.open(monitor);
+ RPMProjectNature.addRPMNature(testProject, monitor);
+ assertTrue(testProject.hasNature(IRPMConstants.RPM_NATURE_ID));
+ testProject.delete(true, false, monitor);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectTest.java b/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectTest.java
index f9e541325f..47829d7130 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/tests/RPMProjectTest.java
@@ -41,186 +41,186 @@ import org.osgi.framework.FrameworkUtil;
public class RPMProjectTest {
- static IWorkspace workspace;
- static IWorkspaceRoot root;
- static NullProgressMonitor monitor;
- String pluginRoot;
-
- final String file_sep = System.getProperty("file.separator"); //$NON-NLS-1$
-
- @BeforeClass
- public static void setUp() {
- workspace = ResourcesPlugin.getWorkspace();
- root = workspace.getRoot();
- monitor = new NullProgressMonitor();
- }
-
- @Test
- public void testImportHelloWorld() throws Exception {
- // Create a project for the test
- IProject testProject = root.getProject("testHelloWorld");
- RPMProject rpmProject = importSrpm(testProject);
-
- // Make sure the original SRPM got copied into the workspace
- IFile srpm = rpmProject.getConfiguration().getSrpmsFolder()
- .getFile(new Path("helloworld-2-2.src.rpm"));
- assertTrue(srpm.exists());
-
- // Make sure everything got installed properly
- IFile spec = rpmProject.getConfiguration().getSpecsFolder()
- .getFile(new Path("helloworld.spec"));
- assertTrue(spec.exists());
- IFile sourceBall = rpmProject.getConfiguration().getSourcesFolder()
- .getFile(new Path("helloworld-2.tar.bz2"));
- assertTrue(sourceBall.exists());
-
- // Make sure we got the spec file
- IResource specFile = rpmProject.getSpecFile();
- assertNotNull(specFile);
-
- // Make sure the RPM nature was added
- assertTrue(testProject.hasNature(IRPMConstants.RPM_NATURE_ID));
-
- // Clean up
- testProject.delete(true, true, monitor);
- }
-
- @Test
- public void testImportHelloWorldFlat() throws Exception {
- // Create a project for the test
- IProject testProject = root.getProject("testHelloWorld");
- testProject.create(monitor);
- testProject.open(monitor);
-
- // Instantiate an RPMProject
- RPMProject rpmProject = new RPMProject(testProject,
- RPMProjectLayout.FLAT);
-
- // Find the test SRPM and install it
- URL url = FileLocator.find(FrameworkUtil
- .getBundle(RPMProjectTest.class), new Path(
- "resources" + file_sep + "srpms" + file_sep + //$NON-NLS-1$ //$NON-NLS-2$
- "helloworld-2-2.src.rpm"), null);
- File foo = new File(FileLocator.toFileURL(url).getPath());
- rpmProject.importSourceRPM(foo);
-
- // Make sure the original SRPM got copied into the workspace
- IFile srpm = rpmProject.getConfiguration().getSrpmsFolder()
- .getFile(new Path("helloworld-2-2.src.rpm"));
- assertTrue(srpm.exists());
-
- // Make sure everything got installed properly
- IFile spec = rpmProject.getConfiguration().getSpecsFolder()
- .getFile(new Path("helloworld.spec"));
- assertTrue(spec.exists());
- IFile sourceBall = rpmProject.getConfiguration().getSourcesFolder()
- .getFile(new Path("helloworld-2.tar.bz2"));
- assertTrue(sourceBall.exists());
-
- // Make sure we got the spec file
- IResource specFile = rpmProject.getSpecFile();
- assertNotNull(specFile);
-
- // Make sure the RPM nature was added
- assertTrue(testProject.hasNature(IRPMConstants.RPM_NATURE_ID));
-
- // Clean up
- testProject.delete(true, true, monitor);
- }
-
- @Test
- public void testBuildPrepHelloWorld() throws Exception {
- // Create a project for the test
- IProject testProject = root.getProject("testBuildPrepHelloWorld");
- RPMProject rpmProject = importSrpm(testProject);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- rpmProject.buildPrep(bos);
-
-
- // Make sure we got everything in the build directory
- IContainer builddir = rpmProject.getConfiguration().getBuildFolder();
- IFolder helloworldFolder = builddir.getFolder(new Path("helloworld-2"));
- assertTrue(helloworldFolder.exists());
-
- // Clean up
- testProject.delete(true, true, monitor);
- }
-
- @Test
- public void testBuildSourceRPMHelloWorld() throws Exception {
- // Create a project for the test
- IProject testProject = root.getProject("testBuildSourceRPMHelloWorld1");
- RPMProject rpmProject = importSrpm(testProject);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- rpmProject.buildSourceRPM(bos);
-
- IFile foo2 = rpmProject.getConfiguration().getSrpmsFolder()
- .getFile(new Path("helloworld-2-2.src.rpm"));
- assertTrue(foo2.exists());
-
- testProject.delete(true, true, null);
- }
-
- @Test
- public void testBuildBinaryRPMHelloWorld() throws Exception {
- // Create a project for the test
- IProject testProject = root.getProject("testBuildBinaryRPMHelloWorld1");
- RPMProject rpmProject = importSrpm(testProject);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- rpmProject.buildBinaryRPM(bos);
-
- IFile foo2 = rpmProject.getConfiguration().getSrpmsFolder()
- .getFile(new Path("helloworld-2-2.src.rpm"));
- assertTrue(foo2.exists());
-
- String arch = Utils.runCommandToString("rpm", "--eval", "%{_arch}").trim();
- IFile foo3 = rpmProject.getConfiguration().getRpmsFolder().getFolder(new Path(arch))
- .getFile(new Path("helloworld-2-2."+arch+".rpm"));
- assertTrue(foo3.exists());
- testProject.delete(true, true, null);
- }
-
- @Test
- public void testBuildAllRPMHelloWorld() throws Exception {
- // Create a project for the test
- IProject testProject = root.getProject("testBuildAllRPMHelloWorld1");
- RPMProject rpmProject = importSrpm(testProject);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- rpmProject.buildAll(bos);
-
- IFile foo2 = rpmProject.getConfiguration().getSrpmsFolder()
- .getFile(new Path("helloworld-2-2.src.rpm"));
- assertTrue(foo2.exists());
-
- String arch = Utils.runCommandToString("rpm", "--eval", "%{_arch}").trim();
- IFile foo3 = rpmProject.getConfiguration().getRpmsFolder().getFolder(new Path(arch))
- .getFile(new Path("helloworld-2-2."+arch+".rpm"));
- assertTrue(foo3.exists());
- testProject.delete(true, true, null);
- }
-
- private RPMProject importSrpm(IProject testProject) throws CoreException,
- IOException {
- testProject.create(monitor);
- testProject.open(monitor);
-
- // Instantiate an RPMProject
- RPMProject rpmProject = new RPMProject(testProject,
- RPMProjectLayout.RPMBUILD);
-
- // Find the test SRPM and install it
- URL url = FileLocator.find(FrameworkUtil
- .getBundle(RPMProjectTest.class), new Path(
- "resources" + file_sep + "srpms" + file_sep + //$NON-NLS-1$ //$NON-NLS-2$
- "helloworld-2-2.src.rpm"), null);
- File foo = new File(FileLocator.toFileURL(url).getPath());
- rpmProject.importSourceRPM(foo);
- return rpmProject;
- }
-
- @Test
- public void testGetSourcesFolder() throws Exception {
-
+ static IWorkspace workspace;
+ static IWorkspaceRoot root;
+ static NullProgressMonitor monitor;
+ String pluginRoot;
+
+ final String file_sep = System.getProperty("file.separator"); //$NON-NLS-1$
+
+ @BeforeClass
+ public static void setUp() {
+ workspace = ResourcesPlugin.getWorkspace();
+ root = workspace.getRoot();
+ monitor = new NullProgressMonitor();
+ }
+
+ @Test
+ public void testImportHelloWorld() throws Exception {
+ // Create a project for the test
+ IProject testProject = root.getProject("testHelloWorld");
+ RPMProject rpmProject = importSrpm(testProject);
+
+ // Make sure the original SRPM got copied into the workspace
+ IFile srpm = rpmProject.getConfiguration().getSrpmsFolder()
+ .getFile(new Path("helloworld-2-2.src.rpm"));
+ assertTrue(srpm.exists());
+
+ // Make sure everything got installed properly
+ IFile spec = rpmProject.getConfiguration().getSpecsFolder()
+ .getFile(new Path("helloworld.spec"));
+ assertTrue(spec.exists());
+ IFile sourceBall = rpmProject.getConfiguration().getSourcesFolder()
+ .getFile(new Path("helloworld-2.tar.bz2"));
+ assertTrue(sourceBall.exists());
+
+ // Make sure we got the spec file
+ IResource specFile = rpmProject.getSpecFile();
+ assertNotNull(specFile);
+
+ // Make sure the RPM nature was added
+ assertTrue(testProject.hasNature(IRPMConstants.RPM_NATURE_ID));
+
+ // Clean up
+ testProject.delete(true, true, monitor);
+ }
+
+ @Test
+ public void testImportHelloWorldFlat() throws Exception {
+ // Create a project for the test
+ IProject testProject = root.getProject("testHelloWorld");
+ testProject.create(monitor);
+ testProject.open(monitor);
+
+ // Instantiate an RPMProject
+ RPMProject rpmProject = new RPMProject(testProject,
+ RPMProjectLayout.FLAT);
+
+ // Find the test SRPM and install it
+ URL url = FileLocator.find(FrameworkUtil
+ .getBundle(RPMProjectTest.class), new Path(
+ "resources" + file_sep + "srpms" + file_sep + //$NON-NLS-1$ //$NON-NLS-2$
+ "helloworld-2-2.src.rpm"), null);
+ File foo = new File(FileLocator.toFileURL(url).getPath());
+ rpmProject.importSourceRPM(foo);
+
+ // Make sure the original SRPM got copied into the workspace
+ IFile srpm = rpmProject.getConfiguration().getSrpmsFolder()
+ .getFile(new Path("helloworld-2-2.src.rpm"));
+ assertTrue(srpm.exists());
+
+ // Make sure everything got installed properly
+ IFile spec = rpmProject.getConfiguration().getSpecsFolder()
+ .getFile(new Path("helloworld.spec"));
+ assertTrue(spec.exists());
+ IFile sourceBall = rpmProject.getConfiguration().getSourcesFolder()
+ .getFile(new Path("helloworld-2.tar.bz2"));
+ assertTrue(sourceBall.exists());
+
+ // Make sure we got the spec file
+ IResource specFile = rpmProject.getSpecFile();
+ assertNotNull(specFile);
+
+ // Make sure the RPM nature was added
+ assertTrue(testProject.hasNature(IRPMConstants.RPM_NATURE_ID));
+
+ // Clean up
+ testProject.delete(true, true, monitor);
+ }
+
+ @Test
+ public void testBuildPrepHelloWorld() throws Exception {
+ // Create a project for the test
+ IProject testProject = root.getProject("testBuildPrepHelloWorld");
+ RPMProject rpmProject = importSrpm(testProject);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ rpmProject.buildPrep(bos);
+
+
+ // Make sure we got everything in the build directory
+ IContainer builddir = rpmProject.getConfiguration().getBuildFolder();
+ IFolder helloworldFolder = builddir.getFolder(new Path("helloworld-2"));
+ assertTrue(helloworldFolder.exists());
+
+ // Clean up
+ testProject.delete(true, true, monitor);
+ }
+
+ @Test
+ public void testBuildSourceRPMHelloWorld() throws Exception {
+ // Create a project for the test
+ IProject testProject = root.getProject("testBuildSourceRPMHelloWorld1");
+ RPMProject rpmProject = importSrpm(testProject);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ rpmProject.buildSourceRPM(bos);
+
+ IFile foo2 = rpmProject.getConfiguration().getSrpmsFolder()
+ .getFile(new Path("helloworld-2-2.src.rpm"));
+ assertTrue(foo2.exists());
+
+ testProject.delete(true, true, null);
+ }
+
+ @Test
+ public void testBuildBinaryRPMHelloWorld() throws Exception {
+ // Create a project for the test
+ IProject testProject = root.getProject("testBuildBinaryRPMHelloWorld1");
+ RPMProject rpmProject = importSrpm(testProject);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ rpmProject.buildBinaryRPM(bos);
+
+ IFile foo2 = rpmProject.getConfiguration().getSrpmsFolder()
+ .getFile(new Path("helloworld-2-2.src.rpm"));
+ assertTrue(foo2.exists());
+
+ String arch = Utils.runCommandToString("rpm", "--eval", "%{_arch}").trim();
+ IFile foo3 = rpmProject.getConfiguration().getRpmsFolder().getFolder(new Path(arch))
+ .getFile(new Path("helloworld-2-2."+arch+".rpm"));
+ assertTrue(foo3.exists());
+ testProject.delete(true, true, null);
+ }
+
+ @Test
+ public void testBuildAllRPMHelloWorld() throws Exception {
+ // Create a project for the test
+ IProject testProject = root.getProject("testBuildAllRPMHelloWorld1");
+ RPMProject rpmProject = importSrpm(testProject);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ rpmProject.buildAll(bos);
+
+ IFile foo2 = rpmProject.getConfiguration().getSrpmsFolder()
+ .getFile(new Path("helloworld-2-2.src.rpm"));
+ assertTrue(foo2.exists());
+
+ String arch = Utils.runCommandToString("rpm", "--eval", "%{_arch}").trim();
+ IFile foo3 = rpmProject.getConfiguration().getRpmsFolder().getFolder(new Path(arch))
+ .getFile(new Path("helloworld-2-2."+arch+".rpm"));
+ assertTrue(foo3.exists());
+ testProject.delete(true, true, null);
+ }
+
+ private RPMProject importSrpm(IProject testProject) throws CoreException,
+ IOException {
+ testProject.create(monitor);
+ testProject.open(monitor);
+
+ // Instantiate an RPMProject
+ RPMProject rpmProject = new RPMProject(testProject,
+ RPMProjectLayout.RPMBUILD);
+
+ // Find the test SRPM and install it
+ URL url = FileLocator.find(FrameworkUtil
+ .getBundle(RPMProjectTest.class), new Path(
+ "resources" + file_sep + "srpms" + file_sep + //$NON-NLS-1$ //$NON-NLS-2$
+ "helloworld-2-2.src.rpm"), null);
+ File foo = new File(FileLocator.toFileURL(url).getPath());
+ rpmProject.importSourceRPM(foo);
+ return rpmProject;
+ }
+
+ @Test
+ public void testGetSourcesFolder() throws Exception {
+
// Create a project for the test
IProject testProject = root.getProject("testBuildSourceRPMHelloWorld1");
testProject.create(monitor);
@@ -230,7 +230,7 @@ public class RPMProjectTest {
RPMProjectLayout.RPMBUILD);
IProjectConfiguration config = rpmProject.getConfiguration();
String folder = config.getSourcesFolder().getLocation().toOSString();
-
+
int sourceFolder = folder.indexOf("SOURCES");
assertTrue(sourceFolder != -1);
testProject.delete(true, true, null);
diff --git a/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/utils/tests/RPMQueryTest.java b/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/utils/tests/RPMQueryTest.java
index 3014e1b154..7a61239f8e 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/utils/tests/RPMQueryTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core.tests/src/org/eclipse/linuxtools/rpm/core/utils/tests/RPMQueryTest.java
@@ -18,46 +18,46 @@ import org.junit.Test;
public class RPMQueryTest {
- private static final String[] testWrongNVRs = {
- "%{?scl_prefix}eclipse-jgit-3.0.0-1.fc20",
- "%{?scl_prefix}eclipse-egit-2.3.1-1.fc20",
- "eclipse-egit-github-2.3.0-5.fc20",
- "eclipse-fedorapackager-0.4.1-6.fc20",
- "%{?scl_prefix}eclipse-jgit-3.0.0-1.fc20",
- "fedora-packager-0.5.10.1-3.fc20"
- };
-
- private static final String[] testCorrectNVRs = {
- "eclipse-jgit-3.0.0-1.fc20",
- "eclipse-egit-2.3.1-1.fc20",
- "eclipse-egit-github-2.3.0-5.fc20",
- "eclipse-fedorapackager-0.4.1-6.fc20",
- "eclipse-jgit-3.0.0-1.fc20",
- "fedora-packager-0.5.10.1-3.fc20"
- };
-
- @Test
- public void testEval() throws CoreException {
- // check eval for string without macro
- assertEquals("should be same", RPMQuery.eval("should be same").trim());
- // check eval for macro only
- assertEquals("/usr/share", RPMQuery.eval("%{_datadir}").trim());
- // check eval for macro and string
- assertEquals("/usr/share/eclipse", RPMQuery.eval("%{_datadir}/eclipse")
- .trim());
- // check eval for conditional undefined macro
- assertEquals("eclipse", RPMQuery.eval("%{?scl_prefix}eclipse").trim());
- }
-
- // Test evaluating NVRs when displaying bodhi update dialog
- @Test
- public void testNVREval() throws CoreException {
- String toEval;
- for (int i = 0; i < testCorrectNVRs.length; i++) {
- toEval = RPMQuery.eval(testWrongNVRs[i]).trim();
- assertNotNull(toEval);
- assertEquals(toEval, testCorrectNVRs[i]);
- }
- }
+ private static final String[] testWrongNVRs = {
+ "%{?scl_prefix}eclipse-jgit-3.0.0-1.fc20",
+ "%{?scl_prefix}eclipse-egit-2.3.1-1.fc20",
+ "eclipse-egit-github-2.3.0-5.fc20",
+ "eclipse-fedorapackager-0.4.1-6.fc20",
+ "%{?scl_prefix}eclipse-jgit-3.0.0-1.fc20",
+ "fedora-packager-0.5.10.1-3.fc20"
+ };
+
+ private static final String[] testCorrectNVRs = {
+ "eclipse-jgit-3.0.0-1.fc20",
+ "eclipse-egit-2.3.1-1.fc20",
+ "eclipse-egit-github-2.3.0-5.fc20",
+ "eclipse-fedorapackager-0.4.1-6.fc20",
+ "eclipse-jgit-3.0.0-1.fc20",
+ "fedora-packager-0.5.10.1-3.fc20"
+ };
+
+ @Test
+ public void testEval() throws CoreException {
+ // check eval for string without macro
+ assertEquals("should be same", RPMQuery.eval("should be same").trim());
+ // check eval for macro only
+ assertEquals("/usr/share", RPMQuery.eval("%{_datadir}").trim());
+ // check eval for macro and string
+ assertEquals("/usr/share/eclipse", RPMQuery.eval("%{_datadir}/eclipse")
+ .trim());
+ // check eval for conditional undefined macro
+ assertEquals("eclipse", RPMQuery.eval("%{?scl_prefix}eclipse").trim());
+ }
+
+ // Test evaluating NVRs when displaying bodhi update dialog
+ @Test
+ public void testNVREval() throws CoreException {
+ String toEval;
+ for (int i = 0; i < testCorrectNVRs.length; i++) {
+ toEval = RPMQuery.eval(testWrongNVRs[i]).trim();
+ assertNotNull(toEval);
+ assertEquals(toEval, testCorrectNVRs[i]);
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.core/plugin.xml b/rpm/org.eclipse.linuxtools.rpm.core/plugin.xml
index 522cd94e99..d4d8fbeb97 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core/plugin.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.core/plugin.xml
@@ -5,7 +5,7 @@
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-
+
Contributors:
Red Hat - initial API and implementation
-->
@@ -16,13 +16,13 @@
name="%extension.name"
point="org.eclipse.core.resources.natures">
<runtime>
- <run class="org.eclipse.linuxtools.rpm.core.RPMProjectNature"></run>
+ <run class="org.eclipse.linuxtools.rpm.core.RPMProjectNature"></run>
</runtime>
</extension>
<extension point="org.eclipse.core.runtime.preferences">
- <initializer
- class="org.eclipse.linuxtools.internal.rpm.core.RPMCoreInitializer" />
- </extension>
+ <initializer
+ class="org.eclipse.linuxtools.internal.rpm.core.RPMCoreInitializer" />
+ </extension>
<extension
point="org.eclipse.core.expressions.definitions">
<definition
diff --git a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/FlatBuildConfiguration.java b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/FlatBuildConfiguration.java
index ada77cf44b..e5b5d8490c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/FlatBuildConfiguration.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/FlatBuildConfiguration.java
@@ -20,84 +20,84 @@ import org.eclipse.linuxtools.rpm.core.IProjectConfiguration;
/**
* Configuration for the flat rpm project layout.
- *
+ *
*/
public class FlatBuildConfiguration implements IProjectConfiguration {
- private IProject project;
- private List<String> configDefines = new ArrayList<>();
+ private IProject project;
+ private List<String> configDefines = new ArrayList<>();
- /**
- * Creates the configuration for the given project.
- *
- * @param project
- * The project whose configuration is represented.
- */
- public FlatBuildConfiguration(IProject project) {
- this.project = project;
- configDefines.add(DEFINE);
- if (project.getLocationURI()==null) {
- configDefines
- .add("_sourcedir " + project.getLocation().toOSString()); //$NON-NLS-1$
- configDefines.add(DEFINE);
- configDefines
- .add("_srcrpmdir " + project.getLocation().toOSString()); //$NON-NLS-1$
- configDefines.add(DEFINE);
- configDefines
- .add("_builddir " + project.getLocation().toOSString()); //$NON-NLS-1$
- configDefines.add(DEFINE);
- configDefines
- .add("_rpmdir " + project.getLocation().toOSString()); //$NON-NLS-1$
- configDefines.add(DEFINE);
- configDefines
- .add("_specdir " + project.getLocation().toOSString()); //$NON-NLS-1$
- } else {
- configDefines
- .add("_sourcedir " + project.getLocationURI().getPath() + IPath.SEPARATOR); //$NON-NLS-1$
- configDefines.add(DEFINE);
- configDefines
- .add("_srcrpmdir " + project.getLocationURI().getPath() + IPath.SEPARATOR); //$NON-NLS-1$
- configDefines.add(DEFINE);
- configDefines
- .add("_builddir " + project.getLocationURI().getPath() + IPath.SEPARATOR); //$NON-NLS-1$
- configDefines.add(DEFINE);
- configDefines
- .add("_rpmdir " + project.getLocationURI().getPath() + IPath.SEPARATOR); //$NON-NLS-1$
- configDefines.add(DEFINE);
- configDefines
- .add("_specdir " + project.getLocationURI().getPath() + IPath.SEPARATOR); //$NON-NLS-1$
+ /**
+ * Creates the configuration for the given project.
+ *
+ * @param project
+ * The project whose configuration is represented.
+ */
+ public FlatBuildConfiguration(IProject project) {
+ this.project = project;
+ configDefines.add(DEFINE);
+ if (project.getLocationURI()==null) {
+ configDefines
+ .add("_sourcedir " + project.getLocation().toOSString()); //$NON-NLS-1$
+ configDefines.add(DEFINE);
+ configDefines
+ .add("_srcrpmdir " + project.getLocation().toOSString()); //$NON-NLS-1$
+ configDefines.add(DEFINE);
+ configDefines
+ .add("_builddir " + project.getLocation().toOSString()); //$NON-NLS-1$
+ configDefines.add(DEFINE);
+ configDefines
+ .add("_rpmdir " + project.getLocation().toOSString()); //$NON-NLS-1$
+ configDefines.add(DEFINE);
+ configDefines
+ .add("_specdir " + project.getLocation().toOSString()); //$NON-NLS-1$
+ } else {
+ configDefines
+ .add("_sourcedir " + project.getLocationURI().getPath() + IPath.SEPARATOR); //$NON-NLS-1$
+ configDefines.add(DEFINE);
+ configDefines
+ .add("_srcrpmdir " + project.getLocationURI().getPath() + IPath.SEPARATOR); //$NON-NLS-1$
+ configDefines.add(DEFINE);
+ configDefines
+ .add("_builddir " + project.getLocationURI().getPath() + IPath.SEPARATOR); //$NON-NLS-1$
+ configDefines.add(DEFINE);
+ configDefines
+ .add("_rpmdir " + project.getLocationURI().getPath() + IPath.SEPARATOR); //$NON-NLS-1$
+ configDefines.add(DEFINE);
+ configDefines
+ .add("_specdir " + project.getLocationURI().getPath() + IPath.SEPARATOR); //$NON-NLS-1$
- }
- }
+ }
+ }
- @Override
- public IContainer getBuildFolder() {
- return project;
- }
+ @Override
+ public IContainer getBuildFolder() {
+ return project;
+ }
- @Override
- public IContainer getRpmsFolder() {
- return project;
- }
+ @Override
+ public IContainer getRpmsFolder() {
+ return project;
+ }
- @Override
- public IContainer getSourcesFolder() {
- return project;
- }
+ @Override
+ public IContainer getSourcesFolder() {
+ return project;
+ }
- @Override
- public IContainer getSpecsFolder() {
- return project;
- }
+ @Override
+ public IContainer getSpecsFolder() {
+ return project;
+ }
- @Override
- public IContainer getSrpmsFolder() {
- return project;
- }
+ @Override
+ public IContainer getSrpmsFolder() {
+ return project;
+ }
- @Override
- public List<String> getConfigDefines() {
- return configDefines;
- }
+ @Override
+ public List<String> getConfigDefines() {
+ return configDefines;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/Messages.java b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/Messages.java
index f2f2ad7b8c..e4b4817804 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/Messages.java
@@ -15,18 +15,18 @@ import java.util.ResourceBundle;
@SuppressWarnings("javadoc")
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.core.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.core.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/RPMCoreInitializer.java b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/RPMCoreInitializer.java
index ef09a65e3b..d51d213af5 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/RPMCoreInitializer.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/RPMCoreInitializer.java
@@ -22,17 +22,17 @@ import org.eclipse.ui.preferences.ScopedPreferenceStore;
*/
public class RPMCoreInitializer extends AbstractPreferenceInitializer {
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE,IRPMConstants.RPM_CORE_ID);
- String userName = System.getProperty("user.name"); //$NON-NLS-1$
- store.setDefault(IRPMConstants.RPM_DISPLAYED_LOG_NAME, ".logfilename_" //$NON-NLS-1$
- + userName);
- store.setDefault(IRPMConstants.RPM_LOG_NAME, "rpmbuild.log"); //$NON-NLS-1$
+ @Override
+ public void initializeDefaultPreferences() {
+ IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE,IRPMConstants.RPM_CORE_ID);
+ String userName = System.getProperty("user.name"); //$NON-NLS-1$
+ store.setDefault(IRPMConstants.RPM_DISPLAYED_LOG_NAME, ".logfilename_" //$NON-NLS-1$
+ + userName);
+ store.setDefault(IRPMConstants.RPM_LOG_NAME, "rpmbuild.log"); //$NON-NLS-1$
- store.setDefault(IRPMConstants.RPM_CMD, "rpm"); //$NON-NLS-1$
- store.setDefault(IRPMConstants.RPMBUILD_CMD, "rpmbuild"); //$NON-NLS-1$
- store.setDefault(IRPMConstants.DIFF_CMD, "diff"); //$NON-NLS-1$
- }
+ store.setDefault(IRPMConstants.RPM_CMD, "rpm"); //$NON-NLS-1$
+ store.setDefault(IRPMConstants.RPMBUILD_CMD, "rpmbuild"); //$NON-NLS-1$
+ store.setDefault(IRPMConstants.DIFF_CMD, "diff"); //$NON-NLS-1$
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/utils/FileDownloadJob.java b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/utils/FileDownloadJob.java
index a37111ac52..e15b368c8d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/utils/FileDownloadJob.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/utils/FileDownloadJob.java
@@ -30,42 +30,42 @@ import org.eclipse.osgi.util.NLS;
*
*/
public class FileDownloadJob extends Job {
- private File file;
- private URLConnection content;
+ private File file;
+ private URLConnection content;
- /**
- * Creates the download job.
- * @param file The file to store the remote content.
- * @param content The URLConnection to the remote file.
- */
- public FileDownloadJob(File file, URLConnection content) {
- super(NLS.bind(Messages.DownloadJob_0, file.getName()));
- this.file = file;
- this.content = content;
- }
+ /**
+ * Creates the download job.
+ * @param file The file to store the remote content.
+ * @param content The URLConnection to the remote file.
+ */
+ public FileDownloadJob(File file, URLConnection content) {
+ super(NLS.bind(Messages.DownloadJob_0, file.getName()));
+ this.file = file;
+ this.content = content;
+ }
- @Override
- public IStatus run(IProgressMonitor monitor) {
- monitor.beginTask(NLS.bind(Messages.DownloadJob_0, file.getName()),
- content.getContentLength());
- try (FileOutputStream fos = new FileOutputStream(file);
- InputStream is = new BufferedInputStream(
- content.getInputStream())) {
- int b;
- while ((b = is.read()) != -1) {
- if (monitor.isCanceled()) {
- break;
- }
- fos.write(b);
- monitor.worked(1);
- }
- } catch (IOException e) {
- Platform.getLog(Platform.getBundle(IRPMConstants.RPM_CORE_ID)).log(
- new Status(IStatus.ERROR, IRPMConstants.RPM_CORE_ID, e
- .getMessage(), e));
- return Status.CANCEL_STATUS;
- }
- monitor.done();
- return Status.OK_STATUS;
- }
+ @Override
+ public IStatus run(IProgressMonitor monitor) {
+ monitor.beginTask(NLS.bind(Messages.DownloadJob_0, file.getName()),
+ content.getContentLength());
+ try (FileOutputStream fos = new FileOutputStream(file);
+ InputStream is = new BufferedInputStream(
+ content.getInputStream())) {
+ int b;
+ while ((b = is.read()) != -1) {
+ if (monitor.isCanceled()) {
+ break;
+ }
+ fos.write(b);
+ monitor.worked(1);
+ }
+ } catch (IOException e) {
+ Platform.getLog(Platform.getBundle(IRPMConstants.RPM_CORE_ID)).log(
+ new Status(IStatus.ERROR, IRPMConstants.RPM_CORE_ID, e
+ .getMessage(), e));
+ return Status.CANCEL_STATUS;
+ }
+ monitor.done();
+ return Status.OK_STATUS;
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/utils/Messages.java b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/utils/Messages.java
index e6215ee79f..d3c7b19aab 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/utils/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/internal/rpm/core/utils/Messages.java
@@ -16,16 +16,16 @@ import org.eclipse.osgi.util.NLS;
* Messages for this package.
*/
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.core.utils.messages"; //$NON-NLS-1$
- /** Download + name message */
- public static String DownloadJob_0;
- /** Message shown when trying to export a RPM project that doesn't have a specfile*/
- public static String Specfile_not_found;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.core.utils.messages"; //$NON-NLS-1$
+ /** Download + name message */
+ public static String DownloadJob_0;
+ /** Message shown when trying to export a RPM project that doesn't have a specfile*/
+ public static String Specfile_not_found;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/RPMProject.java b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/RPMProject.java
index f0ef542fa7..2161b8f0cd 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/RPMProject.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/RPMProject.java
@@ -42,185 +42,185 @@ import org.eclipse.linuxtools.internal.rpm.core.utils.RPMBuild;
*/
public class RPMProject {
- private IProject project;
- private IProjectConfiguration rpmConfig;
-
- /**
- * Creates the rpm project for the given IProject and layout.
- *
- * @param project The Eclipse project this RPMProject is represented by.
- * @param projectLayout The layout of the rpm project
- * @throws CoreException Thrown only in the RPMbuild layout case if a problem with some of the folders exist.
- */
- public RPMProject(IProject project, RPMProjectLayout projectLayout)
- throws CoreException {
- this.project = project;
- switch (projectLayout) {
- case FLAT:
- rpmConfig = new FlatBuildConfiguration(this.project);
- break;
- case RPMBUILD:
- default:
- rpmConfig = new RPMBuildConfiguration(this.project);
- break;
- }
- }
-
- /**
- * Returns the configuration (RPMBuild, FLAT) for this project.
- *
- * @return The project configuration.
- */
- public IProjectConfiguration getConfiguration() {
- return rpmConfig;
- }
-
- /**
- * Returns the .spec file of this project.
- *
- * @return The .spec file or null if one is not found.
- */
- public IResource getSpecFile() {
- IContainer specsFolder = getConfiguration().getSpecsFolder();
- IResource file = null;
- SpecfileVisitor specVisitor = new SpecfileVisitor();
-
- try {
- specsFolder.accept(specVisitor);
- List<IResource> installedSpecs = specVisitor.getSpecFiles();
- if(installedSpecs.size() > 0){
- file = installedSpecs.get(0);
- }
- } catch (CoreException e) {
- // ignore, failed to find .spec file.
- }
- return file;
- }
-
- /**
- * Import a SRPM into this RPM project using local file.
- *
- * @param externalFile The SRPM file.
- * @throws CoreException If there is problem with the .src.rpm file.
- */
- public void importSourceRPM(File externalFile) throws CoreException {
- // Copy original SRPM to workspace
- IFile srpmFile = getConfiguration().getSrpmsFolder().getFile(
- new Path(externalFile.getName()));
- try {
- srpmFile.create(new FileInputStream(externalFile), false, null);
- } catch (FileNotFoundException e) {
- String throwMessage = Messages
- .getString("RPMCore.Error_trying_to_copy__") + //$NON-NLS-1$
- rpmConfig.getSpecsFolder().getLocation().toOSString();
- IStatus error = new Status(IStatus.ERROR, IRPMConstants.ERROR, 1,
- throwMessage, e);
- throw new CoreException(error);
- }
-
- // Install the SRPM
- RPM rpm = new RPM(getConfiguration());
- rpm.install(srpmFile);
- project.refreshLocal(IResource.DEPTH_INFINITE, null);
-
- // Set the project nature
- RPMProjectNature.addRPMNature(project, null);
-
- }
-
- /**
- * Import a remote SRPM into this RPM project, by downloading the file
- * and calling {@link RPMProject#importSourceRPM(File)}.
- *
- * @param remoteFile URI to the remote SRPM file.
- * @param monitor The progress monitor.
- * @throws CoreException Thrown if the import failed.
- */
- public void importSourceRPM(URL remoteFile, IProgressMonitor monitor) throws CoreException {
- URLConnection content;
- try {
- content = remoteFile.openConnection();
- } catch (IOException e) {
- Status status = new Status(IStatus.ERROR, IRPMConstants.RPM_CORE_ID,
- e.getMessage(), e);
- throw new CoreException(status);
- }
- File tempFile = new File(
- System.getProperty("java.io.tmpdir"), remoteFile.toString().substring(remoteFile.toString().lastIndexOf('/') + 1)); //$NON-NLS-1$
- if (tempFile.exists()) {
- tempFile.delete();
- }
- final FileDownloadJob downloadJob = new FileDownloadJob(tempFile,
- content);
- downloadJob.run(monitor);
- importSourceRPM(tempFile);
- }
-
- /**
- * Build both source and binary rpms.
- * @param outStream The stream to right command output to.
- * @return The result of the command.
- * @throws CoreException If exception occurs during building.
- */
- public IStatus buildAll(OutputStream outStream) throws CoreException {
- RPMBuild rpmbuild = new RPMBuild(getConfiguration());
- IStatus result = rpmbuild.buildAll(getSpecFile(), outStream);
-
- getConfiguration().getBuildFolder().refreshLocal(
- IResource.DEPTH_INFINITE, null);
- getConfiguration().getRpmsFolder().refreshLocal(
- IResource.DEPTH_INFINITE, null);
- getConfiguration().getSrpmsFolder().refreshLocal(
- IResource.DEPTH_INFINITE, null);
- return result;
- }
-
- /**
- * Builds binary rpm.
- * @param out The stream to right command output to.
- * @return The result of the command.
- * @throws CoreException If exception occurs during building.
- */
- public IStatus buildBinaryRPM(OutputStream out) throws CoreException {
- RPMBuild rpmbuild = new RPMBuild(getConfiguration());
- IStatus result = rpmbuild.buildBinary(getSpecFile(), out);
-
- getConfiguration().getBuildFolder().refreshLocal(
- IResource.DEPTH_INFINITE, null);
- getConfiguration().getRpmsFolder().refreshLocal(
- IResource.DEPTH_INFINITE, null);
- return result;
- }
-
- /**
- * Builds source rpm.
- * @param out The stream to right command output to.
- * @return The result of the command.
- * @throws CoreException If exception occurs during building.
- */
- public IStatus buildSourceRPM(OutputStream out) throws CoreException {
- RPMBuild rpmbuild = new RPMBuild(getConfiguration());
- IStatus result = rpmbuild.buildSource(getSpecFile(), out);
-
- getConfiguration().getBuildFolder().refreshLocal(
- IResource.DEPTH_INFINITE, null);
- getConfiguration().getSrpmsFolder().refreshLocal(
- IResource.DEPTH_INFINITE, null);
- return result;
- }
-
- /**
- * Prepares sources for build (rpmbuild -bp).
- * @param out The stream to right command output to.
- * @return The result of the command.
- * @throws CoreException If exception occurs during building.
- */
- public IStatus buildPrep(OutputStream out) throws CoreException {
- RPMBuild rpmbuild = new RPMBuild(getConfiguration());
- IStatus result = rpmbuild.buildPrep(getSpecFile(), out);
- getConfiguration().getBuildFolder().refreshLocal(
- IResource.DEPTH_INFINITE, null);
- return result;
- }
+ private IProject project;
+ private IProjectConfiguration rpmConfig;
+
+ /**
+ * Creates the rpm project for the given IProject and layout.
+ *
+ * @param project The Eclipse project this RPMProject is represented by.
+ * @param projectLayout The layout of the rpm project
+ * @throws CoreException Thrown only in the RPMbuild layout case if a problem with some of the folders exist.
+ */
+ public RPMProject(IProject project, RPMProjectLayout projectLayout)
+ throws CoreException {
+ this.project = project;
+ switch (projectLayout) {
+ case FLAT:
+ rpmConfig = new FlatBuildConfiguration(this.project);
+ break;
+ case RPMBUILD:
+ default:
+ rpmConfig = new RPMBuildConfiguration(this.project);
+ break;
+ }
+ }
+
+ /**
+ * Returns the configuration (RPMBuild, FLAT) for this project.
+ *
+ * @return The project configuration.
+ */
+ public IProjectConfiguration getConfiguration() {
+ return rpmConfig;
+ }
+
+ /**
+ * Returns the .spec file of this project.
+ *
+ * @return The .spec file or null if one is not found.
+ */
+ public IResource getSpecFile() {
+ IContainer specsFolder = getConfiguration().getSpecsFolder();
+ IResource file = null;
+ SpecfileVisitor specVisitor = new SpecfileVisitor();
+
+ try {
+ specsFolder.accept(specVisitor);
+ List<IResource> installedSpecs = specVisitor.getSpecFiles();
+ if(installedSpecs.size() > 0){
+ file = installedSpecs.get(0);
+ }
+ } catch (CoreException e) {
+ // ignore, failed to find .spec file.
+ }
+ return file;
+ }
+
+ /**
+ * Import a SRPM into this RPM project using local file.
+ *
+ * @param externalFile The SRPM file.
+ * @throws CoreException If there is problem with the .src.rpm file.
+ */
+ public void importSourceRPM(File externalFile) throws CoreException {
+ // Copy original SRPM to workspace
+ IFile srpmFile = getConfiguration().getSrpmsFolder().getFile(
+ new Path(externalFile.getName()));
+ try {
+ srpmFile.create(new FileInputStream(externalFile), false, null);
+ } catch (FileNotFoundException e) {
+ String throwMessage = Messages
+ .getString("RPMCore.Error_trying_to_copy__") + //$NON-NLS-1$
+ rpmConfig.getSpecsFolder().getLocation().toOSString();
+ IStatus error = new Status(IStatus.ERROR, IRPMConstants.ERROR, 1,
+ throwMessage, e);
+ throw new CoreException(error);
+ }
+
+ // Install the SRPM
+ RPM rpm = new RPM(getConfiguration());
+ rpm.install(srpmFile);
+ project.refreshLocal(IResource.DEPTH_INFINITE, null);
+
+ // Set the project nature
+ RPMProjectNature.addRPMNature(project, null);
+
+ }
+
+ /**
+ * Import a remote SRPM into this RPM project, by downloading the file
+ * and calling {@link RPMProject#importSourceRPM(File)}.
+ *
+ * @param remoteFile URI to the remote SRPM file.
+ * @param monitor The progress monitor.
+ * @throws CoreException Thrown if the import failed.
+ */
+ public void importSourceRPM(URL remoteFile, IProgressMonitor monitor) throws CoreException {
+ URLConnection content;
+ try {
+ content = remoteFile.openConnection();
+ } catch (IOException e) {
+ Status status = new Status(IStatus.ERROR, IRPMConstants.RPM_CORE_ID,
+ e.getMessage(), e);
+ throw new CoreException(status);
+ }
+ File tempFile = new File(
+ System.getProperty("java.io.tmpdir"), remoteFile.toString().substring(remoteFile.toString().lastIndexOf('/') + 1)); //$NON-NLS-1$
+ if (tempFile.exists()) {
+ tempFile.delete();
+ }
+ final FileDownloadJob downloadJob = new FileDownloadJob(tempFile,
+ content);
+ downloadJob.run(monitor);
+ importSourceRPM(tempFile);
+ }
+
+ /**
+ * Build both source and binary rpms.
+ * @param outStream The stream to right command output to.
+ * @return The result of the command.
+ * @throws CoreException If exception occurs during building.
+ */
+ public IStatus buildAll(OutputStream outStream) throws CoreException {
+ RPMBuild rpmbuild = new RPMBuild(getConfiguration());
+ IStatus result = rpmbuild.buildAll(getSpecFile(), outStream);
+
+ getConfiguration().getBuildFolder().refreshLocal(
+ IResource.DEPTH_INFINITE, null);
+ getConfiguration().getRpmsFolder().refreshLocal(
+ IResource.DEPTH_INFINITE, null);
+ getConfiguration().getSrpmsFolder().refreshLocal(
+ IResource.DEPTH_INFINITE, null);
+ return result;
+ }
+
+ /**
+ * Builds binary rpm.
+ * @param out The stream to right command output to.
+ * @return The result of the command.
+ * @throws CoreException If exception occurs during building.
+ */
+ public IStatus buildBinaryRPM(OutputStream out) throws CoreException {
+ RPMBuild rpmbuild = new RPMBuild(getConfiguration());
+ IStatus result = rpmbuild.buildBinary(getSpecFile(), out);
+
+ getConfiguration().getBuildFolder().refreshLocal(
+ IResource.DEPTH_INFINITE, null);
+ getConfiguration().getRpmsFolder().refreshLocal(
+ IResource.DEPTH_INFINITE, null);
+ return result;
+ }
+
+ /**
+ * Builds source rpm.
+ * @param out The stream to right command output to.
+ * @return The result of the command.
+ * @throws CoreException If exception occurs during building.
+ */
+ public IStatus buildSourceRPM(OutputStream out) throws CoreException {
+ RPMBuild rpmbuild = new RPMBuild(getConfiguration());
+ IStatus result = rpmbuild.buildSource(getSpecFile(), out);
+
+ getConfiguration().getBuildFolder().refreshLocal(
+ IResource.DEPTH_INFINITE, null);
+ getConfiguration().getSrpmsFolder().refreshLocal(
+ IResource.DEPTH_INFINITE, null);
+ return result;
+ }
+
+ /**
+ * Prepares sources for build (rpmbuild -bp).
+ * @param out The stream to right command output to.
+ * @return The result of the command.
+ * @throws CoreException If exception occurs during building.
+ */
+ public IStatus buildPrep(OutputStream out) throws CoreException {
+ RPMBuild rpmbuild = new RPMBuild(getConfiguration());
+ IStatus result = rpmbuild.buildPrep(getSpecFile(), out);
+ getConfiguration().getBuildFolder().refreshLocal(
+ IResource.DEPTH_INFINITE, null);
+ return result;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/RPMProjectNature.java b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/RPMProjectNature.java
index 45e4819152..2c7f2ba296 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/RPMProjectNature.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/RPMProjectNature.java
@@ -22,60 +22,60 @@ import org.eclipse.core.runtime.IProgressMonitor;
*/
public class RPMProjectNature implements IProjectNature {
- private IProject project;
-
- /**
- * Adds the RPM project nature to a given workspace project.
- * @param project the project
- * @param mon a progress monitor, or <code>null</code> if progress monitoring
- * is not desired
- * @throws CoreException if adding the RPM project nature fails
- */
- public static void addRPMNature(IProject project, IProgressMonitor mon) throws CoreException {
- addNature(project, IRPMConstants.RPM_NATURE_ID, mon);
- }
+ private IProject project;
- /**
- * Utility method for adding a nature to a project.
- *
- * @param proj
- * the project to add the nature
- * @param natureId
- * the id of the nature to assign to the project
- * @param monitor
- * a progress monitor to indicate the duration of the operation,
- * or <code>null</code> if progress reporting is not required.
- *
- */
- private static void addNature(IProject project, String natureId, IProgressMonitor monitor) throws CoreException {
- if(project.hasNature(natureId)) {
- return;
- }
- IProjectDescription description = project.getDescription();
- String[] prevNatures = description.getNatureIds();
- String[] newNatures = new String[prevNatures.length + 1];
- System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
- newNatures[prevNatures.length] = natureId;
- description.setNatureIds(newNatures);
- project.setDescription(description, monitor);
- }
+ /**
+ * Adds the RPM project nature to a given workspace project.
+ * @param project the project
+ * @param mon a progress monitor, or <code>null</code> if progress monitoring
+ * is not desired
+ * @throws CoreException if adding the RPM project nature fails
+ */
+ public static void addRPMNature(IProject project, IProgressMonitor mon) throws CoreException {
+ addNature(project, IRPMConstants.RPM_NATURE_ID, mon);
+ }
- @Override
- public void configure() {
- }
+ /**
+ * Utility method for adding a nature to a project.
+ *
+ * @param proj
+ * the project to add the nature
+ * @param natureId
+ * the id of the nature to assign to the project
+ * @param monitor
+ * a progress monitor to indicate the duration of the operation,
+ * or <code>null</code> if progress reporting is not required.
+ *
+ */
+ private static void addNature(IProject project, String natureId, IProgressMonitor monitor) throws CoreException {
+ if(project.hasNature(natureId)) {
+ return;
+ }
+ IProjectDescription description = project.getDescription();
+ String[] prevNatures = description.getNatureIds();
+ String[] newNatures = new String[prevNatures.length + 1];
+ System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
+ newNatures[prevNatures.length] = natureId;
+ description.setNatureIds(newNatures);
+ project.setDescription(description, monitor);
+ }
- @Override
- public void deconfigure() {
- }
+ @Override
+ public void configure() {
+ }
- @Override
- public IProject getProject() {
- return project;
- }
+ @Override
+ public void deconfigure() {
+ }
- @Override
- public void setProject(IProject project) {
- this.project = project;
- }
+ @Override
+ public IProject getProject() {
+ return project;
+ }
+
+ @Override
+ public void setProject(IProject project) {
+ this.project = project;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/utils/Messages.java b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/utils/Messages.java
index 6df27e1c7c..80962cd791 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/utils/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/utils/Messages.java
@@ -17,16 +17,16 @@ import org.eclipse.osgi.util.NLS;
*
*/
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.rpm.core.utils.messages"; //$NON-NLS-1$
- /**
- * Message when runCommand returns non zero code.
- */
- public static String Utils_NON_ZERO_RETURN_CODE;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.rpm.core.utils.messages"; //$NON-NLS-1$
+ /**
+ * Message when runCommand returns non zero code.
+ */
+ public static String Utils_NON_ZERO_RETURN_CODE;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/utils/Utils.java b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/utils/Utils.java
index 40e008e42f..ea0c9b1752 100644
--- a/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/utils/Utils.java
+++ b/rpm/org.eclipse.linuxtools.rpm.core/src/org/eclipse/linuxtools/rpm/core/utils/Utils.java
@@ -71,7 +71,7 @@ public class Utils {
* @param outStream
* The stream to write the output to.
* @param project
- * The project which is executing this command.
+ * The project which is executing this command.
* @param command
* The command with all parameters.
* @return int The return value of the command.
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/AllTests.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/AllTests.java
index ee4aae6449..92266ae268 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/AllTests.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/AllTests.java
@@ -26,11 +26,11 @@ import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({CreaterepoProjectCreatorTest.class, CreaterepoUtilsTest.class,
- CreaterepoProjectTest.class, CreaterepoTreeCategoryTest.class, CreaterepoTreeTest.class,
- CreaterepoWizardTest.class, CreaterepoTest.class, CreaterepoPreferenceInitializationTest.class,
- CreaterepoRepoFormEditorTest.class, CreaterepoImportRPMsPageTest.class, CreaterepoMetadataPageTest.class,
- CreaterepoResourceListenerTest.class, CreaterepoCommandCreatorTest.class,
- CreaterepoPreferencePageTest.class, CreaterepoGeneralPropertyPageTest.class, CreaterepoDeltaPropertyPageTest.class})
+ CreaterepoProjectTest.class, CreaterepoTreeCategoryTest.class, CreaterepoTreeTest.class,
+ CreaterepoWizardTest.class, CreaterepoTest.class, CreaterepoPreferenceInitializationTest.class,
+ CreaterepoRepoFormEditorTest.class, CreaterepoImportRPMsPageTest.class, CreaterepoMetadataPageTest.class,
+ CreaterepoResourceListenerTest.class, CreaterepoCommandCreatorTest.class,
+ CreaterepoPreferencePageTest.class, CreaterepoGeneralPropertyPageTest.class, CreaterepoDeltaPropertyPageTest.class})
public class AllTests {
- //Nothing here as annotation is important
+ //Nothing here as annotation is important
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoImportRPMsPageTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoImportRPMsPageTest.java
index d9516f0c84..b9c5f01e49 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoImportRPMsPageTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoImportRPMsPageTest.java
@@ -55,173 +55,173 @@ import org.osgi.framework.FrameworkUtil;
@RunWith(SWTBotJunit4ClassRunner.class)
public class CreaterepoImportRPMsPageTest {
- private static final String TEST_RPM_LOC1 = ICreaterepoTestConstants.RPM_RESOURCE_LOC
- .concat(ICreaterepoTestConstants.RPM1);
+ private static final String TEST_RPM_LOC1 = ICreaterepoTestConstants.RPM_RESOURCE_LOC
+ .concat(ICreaterepoTestConstants.RPM1);
- private static TestCreaterepoProject testProject;
- private static SWTWorkbenchBot bot;
- private static NullProgressMonitor monitor;
- private static SWTBotView navigator;
- private CreaterepoProject project;
- private SWTBot importPageBot;
+ private static TestCreaterepoProject testProject;
+ private static SWTWorkbenchBot bot;
+ private static NullProgressMonitor monitor;
+ private static SWTBotView navigator;
+ private CreaterepoProject project;
+ private SWTBot importPageBot;
- /**
- * Initialize the test project.
- *
- * @throws CoreException
- */
- @BeforeClass
- public static void setUpBeforeClass() throws CoreException {
- testProject = new TestCreaterepoProject();
- assertTrue(testProject.getProject().exists());
- bot = new SWTWorkbenchBot();
- try {
- bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
- } catch (WidgetNotFoundException e) {
- // cannot activate main shell, continue anyways
- }
- monitor = new NullProgressMonitor();
- TestUtils.openResourcePerspective(bot);
- navigator = TestUtils.enterProjectFolder(bot);
- }
+ /**
+ * Initialize the test project.
+ *
+ * @throws CoreException
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws CoreException {
+ testProject = new TestCreaterepoProject();
+ assertTrue(testProject.getProject().exists());
+ bot = new SWTWorkbenchBot();
+ try {
+ bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
+ } catch (WidgetNotFoundException e) {
+ // cannot activate main shell, continue anyways
+ }
+ monitor = new NullProgressMonitor();
+ TestUtils.openResourcePerspective(bot);
+ navigator = TestUtils.enterProjectFolder(bot);
+ }
- /**
- * Delete the project when tests are done.
- *
- * @throws CoreException
- */
- @AfterClass
- public static void tearDownAfterClass() throws CoreException {
- TestUtils.exitProjectFolder(bot, navigator);
- testProject.dispose();
- assertFalse(testProject.getProject().exists());
- }
+ /**
+ * Delete the project when tests are done.
+ *
+ * @throws CoreException
+ */
+ @AfterClass
+ public static void tearDownAfterClass() throws CoreException {
+ TestUtils.exitProjectFolder(bot, navigator);
+ testProject.dispose();
+ assertFalse(testProject.getProject().exists());
+ }
- /**
- * Get the CreaterepoProject at the beginning of each test, as
- * well as import some test RPMs.
- *
- * @throws CoreException
- * @throws IOException
- */
- @Before
- public void setUp() throws CoreException, IOException {
- project = testProject.getCreaterepoProject();
- assertNotNull(project);
- URL rpmURL = FileLocator.find(FrameworkUtil
- .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC1), null);
- File rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
- assertTrue(rpmFile.exists());
- project.importRPM(rpmFile);
- // there should be 1 rpm every setup
- assertEquals(1, project.getRPMs().size());
- initializeImportPage();
- }
+ /**
+ * Get the CreaterepoProject at the beginning of each test, as
+ * well as import some test RPMs.
+ *
+ * @throws CoreException
+ * @throws IOException
+ */
+ @Before
+ public void setUp() throws CoreException, IOException {
+ project = testProject.getCreaterepoProject();
+ assertNotNull(project);
+ URL rpmURL = FileLocator.find(FrameworkUtil
+ .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC1), null);
+ File rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
+ assertTrue(rpmFile.exists());
+ project.importRPM(rpmFile);
+ // there should be 1 rpm every setup
+ assertEquals(1, project.getRPMs().size());
+ initializeImportPage();
+ }
- /**
- * Test out the remove RPMs button.
- */
- @Test
- public void testRemoveRPMs() {
- // run in UI thread because accessing the tree in the import RPMs page
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- Tree tree = importPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
- assertNotNull(tree);
- // current item count should be 1 (from the imported RPM)
- assertEquals(1, tree.getItemCount());
- importPageBot.button(Messages.ImportRPMsPage_buttonRemoveRPMs).click();
- // not selecting a treeitem should do nothing to the tree contents
- assertEquals(1, tree.getItemCount());
- // select the first item
- tree.select(tree.getItem(0));
- importPageBot.button(Messages.ImportRPMsPage_buttonRemoveRPMs).click();
- // item count should be 0 after selecting a tree item and pressing remove
- assertEquals(0, tree.getItemCount());
- try {
- // make sure that the RPM was actually deleted from the project
- assertEquals(0, project.getRPMs().size());
- } catch (CoreException e) {
- fail("Failed to get the RPMs from project"); //$NON-NLS-1$
- }
- }
- });
- }
+ /**
+ * Test out the remove RPMs button.
+ */
+ @Test
+ public void testRemoveRPMs() {
+ // run in UI thread because accessing the tree in the import RPMs page
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ Tree tree = importPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
+ assertNotNull(tree);
+ // current item count should be 1 (from the imported RPM)
+ assertEquals(1, tree.getItemCount());
+ importPageBot.button(Messages.ImportRPMsPage_buttonRemoveRPMs).click();
+ // not selecting a treeitem should do nothing to the tree contents
+ assertEquals(1, tree.getItemCount());
+ // select the first item
+ tree.select(tree.getItem(0));
+ importPageBot.button(Messages.ImportRPMsPage_buttonRemoveRPMs).click();
+ // item count should be 0 after selecting a tree item and pressing remove
+ assertEquals(0, tree.getItemCount());
+ try {
+ // make sure that the RPM was actually deleted from the project
+ assertEquals(0, project.getRPMs().size());
+ } catch (CoreException e) {
+ fail("Failed to get the RPMs from project"); //$NON-NLS-1$
+ }
+ }
+ });
+ }
- /**
- * Test to see if createrepo executed.
- *
- * @throws CoreException
- */
- @Test
- public void testCreaterepo() throws CoreException {
- // assume that there is creatrepo version of >= 0.9.8
- IStatus validVersion = Createrepo.isCorrectVersion();
- Assume.assumeTrue(validVersion.isOK());
- importPageBot.button(Messages.ImportRPMsPage_buttonCreateRepo).click();
- // make the bot wait until the download job shell closes before proceeding the tests
- importPageBot.waitUntil(Conditions.shellCloses(bot.shell(Messages.Createrepo_jobName)));
- // assert that the content folder has more than just the RPM inside it
- assertTrue(project.getContentFolder().members().length > 1);
- // assert that the repodata folder exists within the content folder
- assertTrue(project.getContentFolder().findMember(ICreaterepoTestConstants.REPODATA_FOLDER).exists());
- // assert that the repomd.xml file was created (successful createrepo execution)
- IFolder repodata = (IFolder) project.getContentFolder().findMember(ICreaterepoTestConstants.REPODATA_FOLDER);
- assertTrue(repodata.findMember(ICreaterepoTestConstants.REPO_MD_NAME).exists());
- }
+ /**
+ * Test to see if createrepo executed.
+ *
+ * @throws CoreException
+ */
+ @Test
+ public void testCreaterepo() throws CoreException {
+ // assume that there is creatrepo version of >= 0.9.8
+ IStatus validVersion = Createrepo.isCorrectVersion();
+ Assume.assumeTrue(validVersion.isOK());
+ importPageBot.button(Messages.ImportRPMsPage_buttonCreateRepo).click();
+ // make the bot wait until the download job shell closes before proceeding the tests
+ importPageBot.waitUntil(Conditions.shellCloses(bot.shell(Messages.Createrepo_jobName)));
+ // assert that the content folder has more than just the RPM inside it
+ assertTrue(project.getContentFolder().members().length > 1);
+ // assert that the repodata folder exists within the content folder
+ assertTrue(project.getContentFolder().findMember(ICreaterepoTestConstants.REPODATA_FOLDER).exists());
+ // assert that the repomd.xml file was created (successful createrepo execution)
+ IFolder repodata = (IFolder) project.getContentFolder().findMember(ICreaterepoTestConstants.REPODATA_FOLDER);
+ assertTrue(repodata.findMember(ICreaterepoTestConstants.REPO_MD_NAME).exists());
+ }
- /**
- * Test if deleting/adding an RPM into content folder updates the RPM list.
- *
- * @throws CoreException
- * @throws IOException
- */
- @Test
- public void testResourceChangeListener() throws CoreException, IOException {
- // delete the contents of the content folder
- for (IResource resource : project.getContentFolder().members()) {
- resource.delete(true, monitor);
- }
- // run in UI thread because accessing the tree in the import RPMs page
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- Tree tree = importPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
- assertNotNull(tree);
- // check items in tree are gone
- assertEquals(0, tree.getItemCount());
- }
- });
- // import a file again into the content folder
- URL rpmURL = FileLocator.find(FrameworkUtil
- .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC1), null);
- final File rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
- assertTrue(rpmFile.exists());
- project.importRPM(rpmFile);
- // run in UI thread because accessing the tree in the import RPMs page
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- Tree tree = importPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
- assertNotNull(tree);
- // check if items are in tree
- assertEquals(1, tree.getItemCount());
- assertEquals(rpmFile.getName(), tree.getItem(0).getText());
- }
- });
- }
+ /**
+ * Test if deleting/adding an RPM into content folder updates the RPM list.
+ *
+ * @throws CoreException
+ * @throws IOException
+ */
+ @Test
+ public void testResourceChangeListener() throws CoreException, IOException {
+ // delete the contents of the content folder
+ for (IResource resource : project.getContentFolder().members()) {
+ resource.delete(true, monitor);
+ }
+ // run in UI thread because accessing the tree in the import RPMs page
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ Tree tree = importPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
+ assertNotNull(tree);
+ // check items in tree are gone
+ assertEquals(0, tree.getItemCount());
+ }
+ });
+ // import a file again into the content folder
+ URL rpmURL = FileLocator.find(FrameworkUtil
+ .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC1), null);
+ final File rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
+ assertTrue(rpmFile.exists());
+ project.importRPM(rpmFile);
+ // run in UI thread because accessing the tree in the import RPMs page
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ Tree tree = importPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
+ assertNotNull(tree);
+ // check if items are in tree
+ assertEquals(1, tree.getItemCount());
+ assertEquals(rpmFile.getName(), tree.getItem(0).getText());
+ }
+ });
+ }
- /**
- * Helper method to help setup the test by opening the .repo file.
- */
- private void initializeImportPage() {
- SWTBotMultiPageEditor editor = TestUtils.openRepoFile(bot, navigator);
- // activate repository page
- editor.activatePage(Messages.ImportRPMsPage_title);
- // make sure correct page is active
- assertEquals(Messages.ImportRPMsPage_title, editor.getActivePageTitle());
- importPageBot = editor.bot();
- }
+ /**
+ * Helper method to help setup the test by opening the .repo file.
+ */
+ private void initializeImportPage() {
+ SWTBotMultiPageEditor editor = TestUtils.openRepoFile(bot, navigator);
+ // activate repository page
+ editor.activatePage(Messages.ImportRPMsPage_title);
+ // make sure correct page is active
+ assertEquals(Messages.ImportRPMsPage_title, editor.getActivePageTitle());
+ importPageBot = editor.bot();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoMetadataPageTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoMetadataPageTest.java
index dfb06d5919..166ef54b19 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoMetadataPageTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoMetadataPageTest.java
@@ -48,229 +48,229 @@ import org.osgi.service.prefs.BackingStoreException;
@RunWith(SWTBotJunit4ClassRunner.class)
public class CreaterepoMetadataPageTest {
- private static TestCreaterepoProject testProject;
- private static SWTWorkbenchBot bot;
- private static SWTBotView navigator;
- private CreaterepoProject project;
- private SWTBot metadataPageBot;
+ private static TestCreaterepoProject testProject;
+ private static SWTWorkbenchBot bot;
+ private static SWTBotView navigator;
+ private CreaterepoProject project;
+ private SWTBot metadataPageBot;
- /**
- * Initialize the test project.
- *
- * @throws CoreException
- */
- @BeforeClass
- public static void setUpBeforeClass() throws CoreException {
- testProject = new TestCreaterepoProject();
- assertTrue(testProject.getProject().exists());
- bot = new SWTWorkbenchBot();
- try {
- bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
- } catch (WidgetNotFoundException e) {
- // cannot activate main shell, continue anyways
- }
- TestUtils.openResourcePerspective(bot);
- navigator = TestUtils.enterProjectFolder(bot);
- }
+ /**
+ * Initialize the test project.
+ *
+ * @throws CoreException
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws CoreException {
+ testProject = new TestCreaterepoProject();
+ assertTrue(testProject.getProject().exists());
+ bot = new SWTWorkbenchBot();
+ try {
+ bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
+ } catch (WidgetNotFoundException e) {
+ // cannot activate main shell, continue anyways
+ }
+ TestUtils.openResourcePerspective(bot);
+ navigator = TestUtils.enterProjectFolder(bot);
+ }
- /**
- * Delete the project when tests are done.
- *
- * @throws CoreException
- */
- @AfterClass
- public static void tearDownAfterClass() throws CoreException {
- TestUtils.exitProjectFolder(bot, navigator);
- testProject.dispose();
- assertFalse(testProject.getProject().exists());
- }
+ /**
+ * Delete the project when tests are done.
+ *
+ * @throws CoreException
+ */
+ @AfterClass
+ public static void tearDownAfterClass() throws CoreException {
+ TestUtils.exitProjectFolder(bot, navigator);
+ testProject.dispose();
+ assertFalse(testProject.getProject().exists());
+ }
- /**
- * Get the CreaterepoProject at the beginning of each test, as
- * well as import some test RPMs.
- *
- * @throws CoreException
- */
- @Before
- public void setUp() throws CoreException {
- project = testProject.getCreaterepoProject();
- assertNotNull(project);
- initializeMetadataPage();
- }
+ /**
+ * Get the CreaterepoProject at the beginning of each test, as
+ * well as import some test RPMs.
+ *
+ * @throws CoreException
+ */
+ @Before
+ public void setUp() throws CoreException {
+ project = testProject.getCreaterepoProject();
+ assertNotNull(project);
+ initializeMetadataPage();
+ }
- /**
- * Clear the project preferences.
- *
- * @throws BackingStoreException
- */
- @After
- public void tearDown() throws BackingStoreException {
- IEclipsePreferences pref = project.getEclipsePreferences();
- pref.clear();
- pref.flush();
- assertEquals(0, pref.keys().length);
- }
+ /**
+ * Clear the project preferences.
+ *
+ * @throws BackingStoreException
+ */
+ @After
+ public void tearDown() throws BackingStoreException {
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ pref.clear();
+ pref.flush();
+ assertEquals(0, pref.keys().length);
+ }
- /**
- * Test if tags are adding properly. Tags should be unique per category.
- */
- @Test
- public void testAddTags() {
- // run in UI thread because accessing the tree in the metadata page
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- String tagName = "testTag"; //$NON-NLS-1$
- String newTagName = "newUniqueTag"; //$NON-NLS-1$
- String prefValueToBe = ""; //$NON-NLS-1$
- metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(tagName);
- Tree tree = metadataPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
- assertNotNull(tree);
- // 0 = distro, 1 = content, 2 = repo
- int category = 0;
- // select the category and the test adding tags
- tree.select(tree.getItem(category));
- metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
- CreaterepoTreeCategory test = (CreaterepoTreeCategory) tree.getItem(category).getData();
- assertEquals(1, test.getTags().size());
- // it should be distro = {testTag} now
- prefValueToBe = tagName;
- assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, prefValueToBe));
- // try adding the same tag to the same category again, it should not work
- tree.select(tree.getItem(category));
- metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(tagName);
- metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
- assertEquals(1, test.getTags().size());
- // it should still be distro = {testTag}
- prefValueToBe = tagName;
- assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, prefValueToBe));
- // try adding a new unique tag to the same category, it should work
- tree.select(tree.getItem(category));
- metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(newTagName);
- metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
- assertEquals(2, test.getTags().size());
- // it should be distro = {testTag, newUniqueTag} now
- prefValueToBe = tagName + ICreaterepoConstants.DELIMITER + newTagName;
- assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, prefValueToBe));
- }
- });
- }
+ /**
+ * Test if tags are adding properly. Tags should be unique per category.
+ */
+ @Test
+ public void testAddTags() {
+ // run in UI thread because accessing the tree in the metadata page
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ String tagName = "testTag"; //$NON-NLS-1$
+ String newTagName = "newUniqueTag"; //$NON-NLS-1$
+ String prefValueToBe = ""; //$NON-NLS-1$
+ metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(tagName);
+ Tree tree = metadataPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
+ assertNotNull(tree);
+ // 0 = distro, 1 = content, 2 = repo
+ int category = 0;
+ // select the category and the test adding tags
+ tree.select(tree.getItem(category));
+ metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
+ CreaterepoTreeCategory test = (CreaterepoTreeCategory) tree.getItem(category).getData();
+ assertEquals(1, test.getTags().size());
+ // it should be distro = {testTag} now
+ prefValueToBe = tagName;
+ assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, prefValueToBe));
+ // try adding the same tag to the same category again, it should not work
+ tree.select(tree.getItem(category));
+ metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(tagName);
+ metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
+ assertEquals(1, test.getTags().size());
+ // it should still be distro = {testTag}
+ prefValueToBe = tagName;
+ assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, prefValueToBe));
+ // try adding a new unique tag to the same category, it should work
+ tree.select(tree.getItem(category));
+ metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(newTagName);
+ metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
+ assertEquals(2, test.getTags().size());
+ // it should be distro = {testTag, newUniqueTag} now
+ prefValueToBe = tagName + ICreaterepoConstants.DELIMITER + newTagName;
+ assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, prefValueToBe));
+ }
+ });
+ }
- /**
- * Test if tags can be edited correctly.
- */
- @Test
- public void testEditTags() {
- // run in UI thread because accessing the tree in the metadata page
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- String tagName = "testTag"; //$NON-NLS-1$
- String tagName2 = "testTag2"; //$NON-NLS-1$
- String newTagName = "renameTag"; //$NON-NLS-1$
- String prefValueToBe = ""; //$NON-NLS-1$
- Tree tree = metadataPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
- assertNotNull(tree);
- // 0 = distro, 1 = content, 2 = repo
- int category = 1;
- // select the category and test editing tags
- tree.select(tree.getItem(category));
- metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(tagName);
- metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
- metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(tagName2);
- metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
- CreaterepoTreeCategory test = (CreaterepoTreeCategory) tree.getItem(category).getData();
- assertEquals(2, test.getTags().size());
- // it should be content = {testTag1, testTag2} now
- prefValueToBe = tagName + ICreaterepoConstants.DELIMITER + tagName2;
- assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, prefValueToBe));
- // select the first test tag that was created and edit it with a new unique tag
- tree.select(tree.getItem(category).getItem(0));
- metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(newTagName);
- metadataPageBot.button(Messages.MetadataPage_buttonEditTag).click();
- assertEquals(2, test.getTags().size());
- assertEquals(newTagName, test.getTags().get(0));
- // it should be content = {renameTag, testTag2} now
- prefValueToBe = newTagName + ICreaterepoConstants.DELIMITER + tagName2;
- assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, prefValueToBe));
- // select the second test tag and try to rename it as the same name as the first tag, this should not work
- tree.select(tree.getItem(category).getItem(1));
- metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(newTagName);
- metadataPageBot.button(Messages.MetadataPage_buttonEditTag).click();
- assertEquals(2, test.getTags().size());
- assertNotEquals(newTagName, test.getTags().get(1));
- // it should still be content = {renameTag, testTag2}
- prefValueToBe = newTagName + ICreaterepoConstants.DELIMITER + tagName2;
- assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, prefValueToBe));
- }
- });
- }
+ /**
+ * Test if tags can be edited correctly.
+ */
+ @Test
+ public void testEditTags() {
+ // run in UI thread because accessing the tree in the metadata page
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ String tagName = "testTag"; //$NON-NLS-1$
+ String tagName2 = "testTag2"; //$NON-NLS-1$
+ String newTagName = "renameTag"; //$NON-NLS-1$
+ String prefValueToBe = ""; //$NON-NLS-1$
+ Tree tree = metadataPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
+ assertNotNull(tree);
+ // 0 = distro, 1 = content, 2 = repo
+ int category = 1;
+ // select the category and test editing tags
+ tree.select(tree.getItem(category));
+ metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(tagName);
+ metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
+ metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(tagName2);
+ metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
+ CreaterepoTreeCategory test = (CreaterepoTreeCategory) tree.getItem(category).getData();
+ assertEquals(2, test.getTags().size());
+ // it should be content = {testTag1, testTag2} now
+ prefValueToBe = tagName + ICreaterepoConstants.DELIMITER + tagName2;
+ assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, prefValueToBe));
+ // select the first test tag that was created and edit it with a new unique tag
+ tree.select(tree.getItem(category).getItem(0));
+ metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(newTagName);
+ metadataPageBot.button(Messages.MetadataPage_buttonEditTag).click();
+ assertEquals(2, test.getTags().size());
+ assertEquals(newTagName, test.getTags().get(0));
+ // it should be content = {renameTag, testTag2} now
+ prefValueToBe = newTagName + ICreaterepoConstants.DELIMITER + tagName2;
+ assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, prefValueToBe));
+ // select the second test tag and try to rename it as the same name as the first tag, this should not work
+ tree.select(tree.getItem(category).getItem(1));
+ metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(newTagName);
+ metadataPageBot.button(Messages.MetadataPage_buttonEditTag).click();
+ assertEquals(2, test.getTags().size());
+ assertNotEquals(newTagName, test.getTags().get(1));
+ // it should still be content = {renameTag, testTag2}
+ prefValueToBe = newTagName + ICreaterepoConstants.DELIMITER + tagName2;
+ assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, prefValueToBe));
+ }
+ });
+ }
- /**
- * Test if tags can be removed.
- */
- @Test
- public void testRemoveTags() {
- // run in UI thread because accessing the tree in the metadata page
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- String tagName = "testTag"; //$NON-NLS-1$
- String prefValueToBe = ""; //$NON-NLS-1$
- Tree tree = metadataPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
- assertNotNull(tree);
- // 0 = distro, 1 = content, 2 = repo
- int category = 2;
- // select the category and test removing tags
- tree.select(tree.getItem(category));
- metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(tagName);
- metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
- CreaterepoTreeCategory test = (CreaterepoTreeCategory) tree.getItem(category).getData();
- assertEquals(1, test.getTags().size());
- // it should be repo = {testTag} now
- prefValueToBe = tagName;
- assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_REPO_TAG, prefValueToBe));
- // select the first item and delete it
- tree.select(tree.getItem(category).getItem(0));
- metadataPageBot.button(Messages.MetadataPage_buttonRemoveTag).click();
- assertEquals(0, test.getTags().size());
- // it should be repo = {} now
- prefValueToBe = ""; //$NON-NLS-1$
- assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_REPO_TAG, prefValueToBe));
- // try to remove the category
- tree.select(tree.getItem(category));
- metadataPageBot.button(Messages.MetadataPage_buttonRemoveTag).click();
- // it should still be there
- assertNotNull(tree.getItem(category));
- }
- });
- }
+ /**
+ * Test if tags can be removed.
+ */
+ @Test
+ public void testRemoveTags() {
+ // run in UI thread because accessing the tree in the metadata page
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ String tagName = "testTag"; //$NON-NLS-1$
+ String prefValueToBe = ""; //$NON-NLS-1$
+ Tree tree = metadataPageBot.widget(WidgetMatcherFactory.widgetOfType(Tree.class));
+ assertNotNull(tree);
+ // 0 = distro, 1 = content, 2 = repo
+ int category = 2;
+ // select the category and test removing tags
+ tree.select(tree.getItem(category));
+ metadataPageBot.textWithLabel(Messages.MetadataPage_labelTags).setText(tagName);
+ metadataPageBot.button(Messages.MetadataPage_buttonAddTag).click();
+ CreaterepoTreeCategory test = (CreaterepoTreeCategory) tree.getItem(category).getData();
+ assertEquals(1, test.getTags().size());
+ // it should be repo = {testTag} now
+ prefValueToBe = tagName;
+ assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_REPO_TAG, prefValueToBe));
+ // select the first item and delete it
+ tree.select(tree.getItem(category).getItem(0));
+ metadataPageBot.button(Messages.MetadataPage_buttonRemoveTag).click();
+ assertEquals(0, test.getTags().size());
+ // it should be repo = {} now
+ prefValueToBe = ""; //$NON-NLS-1$
+ assertTrue(isPreferencesCorrect(CreaterepoPreferenceConstants.PREF_REPO_TAG, prefValueToBe));
+ // try to remove the category
+ tree.select(tree.getItem(category));
+ metadataPageBot.button(Messages.MetadataPage_buttonRemoveTag).click();
+ // it should still be there
+ assertNotNull(tree.getItem(category));
+ }
+ });
+ }
- /**
- * Get the current project preference for the category tag and check if the values
- * stored are the same as the values passed in.
- *
- * @param category The preference category to check.
- * @param value The value to check.
- * @return True if the value is same as what is stored, false otherwise.
- */
- private boolean isPreferencesCorrect(String category, String value) {
- IEclipsePreferences pref = project.getEclipsePreferences();
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- String actual = pref.get(category, prefStore.getDefaultString(category));
- return actual.equals(value);
- }
+ /**
+ * Get the current project preference for the category tag and check if the values
+ * stored are the same as the values passed in.
+ *
+ * @param category The preference category to check.
+ * @param value The value to check.
+ * @return True if the value is same as what is stored, false otherwise.
+ */
+ private boolean isPreferencesCorrect(String category, String value) {
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ String actual = pref.get(category, prefStore.getDefaultString(category));
+ return actual.equals(value);
+ }
- /**
- * Helper method to help setup the test by opening the .repo file.
- */
- private void initializeMetadataPage() {
- SWTBotMultiPageEditor editor = TestUtils.openRepoFile(bot, navigator);
- // activate the metadata page
- editor.activatePage(Messages.MetadataPage_title);
- // make sure correct page is active
- assertEquals(Messages.MetadataPage_title, editor.getActivePageTitle());
- metadataPageBot = editor.bot();
- }
+ /**
+ * Helper method to help setup the test by opening the .repo file.
+ */
+ private void initializeMetadataPage() {
+ SWTBotMultiPageEditor editor = TestUtils.openRepoFile(bot, navigator);
+ // activate the metadata page
+ editor.activatePage(Messages.MetadataPage_title);
+ // make sure correct page is active
+ assertEquals(Messages.MetadataPage_title, editor.getActivePageTitle());
+ metadataPageBot = editor.bot();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoProjectCreatorTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoProjectCreatorTest.java
index 618101e0ba..ffca75b240 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoProjectCreatorTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoProjectCreatorTest.java
@@ -38,77 +38,77 @@ import org.junit.Test;
*/
public class CreaterepoProjectCreatorTest {
- private static IWorkspaceRoot root;
- private static NullProgressMonitor monitor;
- private IProject project;
+ private static IWorkspaceRoot root;
+ private static NullProgressMonitor monitor;
+ private IProject project;
- /**
- * Initialize workspace root and progress monitor.
- */
- @BeforeClass
- public static void setUpBeforeClass() {
- root = ResourcesPlugin.getWorkspace().getRoot();
- monitor = new NullProgressMonitor();
- }
+ /**
+ * Initialize workspace root and progress monitor.
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ root = ResourcesPlugin.getWorkspace().getRoot();
+ monitor = new NullProgressMonitor();
+ }
- /**
- * Create the project using CreaterepoProjectCreator.
- *
- * @throws CoreException
- */
- @Before
- public void setUp() throws CoreException{
- if (project == null || !project.exists()) {
- project = CreaterepoProjectCreator.create(ICreaterepoTestConstants.PROJECT_NAME,
- root.getLocation(), ICreaterepoTestConstants.REPO_NAME, monitor);
- }
- assertNotNull(project);
- assertTrue(project.exists());
- }
+ /**
+ * Create the project using CreaterepoProjectCreator.
+ *
+ * @throws CoreException
+ */
+ @Before
+ public void setUp() throws CoreException{
+ if (project == null || !project.exists()) {
+ project = CreaterepoProjectCreator.create(ICreaterepoTestConstants.PROJECT_NAME,
+ root.getLocation(), ICreaterepoTestConstants.REPO_NAME, monitor);
+ }
+ assertNotNull(project);
+ assertTrue(project.exists());
+ }
- /**
- * Forcefully delete the project if it exists.
- *
- * @throws CoreException
- */
- @After
- public void tearDown() throws CoreException {
- if (project != null && project.exists()) {
- project.delete(true, true, monitor);
- }
- assertFalse(project.exists());
- }
+ /**
+ * Forcefully delete the project if it exists.
+ *
+ * @throws CoreException
+ */
+ @After
+ public void tearDown() throws CoreException {
+ if (project != null && project.exists()) {
+ project.delete(true, true, monitor);
+ }
+ assertFalse(project.exists());
+ }
- /**
- * Test to see if the project has been properly created. Content folder
- * should not appear due to CreaterepoWizard handling its creation. Repo
- * file should be empty for the same reason.
- *
- * @throws CoreException
- * @throws IOException
- */
- @Test
- public void testProjectContents() throws CoreException, IOException {
- // 2 = .project + .repo file
- assertEquals(2, project.members().length);
+ /**
+ * Test to see if the project has been properly created. Content folder
+ * should not appear due to CreaterepoWizard handling its creation. Repo
+ * file should be empty for the same reason.
+ *
+ * @throws CoreException
+ * @throws IOException
+ */
+ @Test
+ public void testProjectContents() throws CoreException, IOException {
+ // 2 = .project + .repo file
+ assertEquals(2, project.members().length);
- // contains the repo file
- assertTrue(project.findMember(ICreaterepoTestConstants.REPO_NAME).exists());
+ // contains the repo file
+ assertTrue(project.findMember(ICreaterepoTestConstants.REPO_NAME).exists());
- IFile repoFile = (IFile) project.findMember(ICreaterepoTestConstants.REPO_NAME);
- // repo file should be empty because test did not go through project creation
- // to initialize .repo contents
- assertEquals(repoFile.getContents().available(), 0);
- }
+ IFile repoFile = (IFile) project.findMember(ICreaterepoTestConstants.REPO_NAME);
+ // repo file should be empty because test did not go through project creation
+ // to initialize .repo contents
+ assertEquals(repoFile.getContents().available(), 0);
+ }
- /**
- * Test to see if the project has the proper nature.
- *
- * @throws CoreException
- */
- @Test
- public void testProjectNature() throws CoreException {
- assertTrue(project.hasNature(CreaterepoProjectNature.CREATEREPO_NATURE_ID));
- }
+ /**
+ * Test to see if the project has the proper nature.
+ *
+ * @throws CoreException
+ */
+ @Test
+ public void testProjectNature() throws CoreException {
+ assertTrue(project.hasNature(CreaterepoProjectNature.CREATEREPO_NATURE_ID));
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoProjectTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoProjectTest.java
index 3c3fa1b4ef..c989fec069 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoProjectTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoProjectTest.java
@@ -48,179 +48,179 @@ import org.osgi.framework.FrameworkUtil;
*/
public class CreaterepoProjectTest {
- private static final String TEST_RPM_LOC1 = ICreaterepoTestConstants.RPM_RESOURCE_LOC
- .concat(ICreaterepoTestConstants.RPM1);
- private static final String TEST_RPM_LOC2 = ICreaterepoTestConstants.RPM_RESOURCE_LOC
- .concat(ICreaterepoTestConstants.RPM2);
-
- private static IWorkspaceRoot root;
- private static NullProgressMonitor monitor;
- private IProject project;
-
- /**
- * Initialize workspace root and progress monitor.
- */
- @BeforeClass
- public static void setUpBeforeClass() {
- root = ResourcesPlugin.getWorkspace().getRoot();
- monitor = new NullProgressMonitor();
- }
-
- /**
- * Create the project using CreaterepoProjectCreator.
- *
- * @throws CoreException
- */
- @Before
- public void setUp() throws CoreException {
- if (project == null || !project.exists()) {
- project = CreaterepoProjectCreator.create(ICreaterepoTestConstants.PROJECT_NAME,
- root.getLocation(), ICreaterepoTestConstants.REPO_NAME, monitor);
- }
- assertNotNull(project);
- assertTrue(project.exists());
- }
-
- /**
- * Forcefully delete the project if it exists.
- *
- * @throws CoreException
- */
- @After
- public void tearDown() throws CoreException {
- if (project != null && project.exists()) {
- project.delete(true, true, monitor);
- }
- assertFalse(project.exists());
- }
-
- /**
- * Test if initializing createrepo project is successful. This means that
- * content folder is initialized but not created (done by wizard, import, or
- * execute commands) and that .repo file exists.
- *
- * @throws CoreException
- */
- @Test
- public void testInitialize() throws CoreException {
- CreaterepoProject createrepoProject = new CreaterepoProject(project,
- (IFile)project.findMember(ICreaterepoTestConstants.REPO_NAME));
- // content folder is defined, but not created (wizard does that)
- assertNotNull(createrepoProject.getContentFolder());
- assertFalse(createrepoProject.getContentFolder().exists());
- // repo file is found and exists
- assertNotNull(createrepoProject.getRepoFile());
- assertTrue(createrepoProject.getRepoFile().exists());
- assertEquals(ICreaterepoTestConstants.REPO_NAME, createrepoProject.getRepoFile().getName());
- }
-
- /**
- * Test if initializing createrepo project is successful
- * without specifying .repo file.
- *
- * @throws CoreException
- */
- @Test
- public void testInitializeNoRepoFileSpecfied() throws CoreException {
- // repo file will be found rather than initialized
- CreaterepoProject createrepoProject = new CreaterepoProject(project);
- // content folder is defined, but not created (wizard does that)
- assertNotNull(createrepoProject.getContentFolder());
- assertFalse(createrepoProject.getContentFolder().exists());
- // repo file is found and exists
- assertNotNull(createrepoProject.getRepoFile());
- assertTrue(createrepoProject.getRepoFile().exists());
- assertEquals(ICreaterepoTestConstants.REPO_NAME, createrepoProject.getRepoFile().getName());
- }
-
- /**
- * Test if importing RPMs from external source successfully saves into
- * the "content" folder.
- *
- * @throws CoreException
- * @throws IOException
- */
- @Test
- public void testImportRPM() throws CoreException, IOException {
- CreaterepoProject createrepoProject = new CreaterepoProject(project);
-
- // test for file
- URL rpmURL = FileLocator.find(FrameworkUtil
- .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC1), null);
- File rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
- createrepoProject.importRPM(rpmFile);
- assertNotNull(createrepoProject.getContentFolder());
- assertTrue(createrepoProject.getContentFolder().exists());
- assertEquals(1, createrepoProject.getContentFolder().members().length);
- assertTrue(createrepoProject.getContentFolder().findMember(ICreaterepoTestConstants.RPM1).exists());
-
- // test for duplicate file
- createrepoProject.importRPM(rpmFile);
- assertEquals(1, createrepoProject.getContentFolder().members().length);
- assertTrue(createrepoProject.getContentFolder().findMember(ICreaterepoTestConstants.RPM1).exists());
-
- // test for new file
- rpmURL = FileLocator.find(FrameworkUtil
- .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC2), null);
- rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
- createrepoProject.importRPM(rpmFile);
- assertEquals(2, createrepoProject.getContentFolder().members().length);
- assertTrue(createrepoProject.getContentFolder().findMember(ICreaterepoTestConstants.RPM2).exists());
- }
-
- /**
- * Test if getting the RPMs is successful.
- *
- * @throws CoreException
- * @throws IOException
- */
- @Test
- public void testGetRPMs() throws CoreException, IOException {
- CreaterepoProject createrepoProject = new CreaterepoProject(project);
- URL rpmURL = FileLocator.find(FrameworkUtil
- .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC1), null);
- File rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
- createrepoProject.importRPM(rpmFile);
- rpmURL = FileLocator.find(FrameworkUtil
- .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC2), null);
- rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
- createrepoProject.importRPM(rpmFile);
-
- List<IResource> rpms = createrepoProject.getRPMs();
- assertEquals(2, rpms.size());
- }
-
- /**
- * Simple test execution of createrepo. This checks to see if the "content" folder
- * was created while executing and that the execution is successful if repomd.xml was created
- * under the repodata folder.
- *
- * @throws CoreException
- */
- @Test
- public void testSimpleExecute() throws CoreException {
- CreaterepoProject createrepoProject = new CreaterepoProject(project);
- // make sure that content folder doesn't exist
- assertFalse(createrepoProject.getContentFolder().exists());
- // assume that there is creatrepo version of >= 0.9.8
- IStatus validVersion = Createrepo.isCorrectVersion();
- Assume.assumeTrue(validVersion.isOK());
-
- IStatus status = createrepoProject.createrepo(CreaterepoUtils.findConsole("test").newMessageStream()); //$NON-NLS-1$
- // check if executing has an OK status and that content folder is created with the repodata contents
- assertEquals(Status.OK_STATUS, status);
- assertTrue(createrepoProject.getContentFolder().exists());
- assertTrue(createrepoProject.getContentFolder().members().length > 0);
-
- // check if the repodata folder exists and repomd.xml exists within it
- assertTrue(createrepoProject.getContentFolder().findMember(
- ICreaterepoTestConstants.REPODATA_FOLDER).exists());
- IFolder repodataFolder = (IFolder) createrepoProject.getContentFolder()
- .findMember(ICreaterepoTestConstants.REPODATA_FOLDER);
- // repodata should have at least more than 1 file: repomd.xml + archives
- assertTrue(repodataFolder.members().length > 1);
- assertTrue(repodataFolder.findMember(ICreaterepoTestConstants.REPO_MD_NAME)
- .exists());
- }
+ private static final String TEST_RPM_LOC1 = ICreaterepoTestConstants.RPM_RESOURCE_LOC
+ .concat(ICreaterepoTestConstants.RPM1);
+ private static final String TEST_RPM_LOC2 = ICreaterepoTestConstants.RPM_RESOURCE_LOC
+ .concat(ICreaterepoTestConstants.RPM2);
+
+ private static IWorkspaceRoot root;
+ private static NullProgressMonitor monitor;
+ private IProject project;
+
+ /**
+ * Initialize workspace root and progress monitor.
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ root = ResourcesPlugin.getWorkspace().getRoot();
+ monitor = new NullProgressMonitor();
+ }
+
+ /**
+ * Create the project using CreaterepoProjectCreator.
+ *
+ * @throws CoreException
+ */
+ @Before
+ public void setUp() throws CoreException {
+ if (project == null || !project.exists()) {
+ project = CreaterepoProjectCreator.create(ICreaterepoTestConstants.PROJECT_NAME,
+ root.getLocation(), ICreaterepoTestConstants.REPO_NAME, monitor);
+ }
+ assertNotNull(project);
+ assertTrue(project.exists());
+ }
+
+ /**
+ * Forcefully delete the project if it exists.
+ *
+ * @throws CoreException
+ */
+ @After
+ public void tearDown() throws CoreException {
+ if (project != null && project.exists()) {
+ project.delete(true, true, monitor);
+ }
+ assertFalse(project.exists());
+ }
+
+ /**
+ * Test if initializing createrepo project is successful. This means that
+ * content folder is initialized but not created (done by wizard, import, or
+ * execute commands) and that .repo file exists.
+ *
+ * @throws CoreException
+ */
+ @Test
+ public void testInitialize() throws CoreException {
+ CreaterepoProject createrepoProject = new CreaterepoProject(project,
+ (IFile)project.findMember(ICreaterepoTestConstants.REPO_NAME));
+ // content folder is defined, but not created (wizard does that)
+ assertNotNull(createrepoProject.getContentFolder());
+ assertFalse(createrepoProject.getContentFolder().exists());
+ // repo file is found and exists
+ assertNotNull(createrepoProject.getRepoFile());
+ assertTrue(createrepoProject.getRepoFile().exists());
+ assertEquals(ICreaterepoTestConstants.REPO_NAME, createrepoProject.getRepoFile().getName());
+ }
+
+ /**
+ * Test if initializing createrepo project is successful
+ * without specifying .repo file.
+ *
+ * @throws CoreException
+ */
+ @Test
+ public void testInitializeNoRepoFileSpecfied() throws CoreException {
+ // repo file will be found rather than initialized
+ CreaterepoProject createrepoProject = new CreaterepoProject(project);
+ // content folder is defined, but not created (wizard does that)
+ assertNotNull(createrepoProject.getContentFolder());
+ assertFalse(createrepoProject.getContentFolder().exists());
+ // repo file is found and exists
+ assertNotNull(createrepoProject.getRepoFile());
+ assertTrue(createrepoProject.getRepoFile().exists());
+ assertEquals(ICreaterepoTestConstants.REPO_NAME, createrepoProject.getRepoFile().getName());
+ }
+
+ /**
+ * Test if importing RPMs from external source successfully saves into
+ * the "content" folder.
+ *
+ * @throws CoreException
+ * @throws IOException
+ */
+ @Test
+ public void testImportRPM() throws CoreException, IOException {
+ CreaterepoProject createrepoProject = new CreaterepoProject(project);
+
+ // test for file
+ URL rpmURL = FileLocator.find(FrameworkUtil
+ .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC1), null);
+ File rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
+ createrepoProject.importRPM(rpmFile);
+ assertNotNull(createrepoProject.getContentFolder());
+ assertTrue(createrepoProject.getContentFolder().exists());
+ assertEquals(1, createrepoProject.getContentFolder().members().length);
+ assertTrue(createrepoProject.getContentFolder().findMember(ICreaterepoTestConstants.RPM1).exists());
+
+ // test for duplicate file
+ createrepoProject.importRPM(rpmFile);
+ assertEquals(1, createrepoProject.getContentFolder().members().length);
+ assertTrue(createrepoProject.getContentFolder().findMember(ICreaterepoTestConstants.RPM1).exists());
+
+ // test for new file
+ rpmURL = FileLocator.find(FrameworkUtil
+ .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC2), null);
+ rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
+ createrepoProject.importRPM(rpmFile);
+ assertEquals(2, createrepoProject.getContentFolder().members().length);
+ assertTrue(createrepoProject.getContentFolder().findMember(ICreaterepoTestConstants.RPM2).exists());
+ }
+
+ /**
+ * Test if getting the RPMs is successful.
+ *
+ * @throws CoreException
+ * @throws IOException
+ */
+ @Test
+ public void testGetRPMs() throws CoreException, IOException {
+ CreaterepoProject createrepoProject = new CreaterepoProject(project);
+ URL rpmURL = FileLocator.find(FrameworkUtil
+ .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC1), null);
+ File rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
+ createrepoProject.importRPM(rpmFile);
+ rpmURL = FileLocator.find(FrameworkUtil
+ .getBundle(CreaterepoProjectTest.class), new Path(TEST_RPM_LOC2), null);
+ rpmFile = new File(FileLocator.toFileURL(rpmURL).getPath());
+ createrepoProject.importRPM(rpmFile);
+
+ List<IResource> rpms = createrepoProject.getRPMs();
+ assertEquals(2, rpms.size());
+ }
+
+ /**
+ * Simple test execution of createrepo. This checks to see if the "content" folder
+ * was created while executing and that the execution is successful if repomd.xml was created
+ * under the repodata folder.
+ *
+ * @throws CoreException
+ */
+ @Test
+ public void testSimpleExecute() throws CoreException {
+ CreaterepoProject createrepoProject = new CreaterepoProject(project);
+ // make sure that content folder doesn't exist
+ assertFalse(createrepoProject.getContentFolder().exists());
+ // assume that there is creatrepo version of >= 0.9.8
+ IStatus validVersion = Createrepo.isCorrectVersion();
+ Assume.assumeTrue(validVersion.isOK());
+
+ IStatus status = createrepoProject.createrepo(CreaterepoUtils.findConsole("test").newMessageStream()); //$NON-NLS-1$
+ // check if executing has an OK status and that content folder is created with the repodata contents
+ assertEquals(Status.OK_STATUS, status);
+ assertTrue(createrepoProject.getContentFolder().exists());
+ assertTrue(createrepoProject.getContentFolder().members().length > 0);
+
+ // check if the repodata folder exists and repomd.xml exists within it
+ assertTrue(createrepoProject.getContentFolder().findMember(
+ ICreaterepoTestConstants.REPODATA_FOLDER).exists());
+ IFolder repodataFolder = (IFolder) createrepoProject.getContentFolder()
+ .findMember(ICreaterepoTestConstants.REPODATA_FOLDER);
+ // repodata should have at least more than 1 file: repomd.xml + archives
+ assertTrue(repodataFolder.members().length > 1);
+ assertTrue(repodataFolder.findMember(ICreaterepoTestConstants.REPO_MD_NAME)
+ .exists());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoRepoFormEditorTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoRepoFormEditorTest.java
index 37e4b8a24e..0bdb31350c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoRepoFormEditorTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoRepoFormEditorTest.java
@@ -31,53 +31,53 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class CreaterepoRepoFormEditorTest {
- private static TestCreaterepoProject testProject;
- private static SWTWorkbenchBot bot;
- private static SWTBotView navigator;
+ private static TestCreaterepoProject testProject;
+ private static SWTWorkbenchBot bot;
+ private static SWTBotView navigator;
- /**
- * Initialize the test project.
- *
- * @throws CoreException
- */
- @BeforeClass
- public static void setUpBeforeClass() throws CoreException {
- testProject = new TestCreaterepoProject();
- assertTrue(testProject.getProject().exists());
- bot = new SWTWorkbenchBot();
- try {
- bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
- } catch (WidgetNotFoundException e) {
- // cannot activate main shell, continue anyways
- }
- TestUtils.openResourcePerspective(bot);
- navigator = TestUtils.enterProjectFolder(bot);
- }
+ /**
+ * Initialize the test project.
+ *
+ * @throws CoreException
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws CoreException {
+ testProject = new TestCreaterepoProject();
+ assertTrue(testProject.getProject().exists());
+ bot = new SWTWorkbenchBot();
+ try {
+ bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
+ } catch (WidgetNotFoundException e) {
+ // cannot activate main shell, continue anyways
+ }
+ TestUtils.openResourcePerspective(bot);
+ navigator = TestUtils.enterProjectFolder(bot);
+ }
- /**
- * Delete the project when tests are done.
- *
- * @throws CoreException
- */
- @AfterClass
- public static void tearDownAfterClass() throws CoreException {
- TestUtils.exitProjectFolder(bot, navigator);
- testProject.dispose();
- assertFalse(testProject.getProject().exists());
- }
+ /**
+ * Delete the project when tests are done.
+ *
+ * @throws CoreException
+ */
+ @AfterClass
+ public static void tearDownAfterClass() throws CoreException {
+ TestUtils.exitProjectFolder(bot, navigator);
+ testProject.dispose();
+ assertFalse(testProject.getProject().exists());
+ }
- /**
- * Test if the multi page editor is properly created. Make sure there are 3
- * pages (Repository, Metadata, repo file), and that all of them can be switched
- * to.
- */
- @Test
- public void testFormEditorCreation() {
- SWTBotMultiPageEditor editor = TestUtils.openRepoFile(bot, navigator);
- // activate the pages to make sure they exist and work
- editor.activatePage(Messages.MetadataPage_title);
- editor.activatePage(ICreaterepoTestConstants.REPO_NAME);
- editor.activatePage(Messages.ImportRPMsPage_title);
- }
+ /**
+ * Test if the multi page editor is properly created. Make sure there are 3
+ * pages (Repository, Metadata, repo file), and that all of them can be switched
+ * to.
+ */
+ @Test
+ public void testFormEditorCreation() {
+ SWTBotMultiPageEditor editor = TestUtils.openRepoFile(bot, navigator);
+ // activate the pages to make sure they exist and work
+ editor.activatePage(Messages.MetadataPage_title);
+ editor.activatePage(ICreaterepoTestConstants.REPO_NAME);
+ editor.activatePage(Messages.ImportRPMsPage_title);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoUtilsTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoUtilsTest.java
index 0173541a9b..1be884ec96 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoUtilsTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/CreaterepoUtilsTest.java
@@ -28,70 +28,70 @@ import org.junit.Test;
*/
public class CreaterepoUtilsTest {
- private static final String CONSOLE_NAME = "CreaterepoConsole"; //$NON-NLS-1$
+ private static final String CONSOLE_NAME = "CreaterepoConsole"; //$NON-NLS-1$
- private static ConsolePlugin plugin;
- private static IConsoleManager manager;
+ private static ConsolePlugin plugin;
+ private static IConsoleManager manager;
- /**
- * Setup the console manager.
- */
- @BeforeClass
- public static void setUpBeforeClass() {
- plugin = ConsolePlugin.getDefault();
- manager = plugin.getConsoleManager();
- }
+ /**
+ * Setup the console manager.
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ plugin = ConsolePlugin.getDefault();
+ manager = plugin.getConsoleManager();
+ }
- /**
- * Find any consoles and remove them.
- */
- @After
- public void tearDown() {
- if (manager != null) {
- manager.removeConsoles(manager.getConsoles());
- }
- assertEquals(0, manager.getConsoles().length);
- }
+ /**
+ * Find any consoles and remove them.
+ */
+ @After
+ public void tearDown() {
+ if (manager != null) {
+ manager.removeConsoles(manager.getConsoles());
+ }
+ assertEquals(0, manager.getConsoles().length);
+ }
- /**
- * Test if findConsole method finds correct console.
- */
- @Test
- public void testFindConsoleSameObject() {
- MessageConsole createrepoConsole = new MessageConsole(CONSOLE_NAME, null, null, true);
- manager.addConsoles(new IConsole[] {
- new MessageConsole("DummyConsole1", null, null, true), //$NON-NLS-1$
- createrepoConsole,
- new MessageConsole("DummyConsole2", null, null, true) //$NON-NLS-1$
- });
- assertEquals(3, manager.getConsoles().length);
- assertEquals(createrepoConsole, CreaterepoUtils.findConsole(CONSOLE_NAME));
- }
+ /**
+ * Test if findConsole method finds correct console.
+ */
+ @Test
+ public void testFindConsoleSameObject() {
+ MessageConsole createrepoConsole = new MessageConsole(CONSOLE_NAME, null, null, true);
+ manager.addConsoles(new IConsole[] {
+ new MessageConsole("DummyConsole1", null, null, true), //$NON-NLS-1$
+ createrepoConsole,
+ new MessageConsole("DummyConsole2", null, null, true) //$NON-NLS-1$
+ });
+ assertEquals(3, manager.getConsoles().length);
+ assertEquals(createrepoConsole, CreaterepoUtils.findConsole(CONSOLE_NAME));
+ }
- /**
- * Test if findConsole finds correct console by name.
- */
- @Test
- public void testFindConsoleByName() {
- MessageConsole createrepoConsole = new MessageConsole(CONSOLE_NAME, null, null, true);
- manager.addConsoles(new IConsole[] {
- new MessageConsole("DummyConsole1", null, null, true), //$NON-NLS-1$
- new MessageConsole(CONSOLE_NAME, null, null, true),
- new MessageConsole("DummyConsole2", null, null, true) //$NON-NLS-1$
- });
- assertEquals(3, manager.getConsoles().length);
- assertNotEquals(createrepoConsole, CreaterepoUtils.findConsole(CONSOLE_NAME));
- assertEquals(CONSOLE_NAME, CreaterepoUtils.findConsole(CONSOLE_NAME).getName());
- }
+ /**
+ * Test if findConsole finds correct console by name.
+ */
+ @Test
+ public void testFindConsoleByName() {
+ MessageConsole createrepoConsole = new MessageConsole(CONSOLE_NAME, null, null, true);
+ manager.addConsoles(new IConsole[] {
+ new MessageConsole("DummyConsole1", null, null, true), //$NON-NLS-1$
+ new MessageConsole(CONSOLE_NAME, null, null, true),
+ new MessageConsole("DummyConsole2", null, null, true) //$NON-NLS-1$
+ });
+ assertEquals(3, manager.getConsoles().length);
+ assertNotEquals(createrepoConsole, CreaterepoUtils.findConsole(CONSOLE_NAME));
+ assertEquals(CONSOLE_NAME, CreaterepoUtils.findConsole(CONSOLE_NAME).getName());
+ }
- /**
- * Test if findConsole creates a console with correct name.
- */
- @Test
- public void testCreateConsoleIfNotFound() {
- MessageConsole console = CreaterepoUtils.findConsole(CONSOLE_NAME);
- assertNotNull(console);
- assertEquals(CONSOLE_NAME, console.getName());
- }
+ /**
+ * Test if findConsole creates a console with correct name.
+ */
+ @Test
+ public void testCreateConsoleIfNotFound() {
+ MessageConsole console = CreaterepoUtils.findConsole(CONSOLE_NAME);
+ assertNotNull(console);
+ assertEquals(CONSOLE_NAME, console.getName());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/ICreaterepoTestConstants.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/ICreaterepoTestConstants.java
index a13b0792bc..3e56ca7722 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/ICreaterepoTestConstants.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/ICreaterepoTestConstants.java
@@ -18,89 +18,89 @@ import org.eclipse.linuxtools.internal.rpm.createrepo.CreaterepoPreferenceConsta
*/
public interface ICreaterepoTestConstants {
- /*
- * Dialog specific stuff
- */
- String MAIN_SHELL = "Resource - Eclipse Platform"; //$NON-NLS-1$
- String FILE = "File"; //$NON-NLS-1$
- String NEW = "New"; //$NON-NLS-1$
- String OTHER = "Other..."; //$NON-NLS-1$
- String NEXT_BUTTON = "Next >"; //$NON-NLS-1$
- String BACK_BUTTON = "< Back"; //$NON-NLS-1$
- String FINISH_BUTTON = "Finish"; //$NON-NLS-1$
- String CANCEL_BUTTON = "Cancel"; //$NON-NLS-1$
- String WINDOW = "Window"; //$NON-NLS-1$
- String SHOW_VIEW = "Show View"; //$NON-NLS-1$
- String PREFERENCES = "Preferences"; //$NON-NLS-1$
- String OK_BUTTON = "OK"; //$NON-NLS-1$
- String OPEN = "Open"; //$NON-NLS-1$
- String DEFAULTS = "Restore Defaults"; //$NON-NLS-1$
- String PROPERTIES = "Properties"; //$NON-NLS-1$
- String PROPERTIES_SHELL = "Properties for %s"; //$NON-NLS-1$
+ /*
+ * Dialog specific stuff
+ */
+ String MAIN_SHELL = "Resource - Eclipse Platform"; //$NON-NLS-1$
+ String FILE = "File"; //$NON-NLS-1$
+ String NEW = "New"; //$NON-NLS-1$
+ String OTHER = "Other..."; //$NON-NLS-1$
+ String NEXT_BUTTON = "Next >"; //$NON-NLS-1$
+ String BACK_BUTTON = "< Back"; //$NON-NLS-1$
+ String FINISH_BUTTON = "Finish"; //$NON-NLS-1$
+ String CANCEL_BUTTON = "Cancel"; //$NON-NLS-1$
+ String WINDOW = "Window"; //$NON-NLS-1$
+ String SHOW_VIEW = "Show View"; //$NON-NLS-1$
+ String PREFERENCES = "Preferences"; //$NON-NLS-1$
+ String OK_BUTTON = "OK"; //$NON-NLS-1$
+ String OPEN = "Open"; //$NON-NLS-1$
+ String DEFAULTS = "Restore Defaults"; //$NON-NLS-1$
+ String PROPERTIES = "Properties"; //$NON-NLS-1$
+ String PROPERTIES_SHELL = "Properties for %s"; //$NON-NLS-1$
- /*
- * Navigator controls
- */
- String GO_INTO = "Go Into"; //$NON-NLS-1$
- String GO_BACK = "Back to Workspace"; //$NON-NLS-1$
- String GO_FORWARD = "Forward"; //$NON-NLS-1$
+ /*
+ * Navigator controls
+ */
+ String GO_INTO = "Go Into"; //$NON-NLS-1$
+ String GO_BACK = "Back to Workspace"; //$NON-NLS-1$
+ String GO_FORWARD = "Forward"; //$NON-NLS-1$
- /*
- * Views
- */
- String WELCOME_VIEW = "Welcome"; //$NON-NLS-1$
- String GENERAL_NODE = "General"; //$NON-NLS-1$
- String NAVIGATOR = "Navigator"; //$NON-NLS-1$
+ /*
+ * Views
+ */
+ String WELCOME_VIEW = "Welcome"; //$NON-NLS-1$
+ String GENERAL_NODE = "General"; //$NON-NLS-1$
+ String NAVIGATOR = "Navigator"; //$NON-NLS-1$
- /*
- * Project Wizard Specific Stuff
- */
- String PROJECT_NAME_LABEL = "Project name:"; //$NON-NLS-1$
- String CREATEREPO_CATEGORY = "Createrepo"; //$NON-NLS-1$
- String CREATEREPO_PROJECT_WIZARD = "Createrepo Wizard"; //$NON-NLS-1$
+ /*
+ * Project Wizard Specific Stuff
+ */
+ String PROJECT_NAME_LABEL = "Project name:"; //$NON-NLS-1$
+ String CREATEREPO_CATEGORY = "Createrepo"; //$NON-NLS-1$
+ String CREATEREPO_PROJECT_WIZARD = "Createrepo Wizard"; //$NON-NLS-1$
- /*
- * Resources
- */
- String RPM_RESOURCE_LOC = "resources" + System.getProperty("file.separator") //$NON-NLS-1$//$NON-NLS-2$
- + "rpms" + System.getProperty("file.separator"); //$NON-NLS-1$ //$NON-NLS-2$
- String RPM1 = "eclipse-egit-github-3.0.0-2.fc19.noarch.rpm"; //$NON-NLS-1$
- String RPM2 = "hello-2.8-1.fc19.src.rpm"; //$NON-NLS-1$
+ /*
+ * Resources
+ */
+ String RPM_RESOURCE_LOC = "resources" + System.getProperty("file.separator") //$NON-NLS-1$//$NON-NLS-2$
+ + "rpms" + System.getProperty("file.separator"); //$NON-NLS-1$ //$NON-NLS-2$
+ String RPM1 = "eclipse-egit-github-3.0.0-2.fc19.noarch.rpm"; //$NON-NLS-1$
+ String RPM2 = "hello-2.8-1.fc19.src.rpm"; //$NON-NLS-1$
- /*
- * Common createrepo files
- */
- String REPODATA_FOLDER = "repodata"; //$NON-NLS-1$
- String REPO_MD_NAME = "repomd.xml"; //$NON-NLS-1$
+ /*
+ * Common createrepo files
+ */
+ String REPODATA_FOLDER = "repodata"; //$NON-NLS-1$
+ String REPO_MD_NAME = "repomd.xml"; //$NON-NLS-1$
- /*
- * Test names
- */
- String PROJECT_NAME = "createrepo-test-project"; //$NON-NLS-1$
- String REPO_NAME = "createrepo-test-repo.repo"; //$NON-NLS-1$
+ /*
+ * Test names
+ */
+ String PROJECT_NAME = "createrepo-test-project"; //$NON-NLS-1$
+ String REPO_NAME = "createrepo-test-repo.repo"; //$NON-NLS-1$
- /*
- * Preferences used
- */
- String DELTAS = "Deltas"; //$NON-NLS-1$
- String[] PREFS_ARRAY = {
- CreaterepoPreferenceConstants.PREF_DISTRO_TAG,
- CreaterepoPreferenceConstants.PREF_CONTENT_TAG,
- CreaterepoPreferenceConstants.PREF_REPO_TAG,
- CreaterepoPreferenceConstants.PREF_REVISION,
- CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
- CreaterepoPreferenceConstants.PREF_GENERATE_DB,
- CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
- CreaterepoPreferenceConstants.PREF_PRETTY_XML,
- CreaterepoPreferenceConstants.PREF_WORKERS,
- CreaterepoPreferenceConstants.PREF_CHECK_TS,
- CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
- CreaterepoPreferenceConstants.PREF_CHECKSUM,
- CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
- CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED,
- CreaterepoPreferenceConstants.PREF_DELTA_ENABLE,
- CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
- CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
- CreaterepoPreferenceConstants.PREF_OLD_PACKAGE_DIRS,
- };
+ /*
+ * Preferences used
+ */
+ String DELTAS = "Deltas"; //$NON-NLS-1$
+ String[] PREFS_ARRAY = {
+ CreaterepoPreferenceConstants.PREF_DISTRO_TAG,
+ CreaterepoPreferenceConstants.PREF_CONTENT_TAG,
+ CreaterepoPreferenceConstants.PREF_REPO_TAG,
+ CreaterepoPreferenceConstants.PREF_REVISION,
+ CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
+ CreaterepoPreferenceConstants.PREF_GENERATE_DB,
+ CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
+ CreaterepoPreferenceConstants.PREF_PRETTY_XML,
+ CreaterepoPreferenceConstants.PREF_WORKERS,
+ CreaterepoPreferenceConstants.PREF_CHECK_TS,
+ CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
+ CreaterepoPreferenceConstants.PREF_CHECKSUM,
+ CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
+ CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED,
+ CreaterepoPreferenceConstants.PREF_DELTA_ENABLE,
+ CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
+ CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
+ CreaterepoPreferenceConstants.PREF_OLD_PACKAGE_DIRS,
+ };
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/TestCreaterepoProject.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/TestCreaterepoProject.java
index 315e58b618..7c4a408bae 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/TestCreaterepoProject.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/TestCreaterepoProject.java
@@ -39,136 +39,136 @@ import org.eclipse.ui.preferences.ScopedPreferenceStore;
*/
public class TestCreaterepoProject {
- private static NullProgressMonitor monitor;
- private IProject project;
+ private static NullProgressMonitor monitor;
+ private IProject project;
- /**
- * Instantiating class creates project, content folder, and .repo file.
- *
- * @throws CoreException
- */
- public TestCreaterepoProject() throws CoreException {
- monitor = new NullProgressMonitor();
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- project = root.getProject(ICreaterepoTestConstants.PROJECT_NAME);
- IProjectDescription description = ResourcesPlugin.getWorkspace()
- .newProjectDescription(ICreaterepoTestConstants.PROJECT_NAME);
- description.setNatureIds(new String[] {CreaterepoProjectNature.CREATEREPO_NATURE_ID});
- if (!project.exists()) {
- project.create(description, monitor);
- }
- project.open(monitor);
- init();
- }
+ /**
+ * Instantiating class creates project, content folder, and .repo file.
+ *
+ * @throws CoreException
+ */
+ public TestCreaterepoProject() throws CoreException {
+ monitor = new NullProgressMonitor();
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ project = root.getProject(ICreaterepoTestConstants.PROJECT_NAME);
+ IProjectDescription description = ResourcesPlugin.getWorkspace()
+ .newProjectDescription(ICreaterepoTestConstants.PROJECT_NAME);
+ description.setNatureIds(new String[] {CreaterepoProjectNature.CREATEREPO_NATURE_ID});
+ if (!project.exists()) {
+ project.create(description, monitor);
+ }
+ project.open(monitor);
+ init();
+ }
- /**
- * Create the content folder and the .repo file.
- *
- * @throws CoreException
- */
- private void init() throws CoreException {
- createFolder(ICreaterepoConstants.CONTENT_FOLDER);
- createFile(ICreaterepoTestConstants.REPO_NAME);
- }
+ /**
+ * Create the content folder and the .repo file.
+ *
+ * @throws CoreException
+ */
+ private void init() throws CoreException {
+ createFolder(ICreaterepoConstants.CONTENT_FOLDER);
+ createFile(ICreaterepoTestConstants.REPO_NAME);
+ }
- /**
- * Create a folder in the project.
- *
- * @param folderName The name of the folder.
- * @return The folder that was created.
- * @throws CoreException
- */
- public IFolder createFolder(String folderName) throws CoreException {
- IFolder folder = project.getFolder(folderName);
- if (!folder.exists()) {
- folder.create(false, true, monitor);
- }
- return folder;
- }
+ /**
+ * Create a folder in the project.
+ *
+ * @param folderName The name of the folder.
+ * @return The folder that was created.
+ * @throws CoreException
+ */
+ public IFolder createFolder(String folderName) throws CoreException {
+ IFolder folder = project.getFolder(folderName);
+ if (!folder.exists()) {
+ folder.create(false, true, monitor);
+ }
+ return folder;
+ }
- /**
- * Create a file in the project. Initialize empty content.
- *
- * @param fileName The name of the file.
- * @return The file that was created.
- * @throws CoreException
- */
- public IFile createFile(String fileName) throws CoreException {
- IFile file = project.getFile(fileName);
- InputStream stream = new ByteArrayInputStream(ICreaterepoConstants.EMPTY_STRING.getBytes());
- if (!file.exists()) {
- file.create(stream, true, monitor);
- }
- return file;
- }
+ /**
+ * Create a file in the project. Initialize empty content.
+ *
+ * @param fileName The name of the file.
+ * @return The file that was created.
+ * @throws CoreException
+ */
+ public IFile createFile(String fileName) throws CoreException {
+ IFile file = project.getFile(fileName);
+ InputStream stream = new ByteArrayInputStream(ICreaterepoConstants.EMPTY_STRING.getBytes());
+ if (!file.exists()) {
+ file.create(stream, true, monitor);
+ }
+ return file;
+ }
- /**
- * Delete the project and all its contents.
- *
- * @throws CoreException
- */
- public void dispose() throws CoreException {
- project.delete(true, true, monitor);
- }
+ /**
+ * Delete the project and all its contents.
+ *
+ * @throws CoreException
+ */
+ public void dispose() throws CoreException {
+ project.delete(true, true, monitor);
+ }
- /**
- * Refresh the project.
- *
- * @throws CoreException
- */
- public void refresh() throws CoreException {
- project.refreshLocal(IResource.DEPTH_INFINITE, null);
- }
+ /**
+ * Refresh the project.
+ *
+ * @throws CoreException
+ */
+ public void refresh() throws CoreException {
+ project.refreshLocal(IResource.DEPTH_INFINITE, null);
+ }
- /**
- * Return a new instance of a CreaterepoProject.
- *
- * @return A new CreaterepoProject.
- * @throws CoreException
- */
- public CreaterepoProject getCreaterepoProject() throws CoreException {
- return new CreaterepoProject(project, project.getFile(ICreaterepoTestConstants.REPO_NAME));
- }
+ /**
+ * Return a new instance of a CreaterepoProject.
+ *
+ * @return A new CreaterepoProject.
+ * @throws CoreException
+ */
+ public CreaterepoProject getCreaterepoProject() throws CoreException {
+ return new CreaterepoProject(project, project.getFile(ICreaterepoTestConstants.REPO_NAME));
+ }
- /**
- * Return the current project instance;
- *
- * @return The current project instance.
- */
- public IProject getProject() {
- return project;
- }
+ /**
+ * Return the current project instance;
+ *
+ * @return The current project instance.
+ */
+ public IProject getProject() {
+ return project;
+ }
- /**
- * Set the file contents of the repofile if it exists, or create a repofile
- * with the specified contents if it does not exist.
- *
- * @param id The repository ID.
- * @param name The human-readable description of the repository.
- * @param url The baseurl of the repository.
- * @throws CoreException
- */
- public void setRepoFileContents(String id, String name, String url) throws CoreException {
- String contents = String.format("[%s]\n", id); //$NON-NLS-1$
- contents = contents.concat(String.format("%s=%s\n", IRepoFileConstants.NAME, name)); //$NON-NLS-1$
- contents = contents.concat(String.format("%s=%s\n", IRepoFileConstants.BASE_URL, url)); //$NON-NLS-1$
- InputStream stream = new ByteArrayInputStream(contents.getBytes());
- IFile repoFile = project.getFile(ICreaterepoTestConstants.REPO_NAME);
- if (repoFile.exists()) {
- repoFile.setContents(stream, true, true, monitor);
- } else {
- repoFile.create(stream, true, monitor);
- }
- }
+ /**
+ * Set the file contents of the repofile if it exists, or create a repofile
+ * with the specified contents if it does not exist.
+ *
+ * @param id The repository ID.
+ * @param name The human-readable description of the repository.
+ * @param url The baseurl of the repository.
+ * @throws CoreException
+ */
+ public void setRepoFileContents(String id, String name, String url) throws CoreException {
+ String contents = String.format("[%s]\n", id); //$NON-NLS-1$
+ contents = contents.concat(String.format("%s=%s\n", IRepoFileConstants.NAME, name)); //$NON-NLS-1$
+ contents = contents.concat(String.format("%s=%s\n", IRepoFileConstants.BASE_URL, url)); //$NON-NLS-1$
+ InputStream stream = new ByteArrayInputStream(contents.getBytes());
+ IFile repoFile = project.getFile(ICreaterepoTestConstants.REPO_NAME);
+ if (repoFile.exists()) {
+ repoFile.setContents(stream, true, true, monitor);
+ } else {
+ repoFile.create(stream, true, monitor);
+ }
+ }
- /**
- * Restore the defaults of the workspace preferences.
- */
- public void restoreDefaults() {
- IPreferenceStore prefStore = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
- for (String preference : ICreaterepoTestConstants.PREFS_ARRAY) {
- prefStore.setToDefault(preference);
- }
- }
+ /**
+ * Restore the defaults of the workspace preferences.
+ */
+ public void restoreDefaults() {
+ IPreferenceStore prefStore = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
+ for (String preference : ICreaterepoTestConstants.PREFS_ARRAY) {
+ prefStore.setToDefault(preference);
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/TestUtils.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/TestUtils.java
index 8cd2a1dd4f..17b2b1e5ba 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/TestUtils.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/tests/TestUtils.java
@@ -28,111 +28,111 @@ import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
public class TestUtils {
- public static class NodeAvailableAndSelect extends DefaultCondition {
+ public static class NodeAvailableAndSelect extends DefaultCondition {
- private SWTBotTree tree;
- private String parent;
- private String node;
-
- /**
- * Wait for a tree node (with a known parent) to become visible, and select it
- * when it does. Note that this wait condition should only be used after having
- * made an attempt to reveal the node.
- * @param tree The SWTBotTree that contains the node to select.
- * @param parent The text of the parent node that contains the node to select.
- * @param node The text of the node to select.
- */
- public NodeAvailableAndSelect(SWTBotTree tree, String parent, String node) {
- this.tree = tree;
- this.node = node;
- this.parent = parent;
- }
-
- @Override
- public boolean test() {
- try {
- SWTBotTreeItem parentNode = tree.getTreeItem(parent);
- parentNode.getNode(node).select();
- return true;
- } catch (WidgetNotFoundException e) {
- return false;
- }
- }
-
- @Override
- public String getFailureMessage() {
- return "Timed out waiting for " + node; //$NON-NLS-1$
- }
- }
+ private SWTBotTree tree;
+ private String parent;
+ private String node;
- /**
- * Open the resource perspective, if it's not already opened. Also, go into the project tree.
- */
- public static void openResourcePerspective(SWTWorkbenchBot bot) {
- try {
- // Check if the required views are already opened
- bot.viewByTitle(ICreaterepoTestConstants.NAVIGATOR);
- } catch (WidgetNotFoundException e) {
- // Not yet opened: turn on the resource perspective
- bot.menu(ICreaterepoTestConstants.WINDOW).menu(ICreaterepoTestConstants.SHOW_VIEW)
- .menu(ICreaterepoTestConstants.OTHER).click();
- SWTBotShell shell = bot.shell(ICreaterepoTestConstants.SHOW_VIEW);
- shell.activate();
- bot.text().setText(ICreaterepoTestConstants.NAVIGATOR);
- bot.waitUntil(new NodeAvailableAndSelect(bot.tree(),
- ICreaterepoTestConstants.GENERAL_NODE, ICreaterepoTestConstants.NAVIGATOR));
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- }
- }
+ /**
+ * Wait for a tree node (with a known parent) to become visible, and select it
+ * when it does. Note that this wait condition should only be used after having
+ * made an attempt to reveal the node.
+ * @param tree The SWTBotTree that contains the node to select.
+ * @param parent The text of the parent node that contains the node to select.
+ * @param node The text of the node to select.
+ */
+ public NodeAvailableAndSelect(SWTBotTree tree, String parent, String node) {
+ this.tree = tree;
+ this.node = node;
+ this.parent = parent;
+ }
- /**
- * Enter the project folder so as to avoid expanding trees later
- */
- public static SWTBotView enterProjectFolder(SWTWorkbenchBot bot) {
- SWTBotView navigator = bot.viewByTitle(ICreaterepoTestConstants.NAVIGATOR);
- navigator.setFocus();
- navigator.bot().tree().select(ICreaterepoTestConstants.PROJECT_NAME).
- contextMenu(ICreaterepoTestConstants.GO_INTO).click();
- bot.waitUntil(waitForWidget(WidgetMatcherFactory.withText(
- ICreaterepoTestConstants.PROJECT_NAME), navigator.getWidget()));
- return navigator;
- }
+ @Override
+ public boolean test() {
+ try {
+ SWTBotTreeItem parentNode = tree.getTreeItem(parent);
+ parentNode.getNode(node).select();
+ return true;
+ } catch (WidgetNotFoundException e) {
+ return false;
+ }
+ }
- /**
- * Exit from the project tree.
- */
- public static void exitProjectFolder(SWTWorkbenchBot bot, SWTBotView navigator) {
- SWTBotToolbarButton forwardButton = navigator.toolbarPushButton(ICreaterepoTestConstants.GO_FORWARD);
- navigator.toolbarPushButton(ICreaterepoTestConstants.GO_BACK).click();
- bot.waitUntil(widgetIsEnabled(forwardButton));
- }
+ @Override
+ public String getFailureMessage() {
+ return "Timed out waiting for " + node; //$NON-NLS-1$
+ }
+ }
- /**
- * Open the property page, and activate its shell.
- */
- public static SWTBotShell openPropertyPage(SWTWorkbenchBot bot, SWTBotView navigator) {
- navigator.show();
- // select the .repo file from the package explorer and open its properties
- SWTBotTree botTree = navigator.bot().tree();
- botTree.select(ICreaterepoTestConstants.REPO_NAME)
- .contextMenu(ICreaterepoTestConstants.PROPERTIES).click();
- // get a handle of the property shell
- SWTBotShell propertyShell = bot.shell(String.format(ICreaterepoTestConstants.PROPERTIES_SHELL,
- ICreaterepoTestConstants.REPO_NAME));
- propertyShell.activate();
- return propertyShell;
- }
+ /**
+ * Open the resource perspective, if it's not already opened. Also, go into the project tree.
+ */
+ public static void openResourcePerspective(SWTWorkbenchBot bot) {
+ try {
+ // Check if the required views are already opened
+ bot.viewByTitle(ICreaterepoTestConstants.NAVIGATOR);
+ } catch (WidgetNotFoundException e) {
+ // Not yet opened: turn on the resource perspective
+ bot.menu(ICreaterepoTestConstants.WINDOW).menu(ICreaterepoTestConstants.SHOW_VIEW)
+ .menu(ICreaterepoTestConstants.OTHER).click();
+ SWTBotShell shell = bot.shell(ICreaterepoTestConstants.SHOW_VIEW);
+ shell.activate();
+ bot.text().setText(ICreaterepoTestConstants.NAVIGATOR);
+ bot.waitUntil(new NodeAvailableAndSelect(bot.tree(),
+ ICreaterepoTestConstants.GENERAL_NODE, ICreaterepoTestConstants.NAVIGATOR));
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ }
+ }
- public static SWTBotMultiPageEditor openRepoFile(SWTWorkbenchBot bot, SWTBotView navigator) {
- // open the package explorer view
- SWTBotTree botTree = navigator.bot().tree();
- botTree.select(ICreaterepoTestConstants.REPO_NAME)
- .contextMenu(ICreaterepoTestConstants.OPEN).click();
- // get a handle on the multipage editor that was opened
- SWTBotMultiPageEditor editor = bot.multipageEditorByTitle(ICreaterepoTestConstants.REPO_NAME);
- editor.show();
- // 3 = repository form page, metadata form page, repo file
- assertEquals(3, editor.getPageCount());
- return editor;
- }
+ /**
+ * Enter the project folder so as to avoid expanding trees later
+ */
+ public static SWTBotView enterProjectFolder(SWTWorkbenchBot bot) {
+ SWTBotView navigator = bot.viewByTitle(ICreaterepoTestConstants.NAVIGATOR);
+ navigator.setFocus();
+ navigator.bot().tree().select(ICreaterepoTestConstants.PROJECT_NAME).
+ contextMenu(ICreaterepoTestConstants.GO_INTO).click();
+ bot.waitUntil(waitForWidget(WidgetMatcherFactory.withText(
+ ICreaterepoTestConstants.PROJECT_NAME), navigator.getWidget()));
+ return navigator;
+ }
+
+ /**
+ * Exit from the project tree.
+ */
+ public static void exitProjectFolder(SWTWorkbenchBot bot, SWTBotView navigator) {
+ SWTBotToolbarButton forwardButton = navigator.toolbarPushButton(ICreaterepoTestConstants.GO_FORWARD);
+ navigator.toolbarPushButton(ICreaterepoTestConstants.GO_BACK).click();
+ bot.waitUntil(widgetIsEnabled(forwardButton));
+ }
+
+ /**
+ * Open the property page, and activate its shell.
+ */
+ public static SWTBotShell openPropertyPage(SWTWorkbenchBot bot, SWTBotView navigator) {
+ navigator.show();
+ // select the .repo file from the package explorer and open its properties
+ SWTBotTree botTree = navigator.bot().tree();
+ botTree.select(ICreaterepoTestConstants.REPO_NAME)
+ .contextMenu(ICreaterepoTestConstants.PROPERTIES).click();
+ // get a handle of the property shell
+ SWTBotShell propertyShell = bot.shell(String.format(ICreaterepoTestConstants.PROPERTIES_SHELL,
+ ICreaterepoTestConstants.REPO_NAME));
+ propertyShell.activate();
+ return propertyShell;
+ }
+
+ public static SWTBotMultiPageEditor openRepoFile(SWTWorkbenchBot bot, SWTBotView navigator) {
+ // open the package explorer view
+ SWTBotTree botTree = navigator.bot().tree();
+ botTree.select(ICreaterepoTestConstants.REPO_NAME)
+ .contextMenu(ICreaterepoTestConstants.OPEN).click();
+ // get a handle on the multipage editor that was opened
+ SWTBotMultiPageEditor editor = bot.multipageEditorByTitle(ICreaterepoTestConstants.REPO_NAME);
+ editor.show();
+ // 3 = repository form page, metadata form page, repo file
+ assertEquals(3, editor.getPageCount());
+ return editor;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/listener/tests/CreaterepoResourceListenerTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/listener/tests/CreaterepoResourceListenerTest.java
index 57db35fa00..e25eabbea3 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/listener/tests/CreaterepoResourceListenerTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/listener/tests/CreaterepoResourceListenerTest.java
@@ -37,81 +37,81 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class CreaterepoResourceListenerTest {
- private static SWTWorkbenchBot bot;
- private static NullProgressMonitor monitor;
- private static SWTBotView navigator;
- private TestCreaterepoProject testProject;
+ private static SWTWorkbenchBot bot;
+ private static NullProgressMonitor monitor;
+ private static SWTBotView navigator;
+ private TestCreaterepoProject testProject;
- /**
- * Initialize the bot.
- */
- @BeforeClass
- public static void setUpBeforeClass() {
- bot = new SWTWorkbenchBot();
- monitor = new NullProgressMonitor();
- try {
- bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
- } catch (WidgetNotFoundException e) {
- // cannot activate main shell, continue anyways
- }
- TestUtils.openResourcePerspective(bot);
- }
+ /**
+ * Initialize the bot.
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ bot = new SWTWorkbenchBot();
+ monitor = new NullProgressMonitor();
+ try {
+ bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
+ } catch (WidgetNotFoundException e) {
+ // cannot activate main shell, continue anyways
+ }
+ TestUtils.openResourcePerspective(bot);
+ }
- /**
- * Create a new test project and open the .repo file.
- *
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- testProject = new TestCreaterepoProject();
- navigator = TestUtils.enterProjectFolder(bot);
- assertTrue(testProject.getProject().exists());
- TestUtils.openRepoFile(bot, navigator);
- }
+ /**
+ * Create a new test project and open the .repo file.
+ *
+ * @throws Exception
+ */
+ @Before
+ public void setUp() throws Exception {
+ testProject = new TestCreaterepoProject();
+ navigator = TestUtils.enterProjectFolder(bot);
+ assertTrue(testProject.getProject().exists());
+ TestUtils.openRepoFile(bot, navigator);
+ }
- /**
- * Delete the project when tests are done.
- *
- * @throws CoreException
- */
- @After
- public void tearDown() throws CoreException {
- TestUtils.exitProjectFolder(bot, navigator);
- testProject.dispose();
- assertFalse(testProject.getProject().exists());
- }
+ /**
+ * Delete the project when tests are done.
+ *
+ * @throws CoreException
+ */
+ @After
+ public void tearDown() throws CoreException {
+ TestUtils.exitProjectFolder(bot, navigator);
+ testProject.dispose();
+ assertFalse(testProject.getProject().exists());
+ }
- /**
- * Test if editor is still open after closing the project.
- *
- * @throws CoreException
- */
- @Test
- public void testCloseProjectCloseEditor() throws CoreException {
- assertFalse(bot.editors().isEmpty());
- assertEquals(1, bot.editors().size());
- assertNotNull(bot.multipageEditorByTitle(ICreaterepoTestConstants.REPO_NAME));
- assertTrue(bot.multipageEditorByTitle(ICreaterepoTestConstants.REPO_NAME).isActive());
- testProject.getProject().close(monitor);
- assertFalse(testProject.getProject().isOpen());
- assertTrue(bot.editors().isEmpty());
- }
+ /**
+ * Test if editor is still open after closing the project.
+ *
+ * @throws CoreException
+ */
+ @Test
+ public void testCloseProjectCloseEditor() throws CoreException {
+ assertFalse(bot.editors().isEmpty());
+ assertEquals(1, bot.editors().size());
+ assertNotNull(bot.multipageEditorByTitle(ICreaterepoTestConstants.REPO_NAME));
+ assertTrue(bot.multipageEditorByTitle(ICreaterepoTestConstants.REPO_NAME).isActive());
+ testProject.getProject().close(monitor);
+ assertFalse(testProject.getProject().isOpen());
+ assertTrue(bot.editors().isEmpty());
+ }
- /**
- * Test if editor is still open after deleting the project.
- *
- * @throws CoreException
- */
- @Test
- public void testDeleteProjectCloseEditor() throws CoreException {
- assertFalse(bot.editors().isEmpty());
- assertEquals(1, bot.editors().size());
- assertNotNull(bot.multipageEditorByTitle(ICreaterepoTestConstants.REPO_NAME));
- assertTrue(bot.multipageEditorByTitle(ICreaterepoTestConstants.REPO_NAME).isActive());
- testProject.dispose();
- assertFalse(testProject.getProject().exists());
- assertTrue(bot.editors().isEmpty());
- }
+ /**
+ * Test if editor is still open after deleting the project.
+ *
+ * @throws CoreException
+ */
+ @Test
+ public void testDeleteProjectCloseEditor() throws CoreException {
+ assertFalse(bot.editors().isEmpty());
+ assertEquals(1, bot.editors().size());
+ assertNotNull(bot.multipageEditorByTitle(ICreaterepoTestConstants.REPO_NAME));
+ assertTrue(bot.multipageEditorByTitle(ICreaterepoTestConstants.REPO_NAME).isActive());
+ testProject.dispose();
+ assertFalse(testProject.getProject().exists());
+ assertTrue(bot.editors().isEmpty());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoDeltaPropertyPageTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoDeltaPropertyPageTest.java
index b47a515d25..a789928b5f 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoDeltaPropertyPageTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoDeltaPropertyPageTest.java
@@ -42,165 +42,165 @@ import org.osgi.service.prefs.BackingStoreException;
*/
public class CreaterepoDeltaPropertyPageTest {
- private static TestCreaterepoProject testProject;
- private static SWTWorkbenchBot bot;
- private static SWTBotView navigator;
- private CreaterepoProject project;
+ private static TestCreaterepoProject testProject;
+ private static SWTWorkbenchBot bot;
+ private static SWTBotView navigator;
+ private CreaterepoProject project;
- /**
- * Initialize the test project.
- *
- * @throws CoreException
- */
- @BeforeClass
- public static void setUpBeforeClass() throws CoreException {
- testProject = new TestCreaterepoProject();
- assertTrue(testProject.getProject().exists());
- bot = new SWTWorkbenchBot();
- testProject.restoreDefaults();
- try {
- bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
- } catch (WidgetNotFoundException e) {
- // cannot activate main shell, continue anyways
- }
- TestUtils.openResourcePerspective(bot);
- navigator = TestUtils.enterProjectFolder(bot);
- }
+ /**
+ * Initialize the test project.
+ *
+ * @throws CoreException
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws CoreException {
+ testProject = new TestCreaterepoProject();
+ assertTrue(testProject.getProject().exists());
+ bot = new SWTWorkbenchBot();
+ testProject.restoreDefaults();
+ try {
+ bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
+ } catch (WidgetNotFoundException e) {
+ // cannot activate main shell, continue anyways
+ }
+ TestUtils.openResourcePerspective(bot);
+ navigator = TestUtils.enterProjectFolder(bot);
+ }
- /**
- * Delete the project when tests are done.
- *
- * @throws CoreException
- */
- @AfterClass
- public static void tearDownAfterClass() throws CoreException {
- TestUtils.exitProjectFolder(bot, navigator);
- testProject.dispose();
- assertFalse(testProject.getProject().exists());
- }
+ /**
+ * Delete the project when tests are done.
+ *
+ * @throws CoreException
+ */
+ @AfterClass
+ public static void tearDownAfterClass() throws CoreException {
+ TestUtils.exitProjectFolder(bot, navigator);
+ testProject.dispose();
+ assertFalse(testProject.getProject().exists());
+ }
- /**
- * Get the CreaterepoProject at the beginning of each test.
- *
- * @throws CoreException
- * @throws IOException
- */
- @Before
- public void setUp() throws CoreException {
- project = testProject.getCreaterepoProject();
- assertNotNull(project);
- // before doing anything with SWTBot, activate the main shell
- try {
- bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
- } catch (WidgetNotFoundException e) {
- // cannot activate main shell, continue anyways
- }
- openPropertyPage();
- }
+ /**
+ * Get the CreaterepoProject at the beginning of each test.
+ *
+ * @throws CoreException
+ * @throws IOException
+ */
+ @Before
+ public void setUp() throws CoreException {
+ project = testProject.getCreaterepoProject();
+ assertNotNull(project);
+ // before doing anything with SWTBot, activate the main shell
+ try {
+ bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
+ } catch (WidgetNotFoundException e) {
+ // cannot activate main shell, continue anyways
+ }
+ openPropertyPage();
+ }
- /**
- * Restore the defaults for the general preference page.
- *
- * @throws BackingStoreException
- */
- @After
- public void tearDown() throws BackingStoreException {
- try {
- if (bot.shell(String.format(ICreaterepoTestConstants.PROPERTIES_SHELL,
- ICreaterepoTestConstants.REPO_NAME)).isActive()) {
- bot.shell(String.format(ICreaterepoTestConstants.PROPERTIES_SHELL,
- ICreaterepoTestConstants.REPO_NAME)).close();
- }
- } catch (WidgetNotFoundException e) {
- // cannot close property shell
- }
- testProject.restoreDefaults();
- IEclipsePreferences pref = project.getEclipsePreferences();
- pref.clear();
- pref.flush();
- assertEquals(0, pref.keys().length);
- }
+ /**
+ * Restore the defaults for the general preference page.
+ *
+ * @throws BackingStoreException
+ */
+ @After
+ public void tearDown() throws BackingStoreException {
+ try {
+ if (bot.shell(String.format(ICreaterepoTestConstants.PROPERTIES_SHELL,
+ ICreaterepoTestConstants.REPO_NAME)).isActive()) {
+ bot.shell(String.format(ICreaterepoTestConstants.PROPERTIES_SHELL,
+ ICreaterepoTestConstants.REPO_NAME)).close();
+ }
+ } catch (WidgetNotFoundException e) {
+ // cannot close property shell
+ }
+ testProject.restoreDefaults();
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ pref.clear();
+ pref.flush();
+ assertEquals(0, pref.keys().length);
+ }
- /**
- * Test if all preferences modified in the deltas createrepo property
- * page persist to project preferences.
- */
- @Test
- public void testChangePreferences() {
- bot.checkBox(Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel).click();
- bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas).setText("9"); //$NON-NLS-1$
- bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxDeltaSize).setText("13"); //$NON-NLS-1$
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- openPropertyPage();
- IEclipsePreferences pref = project.getEclipsePreferences();
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE),
- bot.checkBox(Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel).isChecked());
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS)),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas).getText()));
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE)),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxDeltaSize).getText()));
- }
+ /**
+ * Test if all preferences modified in the deltas createrepo property
+ * page persist to project preferences.
+ */
+ @Test
+ public void testChangePreferences() {
+ bot.checkBox(Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel).click();
+ bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas).setText("9"); //$NON-NLS-1$
+ bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxDeltaSize).setText("13"); //$NON-NLS-1$
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ openPropertyPage();
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE),
+ bot.checkBox(Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel).isChecked());
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS)),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas).getText()));
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE)),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxDeltaSize).getText()));
+ }
- /**
- * Test if all preferences modified in the deltas createrepo property
- * page will reset to default.
- */
- @Test
- public void testRestoreDefaults() {
- bot.checkBox(Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel).click();
- bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas).setText("9"); //$NON-NLS-1$
- bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxDeltaSize).setText("13"); //$NON-NLS-1$
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- openPropertyPage();
- bot.button(ICreaterepoTestConstants.DEFAULTS).click();
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- IEclipsePreferences pref = project.getEclipsePreferences();
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE));
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS)),
- prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS));
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE)),
- prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE));
- }
+ /**
+ * Test if all preferences modified in the deltas createrepo property
+ * page will reset to default.
+ */
+ @Test
+ public void testRestoreDefaults() {
+ bot.checkBox(Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel).click();
+ bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas).setText("9"); //$NON-NLS-1$
+ bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxDeltaSize).setText("13"); //$NON-NLS-1$
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ openPropertyPage();
+ bot.button(ICreaterepoTestConstants.DEFAULTS).click();
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE));
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS)),
+ prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS));
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE)),
+ prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE));
+ }
- /**
- * Test if all preferences stay the same as it was after pressing cancel
- * instead of ok.
- */
- @Test
- public void testCancel() {
- bot.checkBox(Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel).click();
- bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas).setText("9"); //$NON-NLS-1$
- bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxDeltaSize).setText("13"); //$NON-NLS-1$
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- openPropertyPage();
- bot.button(ICreaterepoTestConstants.DEFAULTS).click();
- bot.button(ICreaterepoTestConstants.CANCEL_BUTTON).click();
- openPropertyPage();
- IEclipsePreferences pref = project.getEclipsePreferences();
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE),
- bot.checkBox(Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel).isChecked());
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS)),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas).getText()));
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE)),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxDeltaSize).getText()));
- }
+ /**
+ * Test if all preferences stay the same as it was after pressing cancel
+ * instead of ok.
+ */
+ @Test
+ public void testCancel() {
+ bot.checkBox(Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel).click();
+ bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas).setText("9"); //$NON-NLS-1$
+ bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxDeltaSize).setText("13"); //$NON-NLS-1$
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ openPropertyPage();
+ bot.button(ICreaterepoTestConstants.DEFAULTS).click();
+ bot.button(ICreaterepoTestConstants.CANCEL_BUTTON).click();
+ openPropertyPage();
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE),
+ bot.checkBox(Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel).isChecked());
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS)),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas).getText()));
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE)),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoDeltaPropertyPage_maxDeltaSize).getText()));
+ }
- /**
- * Open the property page.
- */
- private static void openPropertyPage() {
- TestUtils.openPropertyPage(bot, navigator);
- bot.text().setText(ICreaterepoTestConstants.DELTAS);
- bot.waitUntil(new TestUtils.NodeAvailableAndSelect(bot.tree(), ICreaterepoTestConstants.CREATEREPO_CATEGORY, ICreaterepoTestConstants.DELTAS));
- }
+ /**
+ * Open the property page.
+ */
+ private static void openPropertyPage() {
+ TestUtils.openPropertyPage(bot, navigator);
+ bot.text().setText(ICreaterepoTestConstants.DELTAS);
+ bot.waitUntil(new TestUtils.NodeAvailableAndSelect(bot.tree(), ICreaterepoTestConstants.CREATEREPO_CATEGORY, ICreaterepoTestConstants.DELTAS));
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoGeneralPropertyPageTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoGeneralPropertyPageTest.java
index c89c894d8c..b688c13b1a 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoGeneralPropertyPageTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoGeneralPropertyPageTest.java
@@ -47,242 +47,242 @@ import org.osgi.service.prefs.BackingStoreException;
@RunWith(SWTBotJunit4ClassRunner.class)
public class CreaterepoGeneralPropertyPageTest {
- private static TestCreaterepoProject testProject;
- private static SWTWorkbenchBot bot;
- private static SWTBotView navigator;
- private CreaterepoProject project;
+ private static TestCreaterepoProject testProject;
+ private static SWTWorkbenchBot bot;
+ private static SWTBotView navigator;
+ private CreaterepoProject project;
- /**
- * Initialize the test project.
- *
- * @throws CoreException
- */
- @BeforeClass
- public static void setUpBeforeClass() throws CoreException {
- testProject = new TestCreaterepoProject();
- assertTrue(testProject.getProject().exists());
- bot = new SWTWorkbenchBot();
- testProject.restoreDefaults();
- try {
- bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
- } catch (WidgetNotFoundException e) {
- // cannot activate main shell, continue anyways
- }
- TestUtils.openResourcePerspective(bot);
- navigator = TestUtils.enterProjectFolder(bot);
- }
+ /**
+ * Initialize the test project.
+ *
+ * @throws CoreException
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws CoreException {
+ testProject = new TestCreaterepoProject();
+ assertTrue(testProject.getProject().exists());
+ bot = new SWTWorkbenchBot();
+ testProject.restoreDefaults();
+ try {
+ bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
+ } catch (WidgetNotFoundException e) {
+ // cannot activate main shell, continue anyways
+ }
+ TestUtils.openResourcePerspective(bot);
+ navigator = TestUtils.enterProjectFolder(bot);
+ }
- /**
- * Delete the project when tests are done.
- *
- * @throws CoreException
- */
- @AfterClass
- public static void tearDownAfterClass() throws CoreException {
- TestUtils.exitProjectFolder(bot, navigator);
- testProject.dispose();
- assertFalse(testProject.getProject().exists());
- }
+ /**
+ * Delete the project when tests are done.
+ *
+ * @throws CoreException
+ */
+ @AfterClass
+ public static void tearDownAfterClass() throws CoreException {
+ TestUtils.exitProjectFolder(bot, navigator);
+ testProject.dispose();
+ assertFalse(testProject.getProject().exists());
+ }
- /**
- * Get the CreaterepoProject at the beginning of each test.
- *
- * @throws CoreException
- * @throws IOException
- */
- @Before
- public void setUp() throws CoreException {
- project = testProject.getCreaterepoProject();
- assertNotNull(project);
- // before doing anything with SWTBot, activate the main shell
- try {
- bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
- } catch (WidgetNotFoundException e) {
- // cannot activate main shell, continue anyways
- }
- openPropertyPage();
- }
+ /**
+ * Get the CreaterepoProject at the beginning of each test.
+ *
+ * @throws CoreException
+ * @throws IOException
+ */
+ @Before
+ public void setUp() throws CoreException {
+ project = testProject.getCreaterepoProject();
+ assertNotNull(project);
+ // before doing anything with SWTBot, activate the main shell
+ try {
+ bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
+ } catch (WidgetNotFoundException e) {
+ // cannot activate main shell, continue anyways
+ }
+ openPropertyPage();
+ }
- /**
- * Restore the defaults for the general preference page.
- *
- * @throws BackingStoreException
- */
- @After
- public void tearDown() throws BackingStoreException {
- try {
- if (bot.shell(String.format(ICreaterepoTestConstants.PROPERTIES_SHELL,
- ICreaterepoTestConstants.REPO_NAME)).isActive()) {
- bot.shell(String.format(ICreaterepoTestConstants.PROPERTIES_SHELL,
- ICreaterepoTestConstants.REPO_NAME)).close();
- }
- } catch (WidgetNotFoundException e) {
- // cannot close property shell
- }
- testProject.restoreDefaults();
- IEclipsePreferences pref = project.getEclipsePreferences();
- pref.clear();
- pref.flush();
- assertEquals(0, pref.keys().length);
- }
+ /**
+ * Restore the defaults for the general preference page.
+ *
+ * @throws BackingStoreException
+ */
+ @After
+ public void tearDown() throws BackingStoreException {
+ try {
+ if (bot.shell(String.format(ICreaterepoTestConstants.PROPERTIES_SHELL,
+ ICreaterepoTestConstants.REPO_NAME)).isActive()) {
+ bot.shell(String.format(ICreaterepoTestConstants.PROPERTIES_SHELL,
+ ICreaterepoTestConstants.REPO_NAME)).close();
+ }
+ } catch (WidgetNotFoundException e) {
+ // cannot close property shell
+ }
+ testProject.restoreDefaults();
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ pref.clear();
+ pref.flush();
+ assertEquals(0, pref.keys().length);
+ }
- /**
- * Test if all preferences modified in the general createrepo property
- * page persist to project preferences.
- */
- @Test
- public void testChangePreferences() {
- bot.checkBox(Messages.CreaterepoGeneralPropertyPage_projectSettings).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
- bot.radio(ICreaterepoChecksums.SHA512).click();
- bot.radio(ICreaterepoCompressionTypes.XZ).click();
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- openPropertyPage();
- IEclipsePreferences pref = project.getEclipsePreferences();
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED),
- bot.checkBox(Messages.CreaterepoGeneralPropertyPage_projectSettings).isChecked());
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME)),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).isChecked());
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB)),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).isChecked());
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS)),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).isChecked());
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML)),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).isChecked());
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_WORKERS,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_WORKERS)),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).getText()));
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT)),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).getText()));
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS)),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).isChecked());
- assertTrue(bot.radio(pref.get(CreaterepoPreferenceConstants.PREF_CHECKSUM,
- prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_CHECKSUM))).isSelected());
- assertTrue(bot.radio(pref.get(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
- prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE))).isSelected());
- }
+ /**
+ * Test if all preferences modified in the general createrepo property
+ * page persist to project preferences.
+ */
+ @Test
+ public void testChangePreferences() {
+ bot.checkBox(Messages.CreaterepoGeneralPropertyPage_projectSettings).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
+ bot.radio(ICreaterepoChecksums.SHA512).click();
+ bot.radio(ICreaterepoCompressionTypes.XZ).click();
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ openPropertyPage();
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED),
+ bot.checkBox(Messages.CreaterepoGeneralPropertyPage_projectSettings).isChecked());
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME)),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).isChecked());
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB)),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).isChecked());
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS)),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).isChecked());
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML)),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).isChecked());
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_WORKERS,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_WORKERS)),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).getText()));
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT)),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).getText()));
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS)),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).isChecked());
+ assertTrue(bot.radio(pref.get(CreaterepoPreferenceConstants.PREF_CHECKSUM,
+ prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_CHECKSUM))).isSelected());
+ assertTrue(bot.radio(pref.get(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
+ prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE))).isSelected());
+ }
- /**
- * Test if all preferences modified in the general createrepo property
- * page will reset to default.
- */
- @Test
- public void testRestoreDefaults() {
- bot.checkBox(Messages.CreaterepoGeneralPropertyPage_projectSettings).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
- bot.radio(ICreaterepoChecksums.SHA512).click();
- bot.radio(ICreaterepoCompressionTypes.XZ).click();
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- openPropertyPage();
- bot.button(ICreaterepoTestConstants.DEFAULTS).click();
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- IEclipsePreferences pref = project.getEclipsePreferences();
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED));
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME)),
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB)),
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB));
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS)),
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS));
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML)),
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML));
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_WORKERS,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_WORKERS)),
- prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_WORKERS));
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT)),
- prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT));
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS)),
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS));
- assertEquals(pref.get(CreaterepoPreferenceConstants.PREF_CHECKSUM, prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_CHECKSUM)),
- prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_CHECKSUM));
- assertEquals(pref.get(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE)),
- prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE));
- }
+ /**
+ * Test if all preferences modified in the general createrepo property
+ * page will reset to default.
+ */
+ @Test
+ public void testRestoreDefaults() {
+ bot.checkBox(Messages.CreaterepoGeneralPropertyPage_projectSettings).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
+ bot.radio(ICreaterepoChecksums.SHA512).click();
+ bot.radio(ICreaterepoCompressionTypes.XZ).click();
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ openPropertyPage();
+ bot.button(ICreaterepoTestConstants.DEFAULTS).click();
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED));
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME)),
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB)),
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB));
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS)),
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS));
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML)),
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML));
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_WORKERS,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_WORKERS)),
+ prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_WORKERS));
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT)),
+ prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT));
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS)),
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS));
+ assertEquals(pref.get(CreaterepoPreferenceConstants.PREF_CHECKSUM, prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_CHECKSUM)),
+ prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_CHECKSUM));
+ assertEquals(pref.get(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE)),
+ prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE));
+ }
- /**
- * Test if all preferences stay the same as it was after pressing cancel
- * instead of ok.
- */
- @Test
- public void testCancel() {
- bot.checkBox(Messages.CreaterepoGeneralPropertyPage_projectSettings).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
- bot.radio(ICreaterepoChecksums.SHA512).click();
- bot.radio(ICreaterepoCompressionTypes.XZ).click();
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- openPropertyPage();
- bot.button(ICreaterepoTestConstants.DEFAULTS).click();
- bot.button(ICreaterepoTestConstants.CANCEL_BUTTON).click();
- openPropertyPage();
- IEclipsePreferences pref = project.getEclipsePreferences();
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED),
- bot.checkBox(Messages.CreaterepoGeneralPropertyPage_projectSettings).isChecked());
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME)),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).isChecked());
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB)),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).isChecked());
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS)),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).isChecked());
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML)),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).isChecked());
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_WORKERS,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_WORKERS)),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).getText()));
- assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
- prefStore.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT)),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).getText()));
- assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS,
- prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS)),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).isChecked());
- assertTrue(bot.radio(pref.get(CreaterepoPreferenceConstants.PREF_CHECKSUM,
- prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_CHECKSUM))).isSelected());
- assertTrue(bot.radio(pref.get(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
- prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE))).isSelected());
- }
+ /**
+ * Test if all preferences stay the same as it was after pressing cancel
+ * instead of ok.
+ */
+ @Test
+ public void testCancel() {
+ bot.checkBox(Messages.CreaterepoGeneralPropertyPage_projectSettings).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
+ bot.radio(ICreaterepoChecksums.SHA512).click();
+ bot.radio(ICreaterepoCompressionTypes.XZ).click();
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ openPropertyPage();
+ bot.button(ICreaterepoTestConstants.DEFAULTS).click();
+ bot.button(ICreaterepoTestConstants.CANCEL_BUTTON).click();
+ openPropertyPage();
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED),
+ bot.checkBox(Messages.CreaterepoGeneralPropertyPage_projectSettings).isChecked());
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME)),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).isChecked());
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB)),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).isChecked());
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS)),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).isChecked());
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML)),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).isChecked());
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_WORKERS,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_WORKERS)),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).getText()));
+ assertEquals(pref.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
+ prefStore.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT)),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).getText()));
+ assertEquals(pref.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS,
+ prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS)),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).isChecked());
+ assertTrue(bot.radio(pref.get(CreaterepoPreferenceConstants.PREF_CHECKSUM,
+ prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_CHECKSUM))).isSelected());
+ assertTrue(bot.radio(pref.get(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
+ prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE))).isSelected());
+ }
- /**
- * Open the property page.
- */
- private static void openPropertyPage() {
- TestUtils.openPropertyPage(bot, navigator);
- bot.tree().select(ICreaterepoTestConstants.CREATEREPO_CATEGORY);
- }
+ /**
+ * Open the property page.
+ */
+ private static void openPropertyPage() {
+ TestUtils.openPropertyPage(bot, navigator);
+ bot.tree().select(ICreaterepoTestConstants.CREATEREPO_CATEGORY);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoPreferenceInitializationTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoPreferenceInitializationTest.java
index d6352c5992..8f99aa061c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoPreferenceInitializationTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoPreferenceInitializationTest.java
@@ -25,55 +25,55 @@ import org.junit.Test;
*/
public class CreaterepoPreferenceInitializationTest {
- /**
- * Test for the initial preferences to be set for the plugin. Test
- * that if the default value is what the return is, then it failed.
- * The defaults are intentionally wrong to test if correct values are
- * stored incorrectly on initialization.
- */
- @Test
- public void testPreferenceInitialization() {
- IEclipsePreferences node = DefaultScope.INSTANCE.getNode(Activator.PLUGIN_ID);
- assertNotEquals(!CreaterepoPreferenceConstants.DEFAULT_UNIQUE_MD_NAME, node.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
- !CreaterepoPreferenceConstants.DEFAULT_UNIQUE_MD_NAME));
- assertNotEquals(!CreaterepoPreferenceConstants.DEFAULT_GENERATE_DB, node.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
- !CreaterepoPreferenceConstants.DEFAULT_GENERATE_DB));
- assertNotEquals(!CreaterepoPreferenceConstants.DEFAULT_IGNORE_SYMLINKS, node.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
- !CreaterepoPreferenceConstants.DEFAULT_IGNORE_SYMLINKS));
- assertNotEquals(!CreaterepoPreferenceConstants.DEFAULT_PRETTY, node.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
- !CreaterepoPreferenceConstants.DEFAULT_PRETTY));
- assertNotEquals(-1309, node.getInt(CreaterepoPreferenceConstants.PREF_WORKERS, -1309));
- assertNotEquals(!CreaterepoPreferenceConstants.DEFAULT_CHECK_TS, node.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS,
- !CreaterepoPreferenceConstants.DEFAULT_CHECK_TS));
- assertNotEquals(-1309, node.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT, -1309));
- assertNotEquals(CreaterepoPreferenceConstants.DEFAULT_CHECKSUM.concat("test"), node.get(CreaterepoPreferenceConstants.PREF_CHECKSUM, //$NON-NLS-1$
- CreaterepoPreferenceConstants.DEFAULT_CHECKSUM.concat("test"))); //$NON-NLS-1$
- assertNotEquals(CreaterepoPreferenceConstants.DEFAULT_COMPRESS_TYPE.concat("test"), node.get(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, //$NON-NLS-1$
- CreaterepoPreferenceConstants.DEFAULT_COMPRESS_TYPE.concat("test"))); //$NON-NLS-1$
- }
+ /**
+ * Test for the initial preferences to be set for the plugin. Test
+ * that if the default value is what the return is, then it failed.
+ * The defaults are intentionally wrong to test if correct values are
+ * stored incorrectly on initialization.
+ */
+ @Test
+ public void testPreferenceInitialization() {
+ IEclipsePreferences node = DefaultScope.INSTANCE.getNode(Activator.PLUGIN_ID);
+ assertNotEquals(!CreaterepoPreferenceConstants.DEFAULT_UNIQUE_MD_NAME, node.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
+ !CreaterepoPreferenceConstants.DEFAULT_UNIQUE_MD_NAME));
+ assertNotEquals(!CreaterepoPreferenceConstants.DEFAULT_GENERATE_DB, node.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
+ !CreaterepoPreferenceConstants.DEFAULT_GENERATE_DB));
+ assertNotEquals(!CreaterepoPreferenceConstants.DEFAULT_IGNORE_SYMLINKS, node.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
+ !CreaterepoPreferenceConstants.DEFAULT_IGNORE_SYMLINKS));
+ assertNotEquals(!CreaterepoPreferenceConstants.DEFAULT_PRETTY, node.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
+ !CreaterepoPreferenceConstants.DEFAULT_PRETTY));
+ assertNotEquals(-1309, node.getInt(CreaterepoPreferenceConstants.PREF_WORKERS, -1309));
+ assertNotEquals(!CreaterepoPreferenceConstants.DEFAULT_CHECK_TS, node.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS,
+ !CreaterepoPreferenceConstants.DEFAULT_CHECK_TS));
+ assertNotEquals(-1309, node.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT, -1309));
+ assertNotEquals(CreaterepoPreferenceConstants.DEFAULT_CHECKSUM.concat("test"), node.get(CreaterepoPreferenceConstants.PREF_CHECKSUM, //$NON-NLS-1$
+ CreaterepoPreferenceConstants.DEFAULT_CHECKSUM.concat("test"))); //$NON-NLS-1$
+ assertNotEquals(CreaterepoPreferenceConstants.DEFAULT_COMPRESS_TYPE.concat("test"), node.get(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, //$NON-NLS-1$
+ CreaterepoPreferenceConstants.DEFAULT_COMPRESS_TYPE.concat("test"))); //$NON-NLS-1$
+ }
- /**
- * These should be what is stored in the default preferences and what
- * the values should change to if "Restore Defaults" on a preference page
- * is clicked. Make sure it tests are checking values declared in
- * {@linkplain CreaterepoPreferenceConstants}
- */
- @Test
- public void testPreferenceDefaults() {
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_UNIQUE_MD_NAME, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_GENERATE_DB, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_IGNORE_SYMLINKS, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_PRETTY, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_NUM_WORKERS, prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_WORKERS));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_CHECK_TS, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_CHANGELOG_LIMIT, prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_CHECKSUM, prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_CHECKSUM));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_COMPRESS_TYPE, prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_GENERAL_ENABLED, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_DELTA_ENABLE, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_NUM_DELTAS, prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS));
- assertEquals(CreaterepoPreferenceConstants.DEFAULT_MAX_DELTA_SIZE, prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE));
- }
+ /**
+ * These should be what is stored in the default preferences and what
+ * the values should change to if "Restore Defaults" on a preference page
+ * is clicked. Make sure it tests are checking values declared in
+ * {@linkplain CreaterepoPreferenceConstants}
+ */
+ @Test
+ public void testPreferenceDefaults() {
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_UNIQUE_MD_NAME, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_GENERATE_DB, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_IGNORE_SYMLINKS, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_PRETTY, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_NUM_WORKERS, prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_WORKERS));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_CHECK_TS, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_CHANGELOG_LIMIT, prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_CHECKSUM, prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_CHECKSUM));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_COMPRESS_TYPE, prefStore.getDefaultString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_GENERAL_ENABLED, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_DELTA_ENABLE, prefStore.getDefaultBoolean(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_NUM_DELTAS, prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS));
+ assertEquals(CreaterepoPreferenceConstants.DEFAULT_MAX_DELTA_SIZE, prefStore.getDefaultInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE));
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoPreferencePageTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoPreferencePageTest.java
index 43ec6e4bcb..a30a6bce97 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoPreferencePageTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/tests/CreaterepoPreferencePageTest.java
@@ -44,194 +44,194 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class CreaterepoPreferencePageTest {
- private static TestCreaterepoProject testProject;
- private CreaterepoProject project;
- private static SWTWorkbenchBot bot;
+ private static TestCreaterepoProject testProject;
+ private CreaterepoProject project;
+ private static SWTWorkbenchBot bot;
- /**
- * Initialize the test project.
- *
- * @throws CoreException
- */
- @BeforeClass
- public static void setUpBeforeClass() throws CoreException {
- testProject = new TestCreaterepoProject();
- assertTrue(testProject.getProject().exists());
- bot = new SWTWorkbenchBot();
- testProject.restoreDefaults();
- try {
- bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
- } catch (WidgetNotFoundException e) {
- // cannot activate main shell, continue anyways
- }
- }
+ /**
+ * Initialize the test project.
+ *
+ * @throws CoreException
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws CoreException {
+ testProject = new TestCreaterepoProject();
+ assertTrue(testProject.getProject().exists());
+ bot = new SWTWorkbenchBot();
+ testProject.restoreDefaults();
+ try {
+ bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
+ } catch (WidgetNotFoundException e) {
+ // cannot activate main shell, continue anyways
+ }
+ }
- /**
- * Delete the project when tests are done.
- *
- * @throws CoreException
- */
- @AfterClass
- public static void tearDownAfterClass() throws CoreException {
- testProject.dispose();
- assertFalse(testProject.getProject().exists());
- }
+ /**
+ * Delete the project when tests are done.
+ *
+ * @throws CoreException
+ */
+ @AfterClass
+ public static void tearDownAfterClass() throws CoreException {
+ testProject.dispose();
+ assertFalse(testProject.getProject().exists());
+ }
- /**
- * Get the CreaterepoProject at the beginning of each test.
- *
- * @throws CoreException
- * @throws IOException
- */
- @Before
- public void setUp() throws CoreException {
- project = testProject.getCreaterepoProject();
- assertNotNull(project);
- // before doing anything with SWTBot, activate the main shell
- try {
- bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
- } catch (WidgetNotFoundException e) {
- // cannot activate main shell, continue anyways
- }
- openPreferencePage();
- }
+ /**
+ * Get the CreaterepoProject at the beginning of each test.
+ *
+ * @throws CoreException
+ * @throws IOException
+ */
+ @Before
+ public void setUp() throws CoreException {
+ project = testProject.getCreaterepoProject();
+ assertNotNull(project);
+ // before doing anything with SWTBot, activate the main shell
+ try {
+ bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
+ } catch (WidgetNotFoundException e) {
+ // cannot activate main shell, continue anyways
+ }
+ openPreferencePage();
+ }
- /**
- * Restore the defaults for the general preference page.
- */
- @After
- public void tearDown() {
- try {
- if (bot.shell(ICreaterepoTestConstants.PREFERENCES).isActive()) {
- bot.shell(ICreaterepoTestConstants.PREFERENCES).close();
- }
- } catch (WidgetNotFoundException e) {
- // cannot close preference shell
- }
- testProject.restoreDefaults();
- }
+ /**
+ * Restore the defaults for the general preference page.
+ */
+ @After
+ public void tearDown() {
+ try {
+ if (bot.shell(ICreaterepoTestConstants.PREFERENCES).isActive()) {
+ bot.shell(ICreaterepoTestConstants.PREFERENCES).close();
+ }
+ } catch (WidgetNotFoundException e) {
+ // cannot close preference shell
+ }
+ testProject.restoreDefaults();
+ }
- /**
- * Test if all preferences modified in the general createrepo preference
- * page persist to workspace preferences.
- */
- @Test
- public void testChangePreferences() {
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
- bot.radio(ICreaterepoChecksums.SHA512).click();
- bot.radio(ICreaterepoCompressionTypes.XZ).click();
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- openPreferencePage();
- // verify the changes
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).isChecked());
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).isChecked());
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).isChecked());
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).isChecked());
- assertEquals(prefStore.getInt(CreaterepoPreferenceConstants.PREF_WORKERS),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).getText()));
- assertEquals(prefStore.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).getText()));
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).isChecked());
- assertTrue(bot.radio(prefStore.getString(CreaterepoPreferenceConstants.PREF_CHECKSUM)).isSelected());
- assertTrue(bot.radio(prefStore.getString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE)).isSelected());
- }
+ /**
+ * Test if all preferences modified in the general createrepo preference
+ * page persist to workspace preferences.
+ */
+ @Test
+ public void testChangePreferences() {
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
+ bot.radio(ICreaterepoChecksums.SHA512).click();
+ bot.radio(ICreaterepoCompressionTypes.XZ).click();
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ openPreferencePage();
+ // verify the changes
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).isChecked());
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).isChecked());
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).isChecked());
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).isChecked());
+ assertEquals(prefStore.getInt(CreaterepoPreferenceConstants.PREF_WORKERS),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).getText()));
+ assertEquals(prefStore.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).getText()));
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).isChecked());
+ assertTrue(bot.radio(prefStore.getString(CreaterepoPreferenceConstants.PREF_CHECKSUM)).isSelected());
+ assertTrue(bot.radio(prefStore.getString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE)).isSelected());
+ }
- /**
- * Test if the restore defaults button resets the workspace preference settings back
- * to its defaults.
- */
- @Test
- public void testRestoreDefaults() {
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
- bot.radio(ICreaterepoChecksums.SHA512).click();
- bot.radio(ICreaterepoCompressionTypes.XZ).click();
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- openPreferencePage();
- bot.button(ICreaterepoTestConstants.DEFAULTS).click();
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- // veryify the changes
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_GENERATE_DB));
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS));
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_PRETTY_XML));
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_WORKERS));
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT));
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_CHECK_TS));
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_CHECKSUM));
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE));
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
- assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
- }
+ /**
+ * Test if the restore defaults button resets the workspace preference settings back
+ * to its defaults.
+ */
+ @Test
+ public void testRestoreDefaults() {
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
+ bot.radio(ICreaterepoChecksums.SHA512).click();
+ bot.radio(ICreaterepoCompressionTypes.XZ).click();
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ openPreferencePage();
+ bot.button(ICreaterepoTestConstants.DEFAULTS).click();
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ // veryify the changes
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_GENERATE_DB));
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS));
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_PRETTY_XML));
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_WORKERS));
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT));
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_CHECK_TS));
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_CHECKSUM));
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE));
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
+ assertTrue(prefStore.isDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
+ }
- /**
- * Test if all preferences stay the same as it was after pressing cancel
- * instead of ok.
- */
- @Test
- public void testCancel() {
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
- bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
- bot.radio(ICreaterepoChecksums.SHA512).click();
- bot.radio(ICreaterepoCompressionTypes.XZ).click();
- bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
- openPreferencePage();
- bot.button(ICreaterepoTestConstants.DEFAULTS).click();
- bot.button(ICreaterepoTestConstants.CANCEL_BUTTON).click();
- openPreferencePage();
- // verify the changes
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).isChecked());
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).isChecked());
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).isChecked());
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).isChecked());
- assertEquals(prefStore.getInt(CreaterepoPreferenceConstants.PREF_WORKERS),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).getText()));
- assertEquals(prefStore.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT),
- Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).getText()));
- assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS),
- bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).isChecked());
- assertTrue(bot.radio(prefStore.getString(CreaterepoPreferenceConstants.PREF_CHECKSUM)).isSelected());
- assertTrue(bot.radio(prefStore.getString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE)).isSelected());
- }
+ /**
+ * Test if all preferences stay the same as it was after pressing cancel
+ * instead of ok.
+ */
+ @Test
+ public void testCancel() {
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).click();
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).click();
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).setText("9"); //$NON-NLS-1$
+ bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).setText("13"); //$NON-NLS-1$
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).click();
+ bot.radio(ICreaterepoChecksums.SHA512).click();
+ bot.radio(ICreaterepoCompressionTypes.XZ).click();
+ bot.button(ICreaterepoTestConstants.OK_BUTTON).click();
+ openPreferencePage();
+ bot.button(ICreaterepoTestConstants.DEFAULTS).click();
+ bot.button(ICreaterepoTestConstants.CANCEL_BUTTON).click();
+ openPreferencePage();
+ // verify the changes
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanChecksumName).isChecked());
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanGenerateSQLDB).isChecked());
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks).isChecked());
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanPrettyXML).isChecked());
+ assertEquals(prefStore.getInt(CreaterepoPreferenceConstants.PREF_WORKERS),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numWorkers).getText()));
+ assertEquals(prefStore.getInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT),
+ Integer.parseInt(bot.textWithLabel(Messages.CreaterepoPreferencePage_numChangelogLimit).getText()));
+ assertEquals(prefStore.getBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS),
+ bot.checkBox(Messages.CreaterepoPreferencePage_booleanCheckTS).isChecked());
+ assertTrue(bot.radio(prefStore.getString(CreaterepoPreferenceConstants.PREF_CHECKSUM)).isSelected());
+ assertTrue(bot.radio(prefStore.getString(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE)).isSelected());
+ }
- /**
- * Open the preference page.
- */
- private static void openPreferencePage() {
- // open the preferences window
- bot.menu(ICreaterepoTestConstants.WINDOW).menu(ICreaterepoTestConstants.PREFERENCES).click();
- SWTBotShell shell = bot.shell(ICreaterepoTestConstants.PREFERENCES);
- shell.activate();
- bot.tree().select(ICreaterepoTestConstants.CREATEREPO_CATEGORY);
- }
+ /**
+ * Open the preference page.
+ */
+ private static void openPreferencePage() {
+ // open the preferences window
+ bot.menu(ICreaterepoTestConstants.WINDOW).menu(ICreaterepoTestConstants.PREFERENCES).click();
+ SWTBotShell shell = bot.shell(ICreaterepoTestConstants.PREFERENCES);
+ shell.activate();
+ bot.tree().select(ICreaterepoTestConstants.CREATEREPO_CATEGORY);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tests/CreaterepoCommandCreatorTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tests/CreaterepoCommandCreatorTest.java
index 282eb277b5..b6e382cb7d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tests/CreaterepoCommandCreatorTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tests/CreaterepoCommandCreatorTest.java
@@ -44,237 +44,237 @@ import org.osgi.service.prefs.BackingStoreException;
*/
public class CreaterepoCommandCreatorTest {
- private static TestCreaterepoProject testProject;
- private CreaterepoProject project;
+ private static TestCreaterepoProject testProject;
+ private CreaterepoProject project;
- /**
- * Initialize the project.
- *
- * @throws Exception
- */
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- testProject = new TestCreaterepoProject();
- assertTrue(testProject.getProject().exists());
- }
+ /**
+ * Initialize the project.
+ *
+ * @throws Exception
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ testProject = new TestCreaterepoProject();
+ assertTrue(testProject.getProject().exists());
+ }
- /**
- * Delete the project when tests are done.
- *
- * @throws CoreException
- */
- @AfterClass
- public static void tearDownAfterClass() throws Exception {
- testProject.dispose();
- assertFalse(testProject.getProject().exists());
- }
+ /**
+ * Delete the project when tests are done.
+ *
+ * @throws CoreException
+ */
+ @AfterClass
+ public static void tearDownAfterClass() throws Exception {
+ testProject.dispose();
+ assertFalse(testProject.getProject().exists());
+ }
- /**
- * Get the CreaterepoProject at the beginning of each test.
- *
- * @throws CoreException
- */
- @Before
- public void setUp() throws Exception {
- project = testProject.getCreaterepoProject();
- assertNotNull(project);
- }
+ /**
+ * Get the CreaterepoProject at the beginning of each test.
+ *
+ * @throws CoreException
+ */
+ @Before
+ public void setUp() throws Exception {
+ project = testProject.getCreaterepoProject();
+ assertNotNull(project);
+ }
- /**
- * Clear the preferences after each test.
- *
- * @throws BackingStoreException
- */
- @After
- public void tearDown() throws Exception {
- IEclipsePreferences pref = project.getEclipsePreferences();
- pref.clear();
- pref.flush();
- testProject.restoreDefaults();
- assertEquals(0, pref.keys().length);
- }
+ /**
+ * Clear the preferences after each test.
+ *
+ * @throws BackingStoreException
+ */
+ @After
+ public void tearDown() throws Exception {
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ pref.clear();
+ pref.flush();
+ testProject.restoreDefaults();
+ assertEquals(0, pref.keys().length);
+ }
- /**
- * Preference set should be shown in the command arguments created.
- *
- * @throws BackingStoreException
- */
- @Test
- public void testCommandArgumentsWorkspacePreferences() {
- setWorkspacePreferences();
- CreaterepoCommandCreator commandCreator = new CreaterepoCommandCreator(project.getEclipsePreferences());
- List<String> commands = commandCreator.getCommands();
- assertFalse(commands.isEmpty());
- String switchesToAdd = createStringFromList(commands);
- // waldo should not be found
- assertEquals(0, findCommandSwitch(switchesToAdd, "waldo")); //$NON-NLS-1$
- // deltas was not set
- assertEquals(0, findCommandSwitch(switchesToAdd, "--deltas")); //$NON-NLS-1$
- // these switches can be found set in setWorkspacePreferences()
- assertEquals(1, findCommandSwitch(switchesToAdd, "--simple-md-filenames")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--no-database")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--skip-symlinks")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--pretty")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--workers\\s+\\d+")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--checkts")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--changelog-limit\\s+\\d+")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--checksum\\s+\\S+")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--compress-type\\s+\\S+")); //$NON-NLS-1$
- // intentionally put multiple occurences of a switch that should only occur once
- String testDuplicate = "--changelog-limit 31 --changelog-limit 5 --changelog-limit 2"; //$NON-NLS-1$
- assertTrue(findCommandSwitch(testDuplicate, "--changelog-limit\\s+\\d+") > 1); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--no-database")); //$NON-NLS-1$
- }
+ /**
+ * Preference set should be shown in the command arguments created.
+ *
+ * @throws BackingStoreException
+ */
+ @Test
+ public void testCommandArgumentsWorkspacePreferences() {
+ setWorkspacePreferences();
+ CreaterepoCommandCreator commandCreator = new CreaterepoCommandCreator(project.getEclipsePreferences());
+ List<String> commands = commandCreator.getCommands();
+ assertFalse(commands.isEmpty());
+ String switchesToAdd = createStringFromList(commands);
+ // waldo should not be found
+ assertEquals(0, findCommandSwitch(switchesToAdd, "waldo")); //$NON-NLS-1$
+ // deltas was not set
+ assertEquals(0, findCommandSwitch(switchesToAdd, "--deltas")); //$NON-NLS-1$
+ // these switches can be found set in setWorkspacePreferences()
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--simple-md-filenames")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--no-database")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--skip-symlinks")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--pretty")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--workers\\s+\\d+")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--checkts")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--changelog-limit\\s+\\d+")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--checksum\\s+\\S+")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--compress-type\\s+\\S+")); //$NON-NLS-1$
+ // intentionally put multiple occurences of a switch that should only occur once
+ String testDuplicate = "--changelog-limit 31 --changelog-limit 5 --changelog-limit 2"; //$NON-NLS-1$
+ assertTrue(findCommandSwitch(testDuplicate, "--changelog-limit\\s+\\d+") > 1); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--no-database")); //$NON-NLS-1$
+ }
- /**
- * Set test workspace preferences.
- */
- private static void setWorkspacePreferences() {
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- // --simple-md-filenames
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME, false);
- // --no-database
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_GENERATE_DB, false);
- // --skip-symlinks
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS, true);
- // --pretty
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_PRETTY_XML, true);
- // --workers 73
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_WORKERS, 73);
- // --checkts
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_CHECK_TS, true);
- // --changelog-limit 31
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT, 31);
- // --checksum md5
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_CHECKSUM, ICreaterepoChecksums.MD5);
- // --compress-type gz
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, ICreaterepoCompressionTypes.GZ);
- }
+ /**
+ * Set test workspace preferences.
+ */
+ private static void setWorkspacePreferences() {
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ // --simple-md-filenames
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME, false);
+ // --no-database
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_GENERATE_DB, false);
+ // --skip-symlinks
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS, true);
+ // --pretty
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_PRETTY_XML, true);
+ // --workers 73
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_WORKERS, 73);
+ // --checkts
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_CHECK_TS, true);
+ // --changelog-limit 31
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT, 31);
+ // --checksum md5
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_CHECKSUM, ICreaterepoChecksums.MD5);
+ // --compress-type gz
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, ICreaterepoCompressionTypes.GZ);
+ }
- /**
- * Preference set should be shown in the command arguments created.
- *
- * @throws BackingStoreException
- */
- @Test
- public void testCommandArgumentsProjectPreferences() throws BackingStoreException {
- setProjectPreferences();
- CreaterepoCommandCreator commandCreator = new CreaterepoCommandCreator(project.getEclipsePreferences());
- List<String> commands = commandCreator.getCommands();
- assertFalse(commands.isEmpty());
- String switchesToAdd = createStringFromList(commands);
- // waldo should not be found
- assertEquals(0, findCommandSwitch(switchesToAdd, "waldo")); //$NON-NLS-1$
- // make sure that the workspace preference is using --simple-md-filenames
- assertFalse(Activator.getDefault().getPreferenceStore().getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
- // make sure project properties are being used
- assertTrue(Activator.isProjectPrefEnabled());
- // simple should not be found because project properties are enabled and the project properties set
- // it as unique
- assertEquals(0, findCommandSwitch(switchesToAdd, "--simple-md-filenames")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--unique-md-filenames")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--no-database")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--skip-symlinks")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--workers\\s+\\d+")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--checkts")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--changelog-limit\\s+\\d+")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--checksum\\s+\\S+")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--compress-type\\s+\\S+")); //$NON-NLS-1$
- assertTrue(Activator.isDeltaPrefEnabled());
- assertEquals(1, findCommandSwitch(switchesToAdd, "--deltas")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--num-deltas\\s+\\d+")); //$NON-NLS-1$
- assertEquals(1, findCommandSwitch(switchesToAdd, "--max-delta-rpm-size\\s+\\d+")); //$NON-NLS-1$
- // 2 directories were specified
- assertEquals(2, findCommandSwitch(switchesToAdd, "--oldpackagedirs\\s+\\S+")); //$NON-NLS-1$
- // 4 distro tags were specified
- assertEquals(4, findCommandSwitch(switchesToAdd, "--distro\\s+\\S+")); //$NON-NLS-1$
- // no content tags were specified, but it is left over from removing a content tag in the metadata page
- // it should not appear
- assertEquals(0, findCommandSwitch(switchesToAdd, "--content\\s+\\S+")); //$NON-NLS-1$
- // pretty setting was not set
- assertEquals(0, findCommandSwitch(switchesToAdd, "--pretty")); //$NON-NLS-1$
- }
+ /**
+ * Preference set should be shown in the command arguments created.
+ *
+ * @throws BackingStoreException
+ */
+ @Test
+ public void testCommandArgumentsProjectPreferences() throws BackingStoreException {
+ setProjectPreferences();
+ CreaterepoCommandCreator commandCreator = new CreaterepoCommandCreator(project.getEclipsePreferences());
+ List<String> commands = commandCreator.getCommands();
+ assertFalse(commands.isEmpty());
+ String switchesToAdd = createStringFromList(commands);
+ // waldo should not be found
+ assertEquals(0, findCommandSwitch(switchesToAdd, "waldo")); //$NON-NLS-1$
+ // make sure that the workspace preference is using --simple-md-filenames
+ assertFalse(Activator.getDefault().getPreferenceStore().getBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME));
+ // make sure project properties are being used
+ assertTrue(Activator.isProjectPrefEnabled());
+ // simple should not be found because project properties are enabled and the project properties set
+ // it as unique
+ assertEquals(0, findCommandSwitch(switchesToAdd, "--simple-md-filenames")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--unique-md-filenames")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--no-database")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--skip-symlinks")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--workers\\s+\\d+")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--checkts")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--changelog-limit\\s+\\d+")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--checksum\\s+\\S+")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--compress-type\\s+\\S+")); //$NON-NLS-1$
+ assertTrue(Activator.isDeltaPrefEnabled());
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--deltas")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--num-deltas\\s+\\d+")); //$NON-NLS-1$
+ assertEquals(1, findCommandSwitch(switchesToAdd, "--max-delta-rpm-size\\s+\\d+")); //$NON-NLS-1$
+ // 2 directories were specified
+ assertEquals(2, findCommandSwitch(switchesToAdd, "--oldpackagedirs\\s+\\S+")); //$NON-NLS-1$
+ // 4 distro tags were specified
+ assertEquals(4, findCommandSwitch(switchesToAdd, "--distro\\s+\\S+")); //$NON-NLS-1$
+ // no content tags were specified, but it is left over from removing a content tag in the metadata page
+ // it should not appear
+ assertEquals(0, findCommandSwitch(switchesToAdd, "--content\\s+\\S+")); //$NON-NLS-1$
+ // pretty setting was not set
+ assertEquals(0, findCommandSwitch(switchesToAdd, "--pretty")); //$NON-NLS-1$
+ }
- /**
- * Set test project preferences.
- *
- * @throws BackingStoreException
- */
- private void setProjectPreferences() throws BackingStoreException {
- // enable use of project preferences
- IPreferenceStore prefStore = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED, true);
- // --simple-md-filenames should not be used because project properties are enabled
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME, false);
- // set the project preferences
- IEclipsePreferences pref = project.getEclipsePreferences();
- // --unique-md-filenames
- pref.putBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME, true);
- // --no-database
- pref.putBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB, false);
- // --skip-symlinks
- pref.putBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS, true);
- // --pretty
- pref.putBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML, false);
- // --workers 13
- pref.putInt(CreaterepoPreferenceConstants.PREF_WORKERS, 13);
- // --checkts
- pref.putBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS, true);
- // --changelog-limit 37
- pref.putInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT, 37);
- // --checksum sha512
- pref.put(CreaterepoPreferenceConstants.PREF_CHECKSUM, ICreaterepoChecksums.SHA512);
- // --compress-type xz
- pref.put(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, ICreaterepoCompressionTypes.XZ);
- // enable deltas
- // --deltas
- prefStore.setValue(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE, true);
- // --num-deltas 13
- pref.putInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS, 13);
- // --max-delta-rpm-size 37
- pref.putInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE, 37);
- // --oldpackagedirs /tmp --oldpackagedirs /home
- pref.put(CreaterepoPreferenceConstants.PREF_OLD_PACKAGE_DIRS, "/tmp;/home"); //$NON-NLS-1$
- // --distro cpeid,distrotag --distro tag2 --distro tag3 --distro tag4
- pref.put(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, "cpeid,distrotag;tag2;tag3;tag4"); //$NON-NLS-1$
- pref.put(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, ""); //$NON-NLS-1$
- pref.flush();
- }
+ /**
+ * Set test project preferences.
+ *
+ * @throws BackingStoreException
+ */
+ private void setProjectPreferences() throws BackingStoreException {
+ // enable use of project preferences
+ IPreferenceStore prefStore = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED, true);
+ // --simple-md-filenames should not be used because project properties are enabled
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME, false);
+ // set the project preferences
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ // --unique-md-filenames
+ pref.putBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME, true);
+ // --no-database
+ pref.putBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB, false);
+ // --skip-symlinks
+ pref.putBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS, true);
+ // --pretty
+ pref.putBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML, false);
+ // --workers 13
+ pref.putInt(CreaterepoPreferenceConstants.PREF_WORKERS, 13);
+ // --checkts
+ pref.putBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS, true);
+ // --changelog-limit 37
+ pref.putInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT, 37);
+ // --checksum sha512
+ pref.put(CreaterepoPreferenceConstants.PREF_CHECKSUM, ICreaterepoChecksums.SHA512);
+ // --compress-type xz
+ pref.put(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, ICreaterepoCompressionTypes.XZ);
+ // enable deltas
+ // --deltas
+ prefStore.setValue(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE, true);
+ // --num-deltas 13
+ pref.putInt(CreaterepoPreferenceConstants.PREF_NUM_DELTAS, 13);
+ // --max-delta-rpm-size 37
+ pref.putInt(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE, 37);
+ // --oldpackagedirs /tmp --oldpackagedirs /home
+ pref.put(CreaterepoPreferenceConstants.PREF_OLD_PACKAGE_DIRS, "/tmp;/home"); //$NON-NLS-1$
+ // --distro cpeid,distrotag --distro tag2 --distro tag3 --distro tag4
+ pref.put(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, "cpeid,distrotag;tag2;tag3;tag4"); //$NON-NLS-1$
+ pref.put(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, ""); //$NON-NLS-1$
+ pref.flush();
+ }
- /**
- * Create a string from a given list of strings.
- *
- * @param list A list of strings.
- * @return A string.
- */
- private static String createStringFromList(List<String> list) {
- String str = ""; //$NON-NLS-1$
- if (!list.isEmpty()) {
- for (String temp : list) {
- if (!temp.isEmpty()) {
- str = str.concat(temp).concat(" "); //$NON-NLS-1$
- }
- }
- str = str.trim();
- }
- return str;
- }
+ /**
+ * Create a string from a given list of strings.
+ *
+ * @param list A list of strings.
+ * @return A string.
+ */
+ private static String createStringFromList(List<String> list) {
+ String str = ""; //$NON-NLS-1$
+ if (!list.isEmpty()) {
+ for (String temp : list) {
+ if (!temp.isEmpty()) {
+ str = str.concat(temp).concat(" "); //$NON-NLS-1$
+ }
+ }
+ str = str.trim();
+ }
+ return str;
+ }
- /**
- * Try and find if a command string has a specific switch in it.
- *
- * @param command The command string.
- * @param switchPattern The switch to look for.
- * @return 0 if switch cannot be found, 1 if single found, >1 if multiple found.
- */
- private static int findCommandSwitch(String command, String switchPattern) {
- int matches = 0;
- Pattern pattern = Pattern.compile(switchPattern, Pattern.CASE_INSENSITIVE);
- Matcher variableMatcher = pattern.matcher(command);
- while (variableMatcher.find()) {
- matches++;
- }
- return matches;
- }
+ /**
+ * Try and find if a command string has a specific switch in it.
+ *
+ * @param command The command string.
+ * @param switchPattern The switch to look for.
+ * @return 0 if switch cannot be found, 1 if single found, >1 if multiple found.
+ */
+ private static int findCommandSwitch(String command, String switchPattern) {
+ int matches = 0;
+ Pattern pattern = Pattern.compile(switchPattern, Pattern.CASE_INSENSITIVE);
+ Matcher variableMatcher = pattern.matcher(command);
+ while (variableMatcher.find()) {
+ matches++;
+ }
+ return matches;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tests/CreaterepoTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tests/CreaterepoTest.java
index f895c4fcfa..2c4fc1ec55 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tests/CreaterepoTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tests/CreaterepoTest.java
@@ -41,80 +41,80 @@ import org.osgi.service.prefs.BackingStoreException;
*/
public class CreaterepoTest {
- private static TestCreaterepoProject testProject;
- private CreaterepoProject project;
- private MessageConsole console;
+ private static TestCreaterepoProject testProject;
+ private CreaterepoProject project;
+ private MessageConsole console;
- /**
- * Initialize the test project. Will fail immediately if it cannot find
- * the createrepo command.
- *
- * @throws CoreException
- * @throws IOException
- * @throws InterruptedException
- */
- @BeforeClass
- public static void setUpBeforeClass() throws CoreException, IOException, InterruptedException {
- BufferedProcessInputStream bpis = Utils.runCommandToInputStream("which", "createrepo"); //$NON-NLS-1$ //$NON-NLS-2$
- if (bpis.getExitValue() == 1) {
- fail("Failed due to system not having the 'createrepo' command, or it cannot be found."); //$NON-NLS-1$
- }
- testProject = new TestCreaterepoProject();
- assertTrue(testProject.getProject().exists());
- }
+ /**
+ * Initialize the test project. Will fail immediately if it cannot find
+ * the createrepo command.
+ *
+ * @throws CoreException
+ * @throws IOException
+ * @throws InterruptedException
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws CoreException, IOException, InterruptedException {
+ BufferedProcessInputStream bpis = Utils.runCommandToInputStream("which", "createrepo"); //$NON-NLS-1$ //$NON-NLS-2$
+ if (bpis.getExitValue() == 1) {
+ fail("Failed due to system not having the 'createrepo' command, or it cannot be found."); //$NON-NLS-1$
+ }
+ testProject = new TestCreaterepoProject();
+ assertTrue(testProject.getProject().exists());
+ }
- /**
- * Delete the project when tests are done.
- *
- * @throws CoreException
- */
- @AfterClass
- public static void tearDownAfterClass() throws CoreException {
- testProject.dispose();
- assertFalse(testProject.getProject().exists());
- }
+ /**
+ * Delete the project when tests are done.
+ *
+ * @throws CoreException
+ */
+ @AfterClass
+ public static void tearDownAfterClass() throws CoreException {
+ testProject.dispose();
+ assertFalse(testProject.getProject().exists());
+ }
- /**
- * Get the CreaterepoProject at the beginning of each test, as
- * well as create the console.
- *
- * @throws CoreException
- */
- @Before
- public void setUp() throws CoreException {
- project = testProject.getCreaterepoProject();
- assertNotNull(project);
- console = new MessageConsole("testConsole", null, null, true); //$NON-NLS-1$
- }
+ /**
+ * Get the CreaterepoProject at the beginning of each test, as
+ * well as create the console.
+ *
+ * @throws CoreException
+ */
+ @Before
+ public void setUp() throws CoreException {
+ project = testProject.getCreaterepoProject();
+ assertNotNull(project);
+ console = new MessageConsole("testConsole", null, null, true); //$NON-NLS-1$
+ }
- /**
- * Clear the preferences after each test and destroy the console.
- *
- * @throws BackingStoreException
- */
- @After
- public void tearDown() throws BackingStoreException {
- IEclipsePreferences pref = project.getEclipsePreferences();
- pref.clear();
- pref.flush();
- assertEquals(0, pref.keys().length);
- console.destroy();
- }
+ /**
+ * Clear the preferences after each test and destroy the console.
+ *
+ * @throws BackingStoreException
+ */
+ @After
+ public void tearDown() throws BackingStoreException {
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ pref.clear();
+ pref.flush();
+ assertEquals(0, pref.keys().length);
+ console.destroy();
+ }
- /**
- * Test a simple createrepo execution taking in no extra commands.
- *
- * @throws CoreException
- */
- @Test
- public void testSimpleCreaterepoExecution() throws CoreException {
- Createrepo command = new Createrepo();
- IStatus status = command.execute(console.newMessageStream(),
- project, new ArrayList<String>());
- if (status.getCode() == IStatus.ERROR) {
- fail("Possibly failed due to system not having the 'createrepo' command, or it cannot be found."); //$NON-NLS-1$
- }
- assertEquals(IStatus.OK, status.getCode());
- }
+ /**
+ * Test a simple createrepo execution taking in no extra commands.
+ *
+ * @throws CoreException
+ */
+ @Test
+ public void testSimpleCreaterepoExecution() throws CoreException {
+ Createrepo command = new Createrepo();
+ IStatus status = command.execute(console.newMessageStream(),
+ project, new ArrayList<String>());
+ if (status.getCode() == IStatus.ERROR) {
+ fail("Possibly failed due to system not having the 'createrepo' command, or it cannot be found."); //$NON-NLS-1$
+ }
+ assertEquals(IStatus.OK, status.getCode());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/tests/CreaterepoTreeCategoryTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/tests/CreaterepoTreeCategoryTest.java
index 97e601a815..8c0c8859e8 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/tests/CreaterepoTreeCategoryTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/tests/CreaterepoTreeCategoryTest.java
@@ -23,29 +23,29 @@ import org.junit.Test;
*/
public class CreaterepoTreeCategoryTest {
- private static final String CATEGORY_NAME = "test"; //$NON-NLS-1$
- private static final String TAG1 = "tag1"; //$NON-NLS-1$
- private static final String TAG2 = "tag2"; //$NON-NLS-1$
+ private static final String CATEGORY_NAME = "test"; //$NON-NLS-1$
+ private static final String TAG1 = "tag1"; //$NON-NLS-1$
+ private static final String TAG2 = "tag2"; //$NON-NLS-1$
- /**
- * Test the tree category to make sure it initializes and stores tags properly.
- * Tags must be unique, so the category should not add tags that already exist
- * within the category.
- */
- @Test
- public void testCreaterepoTreeCategory() {
- List<String> tagsToCheck = new ArrayList<>();
- tagsToCheck.add(TAG1);
- tagsToCheck.add(TAG2);
- CreaterepoTreeCategory categoryTest = new CreaterepoTreeCategory(CATEGORY_NAME);
- assertEquals(0, categoryTest.getTags().size());
- assertEquals(CATEGORY_NAME, categoryTest.getName());
- categoryTest.addTag(TAG2);
- assertEquals(1, categoryTest.getTags().size());
- assertEquals(TAG2, categoryTest.getTags().get(0));
- categoryTest.addAllTags(tagsToCheck);
- // TAG2 should not be added again, hence size should = 2
- assertEquals(2, categoryTest.getTags().size());
- }
+ /**
+ * Test the tree category to make sure it initializes and stores tags properly.
+ * Tags must be unique, so the category should not add tags that already exist
+ * within the category.
+ */
+ @Test
+ public void testCreaterepoTreeCategory() {
+ List<String> tagsToCheck = new ArrayList<>();
+ tagsToCheck.add(TAG1);
+ tagsToCheck.add(TAG2);
+ CreaterepoTreeCategory categoryTest = new CreaterepoTreeCategory(CATEGORY_NAME);
+ assertEquals(0, categoryTest.getTags().size());
+ assertEquals(CATEGORY_NAME, categoryTest.getName());
+ categoryTest.addTag(TAG2);
+ assertEquals(1, categoryTest.getTags().size());
+ assertEquals(TAG2, categoryTest.getTags().get(0));
+ categoryTest.addAllTags(tagsToCheck);
+ // TAG2 should not be added again, hence size should = 2
+ assertEquals(2, categoryTest.getTags().size());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/tests/CreaterepoTreeTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/tests/CreaterepoTreeTest.java
index 40e5d498e3..419cf4c7b6 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/tests/CreaterepoTreeTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/tests/CreaterepoTreeTest.java
@@ -48,188 +48,188 @@ import org.osgi.service.prefs.BackingStoreException;
*/
public class CreaterepoTreeTest {
- /*
- * Tags being used to test with.
- */
- private static final String[] DISTRO_TAGS =
- {"tag1","tag2","tag3","tag4","tag5"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- private static final String[] CONTENT_TAGS = {};
- private static final String[] REPO_TAGS = {"tag1"}; //$NON-NLS-1$
-
- /*
- * Categories and how many tags per categories to test with.
- */
- private static final Map<String, Integer> CORRECT_CATEGORIES;
- static {
- Map<String, Integer> temp = new HashMap<>();
- temp.put(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, DISTRO_TAGS.length);
- temp.put(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, CONTENT_TAGS.length);
- temp.put(CreaterepoPreferenceConstants.PREF_REPO_TAG, REPO_TAGS.length);
- CORRECT_CATEGORIES = Collections.unmodifiableMap(temp);
- }
-
- private static TestCreaterepoProject testProject;
- private CreaterepoProject project;
- private TreeViewer viewer;
- private Tree tree;
-
- /**
- * Initialize the test project.
- *
- * @throws CoreException
- */
- @BeforeClass
- public static void setUpBeforeClass() throws CoreException {
- testProject = new TestCreaterepoProject();
- assertTrue(testProject.getProject().exists());
- }
-
- /**
- * Delete the project when tests are done.
- *
- * @throws CoreException
- */
- @AfterClass
- public static void tearDownAfterClass() throws CoreException {
- testProject.dispose();
- assertFalse(testProject.getProject().exists());
- }
-
- /**
- * Get the CreaterepoProject at the beginning of each test.
- *
- * @throws CoreException
- */
- @Before
- public void setUp() throws CoreException {
- project = testProject.getCreaterepoProject();
- assertNotNull(project);
- }
-
- /**
- * Clear the preferences after each test.
- *
- * @throws BackingStoreException
- */
- @After
- public void tearDown() throws BackingStoreException {
- IEclipsePreferences pref = project.getEclipsePreferences();
- pref.clear();
- pref.flush();
- assertEquals(0, pref.keys().length);
- }
-
- /**
- * Test if the treeviewer is initialized properly with the correct labels.
- */
- @Test
- public void testTreeViewerInitialization() {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- initViewer();
- // there should only be 3 categories
- assertEquals(3, tree.getItemCount());
- // and these should be the correct categories
- for (TreeItem treeItem : tree.getItems()) {
- assertTrue(inCategory(treeItem.getText()));
- }
- }
- });
- }
-
- /**
- * Test if the treeviewer properly loads the preferences.
- *
- * @throws BackingStoreException
- */
- @Test
- public void testTreeViewerPreferences() throws BackingStoreException {
- addTestPreferences();
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- initViewer();
- for (TreeItem treeItem : tree.getItems()) {
- if (treeItem.getData() instanceof CreaterepoTreeCategory) {
- CreaterepoTreeCategory category = (CreaterepoTreeCategory) treeItem.getData();
- // make sure the categories are still correct
- assertTrue(CORRECT_CATEGORIES.containsKey(category.getName()));
- // assert that the number of tags stored is the correct amount
- assertEquals(CORRECT_CATEGORIES.get(category.getName()).intValue(), category.getTags().size());
- }
- }
- // do 1 test to make sure the tags were properly stored/loaded
- for (TreeItem treeItem : tree.getItems()) {
- if (treeItem.getData() instanceof CreaterepoTreeCategory) {
- CreaterepoTreeCategory category = (CreaterepoTreeCategory) treeItem.getData();
- // only check 1 category's tags, as all are loaded the same way
- if (category.getName().equals(CreaterepoPreferenceConstants.PREF_DISTRO_TAG)) {
- assertArrayEquals(DISTRO_TAGS, category.getTags().toArray());
- break;
- }
- }
- }
- }
- });
- }
-
- /**
- * Initialize the treeviewer and tree. Needs access to UI thread when using
- * SWTBot tests. Need to wrap tests in Display.getDefault().syncExec().
- */
- private void initViewer() {
- viewer = new TreeViewer(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
- viewer.setContentProvider(new CreaterepoTreeContentProvider());
- viewer.setLabelProvider(new CreaterepoTreeLabelProvider());
- CreaterepoCategoryModel model = new CreaterepoCategoryModel(project);
- viewer.setInput(model);
- tree = viewer.getTree();
- }
-
- /**
- * Add some test tags in the preferences.
- *
- * @throws BackingStoreException
- */
- private void addTestPreferences() throws BackingStoreException {
- IEclipsePreferences pref = project.getEclipsePreferences();
- pref.put(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, preparePrefValue(DISTRO_TAGS));
- pref.put(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, preparePrefValue(CONTENT_TAGS));
- pref.put(CreaterepoPreferenceConstants.PREF_REPO_TAG, preparePrefValue(REPO_TAGS));
- pref.flush();
- }
-
- /**
- * Helper method to prepare the tags the way it should be stored in preferences.
- *
- * @param values The values to store.
- * @return The string as it should be stored.
- */
- private static String preparePrefValue(String[] values) {
- String str = ICreaterepoConstants.EMPTY_STRING;
- if (values.length > 0) {
- for (String temp : values) {
- str = str.concat(temp+ICreaterepoConstants.DELIMITER);
- }
- str = str.substring(0, str.length()-1);
- }
- return str;
- }
-
- /**
- * Helper method to check if the item is one of the correct categories.
- *
- * @param itemToCheck The item to check.
- * @return True if the item should exist, false otherwise.
- */
- private static boolean inCategory(String itemToCheck) {
- for (String str : CORRECT_CATEGORIES.keySet()) {
- if (str.equals(itemToCheck)) {
- return true;
- }
- }
- return false;
- }
+ /*
+ * Tags being used to test with.
+ */
+ private static final String[] DISTRO_TAGS =
+ {"tag1","tag2","tag3","tag4","tag5"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ private static final String[] CONTENT_TAGS = {};
+ private static final String[] REPO_TAGS = {"tag1"}; //$NON-NLS-1$
+
+ /*
+ * Categories and how many tags per categories to test with.
+ */
+ private static final Map<String, Integer> CORRECT_CATEGORIES;
+ static {
+ Map<String, Integer> temp = new HashMap<>();
+ temp.put(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, DISTRO_TAGS.length);
+ temp.put(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, CONTENT_TAGS.length);
+ temp.put(CreaterepoPreferenceConstants.PREF_REPO_TAG, REPO_TAGS.length);
+ CORRECT_CATEGORIES = Collections.unmodifiableMap(temp);
+ }
+
+ private static TestCreaterepoProject testProject;
+ private CreaterepoProject project;
+ private TreeViewer viewer;
+ private Tree tree;
+
+ /**
+ * Initialize the test project.
+ *
+ * @throws CoreException
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() throws CoreException {
+ testProject = new TestCreaterepoProject();
+ assertTrue(testProject.getProject().exists());
+ }
+
+ /**
+ * Delete the project when tests are done.
+ *
+ * @throws CoreException
+ */
+ @AfterClass
+ public static void tearDownAfterClass() throws CoreException {
+ testProject.dispose();
+ assertFalse(testProject.getProject().exists());
+ }
+
+ /**
+ * Get the CreaterepoProject at the beginning of each test.
+ *
+ * @throws CoreException
+ */
+ @Before
+ public void setUp() throws CoreException {
+ project = testProject.getCreaterepoProject();
+ assertNotNull(project);
+ }
+
+ /**
+ * Clear the preferences after each test.
+ *
+ * @throws BackingStoreException
+ */
+ @After
+ public void tearDown() throws BackingStoreException {
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ pref.clear();
+ pref.flush();
+ assertEquals(0, pref.keys().length);
+ }
+
+ /**
+ * Test if the treeviewer is initialized properly with the correct labels.
+ */
+ @Test
+ public void testTreeViewerInitialization() {
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ initViewer();
+ // there should only be 3 categories
+ assertEquals(3, tree.getItemCount());
+ // and these should be the correct categories
+ for (TreeItem treeItem : tree.getItems()) {
+ assertTrue(inCategory(treeItem.getText()));
+ }
+ }
+ });
+ }
+
+ /**
+ * Test if the treeviewer properly loads the preferences.
+ *
+ * @throws BackingStoreException
+ */
+ @Test
+ public void testTreeViewerPreferences() throws BackingStoreException {
+ addTestPreferences();
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ initViewer();
+ for (TreeItem treeItem : tree.getItems()) {
+ if (treeItem.getData() instanceof CreaterepoTreeCategory) {
+ CreaterepoTreeCategory category = (CreaterepoTreeCategory) treeItem.getData();
+ // make sure the categories are still correct
+ assertTrue(CORRECT_CATEGORIES.containsKey(category.getName()));
+ // assert that the number of tags stored is the correct amount
+ assertEquals(CORRECT_CATEGORIES.get(category.getName()).intValue(), category.getTags().size());
+ }
+ }
+ // do 1 test to make sure the tags were properly stored/loaded
+ for (TreeItem treeItem : tree.getItems()) {
+ if (treeItem.getData() instanceof CreaterepoTreeCategory) {
+ CreaterepoTreeCategory category = (CreaterepoTreeCategory) treeItem.getData();
+ // only check 1 category's tags, as all are loaded the same way
+ if (category.getName().equals(CreaterepoPreferenceConstants.PREF_DISTRO_TAG)) {
+ assertArrayEquals(DISTRO_TAGS, category.getTags().toArray());
+ break;
+ }
+ }
+ }
+ }
+ });
+ }
+
+ /**
+ * Initialize the treeviewer and tree. Needs access to UI thread when using
+ * SWTBot tests. Need to wrap tests in Display.getDefault().syncExec().
+ */
+ private void initViewer() {
+ viewer = new TreeViewer(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
+ viewer.setContentProvider(new CreaterepoTreeContentProvider());
+ viewer.setLabelProvider(new CreaterepoTreeLabelProvider());
+ CreaterepoCategoryModel model = new CreaterepoCategoryModel(project);
+ viewer.setInput(model);
+ tree = viewer.getTree();
+ }
+
+ /**
+ * Add some test tags in the preferences.
+ *
+ * @throws BackingStoreException
+ */
+ private void addTestPreferences() throws BackingStoreException {
+ IEclipsePreferences pref = project.getEclipsePreferences();
+ pref.put(CreaterepoPreferenceConstants.PREF_DISTRO_TAG, preparePrefValue(DISTRO_TAGS));
+ pref.put(CreaterepoPreferenceConstants.PREF_CONTENT_TAG, preparePrefValue(CONTENT_TAGS));
+ pref.put(CreaterepoPreferenceConstants.PREF_REPO_TAG, preparePrefValue(REPO_TAGS));
+ pref.flush();
+ }
+
+ /**
+ * Helper method to prepare the tags the way it should be stored in preferences.
+ *
+ * @param values The values to store.
+ * @return The string as it should be stored.
+ */
+ private static String preparePrefValue(String[] values) {
+ String str = ICreaterepoConstants.EMPTY_STRING;
+ if (values.length > 0) {
+ for (String temp : values) {
+ str = str.concat(temp+ICreaterepoConstants.DELIMITER);
+ }
+ str = str.substring(0, str.length()-1);
+ }
+ return str;
+ }
+
+ /**
+ * Helper method to check if the item is one of the correct categories.
+ *
+ * @param itemToCheck The item to check.
+ * @return True if the item should exist, false otherwise.
+ */
+ private static boolean inCategory(String itemToCheck) {
+ for (String str : CORRECT_CATEGORIES.keySet()) {
+ if (str.equals(itemToCheck)) {
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/tests/CreaterepoWizardTest.java b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/tests/CreaterepoWizardTest.java
index 4f41af871b..217dcb9776 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/tests/CreaterepoWizardTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo.tests/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/tests/CreaterepoWizardTest.java
@@ -47,98 +47,98 @@ import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class CreaterepoWizardTest {
- private static final String REPO_ID = "createrepo-test-repo"; //$NON-NLS-1$
- private static final String REPO_FILE = REPO_ID.concat(".repo"); //$NON-NLS-1$
+ private static final String REPO_ID = "createrepo-test-repo"; //$NON-NLS-1$
+ private static final String REPO_FILE = REPO_ID.concat(".repo"); //$NON-NLS-1$
- private static final String REPO_WIZARD_NAME = "Test repository for createrepo plugin"; //$NON-NLS-1$
- private static final String REPO_WIZARD_URL = "http://www.example.com/test"; //$NON-NLS-1$
- private static final String REPO_FILE_CONTENTS =
- String.format("[%s]%s=%s%s=%s", REPO_ID, IRepoFileConstants.NAME, //$NON-NLS-1$
- REPO_WIZARD_NAME, IRepoFileConstants.BASE_URL, REPO_WIZARD_URL);
+ private static final String REPO_WIZARD_NAME = "Test repository for createrepo plugin"; //$NON-NLS-1$
+ private static final String REPO_WIZARD_URL = "http://www.example.com/test"; //$NON-NLS-1$
+ private static final String REPO_FILE_CONTENTS =
+ String.format("[%s]%s=%s%s=%s", REPO_ID, IRepoFileConstants.NAME, //$NON-NLS-1$
+ REPO_WIZARD_NAME, IRepoFileConstants.BASE_URL, REPO_WIZARD_URL);
- private static SWTWorkbenchBot bot;
- private static IWorkspaceRoot root;
- private static NullProgressMonitor monitor;
- private IProject project;
+ private static SWTWorkbenchBot bot;
+ private static IWorkspaceRoot root;
+ private static NullProgressMonitor monitor;
+ private IProject project;
- /**
- * Setup the bot, monitor and workspace root.
- */
- @BeforeClass
- public static void setUpBeforeClass() {
- bot = new SWTWorkbenchBot();
- root = ResourcesPlugin.getWorkspace().getRoot();
- monitor = new NullProgressMonitor();
- try {
- bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
- } catch (WidgetNotFoundException e) {
- // cannot activate main shell, continue anyways
- }
- }
+ /**
+ * Setup the bot, monitor and workspace root.
+ */
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ bot = new SWTWorkbenchBot();
+ root = ResourcesPlugin.getWorkspace().getRoot();
+ monitor = new NullProgressMonitor();
+ try {
+ bot.shell(ICreaterepoTestConstants.MAIN_SHELL).activate();
+ } catch (WidgetNotFoundException e) {
+ // cannot activate main shell, continue anyways
+ }
+ }
- /**
- * Delete the project and its contents for each test itereation.
- *
- * @throws CoreException
- */
- @After
- public void tearDown() throws CoreException {
- if (project != null && project.exists()) {
- project.delete(true, true, monitor);
- }
- assertFalse(project.exists());
- }
+ /**
+ * Delete the project and its contents for each test itereation.
+ *
+ * @throws CoreException
+ */
+ @After
+ public void tearDown() throws CoreException {
+ if (project != null && project.exists()) {
+ project.delete(true, true, monitor);
+ }
+ assertFalse(project.exists());
+ }
- /**
- * Go through the project creation wizard process of creating a new
- * createrepo project.
- *
- * @throws CoreException
- * @throws IOException
- */
- @Test
- public void testCreaterepoWizardProjectCreation() throws CoreException, IOException {
- // go through the process of creating a new createrepo project
- bot.menu(ICreaterepoTestConstants.FILE).menu(ICreaterepoTestConstants.NEW).menu(ICreaterepoTestConstants.OTHER).click();
- SWTBotShell shell = bot.shell(ICreaterepoTestConstants.NEW);
- shell.activate();
- bot.text().setText(ICreaterepoTestConstants.CREATEREPO_PROJECT_WIZARD);
- bot.waitUntil(new TestUtils.NodeAvailableAndSelect(bot.tree(), ICreaterepoTestConstants.CREATEREPO_CATEGORY, ICreaterepoTestConstants.CREATEREPO_PROJECT_WIZARD));
- bot.button(ICreaterepoTestConstants.NEXT_BUTTON).click();
- bot.textWithLabel(ICreaterepoTestConstants.PROJECT_NAME_LABEL).setText(ICreaterepoTestConstants.PROJECT_NAME);
- bot.button(ICreaterepoTestConstants.NEXT_BUTTON).click();
- bot.textWithLabel(Messages.CreaterepoNewWizardPageTwo_labelID).setText(REPO_ID);
- bot.textWithLabel(Messages.CreaterepoNewWizardPageTwo_labelName).setText(REPO_WIZARD_NAME);
- bot.textWithLabel(Messages.CreaterepoNewWizardPageTwo_labelURL).setText(REPO_WIZARD_URL);
- bot.button(ICreaterepoTestConstants.FINISH_BUTTON).click();
+ /**
+ * Go through the project creation wizard process of creating a new
+ * createrepo project.
+ *
+ * @throws CoreException
+ * @throws IOException
+ */
+ @Test
+ public void testCreaterepoWizardProjectCreation() throws CoreException, IOException {
+ // go through the process of creating a new createrepo project
+ bot.menu(ICreaterepoTestConstants.FILE).menu(ICreaterepoTestConstants.NEW).menu(ICreaterepoTestConstants.OTHER).click();
+ SWTBotShell shell = bot.shell(ICreaterepoTestConstants.NEW);
+ shell.activate();
+ bot.text().setText(ICreaterepoTestConstants.CREATEREPO_PROJECT_WIZARD);
+ bot.waitUntil(new TestUtils.NodeAvailableAndSelect(bot.tree(), ICreaterepoTestConstants.CREATEREPO_CATEGORY, ICreaterepoTestConstants.CREATEREPO_PROJECT_WIZARD));
+ bot.button(ICreaterepoTestConstants.NEXT_BUTTON).click();
+ bot.textWithLabel(ICreaterepoTestConstants.PROJECT_NAME_LABEL).setText(ICreaterepoTestConstants.PROJECT_NAME);
+ bot.button(ICreaterepoTestConstants.NEXT_BUTTON).click();
+ bot.textWithLabel(Messages.CreaterepoNewWizardPageTwo_labelID).setText(REPO_ID);
+ bot.textWithLabel(Messages.CreaterepoNewWizardPageTwo_labelName).setText(REPO_WIZARD_NAME);
+ bot.textWithLabel(Messages.CreaterepoNewWizardPageTwo_labelURL).setText(REPO_WIZARD_URL);
+ bot.button(ICreaterepoTestConstants.FINISH_BUTTON).click();
- // verify that project has been initialized properly
- project = root.getProject(ICreaterepoTestConstants.PROJECT_NAME);
- assertTrue(project.exists());
- assertTrue(project.hasNature(CreaterepoProjectNature.CREATEREPO_NATURE_ID));
- // 3 = .project + content folder + .repo file
- assertEquals(3, project.members().length);
+ // verify that project has been initialized properly
+ project = root.getProject(ICreaterepoTestConstants.PROJECT_NAME);
+ assertTrue(project.exists());
+ assertTrue(project.hasNature(CreaterepoProjectNature.CREATEREPO_NATURE_ID));
+ // 3 = .project + content folder + .repo file
+ assertEquals(3, project.members().length);
- // contains the content folder and repo file
- assertTrue(project.findMember(ICreaterepoConstants.CONTENT_FOLDER).exists());
- assertTrue(project.findMember(REPO_FILE).exists());
+ // contains the content folder and repo file
+ assertTrue(project.findMember(ICreaterepoConstants.CONTENT_FOLDER).exists());
+ assertTrue(project.findMember(REPO_FILE).exists());
- // content folder has nothing in it
- IFolder contentFolder = (IFolder) project.findMember(ICreaterepoConstants.CONTENT_FOLDER);
- assertEquals(0, contentFolder.members().length);
+ // content folder has nothing in it
+ IFolder contentFolder = (IFolder) project.findMember(ICreaterepoConstants.CONTENT_FOLDER);
+ assertEquals(0, contentFolder.members().length);
- // get the created .repo file contents
- IFile repoFile = (IFile) project.findMember(REPO_FILE);
- // repo file should not be empty
- assertNotEquals(0, repoFile.getContents().available());
- StringBuilder sb = new StringBuilder();
- BufferedReader br = new BufferedReader(new InputStreamReader(repoFile.getContents()));
- String line;
- while ((line = br.readLine()) != null) {
- // disregards newline
- sb.append(line);
- }
- assertEquals(REPO_FILE_CONTENTS, sb.toString());
- }
+ // get the created .repo file contents
+ IFile repoFile = (IFile) project.findMember(REPO_FILE);
+ // repo file should not be empty
+ assertNotEquals(0, repoFile.getContents().available());
+ StringBuilder sb = new StringBuilder();
+ BufferedReader br = new BufferedReader(new InputStreamReader(repoFile.getContents()));
+ String line;
+ while ((line = br.readLine()) != null) {
+ // disregards newline
+ sb.append(line);
+ }
+ assertEquals(REPO_FILE_CONTENTS, sb.toString());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/plugin.xml b/rpm/org.eclipse.linuxtools.rpm.createrepo/plugin.xml
index c6ff6b14d7..8f4e721bf9 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/plugin.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/plugin.xml
@@ -1,14 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<!--
- Copyright (c) 2013 Red Hat, Inc. and others.
- All rights reserved. This program andthe accompanying materials
- are made available under the terms of the Eclipse Public License v1.0
- which accompanies this distribution, and is available at
- http://www.eclipse.org/legal/epl-v10.html
+ Copyright (c) 2013 Red Hat, Inc. and others.
+ All rights reserved. This program andthe accompanying materials
+ are made available under the terms of the Eclipse Public License v1.0
+ which accompanies this distribution, and is available at
+ http://www.eclipse.org/legal/epl-v10.html
- Contributors:
- Neil Guzman - initial API and implementation
+ Contributors:
+ Neil Guzman - initial API and implementation
-->
<plugin>
<extension
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Activator.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Activator.java
index b0cd8a5691..b8278d1b23 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Activator.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Activator.java
@@ -21,88 +21,88 @@ import org.osgi.framework.BundleContext;
*/
public class Activator extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.rpm.createrepo"; //$NON-NLS-1$
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.rpm.createrepo"; //$NON-NLS-1$
- // The shared instance
- private static Activator plugin;
+ // The shared instance
+ private static Activator plugin;
- /**
- * The constructor
- */
- public Activator() {
- }
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
- /**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
+ /**
+ * Returns an image descriptor for the image file at the given
+ * plug-in relative path
+ *
+ * @param path the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
- /**
- * Get the enabled status of using the project specific settings of
- * createrepo.
- *
- * @return True if it is being used, false otherwise.
- */
- public static boolean isProjectPrefEnabled() {
- return getDefault().getPreferenceStore().getBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED);
- }
+ /**
+ * Get the enabled status of using the project specific settings of
+ * createrepo.
+ *
+ * @return True if it is being used, false otherwise.
+ */
+ public static boolean isProjectPrefEnabled() {
+ return getDefault().getPreferenceStore().getBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED);
+ }
- /**
- * Get the enabled status of using the delta preferences of
- * createrepo.
- *
- * @return True if it is being used, false otherwise.
- */
- public static boolean isDeltaPrefEnabled() {
- return getDefault().getPreferenceStore().getBoolean(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE);
- }
+ /**
+ * Get the enabled status of using the delta preferences of
+ * createrepo.
+ *
+ * @return True if it is being used, false otherwise.
+ */
+ public static boolean isDeltaPrefEnabled() {
+ return getDefault().getPreferenceStore().getBoolean(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE);
+ }
- /**
- * Log an error.
- *
- * @param message A human-readable message.
- * @param exception The exception to log.
- */
- public static void logError(String message, Throwable exception) {
- IStatus status = new Status(IStatus.ERROR, PLUGIN_ID, message,
- exception);
- getDefault().getLog().log(status);
- }
+ /**
+ * Log an error.
+ *
+ * @param message A human-readable message.
+ * @param exception The exception to log.
+ */
+ public static void logError(String message, Throwable exception) {
+ IStatus status = new Status(IStatus.ERROR, PLUGIN_ID, message,
+ exception);
+ getDefault().getLog().log(status);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Createrepo.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Createrepo.java
index da4d699e6b..8a46a36cf5 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Createrepo.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Createrepo.java
@@ -129,7 +129,7 @@ public class Createrepo {
* can continue on executing.
*
* 0.9.8 = latest development release
- * requires: yum version >= 3.2.23
+ * requires: yum version >= 3.2.23
*
* @return True if version is supported, false otherwise.
* @throws CoreException Occurs when failure to get version number.
@@ -160,8 +160,8 @@ public class Createrepo {
String yumOutput = Utils.runCommandToString("yum", "--version").trim(); //$NON-NLS-1$ //$NON-NLS-2$
// yum --version output is like:
// x.x.x
- // blah...
- // blah...
+ // blah...
+ // blah...
String[] yumTemp = yumOutput.split("\n"); //$NON-NLS-1$
if (yumTemp.length > 0) {
yumVersion = yumTemp[0];
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoCommandCreator.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoCommandCreator.java
index 0a8808c75e..c130745136 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoCommandCreator.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoCommandCreator.java
@@ -21,183 +21,183 @@ import org.eclipse.jface.preference.IPreferenceStore;
*/
public class CreaterepoCommandCreator {
- // commands that are either used or not used
- private static final String[] BOOLEAN_COMMANDS = {
- // general
- CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
- CreaterepoPreferenceConstants.PREF_GENERATE_DB,
- CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
- CreaterepoPreferenceConstants.PREF_PRETTY_XML,
- CreaterepoPreferenceConstants.PREF_CHECK_TS,
- };
-
- // commands that determine used state by arguments passed with it
- private static final String[] STRING_COMMANDS = {
- // general
- CreaterepoPreferenceConstants.PREF_CHECKSUM,
- CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
- };
-
- private static final String[] STRING_META_COMMANDS = {
- // metadata
- CreaterepoPreferenceConstants.PREF_REVISION,
- CreaterepoPreferenceConstants.PREF_DISTRO_TAG,
- CreaterepoPreferenceConstants.PREF_CONTENT_TAG,
- CreaterepoPreferenceConstants.PREF_REPO_TAG,
- };
-
- private static final String[] STRING_DELTA_COMMANDS = {
- // deltas
- CreaterepoPreferenceConstants.PREF_OLD_PACKAGE_DIRS,
- };
-
- // commands that determine used state by int passed with it
- private static final String[] INT_COMMANDS = {
- // general
- CreaterepoPreferenceConstants.PREF_WORKERS,
- CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
- };
-
- private static final String[] INT_DELTA_COMMANDS = {
- // deltas
- CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
- CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
- };
-
- private IEclipsePreferences projectPreferences;
- private IPreferenceStore preferenceStore;
- private boolean project;
- private boolean delta;
-
- public CreaterepoCommandCreator(IEclipsePreferences projectPreferences) {
- project = Activator.isProjectPrefEnabled();
- delta = Activator.isDeltaPrefEnabled();
- this.projectPreferences = projectPreferences;
- preferenceStore = Activator.getDefault().getPreferenceStore();
- }
-
- /**
- * Get all the command arguments.
- *
- * @return A list of all the command arguments.
- */
- public List<String> getCommands() {
- List<String> commands = new ArrayList<>();
- commands.addAll(prepareBooleanCommands());
- commands.addAll(prepareStringCommands());
- commands.addAll(prepareIntCommands());
- return commands;
- }
-
- /**
- * These commands are either added to the execution or not, depending
- * on the enabled status from the preferences.
- *
- * @return The command options to add.
- */
- public List<String> prepareBooleanCommands() {
- List<String> commands = new ArrayList<>();
- if (delta) {
- commands.add(ICreaterepoConstants.DASH.concat(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE));
- }
- for (String arg : BOOLEAN_COMMANDS) {
- // if project preferences are enabled, use the preferences from there
- boolean value = project ? projectPreferences.getBoolean(arg, preferenceStore.getDefaultBoolean(arg))
- : preferenceStore.getBoolean(arg);
- // if the value returned is true, that means the switch should be added
- if (value) {
- if (arg.equals(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME)) {
- arg = ICreaterepoConstants.DASH.concat("unique-").concat(arg); //$NON-NLS-1$
- } else {
- arg = ICreaterepoConstants.DASH.concat(arg);
- }
- commands.add(arg);
- } else {
- // only add the switch if its one of these options
- if (arg.equals(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME)) {
- arg = ICreaterepoConstants.DASH.concat("simple-").concat(arg); //$NON-NLS-1$
- commands.add(arg);
- } else if (arg.equals(CreaterepoPreferenceConstants.PREF_GENERATE_DB)) {
- arg = ICreaterepoConstants.DASH.concat("no-").concat(arg); //$NON-NLS-1$
- commands.add(arg);
- }
- }
- }
- return commands;
- }
-
- /**
- * Prepare the commands that require a string passed with them
- * when executing.
- *
- * @return The command options to add.
- */
- public List<String> prepareStringCommands() {
- List<String> commands = new ArrayList<>();
- for (String arg : STRING_COMMANDS) {
- String value = project ? projectPreferences.get(arg, preferenceStore.getDefaultString(arg))
- : preferenceStore.getString(arg);
- arg = ICreaterepoConstants.DASH.concat(arg);
- if (!value.isEmpty()) {
- commands.add(arg);
- commands.add(value);
- }
- }
- for (String arg : STRING_META_COMMANDS) {
- String value = projectPreferences.get(arg, preferenceStore.getDefaultString(arg));
- arg = ICreaterepoConstants.DASH.concat(arg);
- for (String tag : value.split(ICreaterepoConstants.DELIMITER)) {
- if (!tag.isEmpty()) {
- commands.add(arg);
- commands.add(tag);
- }
- }
- }
- if (delta) {
- for (String arg : STRING_DELTA_COMMANDS) {
- String value = projectPreferences.get(arg, preferenceStore.getDefaultString(arg));
- arg = ICreaterepoConstants.DASH.concat(arg);
- for (String dirs : value.split(ICreaterepoConstants.DELIMITER)) {
- if (!dirs.isEmpty()) {
- commands.add(arg);
- commands.add(dirs);
- }
- }
- }
- }
- return commands;
- }
-
- /**
- * Prepare the commands that require an integer passed with them
- * when executing. Differs from prepareStringCommands() by how it
- * retrieves the values from the preferences.
- *
- * @return The command options to add.
- */
- public List<String> prepareIntCommands() {
- List<String> commands = new ArrayList<>();
- if (delta) {
- for (String arg : INT_DELTA_COMMANDS) {
- long value = projectPreferences.getInt(arg, preferenceStore.getDefaultInt(arg));
- if (arg.equals(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE)) {
- // 1048576 = bytes in a megabyte
- value *= 1048576;
- }
- arg = ICreaterepoConstants.DASH.concat(arg);
- commands.add(arg);
- commands.add(Long.toString(value));
- }
- }
- for (String arg : INT_COMMANDS) {
- // if project preferences are enabled, use the preferences from there
- int value = project ? projectPreferences.getInt(arg, preferenceStore.getDefaultInt(arg))
- : preferenceStore.getInt(arg);
- arg = ICreaterepoConstants.DASH.concat(arg);
- commands.add(arg);
- commands.add(Integer.toString(value));
- }
- return commands;
- }
+ // commands that are either used or not used
+ private static final String[] BOOLEAN_COMMANDS = {
+ // general
+ CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
+ CreaterepoPreferenceConstants.PREF_GENERATE_DB,
+ CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
+ CreaterepoPreferenceConstants.PREF_PRETTY_XML,
+ CreaterepoPreferenceConstants.PREF_CHECK_TS,
+ };
+
+ // commands that determine used state by arguments passed with it
+ private static final String[] STRING_COMMANDS = {
+ // general
+ CreaterepoPreferenceConstants.PREF_CHECKSUM,
+ CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
+ };
+
+ private static final String[] STRING_META_COMMANDS = {
+ // metadata
+ CreaterepoPreferenceConstants.PREF_REVISION,
+ CreaterepoPreferenceConstants.PREF_DISTRO_TAG,
+ CreaterepoPreferenceConstants.PREF_CONTENT_TAG,
+ CreaterepoPreferenceConstants.PREF_REPO_TAG,
+ };
+
+ private static final String[] STRING_DELTA_COMMANDS = {
+ // deltas
+ CreaterepoPreferenceConstants.PREF_OLD_PACKAGE_DIRS,
+ };
+
+ // commands that determine used state by int passed with it
+ private static final String[] INT_COMMANDS = {
+ // general
+ CreaterepoPreferenceConstants.PREF_WORKERS,
+ CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
+ };
+
+ private static final String[] INT_DELTA_COMMANDS = {
+ // deltas
+ CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
+ CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
+ };
+
+ private IEclipsePreferences projectPreferences;
+ private IPreferenceStore preferenceStore;
+ private boolean project;
+ private boolean delta;
+
+ public CreaterepoCommandCreator(IEclipsePreferences projectPreferences) {
+ project = Activator.isProjectPrefEnabled();
+ delta = Activator.isDeltaPrefEnabled();
+ this.projectPreferences = projectPreferences;
+ preferenceStore = Activator.getDefault().getPreferenceStore();
+ }
+
+ /**
+ * Get all the command arguments.
+ *
+ * @return A list of all the command arguments.
+ */
+ public List<String> getCommands() {
+ List<String> commands = new ArrayList<>();
+ commands.addAll(prepareBooleanCommands());
+ commands.addAll(prepareStringCommands());
+ commands.addAll(prepareIntCommands());
+ return commands;
+ }
+
+ /**
+ * These commands are either added to the execution or not, depending
+ * on the enabled status from the preferences.
+ *
+ * @return The command options to add.
+ */
+ public List<String> prepareBooleanCommands() {
+ List<String> commands = new ArrayList<>();
+ if (delta) {
+ commands.add(ICreaterepoConstants.DASH.concat(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE));
+ }
+ for (String arg : BOOLEAN_COMMANDS) {
+ // if project preferences are enabled, use the preferences from there
+ boolean value = project ? projectPreferences.getBoolean(arg, preferenceStore.getDefaultBoolean(arg))
+ : preferenceStore.getBoolean(arg);
+ // if the value returned is true, that means the switch should be added
+ if (value) {
+ if (arg.equals(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME)) {
+ arg = ICreaterepoConstants.DASH.concat("unique-").concat(arg); //$NON-NLS-1$
+ } else {
+ arg = ICreaterepoConstants.DASH.concat(arg);
+ }
+ commands.add(arg);
+ } else {
+ // only add the switch if its one of these options
+ if (arg.equals(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME)) {
+ arg = ICreaterepoConstants.DASH.concat("simple-").concat(arg); //$NON-NLS-1$
+ commands.add(arg);
+ } else if (arg.equals(CreaterepoPreferenceConstants.PREF_GENERATE_DB)) {
+ arg = ICreaterepoConstants.DASH.concat("no-").concat(arg); //$NON-NLS-1$
+ commands.add(arg);
+ }
+ }
+ }
+ return commands;
+ }
+
+ /**
+ * Prepare the commands that require a string passed with them
+ * when executing.
+ *
+ * @return The command options to add.
+ */
+ public List<String> prepareStringCommands() {
+ List<String> commands = new ArrayList<>();
+ for (String arg : STRING_COMMANDS) {
+ String value = project ? projectPreferences.get(arg, preferenceStore.getDefaultString(arg))
+ : preferenceStore.getString(arg);
+ arg = ICreaterepoConstants.DASH.concat(arg);
+ if (!value.isEmpty()) {
+ commands.add(arg);
+ commands.add(value);
+ }
+ }
+ for (String arg : STRING_META_COMMANDS) {
+ String value = projectPreferences.get(arg, preferenceStore.getDefaultString(arg));
+ arg = ICreaterepoConstants.DASH.concat(arg);
+ for (String tag : value.split(ICreaterepoConstants.DELIMITER)) {
+ if (!tag.isEmpty()) {
+ commands.add(arg);
+ commands.add(tag);
+ }
+ }
+ }
+ if (delta) {
+ for (String arg : STRING_DELTA_COMMANDS) {
+ String value = projectPreferences.get(arg, preferenceStore.getDefaultString(arg));
+ arg = ICreaterepoConstants.DASH.concat(arg);
+ for (String dirs : value.split(ICreaterepoConstants.DELIMITER)) {
+ if (!dirs.isEmpty()) {
+ commands.add(arg);
+ commands.add(dirs);
+ }
+ }
+ }
+ }
+ return commands;
+ }
+
+ /**
+ * Prepare the commands that require an integer passed with them
+ * when executing. Differs from prepareStringCommands() by how it
+ * retrieves the values from the preferences.
+ *
+ * @return The command options to add.
+ */
+ public List<String> prepareIntCommands() {
+ List<String> commands = new ArrayList<>();
+ if (delta) {
+ for (String arg : INT_DELTA_COMMANDS) {
+ long value = projectPreferences.getInt(arg, preferenceStore.getDefaultInt(arg));
+ if (arg.equals(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE)) {
+ // 1048576 = bytes in a megabyte
+ value *= 1048576;
+ }
+ arg = ICreaterepoConstants.DASH.concat(arg);
+ commands.add(arg);
+ commands.add(Long.toString(value));
+ }
+ }
+ for (String arg : INT_COMMANDS) {
+ // if project preferences are enabled, use the preferences from there
+ int value = project ? projectPreferences.getInt(arg, preferenceStore.getDefaultInt(arg))
+ : preferenceStore.getInt(arg);
+ arg = ICreaterepoConstants.DASH.concat(arg);
+ commands.add(arg);
+ commands.add(Integer.toString(value));
+ }
+ return commands;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProject.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProject.java
index 9c4f9922c0..3793c34fbc 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProject.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProject.java
@@ -37,213 +37,213 @@ import org.osgi.framework.FrameworkUtil;
*/
public class CreaterepoProject {
- private IEclipsePreferences projectPreferences;
-
- private IProject project;
- private IFolder content;
- private IFile repoFile;
-
- private IProgressMonitor monitor;
-
- /**
- * Constructor without repo file.
- *
- * @param project The project.
- * @throws CoreException Thrown when unable to initialize project.
- */
- public CreaterepoProject(IProject project) throws CoreException {
- this(project, null);
- }
-
- /**
- * Default constructor.
- *
- * @param project The project.
- * @throws CoreException Thrown when unable to initialize project.
- */
- public CreaterepoProject(IProject project, IFile repoFile) throws CoreException {
- this.project = project;
- this.repoFile = repoFile;
- monitor = new NullProgressMonitor();
- projectPreferences = new ProjectScope(project.getProject()).getNode(Activator.PLUGIN_ID);
- intitialize();
- // if something is deleted from the project while outside of eclipse,
- // the tree/preferences will be updated accordingly after refreshing
- getProject().refreshLocal(IResource.DEPTH_ONE, monitor);
- }
-
- /**
- * Initialize the createrepo project by creating the content folder if it doesn't
- * yet exist.
- *
- * @throws CoreException Thrown when unable to create the folders.
- */
- private void intitialize() throws CoreException {
- content = getProject().getFolder(ICreaterepoConstants.CONTENT_FOLDER);
- if (repoFile == null) {
- for (IResource child : getProject().members()) {
- String extension = child.getFileExtension();
- if (extension != null && extension.equals(ICreaterepoConstants.REPO_FILE_EXTENSION)) {
- // assumes that there will only be 1 .repo file in the folder
- repoFile = (IFile) child;
- }
- // if no repo file then keep it null
- }
- }
- }
-
- /**
- * Create the content folder if it doesn't exist.
- *
- * @throws CoreException
- */
- private void createContentFolder() throws CoreException {
- content = getProject().getFolder(ICreaterepoConstants.CONTENT_FOLDER);
- if (!content.exists()) {
- content.create(true, true, monitor);
- }
- }
-
- /**
- * Import an RPM file outside of the eclipse workspace.
- *
- * @param externalFile The external file to import.
- * @throws CoreException Thrown when failure to create a workspace file.
- */
- public void importRPM(File externalFile) throws CoreException {
- // must first check if external file exists
- if (!externalFile.exists()) {
- return;
- }
- // must put imported RPMs into the content folder; create if missing
- if (!getContentFolder().exists()) {
- createContentFolder();
- }
- IFile file = getContentFolder().getFile(new Path(externalFile.getName()));
- // do not import non-RPMs
- if (!file.getFileExtension().equals(ICreaterepoConstants.RPM_FILE_EXTENSION)) {
- return;
- }
- if (!file.exists()) {
- try {
- file.create(new FileInputStream(externalFile), false, monitor);
- } catch (FileNotFoundException e) {
- IStatus status = new Status(
- IStatus.ERROR,
- FrameworkUtil.getBundle(CreaterepoProject.class).getSymbolicName(),
- Messages.CreaterepoProject_errorGettingFile, null);
- throw new CoreException(status);
- }
- getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
- }
- }
-
- /**
- * Execute the createrepo command.
- *
- * @param os Direct execution stream to this.
- * @return The status of the execution.
- * @throws CoreException Thrown when failure to execute command.
- */
- public IStatus createrepo(OutputStream os) throws CoreException {
- if (!getContentFolder().exists()) {
- createContentFolder();
- }
- Createrepo createrepo = new Createrepo();
- IStatus result = createrepo.execute(os, this, getCommandArguments());
- getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
- return result;
- }
-
- /**
- * Execute the createrepo command with a call to update.
- *
- * @param os Direct execution stream to this.
- * @return The status of the execution.
- * @throws CoreException Thrown when failure to execute command.
- */
- public IStatus update(OutputStream os) throws CoreException {
- if (!getContentFolder().exists()) {
- createContentFolder();
- }
- Createrepo createrepo = new Createrepo();
- List<String> commands = getCommandArguments();
- commands.add(ICreaterepoConstants.DASH.concat(CreaterepoPreferenceConstants.PREF_UPDATE));
- IStatus result = createrepo.execute(os, this, commands);
- getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
- return result;
- }
-
- /**
- * Get the project.
- *
- * @return The project.
- */
- public IProject getProject() {
- return project;
- }
-
- /**
- * Get the content folder.
- *
- * @return The content folder.
- */
- public IFolder getContentFolder() {
- return content;
- }
-
- /**
- * Get the .repo file.
- *
- * @return The .repo file.
- */
- public IFile getRepoFile() {
- return repoFile;
- }
-
- /**
- * Get the RPMs in the project.
- *
- * @return A list of RPMs located within the project.
- * @throws CoreException Thrown when unable to look into the project.
- */
- public List<IResource> getRPMs() throws CoreException {
- List<IResource> rpms = new ArrayList<>();
- if (!getContentFolder().exists()) {
- return rpms;
- }
- if (getProject().members().length > 0) {
- for (IResource child : getContentFolder().members()) {
- String extension = child.getFileExtension();
- if (extension != null && extension.equals(ICreaterepoConstants.RPM_FILE_EXTENSION)) {
- rpms.add(child);
- }
- }
- }
- return rpms;
- }
-
- /**
- * Get the eclipse preferences of this project.
- *
- * @return The eclipse preferences for the project.
- */
- public IEclipsePreferences getEclipsePreferences() {
- return projectPreferences;
- }
-
- /**
- * Get the command arguments to pass to the createrepo command. The
- * arguments come from the stored preferences from the preference page
- * and the project preferences.
- *
- * @return The command arguments.
- */
- private List<String> getCommandArguments() {
- List<String> commands = new ArrayList<>();
- CreaterepoCommandCreator creator = new CreaterepoCommandCreator(projectPreferences);
- commands.addAll(creator.getCommands());
- return commands;
- }
+ private IEclipsePreferences projectPreferences;
+
+ private IProject project;
+ private IFolder content;
+ private IFile repoFile;
+
+ private IProgressMonitor monitor;
+
+ /**
+ * Constructor without repo file.
+ *
+ * @param project The project.
+ * @throws CoreException Thrown when unable to initialize project.
+ */
+ public CreaterepoProject(IProject project) throws CoreException {
+ this(project, null);
+ }
+
+ /**
+ * Default constructor.
+ *
+ * @param project The project.
+ * @throws CoreException Thrown when unable to initialize project.
+ */
+ public CreaterepoProject(IProject project, IFile repoFile) throws CoreException {
+ this.project = project;
+ this.repoFile = repoFile;
+ monitor = new NullProgressMonitor();
+ projectPreferences = new ProjectScope(project.getProject()).getNode(Activator.PLUGIN_ID);
+ intitialize();
+ // if something is deleted from the project while outside of eclipse,
+ // the tree/preferences will be updated accordingly after refreshing
+ getProject().refreshLocal(IResource.DEPTH_ONE, monitor);
+ }
+
+ /**
+ * Initialize the createrepo project by creating the content folder if it doesn't
+ * yet exist.
+ *
+ * @throws CoreException Thrown when unable to create the folders.
+ */
+ private void intitialize() throws CoreException {
+ content = getProject().getFolder(ICreaterepoConstants.CONTENT_FOLDER);
+ if (repoFile == null) {
+ for (IResource child : getProject().members()) {
+ String extension = child.getFileExtension();
+ if (extension != null && extension.equals(ICreaterepoConstants.REPO_FILE_EXTENSION)) {
+ // assumes that there will only be 1 .repo file in the folder
+ repoFile = (IFile) child;
+ }
+ // if no repo file then keep it null
+ }
+ }
+ }
+
+ /**
+ * Create the content folder if it doesn't exist.
+ *
+ * @throws CoreException
+ */
+ private void createContentFolder() throws CoreException {
+ content = getProject().getFolder(ICreaterepoConstants.CONTENT_FOLDER);
+ if (!content.exists()) {
+ content.create(true, true, monitor);
+ }
+ }
+
+ /**
+ * Import an RPM file outside of the eclipse workspace.
+ *
+ * @param externalFile The external file to import.
+ * @throws CoreException Thrown when failure to create a workspace file.
+ */
+ public void importRPM(File externalFile) throws CoreException {
+ // must first check if external file exists
+ if (!externalFile.exists()) {
+ return;
+ }
+ // must put imported RPMs into the content folder; create if missing
+ if (!getContentFolder().exists()) {
+ createContentFolder();
+ }
+ IFile file = getContentFolder().getFile(new Path(externalFile.getName()));
+ // do not import non-RPMs
+ if (!file.getFileExtension().equals(ICreaterepoConstants.RPM_FILE_EXTENSION)) {
+ return;
+ }
+ if (!file.exists()) {
+ try {
+ file.create(new FileInputStream(externalFile), false, monitor);
+ } catch (FileNotFoundException e) {
+ IStatus status = new Status(
+ IStatus.ERROR,
+ FrameworkUtil.getBundle(CreaterepoProject.class).getSymbolicName(),
+ Messages.CreaterepoProject_errorGettingFile, null);
+ throw new CoreException(status);
+ }
+ getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
+ }
+ }
+
+ /**
+ * Execute the createrepo command.
+ *
+ * @param os Direct execution stream to this.
+ * @return The status of the execution.
+ * @throws CoreException Thrown when failure to execute command.
+ */
+ public IStatus createrepo(OutputStream os) throws CoreException {
+ if (!getContentFolder().exists()) {
+ createContentFolder();
+ }
+ Createrepo createrepo = new Createrepo();
+ IStatus result = createrepo.execute(os, this, getCommandArguments());
+ getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
+ return result;
+ }
+
+ /**
+ * Execute the createrepo command with a call to update.
+ *
+ * @param os Direct execution stream to this.
+ * @return The status of the execution.
+ * @throws CoreException Thrown when failure to execute command.
+ */
+ public IStatus update(OutputStream os) throws CoreException {
+ if (!getContentFolder().exists()) {
+ createContentFolder();
+ }
+ Createrepo createrepo = new Createrepo();
+ List<String> commands = getCommandArguments();
+ commands.add(ICreaterepoConstants.DASH.concat(CreaterepoPreferenceConstants.PREF_UPDATE));
+ IStatus result = createrepo.execute(os, this, commands);
+ getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
+ return result;
+ }
+
+ /**
+ * Get the project.
+ *
+ * @return The project.
+ */
+ public IProject getProject() {
+ return project;
+ }
+
+ /**
+ * Get the content folder.
+ *
+ * @return The content folder.
+ */
+ public IFolder getContentFolder() {
+ return content;
+ }
+
+ /**
+ * Get the .repo file.
+ *
+ * @return The .repo file.
+ */
+ public IFile getRepoFile() {
+ return repoFile;
+ }
+
+ /**
+ * Get the RPMs in the project.
+ *
+ * @return A list of RPMs located within the project.
+ * @throws CoreException Thrown when unable to look into the project.
+ */
+ public List<IResource> getRPMs() throws CoreException {
+ List<IResource> rpms = new ArrayList<>();
+ if (!getContentFolder().exists()) {
+ return rpms;
+ }
+ if (getProject().members().length > 0) {
+ for (IResource child : getContentFolder().members()) {
+ String extension = child.getFileExtension();
+ if (extension != null && extension.equals(ICreaterepoConstants.RPM_FILE_EXTENSION)) {
+ rpms.add(child);
+ }
+ }
+ }
+ return rpms;
+ }
+
+ /**
+ * Get the eclipse preferences of this project.
+ *
+ * @return The eclipse preferences for the project.
+ */
+ public IEclipsePreferences getEclipsePreferences() {
+ return projectPreferences;
+ }
+
+ /**
+ * Get the command arguments to pass to the createrepo command. The
+ * arguments come from the stored preferences from the preference page
+ * and the project preferences.
+ *
+ * @return The command arguments.
+ */
+ private List<String> getCommandArguments() {
+ List<String> commands = new ArrayList<>();
+ CreaterepoCommandCreator creator = new CreaterepoCommandCreator(projectPreferences);
+ commands.addAll(creator.getCommands());
+ return commands;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProjectCreator.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProjectCreator.java
index 0d23cbcce7..633de37894 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProjectCreator.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProjectCreator.java
@@ -30,34 +30,34 @@ public final class CreaterepoProjectCreator {
private CreaterepoProjectCreator() {}
- /**
- * Create a createrepo project given a project name and the progress
- * monitor. The new project will contain an empty repodata folder.
- *
- * @param projectName The name of the project.
- * @param locationPath The location path of the project
- * @param monitor The progress monitor.
- * @return The newly created project.
- * @throws CoreException Thrown when creating a project fails.
- */
- public static IProject create(String projectName, IPath locationPath,
- String repoName, IProgressMonitor monitor) throws CoreException {
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IProject project = root.getProject(projectName);
- IProjectDescription description = ResourcesPlugin.getWorkspace()
- .newProjectDescription(projectName);
- if (!Platform.getLocation().equals(locationPath)) {
- description.setLocation(locationPath);
- }
- description.setNatureIds(new String[] {CreaterepoProjectNature.CREATEREPO_NATURE_ID});
- project.create(description, monitor);
- project.open(monitor);
- IFile repoFile = project.getFile(repoName);
- InputStream stream = new ByteArrayInputStream(ICreaterepoConstants.EMPTY_STRING.getBytes());
- if (!repoFile.exists()) {
- repoFile.create(stream, true, monitor);
- }
- return project;
- }
+ /**
+ * Create a createrepo project given a project name and the progress
+ * monitor. The new project will contain an empty repodata folder.
+ *
+ * @param projectName The name of the project.
+ * @param locationPath The location path of the project
+ * @param monitor The progress monitor.
+ * @return The newly created project.
+ * @throws CoreException Thrown when creating a project fails.
+ */
+ public static IProject create(String projectName, IPath locationPath,
+ String repoName, IProgressMonitor monitor) throws CoreException {
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ IProject project = root.getProject(projectName);
+ IProjectDescription description = ResourcesPlugin.getWorkspace()
+ .newProjectDescription(projectName);
+ if (!Platform.getLocation().equals(locationPath)) {
+ description.setLocation(locationPath);
+ }
+ description.setNatureIds(new String[] {CreaterepoProjectNature.CREATEREPO_NATURE_ID});
+ project.create(description, monitor);
+ project.open(monitor);
+ IFile repoFile = project.getFile(repoName);
+ InputStream stream = new ByteArrayInputStream(ICreaterepoConstants.EMPTY_STRING.getBytes());
+ if (!repoFile.exists()) {
+ repoFile.create(stream, true, monitor);
+ }
+ return project;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProjectNature.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProjectNature.java
index d0700d1a93..9923602dc0 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProjectNature.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/CreaterepoProjectNature.java
@@ -18,40 +18,40 @@ import org.eclipse.core.resources.IProjectNature;
*/
public class CreaterepoProjectNature implements IProjectNature {
- public static final String CREATEREPO_NATURE_ID = "org.eclipse.linuxtools.rpm.createrepo.createreponature"; //$NON-NLS-1$
-
- private IProject project;
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.resources.IProjectNature#configure()
- */
- @Override
- public void configure(){/* not implemented */}
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.resources.IProjectNature#deconfigure()
- */
- @Override
- public void deconfigure() {/* not implemented */}
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.resources.IProjectNature#getProject()
- */
- @Override
- public IProject getProject() {
- return project;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core.resources.IProject)
- */
- @Override
- public void setProject(IProject project) {
- this.project = project;
- }
+ public static final String CREATEREPO_NATURE_ID = "org.eclipse.linuxtools.rpm.createrepo.createreponature"; //$NON-NLS-1$
+
+ private IProject project;
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.core.resources.IProjectNature#configure()
+ */
+ @Override
+ public void configure(){/* not implemented */}
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.core.resources.IProjectNature#deconfigure()
+ */
+ @Override
+ public void deconfigure() {/* not implemented */}
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.core.resources.IProjectNature#getProject()
+ */
+ @Override
+ public IProject getProject() {
+ return project;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core.resources.IProject)
+ */
+ @Override
+ public void setProject(IProject project) {
+ this.project = project;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/ICreaterepoConstants.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/ICreaterepoConstants.java
index c8f0bbe28b..b48be86d38 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/ICreaterepoConstants.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/ICreaterepoConstants.java
@@ -34,7 +34,7 @@ public interface ICreaterepoConstants {
/**
* The file extension of RPM files.
*/
- String RPM_FILE_EXTENSION = "rpm"; //$NON-NLS-1$
+ String RPM_FILE_EXTENSION = "rpm"; //$NON-NLS-1$
/**
* An empty string.
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/IRepoFileConstants.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/IRepoFileConstants.java
index 7568d15fd9..4df27652da 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/IRepoFileConstants.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/IRepoFileConstants.java
@@ -15,24 +15,24 @@ package org.eclipse.linuxtools.internal.rpm.createrepo;
*/
public interface IRepoFileConstants {
- /*
- * Mandatory options
- */
+ /*
+ * Mandatory options
+ */
- /**
- * A unique identifier for the repository.
- */
- String ID = "id"; //$NON-NLS-1$
+ /**
+ * A unique identifier for the repository.
+ */
+ String ID = "id"; //$NON-NLS-1$
- /**
- * A human-readable string describing the repository.
- */
- String NAME = "name"; //$NON-NLS-1$
+ /**
+ * A human-readable string describing the repository.
+ */
+ String NAME = "name"; //$NON-NLS-1$
- /**
- * The location of the repodata folder. It can point locally (file://),
- * remotely (http://), or via ftp (ftp://).
- */
- String BASE_URL = "baseurl"; //$NON-NLS-1$
+ /**
+ * The location of the repodata folder. It can point locally (file://),
+ * remotely (http://), or via ftp (ftp://).
+ */
+ String BASE_URL = "baseurl"; //$NON-NLS-1$
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Messages.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Messages.java
index 4780a056e1..e461c0716a 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/Messages.java
@@ -17,205 +17,205 @@ import org.eclipse.osgi.util.NLS;
*/
public final class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.createrepo.messages"; //$NON-NLS-1$
-
- // CreaterepoWizard
- /****/
- public static String CreaterepoWizard_errorCreatingProject;
- /****/
- public static String CreaterepoWizard_openFileOnCreation;
- /****/
- public static String CreaterepoWizard_errorOpeningNewlyCreatedFile;
-
- // CreaterepoNewWizardPageOne
- /****/
- public static String CreaterepoNewWizardPageOne_wizardPageName;
- /****/
- public static String CreaterepoNewWizardPageOne_wizardPageTitle;
- /****/
- public static String CreaterepoNewWizardPageOne_wizardPageDescription;
-
- // CreaterepoNewWizardPageTwo
- /****/
- public static String CreaterepoNewWizardPageTwo_wizardPageName;
- /****/
- public static String CreaterepoNewWizardPageTwo_wizardPageTitle;
- /****/
- public static String CreaterepoNewWizardPageTwo_wizardPageDescription;
- /****/
- public static String CreaterepoNewWizardPageTwo_labelID;
- /****/
- public static String CreaterepoNewWizardPageTwo_labelName;
- /****/
- public static String CreaterepoNewWizardPageTwo_labelURL;
- /****/
- public static String CreaterepoNewWizardPageTwo_errorID;
- /****/
- public static String CreaterepoNewWizardPageTwo_errorName;
- /****/
- public static String CreaterepoNewWizardPageTwo_errorURL;
- /****/
- public static String CreaterepoNewWizardPageTwo_tooltipID;
- /****/
- public static String CreaterepoNewWizardPageTwo_tooltipName;
- /****/
- public static String CreaterepoNewWizardPageTwo_tooltipURL;
-
- // CreaterepoProject
- /****/
- public static String CreaterepoProject_executeCreaterepo;
- /****/
- public static String CreaterepoProject_errorGettingFile;
- /****/
- public static String CreaterepoProject_consoleName;
-
- // Createrepo
- /****/
- public static String Createrepo_jobName;
- /****/
- public static String Createrepo_jobCancelled;
- /****/
- public static String Createrepo_errorExecuting;
- /****/
- public static String Createrepo_errorTryingToFindCommand;
- /****/
- public static String Createrepo_errorCommandNotFound;
- /****/
- public static String Createrepo_errorWrongVersionCreaterepo;
- /****/
- public static String Createrepo_errorWrongVersionYum;
- /****/
- public static String Createrepo_errorCancelled;
- /****/
- public static String Createrepo_errorPasingVersion;
-
- // RepoFormEditor
- /****/
- public static String RepoFormEditor_errorInitializingForm;
- /****/
- public static String RepoFormEditor_errorInitializingProject;
-
- // ImportRPMsPage
- /****/
- public static String ImportRPMsPage_title;
- /****/
- public static String ImportRPMsPage_formHeaderText;
- /****/
- public static String ImportRPMsPage_sectionTitle;
- /****/
- public static String ImportRPMsPage_sectionInstruction;
- /****/
- public static String ImportRPMsPage_buttonImportRPMs;
- /****/
- public static String ImportRPMsPage_buttonRemoveRPMs;
- /****/
- public static String ImportRPMsPage_buttonCreateRepo;
- /****/
- public static String ImportRPMsPage_errorRefreshingTree;
- /****/
- public static String ImportRPMsPage_errorResourceChanged;
-
- // ImportRPMsPage$ImportButtonListener
- /****/
- public static String ImportButtonListener_error;
-
- // ImportRPMsPage$RemoveButtonListener
- /****/
- public static String RemoveButtonListener_error;
-
- // MetadataPage
- /****/
- public static String MetadataPage_title;
- /****/
- public static String MetadataPage_formHeaderText;
- /****/
- public static String MetadataPage_sectionTitleRevision;
- /****/
- public static String MetadataPage_sectionInstructionRevision;
- /****/
- public static String MetadataPage_labelRevision;
- /****/
- public static String MetadataPage_sectionTitleTags;
- /****/
- public static String MetadataPage_sectionInstructionTags;
- /****/
- public static String MetadataPage_labelTags;
- /****/
- public static String MetadataPage_buttonAddTag;
- /****/
- public static String MetadataPage_buttonEditTag;
- /****/
- public static String MetadataPage_buttonRemoveTag;
- /****/
- public static String MetadataPage_errorSavingPreferences;
-
- // CreaterepoResourceChangeListener
- /****/
- public static String CreaterepoResourceChangeListener_errorGettingResource;
-
- // CreaterepoPreferencePage
- /****/
- public static String CreaterepoPreferencePage_description;
- /****/
- public static String CreaterepoPreferencePage_generalGroupLabel;
- /****/
- public static String CreaterepoPreferencePage_booleanChecksumName;
- /****/
- public static String CreaterepoPreferencePage_booleanGenerateSQLDB;
- /****/
- public static String CreaterepoPreferencePage_booleanIgnoreSymlinks;
- /****/
- public static String CreaterepoPreferencePage_booleanPrettyXML;
- /****/
- public static String CreaterepoPreferencePage_numWorkers;
- /****/
- public static String CreaterepoPreferencePage_updateGroupLabel;
- /****/
- public static String CreaterepoPreferencePage_booleanCheckTS;
- /****/
- public static String CreaterepoPreferencePage_checkTSNote;
- /****/
- public static String CreaterepoPreferencePage_changelogGroupLabel;
- /****/
- public static String CreaterepoPreferencePage_numChangelogLimit;
- /****/
- public static String CreaterepoPreferencePage_checksumGroupLabel;
- /****/
- public static String CreaterepoPreferencePage_compressionGroupLabel;
-
- // CreaterepoGeneralPropertyPage
- /****/
- public static String CreaterepoGeneralPropertyPage_projectSettings;
- /****/
- public static String CreaterepoGeneralPropertyPage_workspaceSettings;
-
- // CreaterepoDeltaPropertyPage
- /****/
- public static String CreaterepoDeltaPropertyPage_description;
- /****/
- public static String CreaterepoDeltaPropertyPage_groupLabel;
- /****/
- public static String CreaterepoDeltaPropertyPage_groupDirectoryLabel;
- /****/
- public static String CreaterepoDeltaPropertyPage_booleanEnableLabel;
- /****/
- public static String CreaterepoDeltaPropertyPage_maxNumberOfDeltas;
- /****/
- public static String CreaterepoDeltaPropertyPage_maxDeltaSize;
- /****/
- public static String CreaterepoDeltaPropertyPage_errorInvalidText;
- /****/
- public static String CreaterepoDeltaPropertyPage_directoryDescription;
- /****/
- public static String CreaterepoDeltaPropertyPage_directoryDialogLabel;
-
- // ImportRPMDropListener
- /****/
- public static String ImportRPMDropListener_errorCopyingFileToProject;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.createrepo.messages"; //$NON-NLS-1$
+
+ // CreaterepoWizard
+ /****/
+ public static String CreaterepoWizard_errorCreatingProject;
+ /****/
+ public static String CreaterepoWizard_openFileOnCreation;
+ /****/
+ public static String CreaterepoWizard_errorOpeningNewlyCreatedFile;
+
+ // CreaterepoNewWizardPageOne
+ /****/
+ public static String CreaterepoNewWizardPageOne_wizardPageName;
+ /****/
+ public static String CreaterepoNewWizardPageOne_wizardPageTitle;
+ /****/
+ public static String CreaterepoNewWizardPageOne_wizardPageDescription;
+
+ // CreaterepoNewWizardPageTwo
+ /****/
+ public static String CreaterepoNewWizardPageTwo_wizardPageName;
+ /****/
+ public static String CreaterepoNewWizardPageTwo_wizardPageTitle;
+ /****/
+ public static String CreaterepoNewWizardPageTwo_wizardPageDescription;
+ /****/
+ public static String CreaterepoNewWizardPageTwo_labelID;
+ /****/
+ public static String CreaterepoNewWizardPageTwo_labelName;
+ /****/
+ public static String CreaterepoNewWizardPageTwo_labelURL;
+ /****/
+ public static String CreaterepoNewWizardPageTwo_errorID;
+ /****/
+ public static String CreaterepoNewWizardPageTwo_errorName;
+ /****/
+ public static String CreaterepoNewWizardPageTwo_errorURL;
+ /****/
+ public static String CreaterepoNewWizardPageTwo_tooltipID;
+ /****/
+ public static String CreaterepoNewWizardPageTwo_tooltipName;
+ /****/
+ public static String CreaterepoNewWizardPageTwo_tooltipURL;
+
+ // CreaterepoProject
+ /****/
+ public static String CreaterepoProject_executeCreaterepo;
+ /****/
+ public static String CreaterepoProject_errorGettingFile;
+ /****/
+ public static String CreaterepoProject_consoleName;
+
+ // Createrepo
+ /****/
+ public static String Createrepo_jobName;
+ /****/
+ public static String Createrepo_jobCancelled;
+ /****/
+ public static String Createrepo_errorExecuting;
+ /****/
+ public static String Createrepo_errorTryingToFindCommand;
+ /****/
+ public static String Createrepo_errorCommandNotFound;
+ /****/
+ public static String Createrepo_errorWrongVersionCreaterepo;
+ /****/
+ public static String Createrepo_errorWrongVersionYum;
+ /****/
+ public static String Createrepo_errorCancelled;
+ /****/
+ public static String Createrepo_errorPasingVersion;
+
+ // RepoFormEditor
+ /****/
+ public static String RepoFormEditor_errorInitializingForm;
+ /****/
+ public static String RepoFormEditor_errorInitializingProject;
+
+ // ImportRPMsPage
+ /****/
+ public static String ImportRPMsPage_title;
+ /****/
+ public static String ImportRPMsPage_formHeaderText;
+ /****/
+ public static String ImportRPMsPage_sectionTitle;
+ /****/
+ public static String ImportRPMsPage_sectionInstruction;
+ /****/
+ public static String ImportRPMsPage_buttonImportRPMs;
+ /****/
+ public static String ImportRPMsPage_buttonRemoveRPMs;
+ /****/
+ public static String ImportRPMsPage_buttonCreateRepo;
+ /****/
+ public static String ImportRPMsPage_errorRefreshingTree;
+ /****/
+ public static String ImportRPMsPage_errorResourceChanged;
+
+ // ImportRPMsPage$ImportButtonListener
+ /****/
+ public static String ImportButtonListener_error;
+
+ // ImportRPMsPage$RemoveButtonListener
+ /****/
+ public static String RemoveButtonListener_error;
+
+ // MetadataPage
+ /****/
+ public static String MetadataPage_title;
+ /****/
+ public static String MetadataPage_formHeaderText;
+ /****/
+ public static String MetadataPage_sectionTitleRevision;
+ /****/
+ public static String MetadataPage_sectionInstructionRevision;
+ /****/
+ public static String MetadataPage_labelRevision;
+ /****/
+ public static String MetadataPage_sectionTitleTags;
+ /****/
+ public static String MetadataPage_sectionInstructionTags;
+ /****/
+ public static String MetadataPage_labelTags;
+ /****/
+ public static String MetadataPage_buttonAddTag;
+ /****/
+ public static String MetadataPage_buttonEditTag;
+ /****/
+ public static String MetadataPage_buttonRemoveTag;
+ /****/
+ public static String MetadataPage_errorSavingPreferences;
+
+ // CreaterepoResourceChangeListener
+ /****/
+ public static String CreaterepoResourceChangeListener_errorGettingResource;
+
+ // CreaterepoPreferencePage
+ /****/
+ public static String CreaterepoPreferencePage_description;
+ /****/
+ public static String CreaterepoPreferencePage_generalGroupLabel;
+ /****/
+ public static String CreaterepoPreferencePage_booleanChecksumName;
+ /****/
+ public static String CreaterepoPreferencePage_booleanGenerateSQLDB;
+ /****/
+ public static String CreaterepoPreferencePage_booleanIgnoreSymlinks;
+ /****/
+ public static String CreaterepoPreferencePage_booleanPrettyXML;
+ /****/
+ public static String CreaterepoPreferencePage_numWorkers;
+ /****/
+ public static String CreaterepoPreferencePage_updateGroupLabel;
+ /****/
+ public static String CreaterepoPreferencePage_booleanCheckTS;
+ /****/
+ public static String CreaterepoPreferencePage_checkTSNote;
+ /****/
+ public static String CreaterepoPreferencePage_changelogGroupLabel;
+ /****/
+ public static String CreaterepoPreferencePage_numChangelogLimit;
+ /****/
+ public static String CreaterepoPreferencePage_checksumGroupLabel;
+ /****/
+ public static String CreaterepoPreferencePage_compressionGroupLabel;
+
+ // CreaterepoGeneralPropertyPage
+ /****/
+ public static String CreaterepoGeneralPropertyPage_projectSettings;
+ /****/
+ public static String CreaterepoGeneralPropertyPage_workspaceSettings;
+
+ // CreaterepoDeltaPropertyPage
+ /****/
+ public static String CreaterepoDeltaPropertyPage_description;
+ /****/
+ public static String CreaterepoDeltaPropertyPage_groupLabel;
+ /****/
+ public static String CreaterepoDeltaPropertyPage_groupDirectoryLabel;
+ /****/
+ public static String CreaterepoDeltaPropertyPage_booleanEnableLabel;
+ /****/
+ public static String CreaterepoDeltaPropertyPage_maxNumberOfDeltas;
+ /****/
+ public static String CreaterepoDeltaPropertyPage_maxDeltaSize;
+ /****/
+ public static String CreaterepoDeltaPropertyPage_errorInvalidText;
+ /****/
+ public static String CreaterepoDeltaPropertyPage_directoryDescription;
+ /****/
+ public static String CreaterepoDeltaPropertyPage_directoryDialogLabel;
+
+ // ImportRPMDropListener
+ /****/
+ public static String ImportRPMDropListener_errorCopyingFileToProject;
+
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/dnd/ImportRPMDropListener.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/dnd/ImportRPMDropListener.java
index 70f3e4a309..6947fcf68d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/dnd/ImportRPMDropListener.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/dnd/ImportRPMDropListener.java
@@ -30,69 +30,69 @@ import org.eclipse.ui.console.MessageConsoleStream;
*/
public class ImportRPMDropListener extends ViewerDropAdapter {
- private CreaterepoProject project;
+ private CreaterepoProject project;
- /**
- * Default constructor.
- *
- * @param viewer The viewer to listen to.
- * @param project The createrepo project.
- */
- public ImportRPMDropListener(Viewer viewer, CreaterepoProject project) {
- super(viewer);
- this.project = project;
- }
+ /**
+ * Default constructor.
+ *
+ * @param viewer The viewer to listen to.
+ * @param project The createrepo project.
+ */
+ public ImportRPMDropListener(Viewer viewer, CreaterepoProject project) {
+ super(viewer);
+ this.project = project;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.ViewerDropAdapter#dragEnter(org.eclipse.swt.dnd.DropTargetEvent)
- */
- @Override
- public void dragEnter(DropTargetEvent event) {
- // only support file transfer types
- if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) {
- // change the detail to a drag copy if is file transfer
- event.detail = DND.DROP_COPY;
- }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ViewerDropAdapter#dragEnter(org.eclipse.swt.dnd.DropTargetEvent)
+ */
+ @Override
+ public void dragEnter(DropTargetEvent event) {
+ // only support file transfer types
+ if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) {
+ // change the detail to a drag copy if is file transfer
+ event.detail = DND.DROP_COPY;
+ }
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.ViewerDropAdapter#validateDrop(java.lang.Object, int, org.eclipse.swt.dnd.TransferData)
- */
- @Override
- public boolean validateDrop(Object target, int operation,
- TransferData transferType) {
- // true if it is a file transfer and is a copy action
- if (FileTransfer.getInstance().isSupportedType(transferType) && operation == DND.DROP_COPY) {
- return true;
- }
- return false;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ViewerDropAdapter#validateDrop(java.lang.Object, int, org.eclipse.swt.dnd.TransferData)
+ */
+ @Override
+ public boolean validateDrop(Object target, int operation,
+ TransferData transferType) {
+ // true if it is a file transfer and is a copy action
+ if (FileTransfer.getInstance().isSupportedType(transferType) && operation == DND.DROP_COPY) {
+ return true;
+ }
+ return false;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.ViewerDropAdapter#performDrop(java.lang.Object)
- */
- @Override
- public boolean performDrop(Object data) {
- // data should be an array of paths to the file being transferred
- if (data instanceof String[]) {
- String[] dragData = (String[]) data;
- for (String str : dragData) {
- IPath path = new Path(str);
- try {
- project.importRPM(path.toFile());
- } catch (CoreException e) {
- MessageConsoleStream os = CreaterepoUtils.findConsole(Messages.CreaterepoProject_consoleName)
- .newMessageStream();
- os.print(NLS.bind(Messages.ImportRPMDropListener_errorCopyingFileToProject,
- path.segment(path.segmentCount()-1)));
- }
- }
- return true;
- }
- return false;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ViewerDropAdapter#performDrop(java.lang.Object)
+ */
+ @Override
+ public boolean performDrop(Object data) {
+ // data should be an array of paths to the file being transferred
+ if (data instanceof String[]) {
+ String[] dragData = (String[]) data;
+ for (String str : dragData) {
+ IPath path = new Path(str);
+ try {
+ project.importRPM(path.toFile());
+ } catch (CoreException e) {
+ MessageConsoleStream os = CreaterepoUtils.findConsole(Messages.CreaterepoProject_consoleName)
+ .newMessageStream();
+ os.print(NLS.bind(Messages.ImportRPMDropListener_errorCopyingFileToProject,
+ path.segment(path.segmentCount()-1)));
+ }
+ }
+ return true;
+ }
+ return false;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/ImportRPMsPage.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/ImportRPMsPage.java
index c4be1d71bd..915644fb96 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/ImportRPMsPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/ImportRPMsPage.java
@@ -69,386 +69,386 @@ import org.eclipse.ui.menus.IMenuService;
*/
public class ImportRPMsPage extends FormPage implements IResourceChangeListener {
- private CreaterepoProject project;
-
- private FormToolkit toolkit;
- private ScrolledForm form;
-
- private Composite buttonList;
- private Tree tree;
-
- private static final String MENU_URI = "toolbar:formsToolbar"; //$NON-NLS-1$
- private static final String HEADER_ICON = "/icons/repository_rep.gif"; //$NON-NLS-1$
-
- /**
- * Default constructor.
- *
- * @param editor The editor.
- * @param project The project.
- */
- public ImportRPMsPage(FormEditor editor, CreaterepoProject project) {
- super(editor, Messages.ImportRPMsPage_title, Messages.ImportRPMsPage_title);
- this.project = project;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.forms.editor.FormPage#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput)
- */
- @Override
- public void init(IEditorSite site, IEditorInput input) {
- super.init(site, input);
- // add the resource change listener
- ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.forms.editor.FormPage#dispose()
- */
- @Override
- public void dispose() {
- // remove the resource change listener
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
- super.dispose();
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.forms.editor.FormPage#createFormContent(org.eclipse.ui.forms.IManagedForm)
- */
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- // setting up the form page
- super.createFormContent(managedForm);
- GridLayout layout = new GridLayout();
- GridData data = new GridData();
- toolkit = managedForm.getToolkit();
- form = managedForm.getForm();
- form.setText(Messages.ImportRPMsPage_formHeaderText);
- form.setImage(Activator.getImageDescriptor(HEADER_ICON).createImage());
- ToolBarManager toolbarManager = (ToolBarManager) form.getToolBarManager();
- toolkit.decorateFormHeading(form.getForm());
-
- // add the menuContribution from MANIFEST.MF to the form
- IMenuService menuService = (IMenuService) getSite().getService(IMenuService.class);
- menuService.populateContributionManager(toolbarManager, MENU_URI);
- toolbarManager.update(true);
-
- layout = new GridLayout(2, true);
- layout.marginWidth = 6; layout.marginHeight = 12;
- form.getBody().setLayout(layout);
-
- // Section and its client area to manage importing the RPMs
- Section rpmSection = toolkit.createSection(form.getBody(), Section.DESCRIPTION
- | ExpandableComposite.TITLE_BAR);
- layout = new GridLayout();
- rpmSection.setText(Messages.ImportRPMsPage_sectionTitle);
- rpmSection.setDescription(Messages.ImportRPMsPage_sectionInstruction);
- rpmSection.setLayoutData(expandComposite());
-
- // the client area containing the tree + buttons
- Composite sectionClient = toolkit.createComposite(rpmSection);
- layout = new GridLayout(2, false);
- layout.marginWidth = 1; layout.marginHeight = 7;
- sectionClient.setLayout(layout);
- TreeViewer viewer = new TreeViewer(sectionClient, SWT.BORDER | SWT.MULTI | SWT.HORIZONTAL
- | SWT.VERTICAL | SWT.LEFT_TO_RIGHT | SWT.SMOOTH);
- viewer.addDropSupport(DND.DROP_COPY, new Transfer[] {FileTransfer.getInstance()},
- new ImportRPMDropListener(viewer, project));
- tree = viewer.getTree();
- tree.setLayoutData(expandComposite());
-
- buttonList = toolkit.createComposite(sectionClient);
- layout = new GridLayout();
- data = new GridData(SWT.BEGINNING, SWT.FILL, false, true);
- layout.marginWidth = 0; layout.marginHeight = 0;
- buttonList.setLayout(layout);
- buttonList.setLayoutData(data);
-
- createPushButton(buttonList, Messages.ImportRPMsPage_buttonImportRPMs,
- toolkit).addSelectionListener(new ImportButtonListener());
- createPushButton(buttonList, Messages.ImportRPMsPage_buttonRemoveRPMs,
- toolkit).addSelectionListener(new RemoveButtonListener());
- createSpace();
-
- createPushButton(buttonList, Messages.ImportRPMsPage_buttonCreateRepo,
- toolkit).addSelectionListener(new CreaterepoButtonListener());
-
- refreshTree();
- rpmSection.setClient(sectionClient);
- managedForm.refresh();
- }
-
- /**
- * Make a GridData that expands to fill both horizontally
- * and vertically.
- *
- * @return The created GridData.
- */
- private static GridData expandComposite() {
- GridData data = new GridData();
- data.verticalAlignment = GridData.FILL;
- data.horizontalAlignment = GridData.FILL;
- data.grabExcessVerticalSpace = true;
- data.grabExcessHorizontalSpace = true;
- return data;
- }
-
- /**
- * Create a push style button.
- *
- * @param parent The parent the button will belong to.
- * @param buttonText The text show on the button.
- * @param toolkit The form toolkit used in creating a button.
- * @return The button created.
- */
- private static Button createPushButton(Composite parent, String buttonText, FormToolkit toolkit) {
- Button button = toolkit.createButton(parent, buttonText, SWT.PUSH | SWT.FLAT
- | SWT.CENTER | SWT.LEFT_TO_RIGHT);
- button.setFont(parent.getFont());
- GridData gd = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- button.setLayoutData(gd);
- return button;
- }
-
- /**
- * Create space between composites, such as buttons within a button list.
- *
- * @param parent The composite to attach a space to.
- */
- private void createSpace() {
- new Label(buttonList, SWT.NONE).setLayoutData(new GridData(0,0));
- }
-
- /**
- * On creating the form content the tree will be populated with
- * RPMs found in the root of the current project.
- *
- * @throws CoreException Thrown when getting rpms from project fails.
- */
- private void refreshTree() {
- tree.removeAll();
- try {
- for (IResource rpm : project.getRPMs()) {
- addItemToTree(rpm.getName());
- }
- } catch (CoreException e) {
- Activator.logError(Messages.ImportRPMsPage_errorRefreshingTree, e);
- }
- tree.setFocus();
- }
-
- /**
- * Add a new item to the tree if it does not yet exist. A null or empty
- * string will be ignored.
- *
- * @param itemName The name of the new item.
- * @return True if it does not exist and has been added, false otherwise.
- */
- private boolean addItemToTree(String itemName) {
- boolean exists = false;
- if (itemName == null || itemName.isEmpty())
- return false;
- // check to see if the tree item exists in the tree
- if (tree.getItemCount() > 0) {
- for (TreeItem item : tree.getItems()) {
- if (item.getText().equals(itemName)) {
- exists = true;
- }
- }
- }
- // if the tree item doesnt exists or the tree is empty
- if (!exists || tree.getItemCount() == 0) {
- TreeItem treeItem = new TreeItem(tree, SWT.NONE);
- treeItem.setText(itemName);
- return true;
- }
- return false;
- }
-
- /**
- * Handle the import button execution on the Import RPMs page.
- */
- public class ImportButtonListener extends SelectionAdapter {
- private final String[] EXTENSION_FILTERS = {"*." + ICreaterepoConstants.RPM_FILE_EXTENSION}; //$NON-NLS-1$
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- IWorkbench workbench = PlatformUI.getWorkbench();
- Shell shell = workbench.getModalDialogShellProvider().getShell();
- FileDialog fileDialog = new FileDialog(shell, SWT.MULTI);
- fileDialog.setFilterExtensions(EXTENSION_FILTERS);
- if (fileDialog.open() != null) {
- String[] files = fileDialog.getFileNames();
- if (files.length > 0) {
- String directoryPath = fileDialog.getFilterPath();
- for (String file : files) {
- File externalFile = new File(directoryPath, file);
- try {
- project.importRPM(externalFile);
- } catch (CoreException e1) {
- Activator.logError(Messages.ImportButtonListener_error, e1);
- }
- }
- refreshTree();
- }
- }
- }
- }
-
- /**
- * Handle the remove button execution on the Import RPMs page.
- */
- public class RemoveButtonListener extends SelectionAdapter {
- /*
- * (non-Javadoc)
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- TreeItem[] selection = tree.getSelection();
- try {
- List<IResource> rpms = project.getRPMs();
- if (selection.length > 0 && !rpms.isEmpty()) {
- for (IResource resource : rpms) {
- for (TreeItem treeItem : selection) {
- deleteIfEquals(resource, treeItem);
- }
- }
- }
- refreshTree();
- } catch (CoreException e1) {
- Activator.logError(Messages.RemoveButtonListener_error, e1);
- }
- }
-
- /**
+ private CreaterepoProject project;
+
+ private FormToolkit toolkit;
+ private ScrolledForm form;
+
+ private Composite buttonList;
+ private Tree tree;
+
+ private static final String MENU_URI = "toolbar:formsToolbar"; //$NON-NLS-1$
+ private static final String HEADER_ICON = "/icons/repository_rep.gif"; //$NON-NLS-1$
+
+ /**
+ * Default constructor.
+ *
+ * @param editor The editor.
+ * @param project The project.
+ */
+ public ImportRPMsPage(FormEditor editor, CreaterepoProject project) {
+ super(editor, Messages.ImportRPMsPage_title, Messages.ImportRPMsPage_title);
+ this.project = project;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.forms.editor.FormPage#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput)
+ */
+ @Override
+ public void init(IEditorSite site, IEditorInput input) {
+ super.init(site, input);
+ // add the resource change listener
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.forms.editor.FormPage#dispose()
+ */
+ @Override
+ public void dispose() {
+ // remove the resource change listener
+ ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
+ super.dispose();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.forms.editor.FormPage#createFormContent(org.eclipse.ui.forms.IManagedForm)
+ */
+ @Override
+ protected void createFormContent(IManagedForm managedForm) {
+ // setting up the form page
+ super.createFormContent(managedForm);
+ GridLayout layout = new GridLayout();
+ GridData data = new GridData();
+ toolkit = managedForm.getToolkit();
+ form = managedForm.getForm();
+ form.setText(Messages.ImportRPMsPage_formHeaderText);
+ form.setImage(Activator.getImageDescriptor(HEADER_ICON).createImage());
+ ToolBarManager toolbarManager = (ToolBarManager) form.getToolBarManager();
+ toolkit.decorateFormHeading(form.getForm());
+
+ // add the menuContribution from MANIFEST.MF to the form
+ IMenuService menuService = (IMenuService) getSite().getService(IMenuService.class);
+ menuService.populateContributionManager(toolbarManager, MENU_URI);
+ toolbarManager.update(true);
+
+ layout = new GridLayout(2, true);
+ layout.marginWidth = 6; layout.marginHeight = 12;
+ form.getBody().setLayout(layout);
+
+ // Section and its client area to manage importing the RPMs
+ Section rpmSection = toolkit.createSection(form.getBody(), Section.DESCRIPTION
+ | ExpandableComposite.TITLE_BAR);
+ layout = new GridLayout();
+ rpmSection.setText(Messages.ImportRPMsPage_sectionTitle);
+ rpmSection.setDescription(Messages.ImportRPMsPage_sectionInstruction);
+ rpmSection.setLayoutData(expandComposite());
+
+ // the client area containing the tree + buttons
+ Composite sectionClient = toolkit.createComposite(rpmSection);
+ layout = new GridLayout(2, false);
+ layout.marginWidth = 1; layout.marginHeight = 7;
+ sectionClient.setLayout(layout);
+ TreeViewer viewer = new TreeViewer(sectionClient, SWT.BORDER | SWT.MULTI | SWT.HORIZONTAL
+ | SWT.VERTICAL | SWT.LEFT_TO_RIGHT | SWT.SMOOTH);
+ viewer.addDropSupport(DND.DROP_COPY, new Transfer[] {FileTransfer.getInstance()},
+ new ImportRPMDropListener(viewer, project));
+ tree = viewer.getTree();
+ tree.setLayoutData(expandComposite());
+
+ buttonList = toolkit.createComposite(sectionClient);
+ layout = new GridLayout();
+ data = new GridData(SWT.BEGINNING, SWT.FILL, false, true);
+ layout.marginWidth = 0; layout.marginHeight = 0;
+ buttonList.setLayout(layout);
+ buttonList.setLayoutData(data);
+
+ createPushButton(buttonList, Messages.ImportRPMsPage_buttonImportRPMs,
+ toolkit).addSelectionListener(new ImportButtonListener());
+ createPushButton(buttonList, Messages.ImportRPMsPage_buttonRemoveRPMs,
+ toolkit).addSelectionListener(new RemoveButtonListener());
+ createSpace();
+
+ createPushButton(buttonList, Messages.ImportRPMsPage_buttonCreateRepo,
+ toolkit).addSelectionListener(new CreaterepoButtonListener());
+
+ refreshTree();
+ rpmSection.setClient(sectionClient);
+ managedForm.refresh();
+ }
+
+ /**
+ * Make a GridData that expands to fill both horizontally
+ * and vertically.
+ *
+ * @return The created GridData.
+ */
+ private static GridData expandComposite() {
+ GridData data = new GridData();
+ data.verticalAlignment = GridData.FILL;
+ data.horizontalAlignment = GridData.FILL;
+ data.grabExcessVerticalSpace = true;
+ data.grabExcessHorizontalSpace = true;
+ return data;
+ }
+
+ /**
+ * Create a push style button.
+ *
+ * @param parent The parent the button will belong to.
+ * @param buttonText The text show on the button.
+ * @param toolkit The form toolkit used in creating a button.
+ * @return The button created.
+ */
+ private static Button createPushButton(Composite parent, String buttonText, FormToolkit toolkit) {
+ Button button = toolkit.createButton(parent, buttonText, SWT.PUSH | SWT.FLAT
+ | SWT.CENTER | SWT.LEFT_TO_RIGHT);
+ button.setFont(parent.getFont());
+ GridData gd = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
+ button.setLayoutData(gd);
+ return button;
+ }
+
+ /**
+ * Create space between composites, such as buttons within a button list.
+ *
+ * @param parent The composite to attach a space to.
+ */
+ private void createSpace() {
+ new Label(buttonList, SWT.NONE).setLayoutData(new GridData(0,0));
+ }
+
+ /**
+ * On creating the form content the tree will be populated with
+ * RPMs found in the root of the current project.
+ *
+ * @throws CoreException Thrown when getting rpms from project fails.
+ */
+ private void refreshTree() {
+ tree.removeAll();
+ try {
+ for (IResource rpm : project.getRPMs()) {
+ addItemToTree(rpm.getName());
+ }
+ } catch (CoreException e) {
+ Activator.logError(Messages.ImportRPMsPage_errorRefreshingTree, e);
+ }
+ tree.setFocus();
+ }
+
+ /**
+ * Add a new item to the tree if it does not yet exist. A null or empty
+ * string will be ignored.
+ *
+ * @param itemName The name of the new item.
+ * @return True if it does not exist and has been added, false otherwise.
+ */
+ private boolean addItemToTree(String itemName) {
+ boolean exists = false;
+ if (itemName == null || itemName.isEmpty())
+ return false;
+ // check to see if the tree item exists in the tree
+ if (tree.getItemCount() > 0) {
+ for (TreeItem item : tree.getItems()) {
+ if (item.getText().equals(itemName)) {
+ exists = true;
+ }
+ }
+ }
+ // if the tree item doesnt exists or the tree is empty
+ if (!exists || tree.getItemCount() == 0) {
+ TreeItem treeItem = new TreeItem(tree, SWT.NONE);
+ treeItem.setText(itemName);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Handle the import button execution on the Import RPMs page.
+ */
+ public class ImportButtonListener extends SelectionAdapter {
+ private final String[] EXTENSION_FILTERS = {"*." + ICreaterepoConstants.RPM_FILE_EXTENSION}; //$NON-NLS-1$
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ IWorkbench workbench = PlatformUI.getWorkbench();
+ Shell shell = workbench.getModalDialogShellProvider().getShell();
+ FileDialog fileDialog = new FileDialog(shell, SWT.MULTI);
+ fileDialog.setFilterExtensions(EXTENSION_FILTERS);
+ if (fileDialog.open() != null) {
+ String[] files = fileDialog.getFileNames();
+ if (files.length > 0) {
+ String directoryPath = fileDialog.getFilterPath();
+ for (String file : files) {
+ File externalFile = new File(directoryPath, file);
+ try {
+ project.importRPM(externalFile);
+ } catch (CoreException e1) {
+ Activator.logError(Messages.ImportButtonListener_error, e1);
+ }
+ }
+ refreshTree();
+ }
+ }
+ }
+ }
+
+ /**
+ * Handle the remove button execution on the Import RPMs page.
+ */
+ public class RemoveButtonListener extends SelectionAdapter {
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ TreeItem[] selection = tree.getSelection();
+ try {
+ List<IResource> rpms = project.getRPMs();
+ if (selection.length > 0 && !rpms.isEmpty()) {
+ for (IResource resource : rpms) {
+ for (TreeItem treeItem : selection) {
+ deleteIfEquals(resource, treeItem);
+ }
+ }
+ }
+ refreshTree();
+ } catch (CoreException e1) {
+ Activator.logError(Messages.RemoveButtonListener_error, e1);
+ }
+ }
+
+ /**
* Delete the resource if the tree item has the same name as it.
*
* @param resource The resource in the project (the RPM).
* @param treeItem The RPM in the tree.
* @throws CoreException Thrown when deleting fails.
*/
- private void deleteIfEquals(IResource resource, TreeItem treeItem) throws CoreException {
+ private void deleteIfEquals(IResource resource, TreeItem treeItem) throws CoreException {
if (resource.getName().equals(treeItem.getText())) {
resource.delete(false, new NullProgressMonitor());
}
}
- }
-
- /**
- * Handle the createrepo button execution on the Import RPMs page.
- */
- public class CreaterepoButtonListener extends SelectionAdapter {
- /*
- * (non-Javadoc)
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- Job executeCreaterepo = new Job(Messages.Createrepo_jobName) {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- monitor.beginTask(Messages.CreaterepoProject_executeCreaterepo, IProgressMonitor.UNKNOWN);
- MessageConsoleStream os = CreaterepoUtils.findConsole(Messages.CreaterepoProject_consoleName)
- .newMessageStream();
- return project.createrepo(os);
- } catch (CoreException e) {
- Activator.logError(Messages.Createrepo_errorExecuting, e);
- } finally {
- monitor.done();
- }
- return null;
- }
- };
- executeCreaterepo.setUser(true);
- executeCreaterepo.schedule();
- }
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
- */
- @Override
- public void resourceChanged(IResourceChangeEvent event) {
- // might have to place the delete/close events to RepoMetadataFormEditor to
- // occur for all the pages
- switch (event.getType()) {
- case IResourceChangeEvent.POST_CHANGE:
- try {
- IPath projectPath = project.getContentFolder().getFullPath();
- IResourceDelta delta = event.getDelta().findMember(projectPath);
- // delta is only null when nothing changed within the project's
- // content folder
- if (delta != null) {
- delta.accept(new CreaterepoDeltaVisitor());
- }
- } catch (CoreException e) {
- Activator.logError(Messages.ImportRPMsPage_errorResourceChanged, e);
- }
- break;
- }
- }
-
- /**
- * Class to control what to do if something happens in the workspace.
- */
- class CreaterepoDeltaVisitor implements IResourceDeltaVisitor {
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta)
- */
- @Override
- public boolean visit(IResourceDelta delta) {
- // exit if the project is being removed or closed
- if (delta.getKind() == IResourceDelta.REMOVED ||
- (delta.getFlags() | delta.getKind()) == (IResourceDelta.OPEN | IResourceDelta.CHANGED)) {
- return false;
- }
- // get the files that were removed/added and exit if nothing was removed/added
- IResourceDelta[] removedFiles = delta.getAffectedChildren(IResourceDelta.REMOVED);
- IResourceDelta[] addedFiles = delta.getAffectedChildren(IResourceDelta.ADDED);
- if (removedFiles.length <= 0 && addedFiles.length == 0) {
- return false;
- }
- // check if at least 1 of the files removed is an RPM and break out if so
- boolean rpmsDeleted = false;
- for (IResourceDelta resourceDelta : removedFiles) {
- String extension = resourceDelta.getResource().getFileExtension();
- if (extension != null && extension.equals(ICreaterepoConstants.RPM_FILE_EXTENSION)) {
- rpmsDeleted = true;
- break;
- }
- }
- // check if at least 1 of the files added is an RPM and break out if so
- boolean rpmsAdded = false;
- for (IResourceDelta resourceDelta : addedFiles) {
- String extension = resourceDelta.getResource().getFileExtension();
- if (extension != null && extension.equals(ICreaterepoConstants.RPM_FILE_EXTENSION)) {
- rpmsAdded = true;
- break;
- }
- }
- // exit if none of the removed/added files is an RPM; no need to update list
- if (!rpmsDeleted && !rpmsAdded) {
- return false;
- }
- // deals with updating the UI of the page
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- refreshTree();
- }
- });
- return false;
- }
- }
+ }
+
+ /**
+ * Handle the createrepo button execution on the Import RPMs page.
+ */
+ public class CreaterepoButtonListener extends SelectionAdapter {
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ Job executeCreaterepo = new Job(Messages.Createrepo_jobName) {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ monitor.beginTask(Messages.CreaterepoProject_executeCreaterepo, IProgressMonitor.UNKNOWN);
+ MessageConsoleStream os = CreaterepoUtils.findConsole(Messages.CreaterepoProject_consoleName)
+ .newMessageStream();
+ return project.createrepo(os);
+ } catch (CoreException e) {
+ Activator.logError(Messages.Createrepo_errorExecuting, e);
+ } finally {
+ monitor.done();
+ }
+ return null;
+ }
+ };
+ executeCreaterepo.setUser(true);
+ executeCreaterepo.schedule();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
+ */
+ @Override
+ public void resourceChanged(IResourceChangeEvent event) {
+ // might have to place the delete/close events to RepoMetadataFormEditor to
+ // occur for all the pages
+ switch (event.getType()) {
+ case IResourceChangeEvent.POST_CHANGE:
+ try {
+ IPath projectPath = project.getContentFolder().getFullPath();
+ IResourceDelta delta = event.getDelta().findMember(projectPath);
+ // delta is only null when nothing changed within the project's
+ // content folder
+ if (delta != null) {
+ delta.accept(new CreaterepoDeltaVisitor());
+ }
+ } catch (CoreException e) {
+ Activator.logError(Messages.ImportRPMsPage_errorResourceChanged, e);
+ }
+ break;
+ }
+ }
+
+ /**
+ * Class to control what to do if something happens in the workspace.
+ */
+ class CreaterepoDeltaVisitor implements IResourceDeltaVisitor {
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta)
+ */
+ @Override
+ public boolean visit(IResourceDelta delta) {
+ // exit if the project is being removed or closed
+ if (delta.getKind() == IResourceDelta.REMOVED ||
+ (delta.getFlags() | delta.getKind()) == (IResourceDelta.OPEN | IResourceDelta.CHANGED)) {
+ return false;
+ }
+ // get the files that were removed/added and exit if nothing was removed/added
+ IResourceDelta[] removedFiles = delta.getAffectedChildren(IResourceDelta.REMOVED);
+ IResourceDelta[] addedFiles = delta.getAffectedChildren(IResourceDelta.ADDED);
+ if (removedFiles.length <= 0 && addedFiles.length == 0) {
+ return false;
+ }
+ // check if at least 1 of the files removed is an RPM and break out if so
+ boolean rpmsDeleted = false;
+ for (IResourceDelta resourceDelta : removedFiles) {
+ String extension = resourceDelta.getResource().getFileExtension();
+ if (extension != null && extension.equals(ICreaterepoConstants.RPM_FILE_EXTENSION)) {
+ rpmsDeleted = true;
+ break;
+ }
+ }
+ // check if at least 1 of the files added is an RPM and break out if so
+ boolean rpmsAdded = false;
+ for (IResourceDelta resourceDelta : addedFiles) {
+ String extension = resourceDelta.getResource().getFileExtension();
+ if (extension != null && extension.equals(ICreaterepoConstants.RPM_FILE_EXTENSION)) {
+ rpmsAdded = true;
+ break;
+ }
+ }
+ // exit if none of the removed/added files is an RPM; no need to update list
+ if (!rpmsDeleted && !rpmsAdded) {
+ return false;
+ }
+ // deals with updating the UI of the page
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ refreshTree();
+ }
+ });
+ return false;
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/MetadataPage.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/MetadataPage.java
index 794591c98c..ad552ac42c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/MetadataPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/MetadataPage.java
@@ -55,384 +55,384 @@ import org.osgi.service.prefs.BackingStoreException;
*/
public class MetadataPage extends FormPage {
- private CreaterepoProject project;
- private IEclipsePreferences eclipsePreferences;
+ private CreaterepoProject project;
+ private IEclipsePreferences eclipsePreferences;
- private FormToolkit toolkit;
- private ScrolledForm form;
+ private FormToolkit toolkit;
+ private ScrolledForm form;
- private Text revisionTxt;
- private Text tagTxt;
- private Tree tagsTree;
- private TreeViewer tagsTreeViewer;
- private Composite buttonList;
+ private Text revisionTxt;
+ private Text tagTxt;
+ private Tree tagsTree;
+ private TreeViewer tagsTreeViewer;
+ private Composite buttonList;
- private static final String MENU_URI = "toolbar:formsToolbar"; //$NON-NLS-1$
- private static final String HEADER_ICON = "/icons/library_obj.gif"; //$NON-NLS-1$
+ private static final String MENU_URI = "toolbar:formsToolbar"; //$NON-NLS-1$
+ private static final String HEADER_ICON = "/icons/library_obj.gif"; //$NON-NLS-1$
- /** Default constructor. */
- public MetadataPage(FormEditor editor, CreaterepoProject project) {
- super(editor, Messages.MetadataPage_title, Messages.MetadataPage_title);
- this.project = project;
- eclipsePreferences = project.getEclipsePreferences();
- }
+ /** Default constructor. */
+ public MetadataPage(FormEditor editor, CreaterepoProject project) {
+ super(editor, Messages.MetadataPage_title, Messages.MetadataPage_title);
+ this.project = project;
+ eclipsePreferences = project.getEclipsePreferences();
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.forms.editor.FormPage#createFormContent(org.eclipse.ui.forms.IManagedForm)
- */
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- // setting up the form page
- super.createFormContent(managedForm);
- GridLayout layout = new GridLayout();
- GridData data = new GridData();
- toolkit = managedForm.getToolkit();
- form = managedForm.getForm();
- form.setText(Messages.MetadataPage_formHeaderText);
- form.setImage(Activator.getImageDescriptor(HEADER_ICON).createImage());
- ToolBarManager toolbarManager = (ToolBarManager) form.getToolBarManager();
- toolkit.decorateFormHeading(form.getForm());
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.forms.editor.FormPage#createFormContent(org.eclipse.ui.forms.IManagedForm)
+ */
+ @Override
+ protected void createFormContent(IManagedForm managedForm) {
+ // setting up the form page
+ super.createFormContent(managedForm);
+ GridLayout layout = new GridLayout();
+ GridData data = new GridData();
+ toolkit = managedForm.getToolkit();
+ form = managedForm.getForm();
+ form.setText(Messages.MetadataPage_formHeaderText);
+ form.setImage(Activator.getImageDescriptor(HEADER_ICON).createImage());
+ ToolBarManager toolbarManager = (ToolBarManager) form.getToolBarManager();
+ toolkit.decorateFormHeading(form.getForm());
- // add the menuContribution from MANIFEST.MF to the form
- IMenuService menuService = (IMenuService) getSite().getService(IMenuService.class);
- menuService.populateContributionManager(toolbarManager, MENU_URI);
- toolbarManager.update(true);
+ // add the menuContribution from MANIFEST.MF to the form
+ IMenuService menuService = (IMenuService) getSite().getService(IMenuService.class);
+ menuService.populateContributionManager(toolbarManager, MENU_URI);
+ toolbarManager.update(true);
- layout = new GridLayout();
- layout.marginWidth = 6; layout.marginHeight = 12;
- form.getBody().setLayout(layout);
+ layout = new GridLayout();
+ layout.marginWidth = 6; layout.marginHeight = 12;
+ form.getBody().setLayout(layout);
- //--------------------------------- REVISION SECTION START ----------
- // Section and its client area to manage updating revision info
- Section revSection = toolkit.createSection(form.getBody(), Section.DESCRIPTION
- | ExpandableComposite.TITLE_BAR);
- layout = new GridLayout();
- data = new GridData();
- data.verticalAlignment = GridData.FILL;
- data.horizontalAlignment = GridData.FILL;
- data.grabExcessHorizontalSpace = true;
- revSection.setText(Messages.MetadataPage_sectionTitleRevision);
- revSection.setDescription(Messages.MetadataPage_sectionInstructionRevision);
- revSection.setLayoutData(data);
+ //--------------------------------- REVISION SECTION START ----------
+ // Section and its client area to manage updating revision info
+ Section revSection = toolkit.createSection(form.getBody(), Section.DESCRIPTION
+ | ExpandableComposite.TITLE_BAR);
+ layout = new GridLayout();
+ data = new GridData();
+ data.verticalAlignment = GridData.FILL;
+ data.horizontalAlignment = GridData.FILL;
+ data.grabExcessHorizontalSpace = true;
+ revSection.setText(Messages.MetadataPage_sectionTitleRevision);
+ revSection.setDescription(Messages.MetadataPage_sectionInstructionRevision);
+ revSection.setLayoutData(data);
- // the client area containing the editing fields
- Composite sectionClient = toolkit.createComposite(revSection);
- layout = new GridLayout(2, false);
- layout.marginWidth = 1; layout.marginHeight = 7;
- sectionClient.setLayout(layout);
+ // the client area containing the editing fields
+ Composite sectionClient = toolkit.createComposite(revSection);
+ layout = new GridLayout(2, false);
+ layout.marginWidth = 1; layout.marginHeight = 7;
+ sectionClient.setLayout(layout);
- revisionTxt = createTextFieldWithLabel(sectionClient, Messages.MetadataPage_labelRevision);
- String prefRevisionTxt = eclipsePreferences.get(CreaterepoPreferenceConstants.PREF_REVISION, ICreaterepoConstants.EMPTY_STRING);
- if (!prefRevisionTxt.isEmpty()) {
- revisionTxt.setText(prefRevisionTxt);
- }
- revisionTxt.addSelectionListener(new SelectionAdapter() {
- /*
- * (non-Javadoc)
- * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- String revisionText = revisionTxt.getText().trim();
- savePreferences(CreaterepoPreferenceConstants.PREF_REVISION, revisionText);
- }
- });
- revSection.setClient(sectionClient);
- //---------- REVISION SECTION END
+ revisionTxt = createTextFieldWithLabel(sectionClient, Messages.MetadataPage_labelRevision);
+ String prefRevisionTxt = eclipsePreferences.get(CreaterepoPreferenceConstants.PREF_REVISION, ICreaterepoConstants.EMPTY_STRING);
+ if (!prefRevisionTxt.isEmpty()) {
+ revisionTxt.setText(prefRevisionTxt);
+ }
+ revisionTxt.addSelectionListener(new SelectionAdapter() {
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ String revisionText = revisionTxt.getText().trim();
+ savePreferences(CreaterepoPreferenceConstants.PREF_REVISION, revisionText);
+ }
+ });
+ revSection.setClient(sectionClient);
+ //---------- REVISION SECTION END
- //--------------------------------- TAGS SECTION START ----------
- // Section and its client area to manage tags
- Section tagSection = toolkit.createSection(form.getBody(), Section.DESCRIPTION
- | ExpandableComposite.TITLE_BAR);
- layout = new GridLayout();
- tagSection.setText(Messages.MetadataPage_sectionTitleTags);
- tagSection.setDescription(Messages.MetadataPage_sectionInstructionTags);
- tagSection.setLayoutData(expandComposite());
+ //--------------------------------- TAGS SECTION START ----------
+ // Section and its client area to manage tags
+ Section tagSection = toolkit.createSection(form.getBody(), Section.DESCRIPTION
+ | ExpandableComposite.TITLE_BAR);
+ layout = new GridLayout();
+ tagSection.setText(Messages.MetadataPage_sectionTitleTags);
+ tagSection.setDescription(Messages.MetadataPage_sectionInstructionTags);
+ tagSection.setLayoutData(expandComposite());
- // the client area containing the tags
- Composite sectionClientTags = toolkit.createComposite(tagSection);
- layout = new GridLayout(2, false);
- layout.marginWidth = 1; layout.marginHeight = 7;
- sectionClientTags.setLayout(layout);
+ // the client area containing the tags
+ Composite sectionClientTags = toolkit.createComposite(tagSection);
+ layout = new GridLayout(2, false);
+ layout.marginWidth = 1; layout.marginHeight = 7;
+ sectionClientTags.setLayout(layout);
- tagTxt = createTextFieldWithLabel(sectionClientTags, Messages.MetadataPage_labelTags);
- tagTxt.addSelectionListener(new SelectionAdapter() {
- /*
- * (non-Javadoc)
- * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- addTag();
- }
- });
+ tagTxt = createTextFieldWithLabel(sectionClientTags, Messages.MetadataPage_labelTags);
+ tagTxt.addSelectionListener(new SelectionAdapter() {
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ addTag();
+ }
+ });
- tagsTreeViewer = new TreeViewer(sectionClientTags, SWT.BORDER | SWT.SINGLE | SWT.HORIZONTAL
- | SWT.VERTICAL | SWT.LEFT_TO_RIGHT | SWT.SMOOTH);
- tagsTreeViewer.setContentProvider(new CreaterepoTreeContentProvider());
- tagsTreeViewer.setLabelProvider(new CreaterepoTreeLabelProvider());
- CreaterepoCategoryModel model = new CreaterepoCategoryModel(project);
- tagsTreeViewer.setInput(model);
- // change the tag text field on change (make editing tag easier)
- tagsTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- if (tagsTree.getSelectionCount() == 1) {
- TreeItem treeItem = tagsTree.getSelection()[0];
- if (!(treeItem.getData() instanceof CreaterepoTreeCategory)) {
- String tag = (String) treeItem.getData();
- tagTxt.setText(tag);
- } else {
- tagTxt.setText(ICreaterepoConstants.EMPTY_STRING);
- }
- }
- }
- });
- // expand or shrink a category
- tagsTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
- @Override
- public void doubleClick(DoubleClickEvent event) {
- IStructuredSelection selection = (IStructuredSelection) tagsTreeViewer.getSelection();
- if (selection.getFirstElement() instanceof CreaterepoTreeCategory) {
- CreaterepoTreeCategory category = (CreaterepoTreeCategory) selection.getFirstElement();
- tagsTreeViewer.setExpandedState(category, !tagsTreeViewer.getExpandedState(category));
- }
- }
- });
- tagsTree = tagsTreeViewer.getTree();
- tagsTree.setLayoutData(expandComposite());
+ tagsTreeViewer = new TreeViewer(sectionClientTags, SWT.BORDER | SWT.SINGLE | SWT.HORIZONTAL
+ | SWT.VERTICAL | SWT.LEFT_TO_RIGHT | SWT.SMOOTH);
+ tagsTreeViewer.setContentProvider(new CreaterepoTreeContentProvider());
+ tagsTreeViewer.setLabelProvider(new CreaterepoTreeLabelProvider());
+ CreaterepoCategoryModel model = new CreaterepoCategoryModel(project);
+ tagsTreeViewer.setInput(model);
+ // change the tag text field on change (make editing tag easier)
+ tagsTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ if (tagsTree.getSelectionCount() == 1) {
+ TreeItem treeItem = tagsTree.getSelection()[0];
+ if (!(treeItem.getData() instanceof CreaterepoTreeCategory)) {
+ String tag = (String) treeItem.getData();
+ tagTxt.setText(tag);
+ } else {
+ tagTxt.setText(ICreaterepoConstants.EMPTY_STRING);
+ }
+ }
+ }
+ });
+ // expand or shrink a category
+ tagsTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
+ @Override
+ public void doubleClick(DoubleClickEvent event) {
+ IStructuredSelection selection = (IStructuredSelection) tagsTreeViewer.getSelection();
+ if (selection.getFirstElement() instanceof CreaterepoTreeCategory) {
+ CreaterepoTreeCategory category = (CreaterepoTreeCategory) selection.getFirstElement();
+ tagsTreeViewer.setExpandedState(category, !tagsTreeViewer.getExpandedState(category));
+ }
+ }
+ });
+ tagsTree = tagsTreeViewer.getTree();
+ tagsTree.setLayoutData(expandComposite());
- // everything to do with the buttons
- buttonList = toolkit.createComposite(sectionClientTags);
- layout = new GridLayout();
- data = new GridData(SWT.BEGINNING, SWT.FILL, false, true);
- layout.marginWidth = 0; layout.marginHeight = 0;
- buttonList.setLayout(layout);
- buttonList.setLayoutData(data);
- createPushButton(buttonList, Messages.MetadataPage_buttonAddTag,
- toolkit).addSelectionListener(new AddTagButtonListener());
- createPushButton(buttonList, Messages.MetadataPage_buttonEditTag,
- toolkit).addSelectionListener(new EditTagButtonListener());
- createPushButton(buttonList, Messages.MetadataPage_buttonRemoveTag,
- toolkit).addSelectionListener(new RemoveTagButtonListener());
- tagSection.setClient(sectionClientTags);
- //---------- TAGS SECTION END
- refreshTree();
- managedForm.refresh();
- }
+ // everything to do with the buttons
+ buttonList = toolkit.createComposite(sectionClientTags);
+ layout = new GridLayout();
+ data = new GridData(SWT.BEGINNING, SWT.FILL, false, true);
+ layout.marginWidth = 0; layout.marginHeight = 0;
+ buttonList.setLayout(layout);
+ buttonList.setLayoutData(data);
+ createPushButton(buttonList, Messages.MetadataPage_buttonAddTag,
+ toolkit).addSelectionListener(new AddTagButtonListener());
+ createPushButton(buttonList, Messages.MetadataPage_buttonEditTag,
+ toolkit).addSelectionListener(new EditTagButtonListener());
+ createPushButton(buttonList, Messages.MetadataPage_buttonRemoveTag,
+ toolkit).addSelectionListener(new RemoveTagButtonListener());
+ tagSection.setClient(sectionClientTags);
+ //---------- TAGS SECTION END
+ refreshTree();
+ managedForm.refresh();
+ }
- /**
- * Refresh the tree. This includes removing the expand button of a
- * category if there are no tags placed under it.
- */
- private void refreshTree() {
- // expand categories with no tags under them to remove expand button
- for (TreeItem treeItem : tagsTree.getItems()) {
- if (treeItem.getData() instanceof CreaterepoTreeCategory) {
- CreaterepoTreeCategory category = (CreaterepoTreeCategory) treeItem.getData();
- if (category.getTags().isEmpty()) {
- tagsTreeViewer.expandToLevel(category, 1);
- tagsTreeViewer.update(category, null);
- }
- }
- }
- }
+ /**
+ * Refresh the tree. This includes removing the expand button of a
+ * category if there are no tags placed under it.
+ */
+ private void refreshTree() {
+ // expand categories with no tags under them to remove expand button
+ for (TreeItem treeItem : tagsTree.getItems()) {
+ if (treeItem.getData() instanceof CreaterepoTreeCategory) {
+ CreaterepoTreeCategory category = (CreaterepoTreeCategory) treeItem.getData();
+ if (category.getTags().isEmpty()) {
+ tagsTreeViewer.expandToLevel(category, 1);
+ tagsTreeViewer.update(category, null);
+ }
+ }
+ }
+ }
- /**
- * Make a GridData that expands to fill both horizontally
- * and vertically.
- *
- * @return The created GridData.
- */
- protected static GridData expandComposite() {
- GridData data = new GridData();
- data.verticalAlignment = GridData.FILL;
- data.horizontalAlignment = GridData.FILL;
- data.grabExcessHorizontalSpace = true;
- data.grabExcessVerticalSpace = true;
- return data;
- }
+ /**
+ * Make a GridData that expands to fill both horizontally
+ * and vertically.
+ *
+ * @return The created GridData.
+ */
+ protected static GridData expandComposite() {
+ GridData data = new GridData();
+ data.verticalAlignment = GridData.FILL;
+ data.horizontalAlignment = GridData.FILL;
+ data.grabExcessHorizontalSpace = true;
+ data.grabExcessVerticalSpace = true;
+ return data;
+ }
- /**
- * Create a push style button.
- *
- * @param parent The parent the button will belong to.
- * @param buttonText The text show on the button.
- * @param toolkit The form toolkit used in creating a button.
- * @return The button created.
- */
- protected Button createPushButton(Composite parent, String buttonText, FormToolkit toolkit) {
- Button button = toolkit.createButton(parent, buttonText, SWT.PUSH | SWT.FLAT
- | SWT.CENTER | SWT.LEFT_TO_RIGHT);
- button.setFont(parent.getFont());
- GridData gd = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
- button.setLayoutData(gd);
- return button;
- }
+ /**
+ * Create a push style button.
+ *
+ * @param parent The parent the button will belong to.
+ * @param buttonText The text show on the button.
+ * @param toolkit The form toolkit used in creating a button.
+ * @return The button created.
+ */
+ protected Button createPushButton(Composite parent, String buttonText, FormToolkit toolkit) {
+ Button button = toolkit.createButton(parent, buttonText, SWT.PUSH | SWT.FLAT
+ | SWT.CENTER | SWT.LEFT_TO_RIGHT);
+ button.setFont(parent.getFont());
+ GridData gd = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
+ button.setLayoutData(gd);
+ return button;
+ }
- /**
- * Create a text field with a label.
- *
- * @param parent The parent of the text field and label.
- * @param labelName The name on the label.
- * @return The newly created text field.
- */
- protected Text createTextFieldWithLabel(Composite parent, String labelName) {
- // set up the area in which the label and text will reside
- Composite areaLabelText = new Composite(parent, SWT.NONE);
- GridData layoutData = new GridData();
- GridLayout gridlayout = new GridLayout(2, false);
- layoutData.horizontalAlignment = GridData.FILL;
- layoutData.verticalAlignment = GridData.CENTER;
- layoutData.horizontalSpan = 2;
- layoutData.grabExcessHorizontalSpace = true;
- areaLabelText.setLayoutData(layoutData);
- areaLabelText.setLayout(gridlayout);
- // create the label
- Label respositoryBaseURLLbl = new Label(areaLabelText, SWT.NONE);
- respositoryBaseURLLbl.setText(labelName);
- layoutData = new GridData();
- layoutData.widthHint = 100;
- layoutData.horizontalAlignment = GridData.BEGINNING;
- layoutData.verticalAlignment = GridData.CENTER;
- respositoryBaseURLLbl.setLayoutData(layoutData);
- // create the text field
- Text textField = new Text(areaLabelText, SWT.SINGLE);
- layoutData = new GridData();
- layoutData.horizontalIndent = 50;
- layoutData.grabExcessHorizontalSpace = true;
- layoutData.horizontalAlignment = GridData.FILL;
- layoutData.verticalAlignment = GridData.CENTER;
- // achieve flat look (don't put SWT.BORDER)
- textField.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
- textField.setLayoutData(layoutData);
- toolkit.paintBordersFor(areaLabelText);
- return textField;
- }
+ /**
+ * Create a text field with a label.
+ *
+ * @param parent The parent of the text field and label.
+ * @param labelName The name on the label.
+ * @return The newly created text field.
+ */
+ protected Text createTextFieldWithLabel(Composite parent, String labelName) {
+ // set up the area in which the label and text will reside
+ Composite areaLabelText = new Composite(parent, SWT.NONE);
+ GridData layoutData = new GridData();
+ GridLayout gridlayout = new GridLayout(2, false);
+ layoutData.horizontalAlignment = GridData.FILL;
+ layoutData.verticalAlignment = GridData.CENTER;
+ layoutData.horizontalSpan = 2;
+ layoutData.grabExcessHorizontalSpace = true;
+ areaLabelText.setLayoutData(layoutData);
+ areaLabelText.setLayout(gridlayout);
+ // create the label
+ Label respositoryBaseURLLbl = new Label(areaLabelText, SWT.NONE);
+ respositoryBaseURLLbl.setText(labelName);
+ layoutData = new GridData();
+ layoutData.widthHint = 100;
+ layoutData.horizontalAlignment = GridData.BEGINNING;
+ layoutData.verticalAlignment = GridData.CENTER;
+ respositoryBaseURLLbl.setLayoutData(layoutData);
+ // create the text field
+ Text textField = new Text(areaLabelText, SWT.SINGLE);
+ layoutData = new GridData();
+ layoutData.horizontalIndent = 50;
+ layoutData.grabExcessHorizontalSpace = true;
+ layoutData.horizontalAlignment = GridData.FILL;
+ layoutData.verticalAlignment = GridData.CENTER;
+ // achieve flat look (don't put SWT.BORDER)
+ textField.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
+ textField.setLayoutData(layoutData);
+ toolkit.paintBordersFor(areaLabelText);
+ return textField;
+ }
- /**
- * Save the project preferences of some value to a key.
- *
- * @param key The preferences key.
- * @param val The value to save.
- */
- protected void savePreferences(String key, String val) {
- eclipsePreferences.put(key, val);
- try {
- eclipsePreferences.flush();
- refreshTree();
- } catch (BackingStoreException e) {
- Activator.logError(Messages.MetadataPage_errorSavingPreferences, e);
- }
- }
+ /**
+ * Save the project preferences of some value to a key.
+ *
+ * @param key The preferences key.
+ * @param val The value to save.
+ */
+ protected void savePreferences(String key, String val) {
+ eclipsePreferences.put(key, val);
+ try {
+ eclipsePreferences.flush();
+ refreshTree();
+ } catch (BackingStoreException e) {
+ Activator.logError(Messages.MetadataPage_errorSavingPreferences, e);
+ }
+ }
- /**
- * Prepare the tags to be saved to the preference. This class gets all the tags
- * from a category and transforms it into a semicolon-delimited string.
- *
- * @param category The category to prepare the tag string for.
- * @return A semicolon-delimited string of tags taken from the category.
- */
- private static String preparePreferenceTag(CreaterepoTreeCategory category) {
- String preferenceToSave = ICreaterepoConstants.EMPTY_STRING;
- if (!category.getTags().isEmpty()) {
- for (String tag : category.getTags()){
- preferenceToSave = preferenceToSave.concat(tag+ICreaterepoConstants.DELIMITER);
- }
- // remove the hanging delimiter
- preferenceToSave = preferenceToSave.substring(0, preferenceToSave.length()-1);
- }
- return preferenceToSave;
- }
+ /**
+ * Prepare the tags to be saved to the preference. This class gets all the tags
+ * from a category and transforms it into a semicolon-delimited string.
+ *
+ * @param category The category to prepare the tag string for.
+ * @return A semicolon-delimited string of tags taken from the category.
+ */
+ private static String preparePreferenceTag(CreaterepoTreeCategory category) {
+ String preferenceToSave = ICreaterepoConstants.EMPTY_STRING;
+ if (!category.getTags().isEmpty()) {
+ for (String tag : category.getTags()){
+ preferenceToSave = preferenceToSave.concat(tag+ICreaterepoConstants.DELIMITER);
+ }
+ // remove the hanging delimiter
+ preferenceToSave = preferenceToSave.substring(0, preferenceToSave.length()-1);
+ }
+ return preferenceToSave;
+ }
- /**
- * Method to add the tag from the tag text field to the category in the tree.
- * Used by the "Add" button and the default operation when ENTER is pressed while
- * in the tag text field.
- */
- protected void addTag() {
- IStructuredSelection selection = (IStructuredSelection) tagsTreeViewer.getSelection();
- if (selection.getFirstElement() instanceof CreaterepoTreeCategory) {
- CreaterepoTreeCategory category = (CreaterepoTreeCategory) selection.getFirstElement();
- String text = tagTxt.getText().trim();
- if (!text.isEmpty()) {
- category.addTag(text);
- tagsTreeViewer.refresh(category, false);
- tagsTreeViewer.setExpandedState(category, true);
- tagTxt.setText(ICreaterepoConstants.EMPTY_STRING);
- String preferenceToSave = preparePreferenceTag(category);
- savePreferences(category.getName(), preferenceToSave);
- }
- }
- }
+ /**
+ * Method to add the tag from the tag text field to the category in the tree.
+ * Used by the "Add" button and the default operation when ENTER is pressed while
+ * in the tag text field.
+ */
+ protected void addTag() {
+ IStructuredSelection selection = (IStructuredSelection) tagsTreeViewer.getSelection();
+ if (selection.getFirstElement() instanceof CreaterepoTreeCategory) {
+ CreaterepoTreeCategory category = (CreaterepoTreeCategory) selection.getFirstElement();
+ String text = tagTxt.getText().trim();
+ if (!text.isEmpty()) {
+ category.addTag(text);
+ tagsTreeViewer.refresh(category, false);
+ tagsTreeViewer.setExpandedState(category, true);
+ tagTxt.setText(ICreaterepoConstants.EMPTY_STRING);
+ String preferenceToSave = preparePreferenceTag(category);
+ savePreferences(category.getName(), preferenceToSave);
+ }
+ }
+ }
- /**
- * Handle the add button execution on the Metadata page.
- */
- public class AddTagButtonListener extends SelectionAdapter {
- /*
- * (non-Javadoc)
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- addTag();
- }
- }
+ /**
+ * Handle the add button execution on the Metadata page.
+ */
+ public class AddTagButtonListener extends SelectionAdapter {
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ addTag();
+ }
+ }
- /**
- * Handle the edit button execution on the Metadata page.
- */
- public class EditTagButtonListener extends SelectionAdapter {
- /*
- * (non-Javadoc)
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (tagsTree.getSelectionCount() == 1) {
- TreeItem treeItem = tagsTree.getSelection()[0];
- String newTag = tagTxt.getText().trim();
- if (!(treeItem.getData() instanceof CreaterepoTreeCategory) && !newTag.isEmpty()) {
- CreaterepoTreeCategory parent = (CreaterepoTreeCategory) treeItem.getParentItem().getData();
- String oldTag = (String) treeItem.getData();
- int oldTagIndex = parent.getTags().indexOf(oldTag);
- if (parent.getTags().indexOf(newTag) == -1) {
- parent.getTags().set(oldTagIndex, newTag);
- tagsTreeViewer.refresh(parent, true);
- tagsTree.setSelection(treeItem);
- String preferenceToSave = preparePreferenceTag(parent);
- savePreferences(parent.getName(), preferenceToSave);
- }
- }
- }
- }
- }
+ /**
+ * Handle the edit button execution on the Metadata page.
+ */
+ public class EditTagButtonListener extends SelectionAdapter {
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ if (tagsTree.getSelectionCount() == 1) {
+ TreeItem treeItem = tagsTree.getSelection()[0];
+ String newTag = tagTxt.getText().trim();
+ if (!(treeItem.getData() instanceof CreaterepoTreeCategory) && !newTag.isEmpty()) {
+ CreaterepoTreeCategory parent = (CreaterepoTreeCategory) treeItem.getParentItem().getData();
+ String oldTag = (String) treeItem.getData();
+ int oldTagIndex = parent.getTags().indexOf(oldTag);
+ if (parent.getTags().indexOf(newTag) == -1) {
+ parent.getTags().set(oldTagIndex, newTag);
+ tagsTreeViewer.refresh(parent, true);
+ tagsTree.setSelection(treeItem);
+ String preferenceToSave = preparePreferenceTag(parent);
+ savePreferences(parent.getName(), preferenceToSave);
+ }
+ }
+ }
+ }
+ }
- /**
- * Handle the remove button execution on the Metadata page.
- */
- public class RemoveTagButtonListener extends SelectionAdapter {
- /*
- * (non-Javadoc)
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (tagsTree.getSelectionCount() == 1) {
- TreeItem treeItem = tagsTree.getSelection()[0];
- if (!(treeItem.getData() instanceof CreaterepoTreeCategory)) {
- CreaterepoTreeCategory parent = (CreaterepoTreeCategory) treeItem.getParentItem().getData();
- String tag = (String) treeItem.getData();
- parent.removeTag(tag);
- tagsTreeViewer.refresh(parent, true);
- tagTxt.setText(ICreaterepoConstants.EMPTY_STRING);
- String preferenceToSave = preparePreferenceTag(parent);
- savePreferences(parent.getName(), preferenceToSave);
- }
- }
- }
- }
+ /**
+ * Handle the remove button execution on the Metadata page.
+ */
+ public class RemoveTagButtonListener extends SelectionAdapter {
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ if (tagsTree.getSelectionCount() == 1) {
+ TreeItem treeItem = tagsTree.getSelection()[0];
+ if (!(treeItem.getData() instanceof CreaterepoTreeCategory)) {
+ CreaterepoTreeCategory parent = (CreaterepoTreeCategory) treeItem.getParentItem().getData();
+ String tag = (String) treeItem.getData();
+ parent.removeTag(tag);
+ tagsTreeViewer.refresh(parent, true);
+ tagTxt.setText(ICreaterepoConstants.EMPTY_STRING);
+ String preferenceToSave = preparePreferenceTag(parent);
+ savePreferences(parent.getName(), preferenceToSave);
+ }
+ }
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/RepoFormEditor.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/RepoFormEditor.java
index 19f5147c41..e6ce8f19b1 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/RepoFormEditor.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/form/RepoFormEditor.java
@@ -34,117 +34,117 @@ import org.eclipse.ui.ide.ResourceUtil;
*/
public class RepoFormEditor extends FormEditor {
- public static final String EDITOR_ID = "org.eclipse.linuxtools.rpm.createrepo.repoEditor"; //$NON-NLS-1$
+ public static final String EDITOR_ID = "org.eclipse.linuxtools.rpm.createrepo.repoEditor"; //$NON-NLS-1$
- private CreaterepoProject project;
- private TextEditor editor;
- private IResourceChangeListener resourceChangeListener;
+ private CreaterepoProject project;
+ private TextEditor editor;
+ private IResourceChangeListener resourceChangeListener;
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.forms.editor.FormEditor#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput)
- */
- @Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- super.init(site, input);
- IFile file = ResourceUtil.getFile(input);
- setPartName(file.getName());
- try {
- project = new CreaterepoProject(file.getProject(), file);
- } catch (CoreException e) {
- Activator.logError(Messages.RepoFormEditor_errorInitializingProject, e);
- }
- resourceChangeListener = new CreaterepoResourceChangeListener(project);
- ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.forms.editor.FormEditor#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput)
+ */
+ @Override
+ public void init(IEditorSite site, IEditorInput input) throws PartInitException {
+ super.init(site, input);
+ IFile file = ResourceUtil.getFile(input);
+ setPartName(file.getName());
+ try {
+ project = new CreaterepoProject(file.getProject(), file);
+ } catch (CoreException e) {
+ Activator.logError(Messages.RepoFormEditor_errorInitializingProject, e);
+ }
+ resourceChangeListener = new CreaterepoResourceChangeListener(project);
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener);
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.forms.editor.FormEditor#dispose()
- */
- @Override
- public void dispose() {
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceChangeListener);
- super.dispose();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.forms.editor.FormEditor#dispose()
+ */
+ @Override
+ public void dispose() {
+ ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceChangeListener);
+ super.dispose();
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.part.EditorPart#doSave(org.eclipse.core.runtime.IProgressMonitor)
- */
- @Override
- public void doSave(IProgressMonitor monitor) {
- editor.doSave(monitor);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.part.EditorPart#doSave(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ @Override
+ public void doSave(IProgressMonitor monitor) {
+ editor.doSave(monitor);
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.part.EditorPart#doSaveAs()
- */
- @Override
- public void doSaveAs() {
- editor.doSaveAs();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.part.EditorPart#doSaveAs()
+ */
+ @Override
+ public void doSaveAs() {
+ editor.doSaveAs();
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.part.EditorPart#isSaveAsAllowed()
- */
- @Override
- public boolean isSaveAsAllowed() {
- return true;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.part.EditorPart#isSaveAsAllowed()
+ */
+ @Override
+ public boolean isSaveAsAllowed() {
+ return true;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.forms.editor.FormEditor#addPages()
- */
- @Override
- protected void addPages() {
- createPage0();
- createPage1();
- createPage2();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.forms.editor.FormEditor#addPages()
+ */
+ @Override
+ protected void addPages() {
+ createPage0();
+ createPage1();
+ createPage2();
+ }
- /**
- * Page 0 allows the user to import RPMs from the workspace or
- * the file system.
- */
- void createPage0() {
- try {
- FormPage composite = new ImportRPMsPage(this, project);
- addPage(composite);
- } catch (PartInitException e) {
- Activator.logError(Messages.RepoFormEditor_errorInitializingForm, e);
- }
- }
+ /**
+ * Page 0 allows the user to import RPMs from the workspace or
+ * the file system.
+ */
+ void createPage0() {
+ try {
+ FormPage composite = new ImportRPMsPage(this, project);
+ addPage(composite);
+ } catch (PartInitException e) {
+ Activator.logError(Messages.RepoFormEditor_errorInitializingForm, e);
+ }
+ }
- /**
- * Page 1 allows the user to modify some of the data in the
- * repomd.xml as well as some options when customizing the
- * execution of the createrepo command. The default execution
- * would satisfy most users.
- */
- void createPage1() {
- try {
- FormPage composite = new MetadataPage(this, project);
- addPage(composite);
- } catch (PartInitException e) {
- Activator.logError(Messages.RepoFormEditor_errorInitializingForm, e);
- }
- }
+ /**
+ * Page 1 allows the user to modify some of the data in the
+ * repomd.xml as well as some options when customizing the
+ * execution of the createrepo command. The default execution
+ * would satisfy most users.
+ */
+ void createPage1() {
+ try {
+ FormPage composite = new MetadataPage(this, project);
+ addPage(composite);
+ } catch (PartInitException e) {
+ Activator.logError(Messages.RepoFormEditor_errorInitializingForm, e);
+ }
+ }
- /**
- * Page 2 allows the user to view the current .repo file.
- */
- void createPage2() {
- try {
- editor = new TextEditor();
- int index = addPage(editor, getEditorInput());
- setPageText(index, editor.getTitle());
- } catch (PartInitException e) {
- Activator.logError(Messages.RepoFormEditor_errorInitializingForm, e);
- }
- }
+ /**
+ * Page 2 allows the user to view the current .repo file.
+ */
+ void createPage2() {
+ try {
+ editor = new TextEditor();
+ int index = addPage(editor, getEditorInput());
+ setPageText(index, editor.getTitle());
+ } catch (PartInitException e) {
+ Activator.logError(Messages.RepoFormEditor_errorInitializingForm, e);
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/handler/CreaterepoCommandHandler.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/handler/CreaterepoCommandHandler.java
index a652aa13bf..40573ff2e3 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/handler/CreaterepoCommandHandler.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/handler/CreaterepoCommandHandler.java
@@ -33,45 +33,45 @@ import org.eclipse.ui.ide.ResourceUtil;
*/
public class CreaterepoCommandHandler extends AbstractHandler {
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
- */
- @Override
- public Object execute(ExecutionEvent event) {
- final String executionType = event.getParameter("executionType"); //$NON-NLS-1$
- try {
- IWorkbench wb = PlatformUI.getWorkbench();
- IWorkbenchPage wbPage = wb.getActiveWorkbenchWindow().getActivePage();
- IEditorInput editorInput = wbPage.getActiveEditor().getEditorInput();
- IResource resource = ResourceUtil.getResource(editorInput);
- final CreaterepoProject project = new CreaterepoProject(resource.getProject());
- Job executeCreaterepo = new Job(Messages.Createrepo_jobName) {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- monitor.beginTask(Messages.CreaterepoProject_executeCreaterepo, IProgressMonitor.UNKNOWN);
- MessageConsoleStream os = CreaterepoUtils.findConsole(Messages.CreaterepoProject_consoleName)
- .newMessageStream();
- if (executionType.equals("refresh")) { //$NON-NLS-1$
- return project.update(os);
- } else {
- return project.createrepo(os);
- }
- } catch (CoreException e) {
- Activator.logError(Messages.Createrepo_errorExecuting, e);
- } finally {
- monitor.done();
- }
- return null;
- }
- };
- executeCreaterepo.setUser(true);
- executeCreaterepo.schedule();
- } catch (CoreException e) {
- Activator.logError(Messages.CreaterepoProject_executeCreaterepo, e);
- }
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
+ */
+ @Override
+ public Object execute(ExecutionEvent event) {
+ final String executionType = event.getParameter("executionType"); //$NON-NLS-1$
+ try {
+ IWorkbench wb = PlatformUI.getWorkbench();
+ IWorkbenchPage wbPage = wb.getActiveWorkbenchWindow().getActivePage();
+ IEditorInput editorInput = wbPage.getActiveEditor().getEditorInput();
+ IResource resource = ResourceUtil.getResource(editorInput);
+ final CreaterepoProject project = new CreaterepoProject(resource.getProject());
+ Job executeCreaterepo = new Job(Messages.Createrepo_jobName) {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ monitor.beginTask(Messages.CreaterepoProject_executeCreaterepo, IProgressMonitor.UNKNOWN);
+ MessageConsoleStream os = CreaterepoUtils.findConsole(Messages.CreaterepoProject_consoleName)
+ .newMessageStream();
+ if (executionType.equals("refresh")) { //$NON-NLS-1$
+ return project.update(os);
+ } else {
+ return project.createrepo(os);
+ }
+ } catch (CoreException e) {
+ Activator.logError(Messages.Createrepo_errorExecuting, e);
+ } finally {
+ monitor.done();
+ }
+ return null;
+ }
+ };
+ executeCreaterepo.setUser(true);
+ executeCreaterepo.schedule();
+ } catch (CoreException e) {
+ Activator.logError(Messages.CreaterepoProject_executeCreaterepo, e);
+ }
+ return null;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/listener/CreaterepoResourceChangeListener.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/listener/CreaterepoResourceChangeListener.java
index 7cbb82e545..fc8c17bfd9 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/listener/CreaterepoResourceChangeListener.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/listener/CreaterepoResourceChangeListener.java
@@ -29,62 +29,62 @@ import org.eclipse.ui.ide.ResourceUtil;
* get deleted or closed.
*/
public class CreaterepoResourceChangeListener implements
- IResourceChangeListener {
+ IResourceChangeListener {
- private CreaterepoProject project;
+ private CreaterepoProject project;
- /** Default Constructor. */
- public CreaterepoResourceChangeListener(CreaterepoProject project) {
- this.project = project;
- }
+ /** Default Constructor. */
+ public CreaterepoResourceChangeListener(CreaterepoProject project) {
+ this.project = project;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
- */
- @Override
- public void resourceChanged(IResourceChangeEvent event) {
- switch (event.getType()) {
- case IResourceChangeEvent.POST_CHANGE:
- case IResourceChangeEvent.PRE_CLOSE:
- case IResourceChangeEvent.PRE_DELETE:
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- closeEditors();
- }
- });
- break;
- }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
+ */
+ @Override
+ public void resourceChanged(IResourceChangeEvent event) {
+ switch (event.getType()) {
+ case IResourceChangeEvent.POST_CHANGE:
+ case IResourceChangeEvent.PRE_CLOSE:
+ case IResourceChangeEvent.PRE_DELETE:
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ closeEditors();
+ }
+ });
+ break;
+ }
+ }
- /**
- * Close the editors thats resource has been affected by a change in the
- * workspace. E.g. if an editor's project has been closed/deleted, close the
- * editor.
- */
- private void closeEditors() {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IResource repomdFile = project.getRepoFile();
- // If the file is gone, that could mean: the project is closed, the project was
- // deleted, or the file was deleted. If so, close the editor of the file.
- if (!repomdFile.exists()) {
- for (IWorkbenchPage page : workbench.getActiveWorkbenchWindow().getPages()) {
- for (IEditorReference ref : page.getEditorReferences()) {
- try {
- // get the resource from the editor part and exit the editor if
- // it is within the project(s) being closed/deleted
- IResource resource = ResourceUtil.getResource(ref.getEditorInput());
- if (ref.getId().equals(RepoFormEditor.EDITOR_ID) &&
- resource.getProject().equals(project.getProject())) {
- page.closeEditor(ref.getEditor(false), false);
- }
- } catch (PartInitException e) {
- Activator.logError(Messages.CreaterepoResourceChangeListener_errorGettingResource, e);
- }
- }
- }
- }
- }
+ /**
+ * Close the editors thats resource has been affected by a change in the
+ * workspace. E.g. if an editor's project has been closed/deleted, close the
+ * editor.
+ */
+ private void closeEditors() {
+ IWorkbench workbench = PlatformUI.getWorkbench();
+ IResource repomdFile = project.getRepoFile();
+ // If the file is gone, that could mean: the project is closed, the project was
+ // deleted, or the file was deleted. If so, close the editor of the file.
+ if (!repomdFile.exists()) {
+ for (IWorkbenchPage page : workbench.getActiveWorkbenchWindow().getPages()) {
+ for (IEditorReference ref : page.getEditorReferences()) {
+ try {
+ // get the resource from the editor part and exit the editor if
+ // it is within the project(s) being closed/deleted
+ IResource resource = ResourceUtil.getResource(ref.getEditorInput());
+ if (ref.getId().equals(RepoFormEditor.EDITOR_ID) &&
+ resource.getProject().equals(project.getProject())) {
+ page.closeEditor(ref.getEditor(false), false);
+ }
+ } catch (PartInitException e) {
+ Activator.logError(Messages.CreaterepoResourceChangeListener_errorGettingResource, e);
+ }
+ }
+ }
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoDeltaPropertyPage.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoDeltaPropertyPage.java
index 7f870cf828..c889a537f4 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoDeltaPropertyPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoDeltaPropertyPage.java
@@ -26,150 +26,150 @@ import org.eclipse.swt.widgets.Group;
*/
public class CreaterepoDeltaPropertyPage extends CreaterepoPropertyPage {
- private Composite composite;
- private BooleanFieldEditor bfeEnableDeltas;
- private Group optionsGroup;
- private IntegerFieldEditor ifeNumDeltas;
- private IntegerFieldEditor ifeMaxSizeDeltas;
-
- private Group dirGroup;
- private CreaterepoPathEditor peDirectories;
-
- /**
- * Default Constructor. Sets the description of the property page.
- */
- public CreaterepoDeltaPropertyPage() {
- super(Messages.CreaterepoDeltaPropertyPage_description);
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.linuxtools.internal.rpm.createrepo.preference.CreaterepoPropertyPage#addContents(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Composite addContents(Composite parent) {
- composite = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout();
- composite.setLayout(layout);
-
- bfeEnableDeltas = new BooleanFieldEditor(
- CreaterepoPreferenceConstants.PREF_DELTA_ENABLE,
- Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel, composite);
- bfeEnableDeltas.setPreferenceStore(Activator.getDefault().getPreferenceStore());
- bfeEnableDeltas.load();
- bfeEnableDeltas.setPropertyChangeListener(this);
-
- optionsGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
-
- layout = new GridLayout(2, false);
- optionsGroup.setLayout(layout);
- optionsGroup.setText(Messages.CreaterepoDeltaPropertyPage_groupLabel);
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER)
- .grab(true, false).applyTo(optionsGroup);
-
- // max deltas.
- ifeNumDeltas = new IntegerFieldEditor(
- CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
- Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas, optionsGroup);
- ifeNumDeltas.setPreferenceStore(preferenceStore);
- ifeNumDeltas.setValidRange(0, Integer.MAX_VALUE);
- ifeNumDeltas.load();
- ifeNumDeltas.setPropertyChangeListener(this);
- ifeNumDeltas.setTextLimit(String.valueOf(Integer.MAX_VALUE).length());
-
- // max delta size. stored in megabytes for convenience to user
- ifeMaxSizeDeltas = new IntegerFieldEditor(
- CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
- Messages.CreaterepoDeltaPropertyPage_maxDeltaSize, optionsGroup);
- ifeMaxSizeDeltas.setPreferenceStore(preferenceStore);
- ifeMaxSizeDeltas.setValidRange(0, Integer.MAX_VALUE);
- ifeMaxSizeDeltas.load();
- ifeMaxSizeDeltas.setPropertyChangeListener(this);
- ifeMaxSizeDeltas.setTextLimit(String.valueOf(Integer.MAX_VALUE).length());
-
- // spaces around the group
- layout = (GridLayout) optionsGroup.getLayout();
- layout.marginWidth = 5;
- layout.marginHeight = 5;
-
- // the group for directories to package against
- dirGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
- layout = new GridLayout(2, false);
- dirGroup.setLayout(layout);
- dirGroup.setText(Messages.CreaterepoDeltaPropertyPage_groupDirectoryLabel);
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER)
- .grab(true, false).applyTo(dirGroup);
-
- peDirectories = new CreaterepoPathEditor(CreaterepoPreferenceConstants.PREF_OLD_PACKAGE_DIRS,
- Messages.CreaterepoDeltaPropertyPage_directoryDescription,
- Messages.CreaterepoDeltaPropertyPage_directoryDialogLabel, dirGroup);
- peDirectories.setPreferenceStore(preferenceStore);
- peDirectories.load();
- peDirectories.setPropertyChangeListener(this);
-
- layout = (GridLayout) dirGroup.getLayout();
- layout.marginWidth = 5;
- layout.marginHeight = 5;
- toggleEnabled();
- return composite;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
- */
- @Override
- public void performDefaults() {
- Activator.getDefault().getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE);
- bfeEnableDeltas.loadDefault();
- ifeNumDeltas.loadDefault();
- ifeMaxSizeDeltas.loadDefault();
- peDirectories.loadDefault();
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#performOk()
- */
- @Override
- public boolean performOk() {
- Activator.getDefault().getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE,
- bfeEnableDeltas.getBooleanValue());
- getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
- ifeNumDeltas.getIntValue());
- getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
- ifeMaxSizeDeltas.getIntValue());
- peDirectories.store();
- return true;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.linuxtools.internal.rpm.createrepo.preference.CreaterepoPropertyPage#checkState()
- */
- @Override
- protected void checkState() {
- if (!ifeNumDeltas.isValid() || !ifeMaxSizeDeltas.isValid()) {
- bfeEnableDeltas.setEnabled(false, composite);
- setErrorMessage(ifeMaxSizeDeltas.getErrorMessage());
- setValid(false);
- } else {
- bfeEnableDeltas.setEnabled(true, composite);
- setErrorMessage(null);
- setValid(true);
- }
- toggleEnabled();
- }
-
- /**
- * Toggle the enabled status of the field editors dependending on the
- * enabled status of the button.
- */
- private void toggleEnabled() {
- boolean enabled = bfeEnableDeltas.getBooleanValue();
- ifeNumDeltas.setEnabled(enabled, optionsGroup);
- ifeMaxSizeDeltas.setEnabled(enabled, optionsGroup);
- peDirectories.setEnabled(enabled, dirGroup);
- }
+ private Composite composite;
+ private BooleanFieldEditor bfeEnableDeltas;
+ private Group optionsGroup;
+ private IntegerFieldEditor ifeNumDeltas;
+ private IntegerFieldEditor ifeMaxSizeDeltas;
+
+ private Group dirGroup;
+ private CreaterepoPathEditor peDirectories;
+
+ /**
+ * Default Constructor. Sets the description of the property page.
+ */
+ public CreaterepoDeltaPropertyPage() {
+ super(Messages.CreaterepoDeltaPropertyPage_description);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.linuxtools.internal.rpm.createrepo.preference.CreaterepoPropertyPage#addContents(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ protected Composite addContents(Composite parent) {
+ composite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ composite.setLayout(layout);
+
+ bfeEnableDeltas = new BooleanFieldEditor(
+ CreaterepoPreferenceConstants.PREF_DELTA_ENABLE,
+ Messages.CreaterepoDeltaPropertyPage_booleanEnableLabel, composite);
+ bfeEnableDeltas.setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ bfeEnableDeltas.load();
+ bfeEnableDeltas.setPropertyChangeListener(this);
+
+ optionsGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
+
+ layout = new GridLayout(2, false);
+ optionsGroup.setLayout(layout);
+ optionsGroup.setText(Messages.CreaterepoDeltaPropertyPage_groupLabel);
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER)
+ .grab(true, false).applyTo(optionsGroup);
+
+ // max deltas.
+ ifeNumDeltas = new IntegerFieldEditor(
+ CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
+ Messages.CreaterepoDeltaPropertyPage_maxNumberOfDeltas, optionsGroup);
+ ifeNumDeltas.setPreferenceStore(preferenceStore);
+ ifeNumDeltas.setValidRange(0, Integer.MAX_VALUE);
+ ifeNumDeltas.load();
+ ifeNumDeltas.setPropertyChangeListener(this);
+ ifeNumDeltas.setTextLimit(String.valueOf(Integer.MAX_VALUE).length());
+
+ // max delta size. stored in megabytes for convenience to user
+ ifeMaxSizeDeltas = new IntegerFieldEditor(
+ CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
+ Messages.CreaterepoDeltaPropertyPage_maxDeltaSize, optionsGroup);
+ ifeMaxSizeDeltas.setPreferenceStore(preferenceStore);
+ ifeMaxSizeDeltas.setValidRange(0, Integer.MAX_VALUE);
+ ifeMaxSizeDeltas.load();
+ ifeMaxSizeDeltas.setPropertyChangeListener(this);
+ ifeMaxSizeDeltas.setTextLimit(String.valueOf(Integer.MAX_VALUE).length());
+
+ // spaces around the group
+ layout = (GridLayout) optionsGroup.getLayout();
+ layout.marginWidth = 5;
+ layout.marginHeight = 5;
+
+ // the group for directories to package against
+ dirGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
+ layout = new GridLayout(2, false);
+ dirGroup.setLayout(layout);
+ dirGroup.setText(Messages.CreaterepoDeltaPropertyPage_groupDirectoryLabel);
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER)
+ .grab(true, false).applyTo(dirGroup);
+
+ peDirectories = new CreaterepoPathEditor(CreaterepoPreferenceConstants.PREF_OLD_PACKAGE_DIRS,
+ Messages.CreaterepoDeltaPropertyPage_directoryDescription,
+ Messages.CreaterepoDeltaPropertyPage_directoryDialogLabel, dirGroup);
+ peDirectories.setPreferenceStore(preferenceStore);
+ peDirectories.load();
+ peDirectories.setPropertyChangeListener(this);
+
+ layout = (GridLayout) dirGroup.getLayout();
+ layout.marginWidth = 5;
+ layout.marginHeight = 5;
+ toggleEnabled();
+ return composite;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
+ */
+ @Override
+ public void performDefaults() {
+ Activator.getDefault().getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE);
+ bfeEnableDeltas.loadDefault();
+ ifeNumDeltas.loadDefault();
+ ifeMaxSizeDeltas.loadDefault();
+ peDirectories.loadDefault();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.preference.PreferencePage#performOk()
+ */
+ @Override
+ public boolean performOk() {
+ Activator.getDefault().getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE,
+ bfeEnableDeltas.getBooleanValue());
+ getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_NUM_DELTAS,
+ ifeNumDeltas.getIntValue());
+ getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE,
+ ifeMaxSizeDeltas.getIntValue());
+ peDirectories.store();
+ return true;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.linuxtools.internal.rpm.createrepo.preference.CreaterepoPropertyPage#checkState()
+ */
+ @Override
+ protected void checkState() {
+ if (!ifeNumDeltas.isValid() || !ifeMaxSizeDeltas.isValid()) {
+ bfeEnableDeltas.setEnabled(false, composite);
+ setErrorMessage(ifeMaxSizeDeltas.getErrorMessage());
+ setValid(false);
+ } else {
+ bfeEnableDeltas.setEnabled(true, composite);
+ setErrorMessage(null);
+ setValid(true);
+ }
+ toggleEnabled();
+ }
+
+ /**
+ * Toggle the enabled status of the field editors dependending on the
+ * enabled status of the button.
+ */
+ private void toggleEnabled() {
+ boolean enabled = bfeEnableDeltas.getBooleanValue();
+ ifeNumDeltas.setEnabled(enabled, optionsGroup);
+ ifeMaxSizeDeltas.setEnabled(enabled, optionsGroup);
+ peDirectories.setEnabled(enabled, dirGroup);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoGeneralPropertyPage.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoGeneralPropertyPage.java
index 7d8cfe7db2..87f58b0caa 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoGeneralPropertyPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoGeneralPropertyPage.java
@@ -41,361 +41,361 @@ import org.eclipse.ui.dialogs.PreferencesUtil;
*/
public class CreaterepoGeneralPropertyPage extends CreaterepoPropertyPage {
- private static final String linkTags = "<a>{0}</a>"; //$NON-NLS-1$
-
- private Composite composite;
-
- private Button btnProjectSettings;
- private Link lnWorkspaceSettings;
-
- private Group generalGroup;
- private BooleanFieldEditor bfeIncludeChecksum;
- private BooleanFieldEditor bfeSQLDB;
- private BooleanFieldEditor bfeIgnoreSymlinks;
- private BooleanFieldEditor bfePrettyXML;
- private IntegerFieldEditor ifeSpawns;
-
- private Group updatesGroup;
- private BooleanFieldEditor bfeSameFilename;
- private Label lblCheckTs;
-
- private Group changelogGroup;
- private IntegerFieldEditor ifeChangelogLimit;
-
- private Composite checksumsContainer;
- private RadioGroupFieldEditor rgfeChecksums;
- private Composite compressContainer;
- private RadioGroupFieldEditor rgfeCompressionTypes;
-
- /**
- * Default Constructor. Sets the description of the property page.
- */
- public CreaterepoGeneralPropertyPage() {
- super(Messages.CreaterepoPreferencePage_description);
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.linuxtools.internal.rpm.createrepo.preference.CreaterepoPropertyPage#addContents(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Composite addContents(Composite parent) {
- composite = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout(2, false);
- GridData layoutData = new GridData();
- composite.setLayout(layout);
-
- // TODO: use BooleanFieldEditor and get it to layout properly
- // with the link (lnWorkspaceSettings)
- btnProjectSettings = new Button(composite, SWT.CHECK);
- btnProjectSettings.addListener(SWT.Selection, new Listener() {
- @Override
- public void handleEvent(Event event) {
- toggleEnabled();
- }
- });
- layoutData = new GridData();
- layoutData.horizontalAlignment = GridData.BEGINNING;
- layoutData.horizontalAlignment = GridData.FILL;
- layoutData.grabExcessHorizontalSpace = true;
- btnProjectSettings.setText(Messages.CreaterepoGeneralPropertyPage_projectSettings);
- btnProjectSettings.setLayoutData(layoutData);
- btnProjectSettings.setSelection(Activator.getDefault().getPreferenceStore()
- .getBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED));
- btnProjectSettings.addSelectionListener(new SelectionAdapter() {
- /*
- * (non-Javadoc)
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- checkState();
- }
- });
-
- lnWorkspaceSettings = new Link(composite, SWT.NONE);
- layoutData = new GridData();
- layoutData.horizontalAlignment = SWT.END;
- lnWorkspaceSettings.setLayoutData(layoutData);
- lnWorkspaceSettings.setText(NLS.bind(linkTags, Messages.CreaterepoGeneralPropertyPage_workspaceSettings));
- lnWorkspaceSettings.setFont(parent.getFont());
- lnWorkspaceSettings.addListener(SWT.Selection, new Listener() {
- /*
- * (non-Javadoc)
- * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
- */
- @Override
- public void handleEvent(Event event) {
- PreferenceDialog preferenceDialog = PreferencesUtil.createPreferenceDialogOn(getShell(),
- CREATEREPO_PREFERENCE_ID, new String[] {CREATEREPO_PREFERENCE_ID}, null);
- preferenceDialog.open();
- }
- });
-
- // general group
- generalGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
- layout = new GridLayout(2, false);
- generalGroup.setLayout(layout);
- generalGroup.setText(Messages.CreaterepoPreferencePage_generalGroupLabel);
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2,1).applyTo(generalGroup);
-
- // generate unique metadata filenames
- bfeIncludeChecksum = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
- Messages.CreaterepoPreferencePage_booleanChecksumName, generalGroup);
- bfeIncludeChecksum.fillIntoGrid(generalGroup, 2);
- bfeIncludeChecksum.setPreferenceStore(preferenceStore);
- bfeIncludeChecksum.setPropertyChangeListener(this);
- bfeIncludeChecksum.load();
-
- // generate sqlite databases
- bfeSQLDB = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
- Messages.CreaterepoPreferencePage_booleanGenerateSQLDB, generalGroup);
- bfeSQLDB.fillIntoGrid(generalGroup, 2);
- bfeSQLDB.setPreferenceStore(preferenceStore);
- bfeSQLDB.setPropertyChangeListener(this);
- bfeSQLDB.load();
-
- // ignore symlinks for packages
- bfeIgnoreSymlinks = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
- Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks, generalGroup);
- bfeIgnoreSymlinks.fillIntoGrid(generalGroup, 2);
- bfeIgnoreSymlinks.setPreferenceStore(preferenceStore);
- bfeIgnoreSymlinks.setPropertyChangeListener(this);
- bfeIgnoreSymlinks.load();
-
- // output files in pretty xml format
- bfePrettyXML = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
- Messages.CreaterepoPreferencePage_booleanPrettyXML, generalGroup);
- bfePrettyXML.fillIntoGrid(generalGroup, 2);
- bfePrettyXML.setPreferenceStore(preferenceStore);
- bfePrettyXML.setPropertyChangeListener(this);
- bfePrettyXML.load();
-
- // number of workers
- ifeSpawns = new IntegerFieldEditor(CreaterepoPreferenceConstants.PREF_WORKERS,
- Messages.CreaterepoPreferencePage_numWorkers, generalGroup);
- ifeSpawns.fillIntoGrid(generalGroup, 2);
- // more than 128 is alot. limiting. (createrepo warning)
- ifeSpawns.setValidRange(0, 128);
- ifeSpawns.setPreferenceStore(preferenceStore);
- ifeSpawns.setPropertyChangeListener(this);
- ifeSpawns.load();
- updateGroupSpacing(generalGroup);
-
- // updates group
- updatesGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
- updatesGroup.setText(Messages.CreaterepoPreferencePage_updateGroupLabel);
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, 1).hint(10, SWT.DEFAULT).applyTo(updatesGroup);
-
- // don't generate repo metadata, if their timestamps are newer than its rpms
- bfeSameFilename = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_CHECK_TS,
- Messages.CreaterepoPreferencePage_booleanCheckTS, updatesGroup);
- bfeSameFilename.fillIntoGrid(updatesGroup, 2);
- bfeSameFilename.setPreferenceStore(preferenceStore);
- bfeSameFilename.setPropertyChangeListener(this);
- bfeSameFilename.load();
-
- // note of caution
- lblCheckTs = new Label(updatesGroup, SWT.WRAP);
- lblCheckTs.setText(Messages.CreaterepoPreferencePage_checkTSNote);
- layoutData = new GridData();
- layoutData.widthHint = 130;
- layoutData.horizontalAlignment = SWT.FILL;
- layoutData.grabExcessHorizontalSpace = true;
- layoutData.horizontalIndent = 5;
- lblCheckTs.setLayoutData(layoutData);
- updateGroupSpacing(updatesGroup);
-
- // changelog group
- changelogGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
- changelogGroup.setText(Messages.CreaterepoPreferencePage_changelogGroupLabel);
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, 1).hint(10, SWT.DEFAULT).applyTo(changelogGroup);
-
- // don't generate repo metadata, if their timestamps are newer than its rpms
- ifeChangelogLimit = new IntegerFieldEditor(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
- Messages.CreaterepoPreferencePage_numChangelogLimit, changelogGroup);
- ifeChangelogLimit.fillIntoGrid(changelogGroup, 2);
- ifeChangelogLimit.setValidRange(0, Integer.MAX_VALUE);
- ifeChangelogLimit.setPreferenceStore(preferenceStore);
- ifeChangelogLimit.setPropertyChangeListener(this);
- ifeChangelogLimit.load();
- updateGroupSpacing(changelogGroup);
-
- checksumsContainer = new Composite(composite, SWT.NONE);
- checksumsContainer.setLayout(new GridLayout());
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).indent(0, 20).grab(true, false).applyTo(checksumsContainer);
- // available checksums
- rgfeChecksums = new RadioGroupFieldEditor(CreaterepoPreferenceConstants.PREF_CHECKSUM,
- Messages.CreaterepoPreferencePage_checksumGroupLabel, 1, new String[][]{
- {ICreaterepoChecksums.SHA1, ICreaterepoChecksums.SHA1},
- {ICreaterepoChecksums.MD5, ICreaterepoChecksums.MD5},
- {ICreaterepoChecksums.SHA256, ICreaterepoChecksums.SHA256},
- {ICreaterepoChecksums.SHA512, ICreaterepoChecksums.SHA512}
- }, checksumsContainer, true);
- rgfeChecksums.setPreferenceStore(preferenceStore);
- rgfeChecksums.setPropertyChangeListener(this);
- rgfeChecksums.load();
-
- compressContainer = new Composite(composite, SWT.NONE);
- compressContainer.setLayout(new GridLayout());
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).indent(0, 20).grab(true, false).applyTo(compressContainer);
- // available compression types
- rgfeCompressionTypes = new RadioGroupFieldEditor(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
- Messages.CreaterepoPreferencePage_compressionGroupLabel, 1, new String[][]{
- {ICreaterepoCompressionTypes.COMPAT, ICreaterepoCompressionTypes.COMPAT},
- {ICreaterepoCompressionTypes.XZ, ICreaterepoCompressionTypes.XZ},
- {ICreaterepoCompressionTypes.GZ, ICreaterepoCompressionTypes.GZ},
- {ICreaterepoCompressionTypes.BZ2, ICreaterepoCompressionTypes.BZ2}
- }, compressContainer, true);
- rgfeCompressionTypes.setPreferenceStore(preferenceStore);
- rgfeCompressionTypes.setPropertyChangeListener(this);
- rgfeCompressionTypes.load();
-
- toggleEnabled();
-
- return composite;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
- */
- @Override
- public void performDefaults() {
- // load the defaults UI
- btnProjectSettings.setSelection(Activator.getDefault().getPreferenceStore()
- .getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED));
- bfeIncludeChecksum.loadDefault();
- bfeSQLDB.loadDefault();
- bfeIgnoreSymlinks.loadDefault();
- bfePrettyXML.loadDefault();
- ifeSpawns.loadDefault();
- rgfeChecksums.loadDefault();
- bfeSameFilename.loadDefault();
- ifeChangelogLimit.loadDefault();
- rgfeChecksums.loadDefault();
- rgfeCompressionTypes.loadDefault();
-
- // set the defaults preferences
- Activator.getDefault().getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED);
- getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME);
- getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_GENERATE_DB);
- getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS);
- getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_PRETTY_XML);
- getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_WORKERS);
- getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_CHECK_TS);
- getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT);
- getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_CHECKSUM);
- getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE);
-
- toggleEnabled();
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#performOk()
- */
- @Override
- public boolean performOk() {
- // only save when using project specific settings
- if (btnProjectSettings.getSelection()) {
- Activator.getDefault().getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED,
- true);
- getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
- bfeIncludeChecksum.getBooleanValue());
- getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
- bfeSQLDB.getBooleanValue());
- getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
- bfeIgnoreSymlinks.getBooleanValue());
- getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
- bfePrettyXML.getBooleanValue());
- getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_WORKERS,
- ifeSpawns.getIntValue());
- getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_CHECK_TS,
- bfeSameFilename.getBooleanValue());
- getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
- ifeChangelogLimit.getIntValue());
-
- getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_CHECKSUM,
- getSelectedRadioButton(rgfeChecksums.getRadioBoxControl(checksumsContainer),
- rgfeChecksums.getPreferenceName()));
- getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
- getSelectedRadioButton(rgfeCompressionTypes.getRadioBoxControl(compressContainer),
- rgfeCompressionTypes.getPreferenceName()));
- } else {
- Activator.getDefault().getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED,
- false);
- }
- return true;
- }
-
- /**
- * Helper method to get the selected radio button from the radio button list.
- * The default value of the preference key will be returned if nothing was found to be
- * selected.
- *
- * @param radioBoxControl The radio button list.
- * @param preferenceKey The preference key to get the default from.
- * @return The selected radio button or the default value if nothing selected.
- */
- private String getSelectedRadioButton(Composite radioBoxControl, String preferenceKey) {
- String defaultValue = getPreferenceStore().getDefaultString(preferenceKey);
- Control[] children = radioBoxControl.getChildren();
- if (children.length > 0) {
- for (Control control : children) {
- Button radioButton = (Button) control;
- if (radioButton.getSelection()) {
- return radioButton.getText();
- }
- }
- }
- return defaultValue;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.linuxtools.internal.rpm.createrepo.preference.CreaterepoPropertyPage#checkState()
- */
- @Override
- protected void checkState() {
- // if enable project specific settings is false, then allow performOk
- if (!btnProjectSettings.getSelection()) {
- setErrorMessage(null);
- setValid(true);
- // if the spawns are invalid, disable performOk
- } else if (!ifeSpawns.isValid()) {
- setErrorMessage(ifeSpawns.getErrorMessage());
- setValid(false);
- } else if (!ifeChangelogLimit.isValid()) {
- setErrorMessage(ifeChangelogLimit.getErrorMessage());
- setValid(false);
- // otherwise, allow performOk
- } else {
- setErrorMessage(null);
- setValid(true);
- }
- toggleEnabled();
- }
-
- /**
- * If "Enable project specific settings" is true, so will
- * the options below it. The workspace settings link will be opposite
- * to what value the checkbox is.
- */
- private void toggleEnabled() {
- boolean enabled = btnProjectSettings.getSelection();
- lnWorkspaceSettings.setEnabled(!enabled);
- bfeIncludeChecksum.setEnabled(enabled, generalGroup);
- bfeSQLDB.setEnabled(enabled, generalGroup);
- bfeIgnoreSymlinks.setEnabled(enabled, generalGroup);
- bfePrettyXML.setEnabled(enabled, generalGroup);
- ifeSpawns.setEnabled(enabled, generalGroup);
- rgfeChecksums.setEnabled(enabled, generalGroup);
- bfeSameFilename.setEnabled(enabled, updatesGroup);
- ifeChangelogLimit.setEnabled(enabled, changelogGroup);
- rgfeChecksums.setEnabled(enabled, checksumsContainer);
- rgfeCompressionTypes.setEnabled(enabled, compressContainer);
- lblCheckTs.setEnabled(enabled);
- }
+ private static final String linkTags = "<a>{0}</a>"; //$NON-NLS-1$
+
+ private Composite composite;
+
+ private Button btnProjectSettings;
+ private Link lnWorkspaceSettings;
+
+ private Group generalGroup;
+ private BooleanFieldEditor bfeIncludeChecksum;
+ private BooleanFieldEditor bfeSQLDB;
+ private BooleanFieldEditor bfeIgnoreSymlinks;
+ private BooleanFieldEditor bfePrettyXML;
+ private IntegerFieldEditor ifeSpawns;
+
+ private Group updatesGroup;
+ private BooleanFieldEditor bfeSameFilename;
+ private Label lblCheckTs;
+
+ private Group changelogGroup;
+ private IntegerFieldEditor ifeChangelogLimit;
+
+ private Composite checksumsContainer;
+ private RadioGroupFieldEditor rgfeChecksums;
+ private Composite compressContainer;
+ private RadioGroupFieldEditor rgfeCompressionTypes;
+
+ /**
+ * Default Constructor. Sets the description of the property page.
+ */
+ public CreaterepoGeneralPropertyPage() {
+ super(Messages.CreaterepoPreferencePage_description);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.linuxtools.internal.rpm.createrepo.preference.CreaterepoPropertyPage#addContents(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ protected Composite addContents(Composite parent) {
+ composite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(2, false);
+ GridData layoutData = new GridData();
+ composite.setLayout(layout);
+
+ // TODO: use BooleanFieldEditor and get it to layout properly
+ // with the link (lnWorkspaceSettings)
+ btnProjectSettings = new Button(composite, SWT.CHECK);
+ btnProjectSettings.addListener(SWT.Selection, new Listener() {
+ @Override
+ public void handleEvent(Event event) {
+ toggleEnabled();
+ }
+ });
+ layoutData = new GridData();
+ layoutData.horizontalAlignment = GridData.BEGINNING;
+ layoutData.horizontalAlignment = GridData.FILL;
+ layoutData.grabExcessHorizontalSpace = true;
+ btnProjectSettings.setText(Messages.CreaterepoGeneralPropertyPage_projectSettings);
+ btnProjectSettings.setLayoutData(layoutData);
+ btnProjectSettings.setSelection(Activator.getDefault().getPreferenceStore()
+ .getBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED));
+ btnProjectSettings.addSelectionListener(new SelectionAdapter() {
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ checkState();
+ }
+ });
+
+ lnWorkspaceSettings = new Link(composite, SWT.NONE);
+ layoutData = new GridData();
+ layoutData.horizontalAlignment = SWT.END;
+ lnWorkspaceSettings.setLayoutData(layoutData);
+ lnWorkspaceSettings.setText(NLS.bind(linkTags, Messages.CreaterepoGeneralPropertyPage_workspaceSettings));
+ lnWorkspaceSettings.setFont(parent.getFont());
+ lnWorkspaceSettings.addListener(SWT.Selection, new Listener() {
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
+ */
+ @Override
+ public void handleEvent(Event event) {
+ PreferenceDialog preferenceDialog = PreferencesUtil.createPreferenceDialogOn(getShell(),
+ CREATEREPO_PREFERENCE_ID, new String[] {CREATEREPO_PREFERENCE_ID}, null);
+ preferenceDialog.open();
+ }
+ });
+
+ // general group
+ generalGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
+ layout = new GridLayout(2, false);
+ generalGroup.setLayout(layout);
+ generalGroup.setText(Messages.CreaterepoPreferencePage_generalGroupLabel);
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2,1).applyTo(generalGroup);
+
+ // generate unique metadata filenames
+ bfeIncludeChecksum = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
+ Messages.CreaterepoPreferencePage_booleanChecksumName, generalGroup);
+ bfeIncludeChecksum.fillIntoGrid(generalGroup, 2);
+ bfeIncludeChecksum.setPreferenceStore(preferenceStore);
+ bfeIncludeChecksum.setPropertyChangeListener(this);
+ bfeIncludeChecksum.load();
+
+ // generate sqlite databases
+ bfeSQLDB = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
+ Messages.CreaterepoPreferencePage_booleanGenerateSQLDB, generalGroup);
+ bfeSQLDB.fillIntoGrid(generalGroup, 2);
+ bfeSQLDB.setPreferenceStore(preferenceStore);
+ bfeSQLDB.setPropertyChangeListener(this);
+ bfeSQLDB.load();
+
+ // ignore symlinks for packages
+ bfeIgnoreSymlinks = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
+ Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks, generalGroup);
+ bfeIgnoreSymlinks.fillIntoGrid(generalGroup, 2);
+ bfeIgnoreSymlinks.setPreferenceStore(preferenceStore);
+ bfeIgnoreSymlinks.setPropertyChangeListener(this);
+ bfeIgnoreSymlinks.load();
+
+ // output files in pretty xml format
+ bfePrettyXML = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
+ Messages.CreaterepoPreferencePage_booleanPrettyXML, generalGroup);
+ bfePrettyXML.fillIntoGrid(generalGroup, 2);
+ bfePrettyXML.setPreferenceStore(preferenceStore);
+ bfePrettyXML.setPropertyChangeListener(this);
+ bfePrettyXML.load();
+
+ // number of workers
+ ifeSpawns = new IntegerFieldEditor(CreaterepoPreferenceConstants.PREF_WORKERS,
+ Messages.CreaterepoPreferencePage_numWorkers, generalGroup);
+ ifeSpawns.fillIntoGrid(generalGroup, 2);
+ // more than 128 is alot. limiting. (createrepo warning)
+ ifeSpawns.setValidRange(0, 128);
+ ifeSpawns.setPreferenceStore(preferenceStore);
+ ifeSpawns.setPropertyChangeListener(this);
+ ifeSpawns.load();
+ updateGroupSpacing(generalGroup);
+
+ // updates group
+ updatesGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
+ updatesGroup.setText(Messages.CreaterepoPreferencePage_updateGroupLabel);
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, 1).hint(10, SWT.DEFAULT).applyTo(updatesGroup);
+
+ // don't generate repo metadata, if their timestamps are newer than its rpms
+ bfeSameFilename = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_CHECK_TS,
+ Messages.CreaterepoPreferencePage_booleanCheckTS, updatesGroup);
+ bfeSameFilename.fillIntoGrid(updatesGroup, 2);
+ bfeSameFilename.setPreferenceStore(preferenceStore);
+ bfeSameFilename.setPropertyChangeListener(this);
+ bfeSameFilename.load();
+
+ // note of caution
+ lblCheckTs = new Label(updatesGroup, SWT.WRAP);
+ lblCheckTs.setText(Messages.CreaterepoPreferencePage_checkTSNote);
+ layoutData = new GridData();
+ layoutData.widthHint = 130;
+ layoutData.horizontalAlignment = SWT.FILL;
+ layoutData.grabExcessHorizontalSpace = true;
+ layoutData.horizontalIndent = 5;
+ lblCheckTs.setLayoutData(layoutData);
+ updateGroupSpacing(updatesGroup);
+
+ // changelog group
+ changelogGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
+ changelogGroup.setText(Messages.CreaterepoPreferencePage_changelogGroupLabel);
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, 1).hint(10, SWT.DEFAULT).applyTo(changelogGroup);
+
+ // don't generate repo metadata, if their timestamps are newer than its rpms
+ ifeChangelogLimit = new IntegerFieldEditor(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
+ Messages.CreaterepoPreferencePage_numChangelogLimit, changelogGroup);
+ ifeChangelogLimit.fillIntoGrid(changelogGroup, 2);
+ ifeChangelogLimit.setValidRange(0, Integer.MAX_VALUE);
+ ifeChangelogLimit.setPreferenceStore(preferenceStore);
+ ifeChangelogLimit.setPropertyChangeListener(this);
+ ifeChangelogLimit.load();
+ updateGroupSpacing(changelogGroup);
+
+ checksumsContainer = new Composite(composite, SWT.NONE);
+ checksumsContainer.setLayout(new GridLayout());
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).indent(0, 20).grab(true, false).applyTo(checksumsContainer);
+ // available checksums
+ rgfeChecksums = new RadioGroupFieldEditor(CreaterepoPreferenceConstants.PREF_CHECKSUM,
+ Messages.CreaterepoPreferencePage_checksumGroupLabel, 1, new String[][]{
+ {ICreaterepoChecksums.SHA1, ICreaterepoChecksums.SHA1},
+ {ICreaterepoChecksums.MD5, ICreaterepoChecksums.MD5},
+ {ICreaterepoChecksums.SHA256, ICreaterepoChecksums.SHA256},
+ {ICreaterepoChecksums.SHA512, ICreaterepoChecksums.SHA512}
+ }, checksumsContainer, true);
+ rgfeChecksums.setPreferenceStore(preferenceStore);
+ rgfeChecksums.setPropertyChangeListener(this);
+ rgfeChecksums.load();
+
+ compressContainer = new Composite(composite, SWT.NONE);
+ compressContainer.setLayout(new GridLayout());
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).indent(0, 20).grab(true, false).applyTo(compressContainer);
+ // available compression types
+ rgfeCompressionTypes = new RadioGroupFieldEditor(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
+ Messages.CreaterepoPreferencePage_compressionGroupLabel, 1, new String[][]{
+ {ICreaterepoCompressionTypes.COMPAT, ICreaterepoCompressionTypes.COMPAT},
+ {ICreaterepoCompressionTypes.XZ, ICreaterepoCompressionTypes.XZ},
+ {ICreaterepoCompressionTypes.GZ, ICreaterepoCompressionTypes.GZ},
+ {ICreaterepoCompressionTypes.BZ2, ICreaterepoCompressionTypes.BZ2}
+ }, compressContainer, true);
+ rgfeCompressionTypes.setPreferenceStore(preferenceStore);
+ rgfeCompressionTypes.setPropertyChangeListener(this);
+ rgfeCompressionTypes.load();
+
+ toggleEnabled();
+
+ return composite;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
+ */
+ @Override
+ public void performDefaults() {
+ // load the defaults UI
+ btnProjectSettings.setSelection(Activator.getDefault().getPreferenceStore()
+ .getDefaultBoolean(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED));
+ bfeIncludeChecksum.loadDefault();
+ bfeSQLDB.loadDefault();
+ bfeIgnoreSymlinks.loadDefault();
+ bfePrettyXML.loadDefault();
+ ifeSpawns.loadDefault();
+ rgfeChecksums.loadDefault();
+ bfeSameFilename.loadDefault();
+ ifeChangelogLimit.loadDefault();
+ rgfeChecksums.loadDefault();
+ rgfeCompressionTypes.loadDefault();
+
+ // set the defaults preferences
+ Activator.getDefault().getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED);
+ getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME);
+ getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_GENERATE_DB);
+ getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS);
+ getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_PRETTY_XML);
+ getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_WORKERS);
+ getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_CHECK_TS);
+ getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT);
+ getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_CHECKSUM);
+ getPreferenceStore().setToDefault(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE);
+
+ toggleEnabled();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.preference.PreferencePage#performOk()
+ */
+ @Override
+ public boolean performOk() {
+ // only save when using project specific settings
+ if (btnProjectSettings.getSelection()) {
+ Activator.getDefault().getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED,
+ true);
+ getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
+ bfeIncludeChecksum.getBooleanValue());
+ getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
+ bfeSQLDB.getBooleanValue());
+ getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
+ bfeIgnoreSymlinks.getBooleanValue());
+ getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
+ bfePrettyXML.getBooleanValue());
+ getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_WORKERS,
+ ifeSpawns.getIntValue());
+ getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_CHECK_TS,
+ bfeSameFilename.getBooleanValue());
+ getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
+ ifeChangelogLimit.getIntValue());
+
+ getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_CHECKSUM,
+ getSelectedRadioButton(rgfeChecksums.getRadioBoxControl(checksumsContainer),
+ rgfeChecksums.getPreferenceName()));
+ getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
+ getSelectedRadioButton(rgfeCompressionTypes.getRadioBoxControl(compressContainer),
+ rgfeCompressionTypes.getPreferenceName()));
+ } else {
+ Activator.getDefault().getPreferenceStore().setValue(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED,
+ false);
+ }
+ return true;
+ }
+
+ /**
+ * Helper method to get the selected radio button from the radio button list.
+ * The default value of the preference key will be returned if nothing was found to be
+ * selected.
+ *
+ * @param radioBoxControl The radio button list.
+ * @param preferenceKey The preference key to get the default from.
+ * @return The selected radio button or the default value if nothing selected.
+ */
+ private String getSelectedRadioButton(Composite radioBoxControl, String preferenceKey) {
+ String defaultValue = getPreferenceStore().getDefaultString(preferenceKey);
+ Control[] children = radioBoxControl.getChildren();
+ if (children.length > 0) {
+ for (Control control : children) {
+ Button radioButton = (Button) control;
+ if (radioButton.getSelection()) {
+ return radioButton.getText();
+ }
+ }
+ }
+ return defaultValue;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.linuxtools.internal.rpm.createrepo.preference.CreaterepoPropertyPage#checkState()
+ */
+ @Override
+ protected void checkState() {
+ // if enable project specific settings is false, then allow performOk
+ if (!btnProjectSettings.getSelection()) {
+ setErrorMessage(null);
+ setValid(true);
+ // if the spawns are invalid, disable performOk
+ } else if (!ifeSpawns.isValid()) {
+ setErrorMessage(ifeSpawns.getErrorMessage());
+ setValid(false);
+ } else if (!ifeChangelogLimit.isValid()) {
+ setErrorMessage(ifeChangelogLimit.getErrorMessage());
+ setValid(false);
+ // otherwise, allow performOk
+ } else {
+ setErrorMessage(null);
+ setValid(true);
+ }
+ toggleEnabled();
+ }
+
+ /**
+ * If "Enable project specific settings" is true, so will
+ * the options below it. The workspace settings link will be opposite
+ * to what value the checkbox is.
+ */
+ private void toggleEnabled() {
+ boolean enabled = btnProjectSettings.getSelection();
+ lnWorkspaceSettings.setEnabled(!enabled);
+ bfeIncludeChecksum.setEnabled(enabled, generalGroup);
+ bfeSQLDB.setEnabled(enabled, generalGroup);
+ bfeIgnoreSymlinks.setEnabled(enabled, generalGroup);
+ bfePrettyXML.setEnabled(enabled, generalGroup);
+ ifeSpawns.setEnabled(enabled, generalGroup);
+ rgfeChecksums.setEnabled(enabled, generalGroup);
+ bfeSameFilename.setEnabled(enabled, updatesGroup);
+ ifeChangelogLimit.setEnabled(enabled, changelogGroup);
+ rgfeChecksums.setEnabled(enabled, checksumsContainer);
+ rgfeCompressionTypes.setEnabled(enabled, compressContainer);
+ lblCheckTs.setEnabled(enabled);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPathEditor.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPathEditor.java
index 2aa4643e9d..83eb035091 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPathEditor.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPathEditor.java
@@ -20,45 +20,45 @@ import org.eclipse.swt.widgets.Composite;
*/
public class CreaterepoPathEditor extends PathEditor {
- /**
- * Default Constructor.
- *
- * @param name The name of the preference to save in.
- * @param labelText The description label.
- * @param dirChooserLabelText The label shown at the bottom of the directory dialog.
- * @param parent The parent composite this PathEditor belongs to.
- */
- public CreaterepoPathEditor(String name, String labelText, String dirChooserLabelText, Composite parent) {
- super(name, labelText, dirChooserLabelText, parent);
- }
+ /**
+ * Default Constructor.
+ *
+ * @param name The name of the preference to save in.
+ * @param labelText The description label.
+ * @param dirChooserLabelText The label shown at the bottom of the directory dialog.
+ * @param parent The parent composite this PathEditor belongs to.
+ */
+ public CreaterepoPathEditor(String name, String labelText, String dirChooserLabelText, Composite parent) {
+ super(name, labelText, dirChooserLabelText, parent);
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.preference.PathEditor#createList(java.lang.String[])
- */
- @Override
- protected String createList(String[] items) {
- String preferenceValue = ICreaterepoConstants.EMPTY_STRING;
- if (items.length > 0) {
- for (String str : items) {
- preferenceValue = preferenceValue.concat(str + ICreaterepoConstants.DELIMITER);
- }
- // remove hanging delimiter
- preferenceValue = preferenceValue.substring(0, preferenceValue.length()-1);
- }
- return preferenceValue;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.preference.PathEditor#createList(java.lang.String[])
+ */
+ @Override
+ protected String createList(String[] items) {
+ String preferenceValue = ICreaterepoConstants.EMPTY_STRING;
+ if (items.length > 0) {
+ for (String str : items) {
+ preferenceValue = preferenceValue.concat(str + ICreaterepoConstants.DELIMITER);
+ }
+ // remove hanging delimiter
+ preferenceValue = preferenceValue.substring(0, preferenceValue.length()-1);
+ }
+ return preferenceValue;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.preference.PathEditor#parseString(java.lang.String)
- */
- @Override
- protected String[] parseString(String stringList) {
- if (!stringList.isEmpty()) {
- return stringList.split(ICreaterepoConstants.DELIMITER);
- }
- return new String[]{};
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.preference.PathEditor#parseString(java.lang.String)
+ */
+ @Override
+ protected String[] parseString(String stringList) {
+ if (!stringList.isEmpty()) {
+ return stringList.split(ICreaterepoConstants.DELIMITER);
+ }
+ return new String[]{};
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPreferenceInitializer.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPreferenceInitializer.java
index 2420098df8..eb424ad73c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPreferenceInitializer.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPreferenceInitializer.java
@@ -21,48 +21,48 @@ import org.eclipse.linuxtools.internal.rpm.createrepo.CreaterepoPreferenceConsta
* Initialize the default preferences.
*/
public class CreaterepoPreferenceInitializer extends
- AbstractPreferenceInitializer {
+ AbstractPreferenceInitializer {
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
- */
- @Override
- public void initializeDefaultPreferences() {
- // initial preferences
- IEclipsePreferences node = DefaultScope.INSTANCE.getNode(Activator.PLUGIN_ID);
- // CreaterepoPreferencePage
- node.putBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME, CreaterepoPreferenceConstants.DEFAULT_UNIQUE_MD_NAME);
- node.putBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB, CreaterepoPreferenceConstants.DEFAULT_GENERATE_DB);
- node.putBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS, CreaterepoPreferenceConstants.DEFAULT_IGNORE_SYMLINKS);
- node.putBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML, CreaterepoPreferenceConstants.DEFAULT_PRETTY);
- node.putInt(CreaterepoPreferenceConstants.PREF_WORKERS, CreaterepoPreferenceConstants.DEFAULT_NUM_WORKERS);
- node.putBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS, CreaterepoPreferenceConstants.DEFAULT_CHECK_TS);
- node.putInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT, CreaterepoPreferenceConstants.DEFAULT_CHANGELOG_LIMIT);
- node.put(CreaterepoPreferenceConstants.PREF_CHECKSUM, CreaterepoPreferenceConstants.DEFAULT_CHECKSUM);
- node.put(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, CreaterepoPreferenceConstants.DEFAULT_COMPRESS_TYPE);
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
+ */
+ @Override
+ public void initializeDefaultPreferences() {
+ // initial preferences
+ IEclipsePreferences node = DefaultScope.INSTANCE.getNode(Activator.PLUGIN_ID);
+ // CreaterepoPreferencePage
+ node.putBoolean(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME, CreaterepoPreferenceConstants.DEFAULT_UNIQUE_MD_NAME);
+ node.putBoolean(CreaterepoPreferenceConstants.PREF_GENERATE_DB, CreaterepoPreferenceConstants.DEFAULT_GENERATE_DB);
+ node.putBoolean(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS, CreaterepoPreferenceConstants.DEFAULT_IGNORE_SYMLINKS);
+ node.putBoolean(CreaterepoPreferenceConstants.PREF_PRETTY_XML, CreaterepoPreferenceConstants.DEFAULT_PRETTY);
+ node.putInt(CreaterepoPreferenceConstants.PREF_WORKERS, CreaterepoPreferenceConstants.DEFAULT_NUM_WORKERS);
+ node.putBoolean(CreaterepoPreferenceConstants.PREF_CHECK_TS, CreaterepoPreferenceConstants.DEFAULT_CHECK_TS);
+ node.putInt(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT, CreaterepoPreferenceConstants.DEFAULT_CHANGELOG_LIMIT);
+ node.put(CreaterepoPreferenceConstants.PREF_CHECKSUM, CreaterepoPreferenceConstants.DEFAULT_CHECKSUM);
+ node.put(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, CreaterepoPreferenceConstants.DEFAULT_COMPRESS_TYPE);
- // default preferences
- IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- // CreaterepoPreferencePage
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME, CreaterepoPreferenceConstants.DEFAULT_UNIQUE_MD_NAME);
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_GENERATE_DB, CreaterepoPreferenceConstants.DEFAULT_GENERATE_DB);
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS, CreaterepoPreferenceConstants.DEFAULT_IGNORE_SYMLINKS);
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_PRETTY_XML, CreaterepoPreferenceConstants.DEFAULT_PRETTY);
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_WORKERS, CreaterepoPreferenceConstants.DEFAULT_NUM_WORKERS);
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_CHECK_TS, CreaterepoPreferenceConstants.DEFAULT_CHECK_TS);
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT, CreaterepoPreferenceConstants.DEFAULT_CHANGELOG_LIMIT);
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_CHECKSUM, CreaterepoPreferenceConstants.DEFAULT_CHECKSUM);
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, CreaterepoPreferenceConstants.DEFAULT_COMPRESS_TYPE);
+ // default preferences
+ IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
+ // CreaterepoPreferencePage
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME, CreaterepoPreferenceConstants.DEFAULT_UNIQUE_MD_NAME);
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_GENERATE_DB, CreaterepoPreferenceConstants.DEFAULT_GENERATE_DB);
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS, CreaterepoPreferenceConstants.DEFAULT_IGNORE_SYMLINKS);
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_PRETTY_XML, CreaterepoPreferenceConstants.DEFAULT_PRETTY);
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_WORKERS, CreaterepoPreferenceConstants.DEFAULT_NUM_WORKERS);
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_CHECK_TS, CreaterepoPreferenceConstants.DEFAULT_CHECK_TS);
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT, CreaterepoPreferenceConstants.DEFAULT_CHANGELOG_LIMIT);
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_CHECKSUM, CreaterepoPreferenceConstants.DEFAULT_CHECKSUM);
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE, CreaterepoPreferenceConstants.DEFAULT_COMPRESS_TYPE);
- // CreaterepoGeneralPropertyPage
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED, CreaterepoPreferenceConstants.DEFAULT_GENERAL_ENABLED);
+ // CreaterepoGeneralPropertyPage
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_GENERAL_ENABLED, CreaterepoPreferenceConstants.DEFAULT_GENERAL_ENABLED);
- // CreaterepoDeltaPropertyPage
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE, CreaterepoPreferenceConstants.DEFAULT_DELTA_ENABLE);
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_NUM_DELTAS, CreaterepoPreferenceConstants.DEFAULT_NUM_DELTAS);
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE, CreaterepoPreferenceConstants.DEFAULT_MAX_DELTA_SIZE);
- prefStore.setDefault(CreaterepoPreferenceConstants.PREF_OLD_PACKAGE_DIRS, CreaterepoPreferenceConstants.DEFAULT_OLD_PACKAGE_DIR_LIST);
- }
+ // CreaterepoDeltaPropertyPage
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_DELTA_ENABLE, CreaterepoPreferenceConstants.DEFAULT_DELTA_ENABLE);
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_NUM_DELTAS, CreaterepoPreferenceConstants.DEFAULT_NUM_DELTAS);
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_MAX_DELTA_SIZE, CreaterepoPreferenceConstants.DEFAULT_MAX_DELTA_SIZE);
+ prefStore.setDefault(CreaterepoPreferenceConstants.PREF_OLD_PACKAGE_DIRS, CreaterepoPreferenceConstants.DEFAULT_OLD_PACKAGE_DIR_LIST);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPreferencePage.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPreferencePage.java
index bffda71ea4..0c243dcd03 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPreferencePage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPreferencePage.java
@@ -38,179 +38,179 @@ import org.eclipse.ui.preferences.ScopedPreferenceStore;
* executing the createrepo command.
*/
public class CreaterepoPreferencePage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
-
- private Group generalGroup;
- private BooleanFieldEditor bfeIncludeChecksum;
- private BooleanFieldEditor bfeSQLDB;
- private BooleanFieldEditor bfeIgnoreSymlinks;
- private BooleanFieldEditor bfePrettyXML;
- private IntegerFieldEditor ifeSpawns;
-
- private Group updatesGroup;
- private BooleanFieldEditor bfeSameFilename;
-
- private Group changelogGroup;
- private IntegerFieldEditor ifeChangelogLimit;
-
- private RadioGroupFieldEditor rgfeChecksums;
- private RadioGroupFieldEditor rgfeCompressionTypes;
-
- public CreaterepoPreferencePage() {
- super(GRID);
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- @Override
- public void init(IWorkbench workbench) {
- setPreferenceStore(new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID));
- setDescription(Messages.CreaterepoPreferencePage_description);
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(FieldEditor.VALUE)) {
- checkState();
- }
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors()
- */
- @Override
- protected void createFieldEditors() {
- Composite parent = getFieldEditorParent();
- GridData data = new GridData();
- // general group
- generalGroup = new Group(parent, SWT.SHADOW_ETCHED_IN);
- generalGroup.setText(Messages.CreaterepoPreferencePage_generalGroupLabel);
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, 1).applyTo(generalGroup);
-
- // generate unique metadata filenames
- bfeIncludeChecksum = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
- Messages.CreaterepoPreferencePage_booleanChecksumName, generalGroup);
- bfeIncludeChecksum.load();
- bfeIncludeChecksum.setPropertyChangeListener(this);
- addField(bfeIncludeChecksum);
-
- // generate sqlite databases
- bfeSQLDB = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
- Messages.CreaterepoPreferencePage_booleanGenerateSQLDB, generalGroup);
- bfeSQLDB.load();
- bfeSQLDB.setPropertyChangeListener(this);
- addField(bfeSQLDB);
-
- // ignore symlinks for packages
- bfeIgnoreSymlinks = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
- Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks, generalGroup);
- bfeIgnoreSymlinks.load();
- bfeIgnoreSymlinks.setPropertyChangeListener(this);
- addField(bfeIgnoreSymlinks);
-
- // output files in pretty xml format
- bfePrettyXML = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
- Messages.CreaterepoPreferencePage_booleanPrettyXML, generalGroup);
- bfePrettyXML.load();
- bfePrettyXML.setPropertyChangeListener(this);
- addField(bfePrettyXML);
-
- // number of workers
- ifeSpawns = new IntegerFieldEditor(CreaterepoPreferenceConstants.PREF_WORKERS,
- Messages.CreaterepoPreferencePage_numWorkers, generalGroup);
- // more than 128 is alot. limiting. (createrepo warning)
- ifeSpawns.setValidRange(0, 128);
- ifeSpawns.load();
- addField(ifeSpawns);
- updateGroupSpacing(generalGroup);
-
- // updates group
- updatesGroup = new Group(parent, SWT.SHADOW_ETCHED_IN);
- updatesGroup.setText(Messages.CreaterepoPreferencePage_updateGroupLabel);
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, 1).hint(10, SWT.DEFAULT).applyTo(updatesGroup);
-
- // don't generate repo metadata, if their timestamps are newer than its rpms
- bfeSameFilename = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_CHECK_TS,
- Messages.CreaterepoPreferencePage_booleanCheckTS, updatesGroup);
- bfeSameFilename.load();
- bfeSameFilename.setPropertyChangeListener(this);
- addField(bfeSameFilename);
-
- // note of caution
- Label lblCheckTs = new Label(updatesGroup, SWT.WRAP);
- lblCheckTs.setText(Messages.CreaterepoPreferencePage_checkTSNote);
- data = new GridData();
- data.widthHint = 130;
- data.horizontalAlignment = SWT.FILL;
- data.grabExcessHorizontalSpace = true;
- data.horizontalIndent = 5;
- lblCheckTs.setLayoutData(data);
- updateGroupSpacing(updatesGroup);
-
- // changelog group
- changelogGroup = new Group(parent, SWT.SHADOW_ETCHED_IN);
- changelogGroup.setText(Messages.CreaterepoPreferencePage_changelogGroupLabel);
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, 1).hint(10, SWT.DEFAULT).applyTo(changelogGroup);
-
- // don't generate repo metadata, if their timestamps are newer than its rpms
- ifeChangelogLimit = new IntegerFieldEditor(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
- Messages.CreaterepoPreferencePage_numChangelogLimit, changelogGroup);
- ifeChangelogLimit.setValidRange(0, Integer.MAX_VALUE);
- ifeChangelogLimit.load();
- ifeChangelogLimit.setPropertyChangeListener(this);
- addField(ifeChangelogLimit);
- updateGroupSpacing(changelogGroup);
-
- Composite checksumsContainer = new Composite(parent, SWT.NONE);
- checksumsContainer.setLayout(new GridLayout());
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).indent(0, 20).grab(true, false).applyTo(checksumsContainer);
- // available checksums
- rgfeChecksums = new RadioGroupFieldEditor(CreaterepoPreferenceConstants.PREF_CHECKSUM,
- Messages.CreaterepoPreferencePage_checksumGroupLabel, 1, new String[][]{
- {ICreaterepoChecksums.SHA1, ICreaterepoChecksums.SHA1},
- {ICreaterepoChecksums.MD5, ICreaterepoChecksums.MD5},
- {ICreaterepoChecksums.SHA256, ICreaterepoChecksums.SHA256},
- {ICreaterepoChecksums.SHA512, ICreaterepoChecksums.SHA512}
- }, checksumsContainer, true);
- rgfeChecksums.load();
- rgfeChecksums.setPropertyChangeListener(this);
- addField(rgfeChecksums);
-
- Composite compressContainer = new Composite(parent, SWT.NONE);
- compressContainer.setLayout(new GridLayout());
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).indent(0, 20).grab(true, false).applyTo(compressContainer);
- // available compression types
- rgfeCompressionTypes = new RadioGroupFieldEditor(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
- Messages.CreaterepoPreferencePage_compressionGroupLabel, 1, new String[][]{
- {ICreaterepoCompressionTypes.COMPAT, ICreaterepoCompressionTypes.COMPAT},
- {ICreaterepoCompressionTypes.XZ, ICreaterepoCompressionTypes.XZ},
- {ICreaterepoCompressionTypes.GZ, ICreaterepoCompressionTypes.GZ},
- {ICreaterepoCompressionTypes.BZ2, ICreaterepoCompressionTypes.BZ2}
- }, compressContainer, true);
- rgfeCompressionTypes.load();
- rgfeCompressionTypes.setPropertyChangeListener(this);
- addField(rgfeCompressionTypes);
- }
-
- /**
- * Make sure there is space above the group as well as space
- * between the contents of the group and its border.
- *
- * @param group The group to update the spacing of.
- */
- private static void updateGroupSpacing(Group group) {
- GridLayout layout = (GridLayout) group.getLayout();
- GridData data = (GridData) group.getLayoutData();
- layout.marginWidth = 5;
- layout.marginHeight = 5;
- data.verticalIndent = 20;
- }
+ IWorkbenchPreferencePage {
+
+ private Group generalGroup;
+ private BooleanFieldEditor bfeIncludeChecksum;
+ private BooleanFieldEditor bfeSQLDB;
+ private BooleanFieldEditor bfeIgnoreSymlinks;
+ private BooleanFieldEditor bfePrettyXML;
+ private IntegerFieldEditor ifeSpawns;
+
+ private Group updatesGroup;
+ private BooleanFieldEditor bfeSameFilename;
+
+ private Group changelogGroup;
+ private IntegerFieldEditor ifeChangelogLimit;
+
+ private RadioGroupFieldEditor rgfeChecksums;
+ private RadioGroupFieldEditor rgfeCompressionTypes;
+
+ public CreaterepoPreferencePage() {
+ super(GRID);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
+ */
+ @Override
+ public void init(IWorkbench workbench) {
+ setPreferenceStore(new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID));
+ setDescription(Messages.CreaterepoPreferencePage_description);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
+ */
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ if (event.getProperty().equals(FieldEditor.VALUE)) {
+ checkState();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors()
+ */
+ @Override
+ protected void createFieldEditors() {
+ Composite parent = getFieldEditorParent();
+ GridData data = new GridData();
+ // general group
+ generalGroup = new Group(parent, SWT.SHADOW_ETCHED_IN);
+ generalGroup.setText(Messages.CreaterepoPreferencePage_generalGroupLabel);
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, 1).applyTo(generalGroup);
+
+ // generate unique metadata filenames
+ bfeIncludeChecksum = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_UNIQUE_MD_NAME,
+ Messages.CreaterepoPreferencePage_booleanChecksumName, generalGroup);
+ bfeIncludeChecksum.load();
+ bfeIncludeChecksum.setPropertyChangeListener(this);
+ addField(bfeIncludeChecksum);
+
+ // generate sqlite databases
+ bfeSQLDB = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_GENERATE_DB,
+ Messages.CreaterepoPreferencePage_booleanGenerateSQLDB, generalGroup);
+ bfeSQLDB.load();
+ bfeSQLDB.setPropertyChangeListener(this);
+ addField(bfeSQLDB);
+
+ // ignore symlinks for packages
+ bfeIgnoreSymlinks = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_IGNORE_SYMLINKS,
+ Messages.CreaterepoPreferencePage_booleanIgnoreSymlinks, generalGroup);
+ bfeIgnoreSymlinks.load();
+ bfeIgnoreSymlinks.setPropertyChangeListener(this);
+ addField(bfeIgnoreSymlinks);
+
+ // output files in pretty xml format
+ bfePrettyXML = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_PRETTY_XML,
+ Messages.CreaterepoPreferencePage_booleanPrettyXML, generalGroup);
+ bfePrettyXML.load();
+ bfePrettyXML.setPropertyChangeListener(this);
+ addField(bfePrettyXML);
+
+ // number of workers
+ ifeSpawns = new IntegerFieldEditor(CreaterepoPreferenceConstants.PREF_WORKERS,
+ Messages.CreaterepoPreferencePage_numWorkers, generalGroup);
+ // more than 128 is alot. limiting. (createrepo warning)
+ ifeSpawns.setValidRange(0, 128);
+ ifeSpawns.load();
+ addField(ifeSpawns);
+ updateGroupSpacing(generalGroup);
+
+ // updates group
+ updatesGroup = new Group(parent, SWT.SHADOW_ETCHED_IN);
+ updatesGroup.setText(Messages.CreaterepoPreferencePage_updateGroupLabel);
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, 1).hint(10, SWT.DEFAULT).applyTo(updatesGroup);
+
+ // don't generate repo metadata, if their timestamps are newer than its rpms
+ bfeSameFilename = new BooleanFieldEditor(CreaterepoPreferenceConstants.PREF_CHECK_TS,
+ Messages.CreaterepoPreferencePage_booleanCheckTS, updatesGroup);
+ bfeSameFilename.load();
+ bfeSameFilename.setPropertyChangeListener(this);
+ addField(bfeSameFilename);
+
+ // note of caution
+ Label lblCheckTs = new Label(updatesGroup, SWT.WRAP);
+ lblCheckTs.setText(Messages.CreaterepoPreferencePage_checkTSNote);
+ data = new GridData();
+ data.widthHint = 130;
+ data.horizontalAlignment = SWT.FILL;
+ data.grabExcessHorizontalSpace = true;
+ data.horizontalIndent = 5;
+ lblCheckTs.setLayoutData(data);
+ updateGroupSpacing(updatesGroup);
+
+ // changelog group
+ changelogGroup = new Group(parent, SWT.SHADOW_ETCHED_IN);
+ changelogGroup.setText(Messages.CreaterepoPreferencePage_changelogGroupLabel);
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).span(2, 1).hint(10, SWT.DEFAULT).applyTo(changelogGroup);
+
+ // don't generate repo metadata, if their timestamps are newer than its rpms
+ ifeChangelogLimit = new IntegerFieldEditor(CreaterepoPreferenceConstants.PREF_CHANGELOG_LIMIT,
+ Messages.CreaterepoPreferencePage_numChangelogLimit, changelogGroup);
+ ifeChangelogLimit.setValidRange(0, Integer.MAX_VALUE);
+ ifeChangelogLimit.load();
+ ifeChangelogLimit.setPropertyChangeListener(this);
+ addField(ifeChangelogLimit);
+ updateGroupSpacing(changelogGroup);
+
+ Composite checksumsContainer = new Composite(parent, SWT.NONE);
+ checksumsContainer.setLayout(new GridLayout());
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).indent(0, 20).grab(true, false).applyTo(checksumsContainer);
+ // available checksums
+ rgfeChecksums = new RadioGroupFieldEditor(CreaterepoPreferenceConstants.PREF_CHECKSUM,
+ Messages.CreaterepoPreferencePage_checksumGroupLabel, 1, new String[][]{
+ {ICreaterepoChecksums.SHA1, ICreaterepoChecksums.SHA1},
+ {ICreaterepoChecksums.MD5, ICreaterepoChecksums.MD5},
+ {ICreaterepoChecksums.SHA256, ICreaterepoChecksums.SHA256},
+ {ICreaterepoChecksums.SHA512, ICreaterepoChecksums.SHA512}
+ }, checksumsContainer, true);
+ rgfeChecksums.load();
+ rgfeChecksums.setPropertyChangeListener(this);
+ addField(rgfeChecksums);
+
+ Composite compressContainer = new Composite(parent, SWT.NONE);
+ compressContainer.setLayout(new GridLayout());
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).indent(0, 20).grab(true, false).applyTo(compressContainer);
+ // available compression types
+ rgfeCompressionTypes = new RadioGroupFieldEditor(CreaterepoPreferenceConstants.PREF_COMPRESSION_TYPE,
+ Messages.CreaterepoPreferencePage_compressionGroupLabel, 1, new String[][]{
+ {ICreaterepoCompressionTypes.COMPAT, ICreaterepoCompressionTypes.COMPAT},
+ {ICreaterepoCompressionTypes.XZ, ICreaterepoCompressionTypes.XZ},
+ {ICreaterepoCompressionTypes.GZ, ICreaterepoCompressionTypes.GZ},
+ {ICreaterepoCompressionTypes.BZ2, ICreaterepoCompressionTypes.BZ2}
+ }, compressContainer, true);
+ rgfeCompressionTypes.load();
+ rgfeCompressionTypes.setPropertyChangeListener(this);
+ addField(rgfeCompressionTypes);
+ }
+
+ /**
+ * Make sure there is space above the group as well as space
+ * between the contents of the group and its border.
+ *
+ * @param group The group to update the spacing of.
+ */
+ private static void updateGroupSpacing(Group group) {
+ GridLayout layout = (GridLayout) group.getLayout();
+ GridData data = (GridData) group.getLayoutData();
+ layout.marginWidth = 5;
+ layout.marginHeight = 5;
+ data.verticalIndent = 20;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPropertyPage.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPropertyPage.java
index 3cbe6446cf..aab0db91e9 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPropertyPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/preference/CreaterepoPropertyPage.java
@@ -31,86 +31,86 @@ import org.eclipse.ui.preferences.ScopedPreferenceStore;
*/
public abstract class CreaterepoPropertyPage extends PropertyPage implements IPropertyChangeListener {
- protected static final String CREATEREPO_PREFERENCE_ID = "org.eclipse.linuxtools.rpm.createrepo.preferences"; //$NON-NLS-1$
+ protected static final String CREATEREPO_PREFERENCE_ID = "org.eclipse.linuxtools.rpm.createrepo.preferences"; //$NON-NLS-1$
- protected IProject project;
- protected IPreferenceStore preferenceStore;
+ protected IProject project;
+ protected IPreferenceStore preferenceStore;
- /**
- * Default constructor has no description.
- */
- public CreaterepoPropertyPage() {
- this(null);
- }
+ /**
+ * Default constructor has no description.
+ */
+ public CreaterepoPropertyPage() {
+ this(null);
+ }
- /**
- * Constructor sets the description.
- *
- * @param description The description of the preference page.
- */
- public CreaterepoPropertyPage(String description) {
- setDescription(description);
- }
+ /**
+ * Constructor sets the description.
+ *
+ * @param description The description of the preference page.
+ */
+ public CreaterepoPropertyPage(String description) {
+ setDescription(description);
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Control createContents(Composite parent) {
- if (getElement() instanceof IResource) {
- project = ((IResource) getElement()).getProject();
- } else {
- Object adapter = getElement().getAdapter(IResource.class);
- if (adapter instanceof IResource) {
- project = ((IResource) adapter).getProject();
- }
- }
- setPreferenceStore(new ScopedPreferenceStore(new ProjectScope(project),
- Activator.PLUGIN_ID));
- preferenceStore = getPreferenceStore();
- return addContents(parent);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ protected Control createContents(Composite parent) {
+ if (getElement() instanceof IResource) {
+ project = ((IResource) getElement()).getProject();
+ } else {
+ Object adapter = getElement().getAdapter(IResource.class);
+ if (adapter instanceof IResource) {
+ project = ((IResource) adapter).getProject();
+ }
+ }
+ setPreferenceStore(new ScopedPreferenceStore(new ProjectScope(project),
+ Activator.PLUGIN_ID));
+ preferenceStore = getPreferenceStore();
+ return addContents(parent);
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(FieldEditor.VALUE)) {
- checkState();
- }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
+ */
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ if (event.getProperty().equals(FieldEditor.VALUE)) {
+ checkState();
+ }
+ }
- /**
- * Must be implemented by the subclasses. These are the contents of the
- * property page. Subclasses should implement this rather than createContents
- * to add controls to the property page.
- *
- * @param parent The composite.
- * @return The newly customized composite.
- */
- protected abstract Composite addContents(Composite parent);
+ /**
+ * Must be implemented by the subclasses. These are the contents of the
+ * property page. Subclasses should implement this rather than createContents
+ * to add controls to the property page.
+ *
+ * @param parent The composite.
+ * @return The newly customized composite.
+ */
+ protected abstract Composite addContents(Composite parent);
- /**
- * This method will be called whenever a field editor is changed. Note that
- * the field editor must first set the property change listener to this.
- */
- protected abstract void checkState();
+ /**
+ * This method will be called whenever a field editor is changed. Note that
+ * the field editor must first set the property change listener to this.
+ */
+ protected abstract void checkState();
- /**
- * Make sure there is space above the group as well as space
- * between the contents of the group and its border.
- *
- * @param group The group to update the spacing of.
- */
- protected static void updateGroupSpacing(Group group) {
- GridLayout layout = (GridLayout) group.getLayout();
- GridData data = (GridData) group.getLayoutData();
- layout.marginWidth = 5;
- layout.marginHeight = 5;
- data.verticalIndent = 20;
- }
+ /**
+ * Make sure there is space above the group as well as space
+ * between the contents of the group and its border.
+ *
+ * @param group The group to update the spacing of.
+ */
+ protected static void updateGroupSpacing(Group group) {
+ GridLayout layout = (GridLayout) group.getLayout();
+ GridData data = (GridData) group.getLayoutData();
+ layout.marginWidth = 5;
+ layout.marginHeight = 5;
+ data.verticalIndent = 20;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoCategoryModel.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoCategoryModel.java
index dd82c95a48..36813c64f8 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoCategoryModel.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoCategoryModel.java
@@ -25,83 +25,83 @@ import org.eclipse.linuxtools.internal.rpm.createrepo.ICreaterepoConstants;
*/
public class CreaterepoCategoryModel {
- private IEclipsePreferences projectPreferences;
+ private IEclipsePreferences projectPreferences;
- public CreaterepoCategoryModel(CreaterepoProject project) {
- if (project != null) {
- projectPreferences = project.getEclipsePreferences();
- }
- }
+ public CreaterepoCategoryModel(CreaterepoProject project) {
+ if (project != null) {
+ projectPreferences = project.getEclipsePreferences();
+ }
+ }
- /**
- * The only categories acceptable by createrepo. The categories will be populated with
- * tags found from the project preferences (if any).
- *
- * @return Initial categories and saved tags (if any).
- */
- public List<CreaterepoTreeCategory> getCategories() {
- List<CreaterepoTreeCategory> model = new ArrayList<>();
- CreaterepoTreeCategory distroCat = new CreaterepoTreeCategory(
- CreaterepoPreferenceConstants.PREF_DISTRO_TAG);
- distroCat.addAllTags(getDistroTags());
- CreaterepoTreeCategory contentCat = new CreaterepoTreeCategory(
- CreaterepoPreferenceConstants.PREF_CONTENT_TAG);
- contentCat.addAllTags(getContentTags());
- CreaterepoTreeCategory repoCat = new CreaterepoTreeCategory(
- CreaterepoPreferenceConstants.PREF_REPO_TAG);
- repoCat.addAllTags(getRepoTags());
- model.add(distroCat);
- model.add(contentCat);
- model.add(repoCat);
- return model;
- }
+ /**
+ * The only categories acceptable by createrepo. The categories will be populated with
+ * tags found from the project preferences (if any).
+ *
+ * @return Initial categories and saved tags (if any).
+ */
+ public List<CreaterepoTreeCategory> getCategories() {
+ List<CreaterepoTreeCategory> model = new ArrayList<>();
+ CreaterepoTreeCategory distroCat = new CreaterepoTreeCategory(
+ CreaterepoPreferenceConstants.PREF_DISTRO_TAG);
+ distroCat.addAllTags(getDistroTags());
+ CreaterepoTreeCategory contentCat = new CreaterepoTreeCategory(
+ CreaterepoPreferenceConstants.PREF_CONTENT_TAG);
+ contentCat.addAllTags(getContentTags());
+ CreaterepoTreeCategory repoCat = new CreaterepoTreeCategory(
+ CreaterepoPreferenceConstants.PREF_REPO_TAG);
+ repoCat.addAllTags(getRepoTags());
+ model.add(distroCat);
+ model.add(contentCat);
+ model.add(repoCat);
+ return model;
+ }
- /**
- * Get the distro tags from the project preferences.
- *
- * @return The prefered distro tags or empty if no preferences stored.
- */
- private List<String> getDistroTags() {
- if (projectPreferences != null) {
- String tagPref = projectPreferences.get(CreaterepoPreferenceConstants.PREF_DISTRO_TAG,
- ICreaterepoConstants.EMPTY_STRING);
- if (!tagPref.isEmpty()) {
- return Arrays.asList(tagPref.split(ICreaterepoConstants.DELIMITER));
- }
- }
- return Collections.EMPTY_LIST;
- }
+ /**
+ * Get the distro tags from the project preferences.
+ *
+ * @return The prefered distro tags or empty if no preferences stored.
+ */
+ private List<String> getDistroTags() {
+ if (projectPreferences != null) {
+ String tagPref = projectPreferences.get(CreaterepoPreferenceConstants.PREF_DISTRO_TAG,
+ ICreaterepoConstants.EMPTY_STRING);
+ if (!tagPref.isEmpty()) {
+ return Arrays.asList(tagPref.split(ICreaterepoConstants.DELIMITER));
+ }
+ }
+ return Collections.EMPTY_LIST;
+ }
- /**
- * Get the content tags from the project preferences.
- *
- * @return The prefered content tags or empty if no preferences stored.
- */
- private List<String> getContentTags() {
- if (projectPreferences != null) {
- String tagPref = projectPreferences.get(CreaterepoPreferenceConstants.PREF_CONTENT_TAG,
- ICreaterepoConstants.EMPTY_STRING);
- if (!tagPref.isEmpty()) {
- return Arrays.asList(tagPref.split(ICreaterepoConstants.DELIMITER));
- }
- }
- return Collections.EMPTY_LIST;
- }
+ /**
+ * Get the content tags from the project preferences.
+ *
+ * @return The prefered content tags or empty if no preferences stored.
+ */
+ private List<String> getContentTags() {
+ if (projectPreferences != null) {
+ String tagPref = projectPreferences.get(CreaterepoPreferenceConstants.PREF_CONTENT_TAG,
+ ICreaterepoConstants.EMPTY_STRING);
+ if (!tagPref.isEmpty()) {
+ return Arrays.asList(tagPref.split(ICreaterepoConstants.DELIMITER));
+ }
+ }
+ return Collections.EMPTY_LIST;
+ }
- /**
- * Get the repo tags from the project preferences.
- *
- * @return The prefered repo tags or empty if no preferences stored.
- */
- private List<String> getRepoTags() {
- if (projectPreferences != null) {
- String tagPref = projectPreferences.get(CreaterepoPreferenceConstants.PREF_REPO_TAG,
- ICreaterepoConstants.EMPTY_STRING);
- if (!tagPref.isEmpty()) {
- return Arrays.asList(tagPref.split(ICreaterepoConstants.DELIMITER));
- }
- }
- return Collections.EMPTY_LIST;
- }
+ /**
+ * Get the repo tags from the project preferences.
+ *
+ * @return The prefered repo tags or empty if no preferences stored.
+ */
+ private List<String> getRepoTags() {
+ if (projectPreferences != null) {
+ String tagPref = projectPreferences.get(CreaterepoPreferenceConstants.PREF_REPO_TAG,
+ ICreaterepoConstants.EMPTY_STRING);
+ if (!tagPref.isEmpty()) {
+ return Arrays.asList(tagPref.split(ICreaterepoConstants.DELIMITER));
+ }
+ }
+ return Collections.EMPTY_LIST;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeCategory.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeCategory.java
index dfc0b0588f..57a07bcc03 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeCategory.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeCategory.java
@@ -18,60 +18,60 @@ import java.util.List;
*/
public class CreaterepoTreeCategory {
- private String name;
- private List<String> tags = new ArrayList<>();
+ private String name;
+ private List<String> tags = new ArrayList<>();
- /**
- * Default constructor to initialize name of the
- * category at instantiation.
- *
- * @param name Name of category.
- */
- public CreaterepoTreeCategory(String name) {
- if (name != null && !name.isEmpty()) {
- this.name = name;
- }
- }
+ /**
+ * Default constructor to initialize name of the
+ * category at instantiation.
+ *
+ * @param name Name of category.
+ */
+ public CreaterepoTreeCategory(String name) {
+ if (name != null && !name.isEmpty()) {
+ this.name = name;
+ }
+ }
- /**
- * @return The category name.
- */
- public String getName() {
- return name;
- }
+ /**
+ * @return The category name.
+ */
+ public String getName() {
+ return name;
+ }
- /**
- * @param tag The tag to remove from the category.
- */
- public void removeTag(String tag) {
- if (tags.contains(tag)) {
- tags.remove(tag);
- }
- }
+ /**
+ * @param tag The tag to remove from the category.
+ */
+ public void removeTag(String tag) {
+ if (tags.contains(tag)) {
+ tags.remove(tag);
+ }
+ }
- /**
- * @param tag A unique tag to add to the category.
- */
- public void addTag(String tag) {
- if (!tags.contains(tag)) {
- tags.add(tag);
- }
- }
+ /**
+ * @param tag A unique tag to add to the category.
+ */
+ public void addTag(String tag) {
+ if (!tags.contains(tag)) {
+ tags.add(tag);
+ }
+ }
- /**
- * @param tags A list of tags to add to the category.
- */
- public void addAllTags(List<String> tags) {
- for (String tag : tags) {
- addTag(tag);
- }
- }
+ /**
+ * @param tags A list of tags to add to the category.
+ */
+ public void addAllTags(List<String> tags) {
+ for (String tag : tags) {
+ addTag(tag);
+ }
+ }
- /**
- * @return The tags in the category.
- */
- public List<String> getTags() {
- return tags;
- }
+ /**
+ * @return The tags in the category.
+ */
+ public List<String> getTags() {
+ return tags;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeContentProvider.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeContentProvider.java
index e3f413d351..2453cae55c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeContentProvider.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeContentProvider.java
@@ -18,69 +18,69 @@ import org.eclipse.jface.viewers.Viewer;
*/
public class CreaterepoTreeContentProvider implements ITreeContentProvider {
- private CreaterepoCategoryModel model;
+ private CreaterepoCategoryModel model;
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.IContentProvider#dispose()
- */
- @Override
- public void dispose() {/* not implemented */}
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.IContentProvider#dispose()
+ */
+ @Override
+ public void dispose() {/* not implemented */}
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- if (newInput instanceof CreaterepoCategoryModel) {
- model = (CreaterepoCategoryModel) newInput;
- }
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ if (newInput instanceof CreaterepoCategoryModel) {
+ model = (CreaterepoCategoryModel) newInput;
+ }
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getElements(java.lang.Object)
- */
- @Override
- public Object[] getElements(Object inputElement) {
- return model.getCategories().toArray();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ITreeContentProvider#getElements(java.lang.Object)
+ */
+ @Override
+ public Object[] getElements(Object inputElement) {
+ return model.getCategories().toArray();
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
- */
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof CreaterepoTreeCategory) {
- CreaterepoTreeCategory category = (CreaterepoTreeCategory) parentElement;
- return category.getTags().toArray();
- }
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
+ */
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ if (parentElement instanceof CreaterepoTreeCategory) {
+ CreaterepoTreeCategory category = (CreaterepoTreeCategory) parentElement;
+ return category.getTags().toArray();
+ }
+ return null;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
- */
- @Override
- public Object getParent(Object element) {
- return null;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
+ */
+ @Override
+ public Object getParent(Object element) {
+ return null;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
- */
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof CreaterepoTreeCategory) {
- CreaterepoTreeCategory category = (CreaterepoTreeCategory) element;
- // category has children if ! empty
- return !category.getTags().isEmpty();
- }
- return false;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
+ */
+ @Override
+ public boolean hasChildren(Object element) {
+ if (element instanceof CreaterepoTreeCategory) {
+ CreaterepoTreeCategory category = (CreaterepoTreeCategory) element;
+ // category has children if ! empty
+ return !category.getTags().isEmpty();
+ }
+ return false;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeLabelProvider.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeLabelProvider.java
index f97156c55c..d67da4b98d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeLabelProvider.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/tree/CreaterepoTreeLabelProvider.java
@@ -19,32 +19,32 @@ import org.eclipse.swt.graphics.Image;
*/
public class CreaterepoTreeLabelProvider extends LabelProvider {
- private static final String CATEGORY_IMAGE = "icons/library_obj.gif"; //$NON-NLS-1$
- private static final String TAG_IMAGE = "icons/templateprop_co.gif"; //$NON-NLS-1$
+ private static final String CATEGORY_IMAGE = "icons/library_obj.gif"; //$NON-NLS-1$
+ private static final String TAG_IMAGE = "icons/templateprop_co.gif"; //$NON-NLS-1$
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
- */
- @Override
- public String getText(Object element) {
- if (element instanceof CreaterepoTreeCategory) {
- CreaterepoTreeCategory category = (CreaterepoTreeCategory) element;
- return category.getName();
- }
- return element.toString();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
+ */
+ @Override
+ public String getText(Object element) {
+ if (element instanceof CreaterepoTreeCategory) {
+ CreaterepoTreeCategory category = (CreaterepoTreeCategory) element;
+ return category.getName();
+ }
+ return element.toString();
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
- */
- @Override
- public Image getImage(Object element) {
- if (element instanceof CreaterepoTreeCategory) {
- return Activator.getImageDescriptor(CATEGORY_IMAGE).createImage();
- }
- return Activator.getImageDescriptor(TAG_IMAGE).createImage();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
+ */
+ @Override
+ public Image getImage(Object element) {
+ if (element instanceof CreaterepoTreeCategory) {
+ return Activator.getImageDescriptor(CATEGORY_IMAGE).createImage();
+ }
+ return Activator.getImageDescriptor(TAG_IMAGE).createImage();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoNewWizardPageOne.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoNewWizardPageOne.java
index 528d277bea..2763613efd 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoNewWizardPageOne.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoNewWizardPageOne.java
@@ -17,22 +17,22 @@ import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
* The sole purpose of this page is to create a new project for createrepo.
*/
public class CreaterepoNewWizardPageOne extends
- WizardNewProjectCreationPage {
+ WizardNewProjectCreationPage {
- /*
- * TODO: add in working sets
- */
+ /*
+ * TODO: add in working sets
+ */
- /**
- * Constructor for CreaterepoWizardPage. Will set the page name, title, and
- * description.
- *
- * @param pageName The wizard page's name.
- */
- public CreaterepoNewWizardPageOne(String pageName) {
- super(pageName);
- setTitle(Messages.CreaterepoNewWizardPageOne_wizardPageTitle);
- setDescription(Messages.CreaterepoNewWizardPageOne_wizardPageDescription);
- }
+ /**
+ * Constructor for CreaterepoWizardPage. Will set the page name, title, and
+ * description.
+ *
+ * @param pageName The wizard page's name.
+ */
+ public CreaterepoNewWizardPageOne(String pageName) {
+ super(pageName);
+ setTitle(Messages.CreaterepoNewWizardPageOne_wizardPageTitle);
+ setDescription(Messages.CreaterepoNewWizardPageOne_wizardPageDescription);
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoNewWizardPageTwo.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoNewWizardPageTwo.java
index a8f51b8b2a..65fd8c6434 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoNewWizardPageTwo.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoNewWizardPageTwo.java
@@ -34,173 +34,173 @@ import org.eclipse.swt.widgets.Text;
*/
public class CreaterepoNewWizardPageTwo extends WizardPage {
- private Text repositoryIDTxt;
- private Text repositoryNameTxt;
- private Text repositoryBaseURLTxt;
-
- /**
- * Constructor for CreaterepoWizardPage. Will set the page name, title, and
- * description.
- *
- * @param pageName The wizard page's name.
- */
- public CreaterepoNewWizardPageTwo(String pageName) {
- super(pageName);
- setTitle(Messages.CreaterepoNewWizardPageTwo_wizardPageTitle);
- setDescription(Messages.CreaterepoNewWizardPageTwo_wizardPageDescription);
- setPageComplete(false);
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout();
- GridData layoutData = new GridData();
- layoutData.grabExcessHorizontalSpace = true;
- layoutData.grabExcessVerticalSpace = true;
- layoutData.horizontalAlignment = GridData.FILL;
- layoutData.verticalAlignment = GridData.FILL;
- container.setLayout(layout);
- container.setLayoutData(layoutData);
-
- // composite to hold the required information
- Composite information = new Composite(container, SWT.NONE);
- layout = new GridLayout(2, false);
- layoutData = new GridData();
- layoutData.grabExcessHorizontalSpace = true;
- layoutData.horizontalAlignment = GridData.FILL;
- layoutData.verticalAlignment = GridData.CENTER;
- information.setLayoutData(layoutData);
- information.setLayout(layout);
-
- // listen on modifying the Text widgets
- ModifyListener modifyListner = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- setPageComplete(isValid());
- }
- };
- repositoryIDTxt = createTextFieldWithLabel(information, Messages.CreaterepoNewWizardPageTwo_labelID,
- Messages.CreaterepoNewWizardPageTwo_tooltipID);
- repositoryIDTxt.addModifyListener(modifyListner);
- repositoryNameTxt = createTextFieldWithLabel(information, Messages.CreaterepoNewWizardPageTwo_labelName,
- Messages.CreaterepoNewWizardPageTwo_tooltipName);
- repositoryNameTxt.addModifyListener(modifyListner);
- repositoryBaseURLTxt = createTextFieldWithLabel(information, Messages.CreaterepoNewWizardPageTwo_labelURL,
- Messages.CreaterepoNewWizardPageTwo_tooltipURL);
- repositoryBaseURLTxt.addModifyListener(modifyListner);
- setControl(container);
- }
-
- /**
- * Create a text field with a label.
- *
- * @param parent The parent of the text field and label.
- * @param labelName The name on the label.
- * @return The newly created text field.
- */
- protected Text createTextFieldWithLabel(Composite parent, String labelName, String tooltip) {
- GridData layoutData = new GridData();
- // create the label
- Label respositoryBaseURLLbl = new Label(parent, SWT.NONE);
- respositoryBaseURLLbl.setText(labelName);
- layoutData = new GridData();
- layoutData.horizontalAlignment = GridData.BEGINNING;
- layoutData.verticalAlignment = GridData.CENTER;
- respositoryBaseURLLbl.setToolTipText(tooltip);
- // create the text field
- Text textField = new Text(parent, SWT.BORDER | SWT.SINGLE);
- layoutData = new GridData();
- layoutData.grabExcessHorizontalSpace = true;
- layoutData.horizontalAlignment = GridData.FILL;
- layoutData.verticalAlignment = GridData.CENTER;
- textField.setLayoutData(layoutData);
- textField.setToolTipText(tooltip);
- return textField;
- }
-
- /**
- * Check to see if all the text fields are valid. Otherwise, set error
- * messages appropriately.
- *
- * @return True if all the text fields are valid, false otherwise.
- */
- protected boolean isValid() {
- if (!validateID()) {
- setErrorMessage(Messages.CreaterepoNewWizardPageTwo_errorID);
- }
- if (repositoryNameTxt.getText().trim().isEmpty()) {
- setErrorMessage(Messages.CreaterepoNewWizardPageTwo_errorName);
- }
- if (!validateURL()) {
- setErrorMessage(Messages.CreaterepoNewWizardPageTwo_errorURL);
- }
- if (validateID() && validateURL() && !repositoryNameTxt.getText().trim().isEmpty()) {
- setErrorMessage(null);
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * Check if the ID is valid. It is valid if it is a single string and
- * not empty.
- *
- * @return True if the ID is valid, false otherwise.
- */
- private boolean validateID() {
- // check if repository ID is a single string
- String tmpRepoID = repositoryIDTxt.getText().trim();
- Pattern singleStringPattern = Pattern.compile("\\b(\\S+)\\b", //$NON-NLS-1$
- Pattern.CASE_INSENSITIVE);
- Matcher singleStringMatcher = singleStringPattern.matcher(tmpRepoID);
- if (singleStringMatcher.matches()) {
- return true;
- }
- return false;
- }
-
- /**
- * Check if the URL is valid. It is valid if it contains a valid protocol and link.
- *
- * @return True if the URL is valid, false otherwise.
- */
- private boolean validateURL() {
- // check if baseURL is a valid URL
- String tmpRepoURL = repositoryBaseURLTxt.getText().trim();
- // TODO: possibly validate if pointing to something that exists (not really necessary, but nice)
- try {
- new URL(tmpRepoURL);
- return true;
- } catch (MalformedURLException e) {
- return false;
- }
- }
-
- public String getRepositoryID() {
- if (repositoryIDTxt == null) {
- return ICreaterepoConstants.EMPTY_STRING;
- }
- return repositoryIDTxt.getText().trim();
- }
-
- public String getRepositoryName() {
- if (repositoryNameTxt == null) {
- return ICreaterepoConstants.EMPTY_STRING;
- }
- return repositoryNameTxt.getText().trim();
- }
-
- public String getRepositoryURL() {
- if (repositoryBaseURLTxt == null) {
- return ICreaterepoConstants.EMPTY_STRING;
- }
- return repositoryBaseURLTxt.getText().trim();
- }
+ private Text repositoryIDTxt;
+ private Text repositoryNameTxt;
+ private Text repositoryBaseURLTxt;
+
+ /**
+ * Constructor for CreaterepoWizardPage. Will set the page name, title, and
+ * description.
+ *
+ * @param pageName The wizard page's name.
+ */
+ public CreaterepoNewWizardPageTwo(String pageName) {
+ super(pageName);
+ setTitle(Messages.CreaterepoNewWizardPageTwo_wizardPageTitle);
+ setDescription(Messages.CreaterepoNewWizardPageTwo_wizardPageDescription);
+ setPageComplete(false);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public void createControl(Composite parent) {
+ Composite container = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ GridData layoutData = new GridData();
+ layoutData.grabExcessHorizontalSpace = true;
+ layoutData.grabExcessVerticalSpace = true;
+ layoutData.horizontalAlignment = GridData.FILL;
+ layoutData.verticalAlignment = GridData.FILL;
+ container.setLayout(layout);
+ container.setLayoutData(layoutData);
+
+ // composite to hold the required information
+ Composite information = new Composite(container, SWT.NONE);
+ layout = new GridLayout(2, false);
+ layoutData = new GridData();
+ layoutData.grabExcessHorizontalSpace = true;
+ layoutData.horizontalAlignment = GridData.FILL;
+ layoutData.verticalAlignment = GridData.CENTER;
+ information.setLayoutData(layoutData);
+ information.setLayout(layout);
+
+ // listen on modifying the Text widgets
+ ModifyListener modifyListner = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ setPageComplete(isValid());
+ }
+ };
+ repositoryIDTxt = createTextFieldWithLabel(information, Messages.CreaterepoNewWizardPageTwo_labelID,
+ Messages.CreaterepoNewWizardPageTwo_tooltipID);
+ repositoryIDTxt.addModifyListener(modifyListner);
+ repositoryNameTxt = createTextFieldWithLabel(information, Messages.CreaterepoNewWizardPageTwo_labelName,
+ Messages.CreaterepoNewWizardPageTwo_tooltipName);
+ repositoryNameTxt.addModifyListener(modifyListner);
+ repositoryBaseURLTxt = createTextFieldWithLabel(information, Messages.CreaterepoNewWizardPageTwo_labelURL,
+ Messages.CreaterepoNewWizardPageTwo_tooltipURL);
+ repositoryBaseURLTxt.addModifyListener(modifyListner);
+ setControl(container);
+ }
+
+ /**
+ * Create a text field with a label.
+ *
+ * @param parent The parent of the text field and label.
+ * @param labelName The name on the label.
+ * @return The newly created text field.
+ */
+ protected Text createTextFieldWithLabel(Composite parent, String labelName, String tooltip) {
+ GridData layoutData = new GridData();
+ // create the label
+ Label respositoryBaseURLLbl = new Label(parent, SWT.NONE);
+ respositoryBaseURLLbl.setText(labelName);
+ layoutData = new GridData();
+ layoutData.horizontalAlignment = GridData.BEGINNING;
+ layoutData.verticalAlignment = GridData.CENTER;
+ respositoryBaseURLLbl.setToolTipText(tooltip);
+ // create the text field
+ Text textField = new Text(parent, SWT.BORDER | SWT.SINGLE);
+ layoutData = new GridData();
+ layoutData.grabExcessHorizontalSpace = true;
+ layoutData.horizontalAlignment = GridData.FILL;
+ layoutData.verticalAlignment = GridData.CENTER;
+ textField.setLayoutData(layoutData);
+ textField.setToolTipText(tooltip);
+ return textField;
+ }
+
+ /**
+ * Check to see if all the text fields are valid. Otherwise, set error
+ * messages appropriately.
+ *
+ * @return True if all the text fields are valid, false otherwise.
+ */
+ protected boolean isValid() {
+ if (!validateID()) {
+ setErrorMessage(Messages.CreaterepoNewWizardPageTwo_errorID);
+ }
+ if (repositoryNameTxt.getText().trim().isEmpty()) {
+ setErrorMessage(Messages.CreaterepoNewWizardPageTwo_errorName);
+ }
+ if (!validateURL()) {
+ setErrorMessage(Messages.CreaterepoNewWizardPageTwo_errorURL);
+ }
+ if (validateID() && validateURL() && !repositoryNameTxt.getText().trim().isEmpty()) {
+ setErrorMessage(null);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Check if the ID is valid. It is valid if it is a single string and
+ * not empty.
+ *
+ * @return True if the ID is valid, false otherwise.
+ */
+ private boolean validateID() {
+ // check if repository ID is a single string
+ String tmpRepoID = repositoryIDTxt.getText().trim();
+ Pattern singleStringPattern = Pattern.compile("\\b(\\S+)\\b", //$NON-NLS-1$
+ Pattern.CASE_INSENSITIVE);
+ Matcher singleStringMatcher = singleStringPattern.matcher(tmpRepoID);
+ if (singleStringMatcher.matches()) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Check if the URL is valid. It is valid if it contains a valid protocol and link.
+ *
+ * @return True if the URL is valid, false otherwise.
+ */
+ private boolean validateURL() {
+ // check if baseURL is a valid URL
+ String tmpRepoURL = repositoryBaseURLTxt.getText().trim();
+ // TODO: possibly validate if pointing to something that exists (not really necessary, but nice)
+ try {
+ new URL(tmpRepoURL);
+ return true;
+ } catch (MalformedURLException e) {
+ return false;
+ }
+ }
+
+ public String getRepositoryID() {
+ if (repositoryIDTxt == null) {
+ return ICreaterepoConstants.EMPTY_STRING;
+ }
+ return repositoryIDTxt.getText().trim();
+ }
+
+ public String getRepositoryName() {
+ if (repositoryNameTxt == null) {
+ return ICreaterepoConstants.EMPTY_STRING;
+ }
+ return repositoryNameTxt.getText().trim();
+ }
+
+ public String getRepositoryURL() {
+ if (repositoryBaseURLTxt == null) {
+ return ICreaterepoConstants.EMPTY_STRING;
+ }
+ return repositoryBaseURLTxt.getText().trim();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoWizard.java b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoWizard.java
index ca52698743..6e1aad609c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoWizard.java
+++ b/rpm/org.eclipse.linuxtools.rpm.createrepo/src/org/eclipse/linuxtools/internal/rpm/createrepo/wizard/CreaterepoWizard.java
@@ -40,128 +40,128 @@ import org.eclipse.ui.ide.IDE;
*/
public class CreaterepoWizard extends Wizard implements INewWizard {
- private CreaterepoNewWizardPageOne pageOne;
- private CreaterepoNewWizardPageTwo pageTwo;
- private IProject project;
+ private CreaterepoNewWizardPageOne pageOne;
+ private CreaterepoNewWizardPageTwo pageTwo;
+ private IProject project;
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
- */
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- setNeedsProgressMonitor(true);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
+ */
+ @Override
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ setNeedsProgressMonitor(true);
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.wizard.Wizard#addPages()
- */
- @Override
- public void addPages() {
- super.addPages();
- pageOne = new CreaterepoNewWizardPageOne(
- Messages.CreaterepoNewWizardPageOne_wizardPageName);
- addPage(pageOne);
- pageTwo = new CreaterepoNewWizardPageTwo(
- Messages.CreaterepoNewWizardPageTwo_wizardPageName);
- addPage(pageTwo);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.wizard.Wizard#addPages()
+ */
+ @Override
+ public void addPages() {
+ super.addPages();
+ pageOne = new CreaterepoNewWizardPageOne(
+ Messages.CreaterepoNewWizardPageOne_wizardPageName);
+ addPage(pageOne);
+ pageTwo = new CreaterepoNewWizardPageTwo(
+ Messages.CreaterepoNewWizardPageTwo_wizardPageName);
+ addPage(pageTwo);
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.wizard.Wizard#canFinish()
- */
- @Override
- public boolean canFinish() {
- return getContainer().getCurrentPage() == pageTwo && pageTwo.isPageComplete();
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.wizard.Wizard#canFinish()
+ */
+ @Override
+ public boolean canFinish() {
+ return getContainer().getCurrentPage() == pageTwo && pageTwo.isPageComplete();
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.wizard.Wizard#performFinish()
- */
- @Override
- public boolean performFinish() {
- WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
- @Override
- protected void execute(IProgressMonitor monitor) {
- createProject(monitor);
- }
- };
- try {
- getContainer().run(false, true, op);
- } catch (InvocationTargetException e) {
- Activator.logError(Messages.CreaterepoWizard_errorCreatingProject, e);
- } catch (InterruptedException e) {
- Activator.logError(Messages.CreaterepoWizard_errorCreatingProject, e);
- }
- return true;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.jface.wizard.Wizard#performFinish()
+ */
+ @Override
+ public boolean performFinish() {
+ WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
+ @Override
+ protected void execute(IProgressMonitor monitor) {
+ createProject(monitor);
+ }
+ };
+ try {
+ getContainer().run(false, true, op);
+ } catch (InvocationTargetException e) {
+ Activator.logError(Messages.CreaterepoWizard_errorCreatingProject, e);
+ } catch (InterruptedException e) {
+ Activator.logError(Messages.CreaterepoWizard_errorCreatingProject, e);
+ }
+ return true;
+ }
- /**
- * Create a createrepo project that contains an empty content folder and
- * a quickly initialized .repo file with the mandatory options.
- *
- * @param monitor The progress monitor.
- */
- protected void createProject(IProgressMonitor monitor) {
- try {
- String fileName = pageTwo.getRepositoryID().concat("."+ICreaterepoConstants. //$NON-NLS-1$
- REPO_FILE_EXTENSION);
- // create the project
- project = CreaterepoProjectCreator.create(pageOne.getProjectName(),
- pageOne.getLocationPath(), fileName, monitor);
- // get a handle on the content folder
- IFolder folder = project
- .getFolder(ICreaterepoConstants.CONTENT_FOLDER);
- if (!folder.exists()) {
- folder.create(false, true, monitor);
- }
- // get a handle on the .repo file
- final IFile file = project.getFile(fileName);
- final String repoFileContents = initializeRepoContents(pageTwo.getRepositoryID(),
- pageTwo.getRepositoryName(), pageTwo.getRepositoryURL());
- InputStream stream = new ByteArrayInputStream(repoFileContents.getBytes());
- if (file.exists()) {
- file.setContents(stream, true, true, monitor);
- } else {
- file.create(stream, true, monitor);
- }
- monitor.worked(1);
- monitor.setTaskName(Messages.CreaterepoWizard_openFileOnCreation);
- getShell().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- IWorkbenchPage page = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- try {
- IDE.openEditor(page, file, true);
- } catch (PartInitException e) {
- Activator.logError(
- Messages.CreaterepoWizard_errorOpeningNewlyCreatedFile, e);
- }
- }
- });
- monitor.worked(1);
- } catch (CoreException e) {
- Activator.logError(Messages.CreaterepoWizard_errorCreatingProject, e);
- }
- }
+ /**
+ * Create a createrepo project that contains an empty content folder and
+ * a quickly initialized .repo file with the mandatory options.
+ *
+ * @param monitor The progress monitor.
+ */
+ protected void createProject(IProgressMonitor monitor) {
+ try {
+ String fileName = pageTwo.getRepositoryID().concat("."+ICreaterepoConstants. //$NON-NLS-1$
+ REPO_FILE_EXTENSION);
+ // create the project
+ project = CreaterepoProjectCreator.create(pageOne.getProjectName(),
+ pageOne.getLocationPath(), fileName, monitor);
+ // get a handle on the content folder
+ IFolder folder = project
+ .getFolder(ICreaterepoConstants.CONTENT_FOLDER);
+ if (!folder.exists()) {
+ folder.create(false, true, monitor);
+ }
+ // get a handle on the .repo file
+ final IFile file = project.getFile(fileName);
+ final String repoFileContents = initializeRepoContents(pageTwo.getRepositoryID(),
+ pageTwo.getRepositoryName(), pageTwo.getRepositoryURL());
+ InputStream stream = new ByteArrayInputStream(repoFileContents.getBytes());
+ if (file.exists()) {
+ file.setContents(stream, true, true, monitor);
+ } else {
+ file.create(stream, true, monitor);
+ }
+ monitor.worked(1);
+ monitor.setTaskName(Messages.CreaterepoWizard_openFileOnCreation);
+ getShell().getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ IWorkbenchPage page = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
+ try {
+ IDE.openEditor(page, file, true);
+ } catch (PartInitException e) {
+ Activator.logError(
+ Messages.CreaterepoWizard_errorOpeningNewlyCreatedFile, e);
+ }
+ }
+ });
+ monitor.worked(1);
+ } catch (CoreException e) {
+ Activator.logError(Messages.CreaterepoWizard_errorCreatingProject, e);
+ }
+ }
- /**
- * Helper method to initialize the contents of the .repo file.
- *
- * @param id The unique repository ID.
- * @param name A human readable string that describes the repository.
- * @param url A URL pointing to the repodata folder.
- * @return
- */
- private static String initializeRepoContents(String id, String name, String url) {
- String contents = String.format("[%s]\n", id); //$NON-NLS-1$
- contents = contents.concat(String.format("%s=%s\n", IRepoFileConstants.NAME, name)); //$NON-NLS-1$
- contents = contents.concat(String.format("%s=%s\n", IRepoFileConstants.BASE_URL, url)); //$NON-NLS-1$
- return contents;
- }
+ /**
+ * Helper method to initialize the contents of the .repo file.
+ *
+ * @param id The unique repository ID.
+ * @param name A human readable string that describes the repository.
+ * @param url A URL pointing to the repodata folder.
+ * @return
+ */
+ private static String initializeRepoContents(String id, String name, String url) {
+ String contents = String.format("[%s]\n", id); //$NON-NLS-1$
+ contents = contents.concat(String.format("%s=%s\n", IRepoFileConstants.NAME, name)); //$NON-NLS-1$
+ contents = contents.concat(String.format("%s=%s\n", IRepoFileConstants.BASE_URL, url)); //$NON-NLS-1$
+ return contents;
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.rpmlint/plugin.xml b/rpm/org.eclipse.linuxtools.rpm.rpmlint/plugin.xml
index 0dc63f206c..67731553a1 100644
--- a/rpm/org.eclipse.linuxtools.rpm.rpmlint/plugin.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.rpmlint/plugin.xml
@@ -39,12 +39,12 @@
id="rpmlint.runRpmlint.command"/>
</extension>
<extension point="org.eclipse.ui.handlers">
- <handler
- class="org.eclipse.linuxtools.internal.rpm.rpmlint.actions.ToggleRpmlintNatureAction"
- commandId="rpmlint.toggleRpmlint.command" />
- <handler
- class="org.eclipse.linuxtools.internal.rpm.rpmlint.actions.RunRpmlintAction"
- commandId="rpmlint.runRpmlint.command" />
+ <handler
+ class="org.eclipse.linuxtools.internal.rpm.rpmlint.actions.ToggleRpmlintNatureAction"
+ commandId="rpmlint.toggleRpmlint.command" />
+ <handler
+ class="org.eclipse.linuxtools.internal.rpm.rpmlint.actions.RunRpmlintAction"
+ commandId="rpmlint.runRpmlint.command" />
</extension>
<extension
point="org.eclipse.ui.menus">
@@ -122,5 +122,5 @@
class="org.eclipse.linuxtools.internal.rpm.rpmlint.resolutions.RpmlintMarkerResolutionGenerator"
markerType="org.eclipse.linuxtools.rpm.rpmlint.rpmlintProblem"/>
</extension>
-
+
</plugin>
diff --git a/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/parser/RpmlintItem.java b/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/parser/RpmlintItem.java
index 724b4df08b..7a2e50be5f 100644
--- a/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/parser/RpmlintItem.java
+++ b/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/parser/RpmlintItem.java
@@ -17,164 +17,164 @@ import org.eclipse.linuxtools.rpm.ui.editor.parser.SpecfileParser;
*/
public class RpmlintItem {
- private static final String[] SECTIONS = SpecfileParser.simpleSections;
-
- private int lineNbr;
-
- private int severity;
-
- private String id;
-
- private String refferedContent;
-
- private String message;
-
- private String fileName;
-
- /**
- * Returns the name of the file rpmlint gives warning for.
- *
- * @return The file name.
- */
- public String getFileName() {
- return fileName;
- }
-
- /**
- * Sets the name of the file rpmlint gives warning for.
- * @param file The File name.
- */
- public void setFileName(String file) {
- this.fileName = file;
- }
-
- /**
- * Returns the line number where the warning appears if rpmlint gives it.
- * @return The line number.
- */
- public int getLineNbr() {
- return lineNbr;
- }
-
- /**
- * Sets the line number where the warning appears if rpmlint gives it.
- * @param lineNbr The line number.
- */
- public void setLineNbr(int lineNbr) {
- this.lineNbr = lineNbr;
- }
-
- /**
- * The id of the warning.
- * @return The id.
- */
- public String getId() {
- return id;
- }
-
- /**
- * Sets the id of the warning.
- * @param id The id of the warning.
- */
- public void setId(String id) {
- this.id = id;
- }
-
- /**
- * Returns the message as rpmlint gives it.
- * @return The message.
- */
- public String getMessage() {
- return message;
- }
-
- /**
- * Sets the message as rpmlint gives it.
- * @param message The raw message.
- */
- public void setMessage(String message) {
- this.message = message;
- }
-
- /**
- * Returns the referred content - section, tag, etc.
- * @return The referred content.
- */
- public String getRefferedContent() {
- return refferedContent;
- }
-
- /**
- * Sets the referred content.
- * @param refferedContent The referred content.
- */
- public void setRefferedContent(String refferedContent) {
- for (int i = 0; i < SECTIONS.length; i++) {
- if (refferedContent.startsWith(SECTIONS[i])) {
- this.refferedContent = refferedContent.trim();
- if (this.refferedContent.equals("")) {//$NON-NLS-1$
- this.refferedContent = SECTIONS[i];
- }
- i = SECTIONS.length;
- } else {
- this.refferedContent = refferedContent;
- }
- }
- }
-
- /**
- * Returns the severity of the rpmlint item.
- *
- * @return The severity.
- */
- public int getSeverity() {
- return severity;
- }
-
- /**
- * Returns the severity of the rpmlint item.
- *
- * @param severity The severity of the rpmlint item.
- */
- public void setSeverity(String severity) {
- severity = severity.replaceAll(":", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$
- switch (severity.charAt(0)) {
- case 'I':
- this.severity = 0;
- break;
- case 'W':
- this.severity = 1;
- break;
- case 'E':
- this.severity = 2;
- break;
- default:
- this.severity = 0;
- break;
- }
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("line number: "); //$NON-NLS-1$
- stringBuilder.append(this.lineNbr);
- stringBuilder.append("\nfile name: "); //$NON-NLS-1$
- stringBuilder.append(this.fileName);
- stringBuilder.append("\nseverity: "); //$NON-NLS-1$
- stringBuilder.append(this.severity);
- stringBuilder.append("\nId: "); //$NON-NLS-1$
- stringBuilder.append(this.id);
- stringBuilder.append("\nrefered content: "); //$NON-NLS-1$
- stringBuilder.append(this.refferedContent);
- stringBuilder.append("\nmessage: "); //$NON-NLS-1$
- stringBuilder.append(this.getMessage());
- stringBuilder.append("\n"); //$NON-NLS-1$
- return stringBuilder.toString();
- }
+ private static final String[] SECTIONS = SpecfileParser.simpleSections;
+
+ private int lineNbr;
+
+ private int severity;
+
+ private String id;
+
+ private String refferedContent;
+
+ private String message;
+
+ private String fileName;
+
+ /**
+ * Returns the name of the file rpmlint gives warning for.
+ *
+ * @return The file name.
+ */
+ public String getFileName() {
+ return fileName;
+ }
+
+ /**
+ * Sets the name of the file rpmlint gives warning for.
+ * @param file The File name.
+ */
+ public void setFileName(String file) {
+ this.fileName = file;
+ }
+
+ /**
+ * Returns the line number where the warning appears if rpmlint gives it.
+ * @return The line number.
+ */
+ public int getLineNbr() {
+ return lineNbr;
+ }
+
+ /**
+ * Sets the line number where the warning appears if rpmlint gives it.
+ * @param lineNbr The line number.
+ */
+ public void setLineNbr(int lineNbr) {
+ this.lineNbr = lineNbr;
+ }
+
+ /**
+ * The id of the warning.
+ * @return The id.
+ */
+ public String getId() {
+ return id;
+ }
+
+ /**
+ * Sets the id of the warning.
+ * @param id The id of the warning.
+ */
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ /**
+ * Returns the message as rpmlint gives it.
+ * @return The message.
+ */
+ public String getMessage() {
+ return message;
+ }
+
+ /**
+ * Sets the message as rpmlint gives it.
+ * @param message The raw message.
+ */
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ /**
+ * Returns the referred content - section, tag, etc.
+ * @return The referred content.
+ */
+ public String getRefferedContent() {
+ return refferedContent;
+ }
+
+ /**
+ * Sets the referred content.
+ * @param refferedContent The referred content.
+ */
+ public void setRefferedContent(String refferedContent) {
+ for (int i = 0; i < SECTIONS.length; i++) {
+ if (refferedContent.startsWith(SECTIONS[i])) {
+ this.refferedContent = refferedContent.trim();
+ if (this.refferedContent.equals("")) {//$NON-NLS-1$
+ this.refferedContent = SECTIONS[i];
+ }
+ i = SECTIONS.length;
+ } else {
+ this.refferedContent = refferedContent;
+ }
+ }
+ }
+
+ /**
+ * Returns the severity of the rpmlint item.
+ *
+ * @return The severity.
+ */
+ public int getSeverity() {
+ return severity;
+ }
+
+ /**
+ * Returns the severity of the rpmlint item.
+ *
+ * @param severity The severity of the rpmlint item.
+ */
+ public void setSeverity(String severity) {
+ severity = severity.replaceAll(":", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$
+ switch (severity.charAt(0)) {
+ case 'I':
+ this.severity = 0;
+ break;
+ case 'W':
+ this.severity = 1;
+ break;
+ case 'E':
+ this.severity = 2;
+ break;
+ default:
+ this.severity = 0;
+ break;
+ }
+ }
+
+ /**
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append("line number: "); //$NON-NLS-1$
+ stringBuilder.append(this.lineNbr);
+ stringBuilder.append("\nfile name: "); //$NON-NLS-1$
+ stringBuilder.append(this.fileName);
+ stringBuilder.append("\nseverity: "); //$NON-NLS-1$
+ stringBuilder.append(this.severity);
+ stringBuilder.append("\nId: "); //$NON-NLS-1$
+ stringBuilder.append(this.id);
+ stringBuilder.append("\nrefered content: "); //$NON-NLS-1$
+ stringBuilder.append(this.refferedContent);
+ stringBuilder.append("\nmessage: "); //$NON-NLS-1$
+ stringBuilder.append(this.getMessage());
+ stringBuilder.append("\n"); //$NON-NLS-1$
+ return stringBuilder.toString();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/preferences/PreferenceConstants.java b/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/preferences/PreferenceConstants.java
index 4b87273931..ca9a5495f4 100644
--- a/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/preferences/PreferenceConstants.java
+++ b/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/preferences/PreferenceConstants.java
@@ -15,17 +15,17 @@ package org.eclipse.linuxtools.internal.rpm.rpmlint.preferences;
* Constant definitions for rpmlint plug-in preferences
*/
public class PreferenceConstants {
- /** Path to rpmlint executable. */
- public static final String P_RPMLINT_PATH = "RpmlintPath"; //$NON-NLS-1$
- /** Preference to show warnings about using tabs. */
- public static final String P_RPMLINT_TABS = "RpmlintTab"; //$NON-NLS-1$
- /** Preference to show warnings about using spaces. */
- public static final String P_RPMLINT_SPACES = "RpmlintSpaces"; //$NON-NLS-1$
- /** Preference to show warnings about using tabs or spaces. */
- public static final String P_RPMLINT_TABS_AND_SPACES = P_RPMLINT_SPACES;
-
- /**
- * Default path to rpmlint executable (/usr/bin/rpmlint).
- */
- public static final String DP_RPMLINT_PATH = "/usr/bin/rpmlint"; //$NON-NLS-1$
+ /** Path to rpmlint executable. */
+ public static final String P_RPMLINT_PATH = "RpmlintPath"; //$NON-NLS-1$
+ /** Preference to show warnings about using tabs. */
+ public static final String P_RPMLINT_TABS = "RpmlintTab"; //$NON-NLS-1$
+ /** Preference to show warnings about using spaces. */
+ public static final String P_RPMLINT_SPACES = "RpmlintSpaces"; //$NON-NLS-1$
+ /** Preference to show warnings about using tabs or spaces. */
+ public static final String P_RPMLINT_TABS_AND_SPACES = P_RPMLINT_SPACES;
+
+ /**
+ * Default path to rpmlint executable (/usr/bin/rpmlint).
+ */
+ public static final String DP_RPMLINT_PATH = "/usr/bin/rpmlint"; //$NON-NLS-1$
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/MacroInChangelog.java b/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/MacroInChangelog.java
index 6f7cc3809c..afe333ea87 100644
--- a/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/MacroInChangelog.java
+++ b/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/MacroInChangelog.java
@@ -17,29 +17,29 @@ package org.eclipse.linuxtools.internal.rpm.rpmlint.resolutions;
*/
public class MacroInChangelog extends AReplaceTextResolution {
- /**
- * The string ID of the rpmlint warning.
- */
- public static final String ID = "macro-in-%changelog"; //$NON-NLS-1$
+ /**
+ * The string ID of the rpmlint warning.
+ */
+ public static final String ID = "macro-in-%changelog"; //$NON-NLS-1$
- @Override
- public String getOriginalString() {
- return "%"; //$NON-NLS-1$
- }
+ @Override
+ public String getOriginalString() {
+ return "%"; //$NON-NLS-1$
+ }
- @Override
- public String getReplaceString() {
- return "%%"; //$NON-NLS-1$
- }
+ @Override
+ public String getReplaceString() {
+ return "%%"; //$NON-NLS-1$
+ }
- @Override
- public String getDescription() {
- return Messages.MacroInChangelog_0
- + Messages.MacroInChangelog_1;
- }
+ @Override
+ public String getDescription() {
+ return Messages.MacroInChangelog_0
+ + Messages.MacroInChangelog_1;
+ }
- @Override
- public String getLabel() {
- return ID;
- }
+ @Override
+ public String getLabel() {
+ return ID;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/RpmBuildrootUsage.java b/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/RpmBuildrootUsage.java
index 0ddc86d9eb..88c3d37152 100644
--- a/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/RpmBuildrootUsage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/RpmBuildrootUsage.java
@@ -16,18 +16,18 @@ package org.eclipse.linuxtools.internal.rpm.rpmlint.resolutions;
*
*/
public class RpmBuildrootUsage extends ARemoveLineResolution{
- /**
- * The rpmlint ID of the warning.
- */
- public static final String ID = "rpm-buildroot-usage"; //$NON-NLS-1$
+ /**
+ * The rpmlint ID of the warning.
+ */
+ public static final String ID = "rpm-buildroot-usage"; //$NON-NLS-1$
- @Override
- public String getDescription() {
- return Messages.RpmBuildrootUsage_0;
- }
+ @Override
+ public String getDescription() {
+ return Messages.RpmBuildrootUsage_0;
+ }
- @Override
- public String getLabel() {
- return ID;
- }
+ @Override
+ public String getLabel() {
+ return ID;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/RpmlintMarkerResolutionGenerator.java b/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/RpmlintMarkerResolutionGenerator.java
index 13dca3efb3..9221b9d5f7 100644
--- a/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/RpmlintMarkerResolutionGenerator.java
+++ b/rpm/org.eclipse.linuxtools.rpm.rpmlint/src/org/eclipse/linuxtools/internal/rpm/rpmlint/resolutions/RpmlintMarkerResolutionGenerator.java
@@ -24,77 +24,77 @@ import org.eclipse.ui.IMarkerResolutionGenerator2;
*/
public class RpmlintMarkerResolutionGenerator implements IMarkerResolutionGenerator2 {
- /**
- * Rpmlint error id atribute name.
- */
- public static final String RPMLINT_ERROR_ID = "rpmlintErrorId"; //$NON-NLS-1$
+ /**
+ * Rpmlint error id atribute name.
+ */
+ public static final String RPMLINT_ERROR_ID = "rpmlintErrorId"; //$NON-NLS-1$
- /**
- * Rpmlint refered text
- */
- public static final String RPMLINT_REFFERED_CONTENT = "rpmlintrefferedContent"; //$NON-NLS-1$
+ /**
+ * Rpmlint refered text
+ */
+ public static final String RPMLINT_REFFERED_CONTENT = "rpmlintrefferedContent"; //$NON-NLS-1$
- @Override
- public boolean hasResolutions(IMarker marker) {
- String rpmlintErrorId = getRpmlintErrorId(marker);
- if (rpmlintErrorId.equals(SetupNotQuiet.ID)) {
+ @Override
+ public boolean hasResolutions(IMarker marker) {
+ String rpmlintErrorId = getRpmlintErrorId(marker);
+ if (rpmlintErrorId.equals(SetupNotQuiet.ID)) {
return true;
- } else if (rpmlintErrorId.equals(PatchNotApplied.ID)) {
- return true;
- } else if (rpmlintErrorId.equals(NoBuildSection.ID)){
- return true;
- } else if (rpmlintErrorId.equals(MacroInChangelog.ID)){
- return true;
- } else if (rpmlintErrorId.equals(RpmBuildrootUsage.ID)){
- return true;
- } else if (rpmlintErrorId.equals(HardcodedPrefixTag.ID)){
- return true;
- } else if (rpmlintErrorId.equals(HardcodedPackagerTag.ID)){
- return true;
- } else if (rpmlintErrorId.equals(NoPrepSection.ID)){
- return true;
- } else if (rpmlintErrorId.equals(NoInstallSection.ID)){
- return true;
- }
+ } else if (rpmlintErrorId.equals(PatchNotApplied.ID)) {
+ return true;
+ } else if (rpmlintErrorId.equals(NoBuildSection.ID)){
+ return true;
+ } else if (rpmlintErrorId.equals(MacroInChangelog.ID)){
+ return true;
+ } else if (rpmlintErrorId.equals(RpmBuildrootUsage.ID)){
+ return true;
+ } else if (rpmlintErrorId.equals(HardcodedPrefixTag.ID)){
+ return true;
+ } else if (rpmlintErrorId.equals(HardcodedPackagerTag.ID)){
+ return true;
+ } else if (rpmlintErrorId.equals(NoPrepSection.ID)){
+ return true;
+ } else if (rpmlintErrorId.equals(NoInstallSection.ID)){
+ return true;
+ }
- return false;
- }
+ return false;
+ }
- @Override
- public IMarkerResolution[] getResolutions(IMarker marker) {
- List<IMarkerResolution> resolutions = new ArrayList<>();
- String rpmlintErrorId = getRpmlintErrorId(marker);
- if (rpmlintErrorId.equals(SetupNotQuiet.ID)) {
- resolutions.add(new SetupNotQuiet());
- } else if (rpmlintErrorId.equals(PatchNotApplied.ID)) {
- resolutions.add(new PatchNotApplied());
- } else if (rpmlintErrorId.equals(NoBuildSection.ID)){
- resolutions.add(new NoBuildSection());
- } else if (rpmlintErrorId.equals(MacroInChangelog.ID)){
- resolutions.add(new MacroInChangelog());
- } else if (rpmlintErrorId.equals(RpmBuildrootUsage.ID)){
- resolutions.add(new RpmBuildrootUsage());
- } else if (rpmlintErrorId.equals(HardcodedPrefixTag.ID)){
- resolutions.add(new HardcodedPrefixTag());
- } else if (rpmlintErrorId.equals(HardcodedPackagerTag.ID)){
- resolutions.add(new HardcodedPackagerTag());
- } else if (rpmlintErrorId.equals(NoPrepSection.ID)){
- resolutions.add(new NoPrepSection());
- } else if (rpmlintErrorId.equals(NoInstallSection.ID)){
- resolutions.add(new NoInstallSection());
- }
+ @Override
+ public IMarkerResolution[] getResolutions(IMarker marker) {
+ List<IMarkerResolution> resolutions = new ArrayList<>();
+ String rpmlintErrorId = getRpmlintErrorId(marker);
+ if (rpmlintErrorId.equals(SetupNotQuiet.ID)) {
+ resolutions.add(new SetupNotQuiet());
+ } else if (rpmlintErrorId.equals(PatchNotApplied.ID)) {
+ resolutions.add(new PatchNotApplied());
+ } else if (rpmlintErrorId.equals(NoBuildSection.ID)){
+ resolutions.add(new NoBuildSection());
+ } else if (rpmlintErrorId.equals(MacroInChangelog.ID)){
+ resolutions.add(new MacroInChangelog());
+ } else if (rpmlintErrorId.equals(RpmBuildrootUsage.ID)){
+ resolutions.add(new RpmBuildrootUsage());
+ } else if (rpmlintErrorId.equals(HardcodedPrefixTag.ID)){
+ resolutions.add(new HardcodedPrefixTag());
+ } else if (rpmlintErrorId.equals(HardcodedPackagerTag.ID)){
+ resolutions.add(new HardcodedPackagerTag());
+ } else if (rpmlintErrorId.equals(NoPrepSection.ID)){
+ resolutions.add(new NoPrepSection());
+ } else if (rpmlintErrorId.equals(NoInstallSection.ID)){
+ resolutions.add(new NoInstallSection());
+ }
- return resolutions.toArray(new IMarkerResolution[resolutions.size()]);
- }
+ return resolutions.toArray(new IMarkerResolution[resolutions.size()]);
+ }
- /**
- * Return the rpmlint error id attribute for the specified marker.
- *
- * @param marker The marker to check.
- * @return The rpmlint error id or <code>""</code> if none.
- */
- private static String getRpmlintErrorId(IMarker marker) {
- return marker.getAttribute(RPMLINT_ERROR_ID, ""); //$NON-NLS-1$
- }
+ /**
+ * Return the rpmlint error id attribute for the specified marker.
+ *
+ * @param marker The marker to check.
+ * @return The rpmlint error id or <code>""</code> if none.
+ */
+ private static String getRpmlintErrorId(IMarker marker) {
+ return marker.getAttribute(RPMLINT_ERROR_ID, ""); //$NON-NLS-1$
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/build-helper.xml b/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/build-helper.xml
index e705342f36..2f10059bf5 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/build-helper.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/build-helper.xml
@@ -5,67 +5,67 @@
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-
+
Contributors:
Red Hat - initial API and implementation
-->
<project name="org.eclipse.linuxtools.rpm.ui.editor.doc" default="all">
- <description>
+ <description>
Generate Eclipse help content for the Linux Tools Specfile Editor user guide
</description>
- <property name="specfile.help.doc.url.base" value="http://wiki.eclipse.org" />
- <property name="imageFolder" value="images" />
+ <property name="specfile.help.doc.url.base" value="http://wiki.eclipse.org" />
+ <property name="imageFolder" value="images" />
- <path id="wikitext.tasks.classpath">
- <!-- Replace dir with the dir you have wikitext installed into.-->
- <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
- <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
- </fileset>
- </path>
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
+ <path id="wikitext.tasks.classpath">
+ <!-- Replace dir with the dir you have wikitext installed into.-->
+ <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
+ <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
+ </fileset>
+ </path>
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
- <target name="all" description="Generate Eclipse help content for the Linux Tools Specfile Editor user guide">
- <mediawiki-to-eclipse-help wikiBaseUrl="${specfile.help.doc.url.base}" title="Specfile Editor User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
+ <target name="all" description="Generate Eclipse help content for the Linux Tools Specfile Editor user guide">
+ <mediawiki-to-eclipse-help wikiBaseUrl="${specfile.help.doc.url.base}" title="Specfile Editor User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
- <path name="Linux_Tools_Project/SpecfileEditor/User_Guide" title="Specfile Editor User Guide" generateToc="false" />
- <stylesheet url="book.css" />
- <pageAppendum>
+ <path name="Linux_Tools_Project/SpecfileEditor/User_Guide" title="Specfile Editor User Guide" generateToc="false" />
+ <stylesheet url="book.css" />
+ <pageAppendum>
= Updating This Document =
-This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
+This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
http://wiki.eclipse.org/Linux_Tools_Project/SpecfileEditor/User_Guide .
- </pageAppendum>
- </mediawiki-to-eclipse-help>
- <antcall target="test" />
- </target>
+ </pageAppendum>
+ </mediawiki-to-eclipse-help>
+ <antcall target="test" />
+ </target>
- <target name="test" description="verify that all of the HTML files are well-formed XML">
- <echo level="info">
+ <target name="test" description="verify that all of the HTML files are well-formed XML">
+ <echo level="info">
Validating help content XML and HTML files: The Eclipse help system expects well-formed XML
-
+
If validation fails it is because either:
-
+
* the userguide source code is poorly formed, or
* the WikiText MediaWiki parser has a bug
-
+
Problems with userguide source are usually caused by improper use of HTML markup in the MediaWiki source,
or inadvertently starting a line with a space character (in MediaWiki this starts a preformatted block)
- </echo>
+ </echo>
- <!--
- Don't bother with DTD validation: we only care if the files are well-formed.
- We therefore provide an empty DTD
- -->
- <echo file="tmp/__empty.dtd" message="" />
- <xmlvalidate lenient="true">
- <fileset dir="Linux_Tools_Project">
- <include name="**/*.html" />
- </fileset>
- <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
- </xmlvalidate>
- <delete dir="tmp" />
- </target>
+ <!--
+ Don't bother with DTD validation: we only care if the files are well-formed.
+ We therefore provide an empty DTD
+ -->
+ <echo file="tmp/__empty.dtd" message="" />
+ <xmlvalidate lenient="true">
+ <fileset dir="Linux_Tools_Project">
+ <include name="**/*.html" />
+ </fileset>
+ <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
+ </xmlvalidate>
+ <delete dir="tmp" />
+ </target>
</project>
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/plugin.xml b/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/plugin.xml
index 1b2fdec490..2f6727353b 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/plugin.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/plugin.xml
@@ -5,7 +5,7 @@
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-
+
Contributors:
Red Hat - initial API and implementation
-->
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/toc-doc.xml b/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/toc-doc.xml
index aa41923797..2f36f98d17 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/toc-doc.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/toc-doc.xml
@@ -1,5 +1,5 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/SpecfileEditor/User_Guide/User-Guide.html" label="Specfile Editor User Guide">
-<link toc="toc.xml" />
+<link toc="toc.xml" />
<topic href="doc/notices.html" label="Legal"> </topic>
</toc>
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/toc.xml b/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/toc.xml
index 554864f341..6a61e4f9c8 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/toc.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.doc/toc.xml
@@ -1,46 +1,46 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/SpecfileEditor/User_Guide/User-Guide.html" label="Specfile Editor User Guide">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/User-Guide.html" label="Specfile Editor User Guide">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/User-Guide.html" label="Overview"></topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Installing.html" label="Installing"></topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html" label="General Usage">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Creating_a_New_RPM_project" label="Creating a New RPM project"></topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Creating_a_New_Specfile" label="Creating a New Specfile"></topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Building_RPMs" label="Building RPMs">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Toolbar" label="Toolbar"></topic>
- </topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#rpmlint" label="rpmlint">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Quick_Fixes" label="Quick Fixes"></topic>
- </topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Hyperlink_Detection" label="Hyperlink Detection">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Patches" label="Patches"></topic>
- </topic>
- </topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Import-src-rpm.html" label="Import src.rpm">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Import-src-rpm.html#Invoking_the_Eclipse_SRPM_Import_Feature" label="Invoking the Eclipse SRPM Import Feature"></topic>
- </topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html" label="Createrepo">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html#Creating_a_Repository" label="Creating a Repository"></topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html#Getting_Familiar_with_the_Editor" label="Getting Familiar with the Editor">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html#Repository_Page" label="Repository Page"></topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html#Metadata_Page" label="Metadata Page"></topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html#Repo_Editor" label="Repo Editor"></topic>
- </topic>
- </topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html" label="Configuring Specfile Editor Settings">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#Macro_Completion" label="Macro Completion"></topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#RPM_Completions" label="RPM Completions">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#Package_Information" label="Package Information"></topic>
- </topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#Rpmlint" label="Rpmlint"></topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#Task_Tags" label="Task Tags"></topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#Templates" label="Templates"></topic>
- </topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Createrepo-Execution.html" label="Configuring Createrepo Execution">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Createrepo-Execution.html#Repository_Specific_Configuration" label="Repository Specific Configuration">
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Createrepo-Execution.html#Deltas" label="Deltas"></topic>
- </topic>
- </topic>
- <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
- </topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/User-Guide.html" label="Specfile Editor User Guide">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/User-Guide.html" label="Overview"></topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Installing.html" label="Installing"></topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html" label="General Usage">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Creating_a_New_RPM_project" label="Creating a New RPM project"></topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Creating_a_New_Specfile" label="Creating a New Specfile"></topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Building_RPMs" label="Building RPMs">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Toolbar" label="Toolbar"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#rpmlint" label="rpmlint">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Quick_Fixes" label="Quick Fixes"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Hyperlink_Detection" label="Hyperlink Detection">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/General-Usage.html#Patches" label="Patches"></topic>
+ </topic>
+ </topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Import-src-rpm.html" label="Import src.rpm">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Import-src-rpm.html#Invoking_the_Eclipse_SRPM_Import_Feature" label="Invoking the Eclipse SRPM Import Feature"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html" label="Createrepo">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html#Creating_a_Repository" label="Creating a Repository"></topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html#Getting_Familiar_with_the_Editor" label="Getting Familiar with the Editor">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html#Repository_Page" label="Repository Page"></topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html#Metadata_Page" label="Metadata Page"></topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Createrepo.html#Repo_Editor" label="Repo Editor"></topic>
+ </topic>
+ </topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html" label="Configuring Specfile Editor Settings">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#Macro_Completion" label="Macro Completion"></topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#RPM_Completions" label="RPM Completions">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#Package_Information" label="Package Information"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#Rpmlint" label="Rpmlint"></topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#Task_Tags" label="Task Tags"></topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Specfile-Editor-Settings.html#Templates" label="Templates"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Createrepo-Execution.html" label="Configuring Createrepo Execution">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Createrepo-Execution.html#Repository_Specific_Configuration" label="Repository Specific Configuration">
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Configuring-Createrepo-Execution.html#Deltas" label="Deltas"></topic>
+ </topic>
+ </topic>
+ <topic href="Linux_Tools_Project/SpecfileEditor/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
+ </topic>
</toc> \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/pom.xml b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/pom.xml
index 39bfb28a87..efd986058d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/pom.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/pom.xml
@@ -30,7 +30,7 @@
<artifactId>tycho-surefire-plugin</artifactId>
<version>${tycho-version}</version>
<configuration>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.platform.ide</product>
</configuration>
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/ActionsAllTests.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/ActionsAllTests.java
index 41d1926f2f..ec528c63fb 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/ActionsAllTests.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/ActionsAllTests.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -15,6 +15,6 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ SpecfileChangelogFormatterTest.class,
- SpecfileChangelogParserTest.class })
+ SpecfileChangelogParserTest.class })
public class ActionsAllTests {
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/SpecfileChangelogFormatterTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/SpecfileChangelogFormatterTest.java
index d6cfc3228d..4599d1cbbe 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/SpecfileChangelogFormatterTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/SpecfileChangelogFormatterTest.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -28,42 +28,42 @@ import org.junit.Test;
public class SpecfileChangelogFormatterTest extends FileTestCase {
- private static final String USER_MAIL = "someone@redhat.com";
- private static final String USER_NAME = "Alexander Kurtakov";
- private SpecfileChangelogFormatter formatter;
- private IEditorPart editor;
- public final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("EEE MMM d yyyy");
+ private static final String USER_MAIL = "someone@redhat.com";
+ private static final String USER_NAME = "Alexander Kurtakov";
+ private SpecfileChangelogFormatter formatter;
+ private IEditorPart editor;
+ public final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("EEE MMM d yyyy");
- @Override
- @Before
- public void setUp() throws CoreException {
- super.setUp();
- newFile("%changelog");
- editor = IDE.openEditor(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage(), testFile,
- "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
- formatter = new SpecfileChangelogFormatter();
- }
+ @Override
+ @Before
+ public void setUp() throws CoreException {
+ super.setUp();
+ newFile("%changelog");
+ editor = IDE.openEditor(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage(), testFile,
+ "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
+ formatter = new SpecfileChangelogFormatter();
+ }
- @Override
- @After
- public void tearDown () {
- closeEditor(editor);
- }
+ @Override
+ @After
+ public void tearDown () {
+ closeEditor(editor);
+ }
- @Test
- public void testFormatDateLine() {
- String expectedLine = MessageFormat
- .format("* {0} {1} <{2}> {3}{4}-{5}", SIMPLE_DATE_FORMAT.format(new Date()), //$NON-NLS-1$
- USER_NAME, USER_MAIL, "", "0", "0");
- assertEquals(expectedLine,
- formatter.formatDateLine(USER_NAME, USER_MAIL));
- }
+ @Test
+ public void testFormatDateLine() {
+ String expectedLine = MessageFormat
+ .format("* {0} {1} <{2}> {3}{4}-{5}", SIMPLE_DATE_FORMAT.format(new Date()), //$NON-NLS-1$
+ USER_NAME, USER_MAIL, "", "0", "0");
+ assertEquals(expectedLine,
+ formatter.formatDateLine(USER_NAME, USER_MAIL));
+ }
- @Test
- public void testMergeChangelogStringStringStringIEditorPartStringString() {
- // TODO find how to test this
- formatter.mergeChangelog("proba", "", "", editor, "", "");
- }
+ @Test
+ public void testMergeChangelogStringStringStringIEditorPartStringString() {
+ // TODO find how to test this
+ formatter.mergeChangelog("proba", "", "", editor, "", "");
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/SpecfileChangelogParserTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/SpecfileChangelogParserTest.java
index 83c00672af..5c23916485 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/SpecfileChangelogParserTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/tests/SpecfileChangelogParserTest.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -19,21 +19,21 @@ import org.junit.Test;
public class SpecfileChangelogParserTest {
- private static SpecfileChangelogParser parser;
+ private static SpecfileChangelogParser parser;
- @BeforeClass
- public static void setUp() {
- parser = new SpecfileChangelogParser();
- }
+ @BeforeClass
+ public static void setUp() {
+ parser = new SpecfileChangelogParser();
+ }
- @Test
- public void testParseCurrentFunctionIEditorPart() throws CoreException {
- assertEquals("", parser.parseCurrentFunction(null));
- }
+ @Test
+ public void testParseCurrentFunctionIEditorPart() throws CoreException {
+ assertEquals("", parser.parseCurrentFunction(null));
+ }
- @Test
- public void testParseCurrentFunctionIEditorInputInt() throws CoreException {
- assertEquals("", parser.parseCurrentFunction(null, 0));
- }
+ @Test
+ public void testParseCurrentFunctionIEditorInputInt() throws CoreException {
+ assertEquals("", parser.parseCurrentFunction(null, 0));
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/HyperlinkAllTests.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/HyperlinkAllTests.java
index 504d8c0289..6153abd8a3 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/HyperlinkAllTests.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/HyperlinkAllTests.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -15,9 +15,9 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ MailHyperlinkDetectorTest.class,
- SourcesFileHyperlinkDetectorTest.class,
- SpecfileElementHyperlinkDetectorTest.class,
- URLHyperlinkWithMacroDetectorTest.class,
- SourcesFileCreateHyperlinkTest.class })
+ SourcesFileHyperlinkDetectorTest.class,
+ SpecfileElementHyperlinkDetectorTest.class,
+ URLHyperlinkWithMacroDetectorTest.class,
+ SourcesFileCreateHyperlinkTest.class })
public class HyperlinkAllTests {
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/MailHyperlinkDetectorTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/MailHyperlinkDetectorTest.java
index 246612fa01..5570d0a43d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/MailHyperlinkDetectorTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/MailHyperlinkDetectorTest.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -29,42 +29,42 @@ import org.junit.Test;
public class MailHyperlinkDetectorTest extends FileTestCase {
- @Test
- public void testDetectHyperlinks() throws PartInitException {
- String testText = "Version: 0.0\n" + "Release: 0\n" + "%changelog\n"
- + "* Fri Feb 27 2009 Test <someone@smth.com> 3.3.2.4-6\n-\n"
- + "* Fri Feb 27 2009 Test someone@smth.com 3.3.2.4-6\n-\n";
- newFile(testText);
+ @Test
+ public void testDetectHyperlinks() throws PartInitException {
+ String testText = "Version: 0.0\n" + "Release: 0\n" + "%changelog\n"
+ + "* Fri Feb 27 2009 Test <someone@smth.com> 3.3.2.4-6\n-\n"
+ + "* Fri Feb 27 2009 Test someone@smth.com 3.3.2.4-6\n-\n";
+ newFile(testText);
- IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage(), testFile,
- "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
+ IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage(), testFile,
+ "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
- editor = (SpecfileEditor) openEditor;
- editor.doRevertToSaved();
- MailHyperlinkDetector elementDetector = new MailHyperlinkDetector();
- elementDetector.setEditor(editor);
- // test mail
- IRegion region = new Region(38, 0);
- IHyperlink[] returned = elementDetector.detectHyperlinks(
- editor.getSpecfileSourceViewer(), region, false);
- assertEquals(1, returned.length);
- assertTrue(returned[0] instanceof MailHyperlink);
+ editor = (SpecfileEditor) openEditor;
+ editor.doRevertToSaved();
+ MailHyperlinkDetector elementDetector = new MailHyperlinkDetector();
+ elementDetector.setEditor(editor);
+ // test mail
+ IRegion region = new Region(38, 0);
+ IHyperlink[] returned = elementDetector.detectHyperlinks(
+ editor.getSpecfileSourceViewer(), region, false);
+ assertEquals(1, returned.length);
+ assertTrue(returned[0] instanceof MailHyperlink);
- region = new Region(124, 0);
- returned = elementDetector.detectHyperlinks(
- editor.getSpecfileSourceViewer(), region, false);
- assertEquals(1, returned.length);
- assertTrue(returned[0] instanceof MailHyperlink);
- }
+ region = new Region(124, 0);
+ returned = elementDetector.detectHyperlinks(
+ editor.getSpecfileSourceViewer(), region, false);
+ assertEquals(1, returned.length);
+ assertTrue(returned[0] instanceof MailHyperlink);
+ }
- @Test
- public void testDetectHyperlinksNoRegionAndTextViewer() {
- MailHyperlinkDetector elementDetector = new MailHyperlinkDetector();
- elementDetector.setEditor(editor);
- IHyperlink[] returned = elementDetector.detectHyperlinks(null, null,
- false);
- assertNull(returned);
- }
+ @Test
+ public void testDetectHyperlinksNoRegionAndTextViewer() {
+ MailHyperlinkDetector elementDetector = new MailHyperlinkDetector();
+ elementDetector.setEditor(editor);
+ IHyperlink[] returned = elementDetector.detectHyperlinks(null, null,
+ false);
+ assertNull(returned);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SourcesFileCreateHyperlinkTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SourcesFileCreateHyperlinkTest.java
index a60186f1fa..7aaac9dd41 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SourcesFileCreateHyperlinkTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SourcesFileCreateHyperlinkTest.java
@@ -19,18 +19,18 @@ import org.junit.Before;
import org.junit.Test;
public class SourcesFileCreateHyperlinkTest extends FileTestCase {
- @Before
- public void init() throws CoreException {
- super.setUp();
- String testText = "Patch0: test\n";
- newFile(testText);
- }
+ @Before
+ public void init() throws CoreException {
+ super.setUp();
+ String testText = "Patch0: test\n";
+ newFile(testText);
+ }
- @Test
- public void testCreatePatch() {
- SourcesFileCreateHyperlink patchTest = new SourcesFileCreateHyperlink(testFile, specfile.getPatch(0).getFileName(), null);
- assertNotNull(patchTest);
- patchTest.open();
- assertNotNull(testFile.getProject().findMember("test"));
- }
+ @Test
+ public void testCreatePatch() {
+ SourcesFileCreateHyperlink patchTest = new SourcesFileCreateHyperlink(testFile, specfile.getPatch(0).getFileName(), null);
+ assertNotNull(patchTest);
+ patchTest.open();
+ assertNotNull(testFile.getProject().findMember("test"));
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SourcesFileHyperlinkDetectorTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SourcesFileHyperlinkDetectorTest.java
index 50032796e2..217ae6b16d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SourcesFileHyperlinkDetectorTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SourcesFileHyperlinkDetectorTest.java
@@ -28,95 +28,95 @@ import org.junit.Before;
import org.junit.Test;
public class SourcesFileHyperlinkDetectorTest extends FileTestCase {
- @Before
- public void init() throws CoreException {
- super.setUp();
- String testText = "Source0: test.zip\n"
- + "Patch0: test.patch\n"
- + "Source1: www.example.com/test.zip\n"
- + "Source2: http://www.example.com/test.zip\n";
- newFile(testText);
- }
+ @Before
+ public void init() throws CoreException {
+ super.setUp();
+ String testText = "Source0: test.zip\n"
+ + "Patch0: test.patch\n"
+ + "Source1: www.example.com/test.zip\n"
+ + "Source2: http://www.example.com/test.zip\n";
+ newFile(testText);
+ }
- @Test
- public void testDetectHyperlinks() throws PartInitException {
- IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage(), testFile,
- "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
+ @Test
+ public void testDetectHyperlinks() throws PartInitException {
+ IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage(), testFile,
+ "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
- editor = (SpecfileEditor) openEditor;
- editor.doRevertToSaved();
- SourcesFileHyperlinkDetector elementDetector = new SourcesFileHyperlinkDetector();
- elementDetector.setEditor(editor);
- // test source0 element
- IRegion region = new Region(10, 0);
- IHyperlink[] returned = elementDetector.detectHyperlinks(
- editor.getSpecfileSourceViewer(), region, false);
- // because test.zip does not exist, and is not a valid url
- // it should not have hyperlinks
- assertNull(returned);
- }
+ editor = (SpecfileEditor) openEditor;
+ editor.doRevertToSaved();
+ SourcesFileHyperlinkDetector elementDetector = new SourcesFileHyperlinkDetector();
+ elementDetector.setEditor(editor);
+ // test source0 element
+ IRegion region = new Region(10, 0);
+ IHyperlink[] returned = elementDetector.detectHyperlinks(
+ editor.getSpecfileSourceViewer(), region, false);
+ // because test.zip does not exist, and is not a valid url
+ // it should not have hyperlinks
+ assertNull(returned);
+ }
- @Test
- public void testDetectHyperlinksInvalidURL() throws PartInitException {
- IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage(), testFile,
- "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
+ @Test
+ public void testDetectHyperlinksInvalidURL() throws PartInitException {
+ IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage(), testFile,
+ "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
- editor = (SpecfileEditor) openEditor;
- editor.doRevertToSaved();
- SourcesFileHyperlinkDetector elementDetector = new SourcesFileHyperlinkDetector();
- elementDetector.setEditor(editor);
- // test source1 element
- IRegion region = new Region(47, 0);
- IHyperlink[] returned = elementDetector.detectHyperlinks(
- editor.getSpecfileSourceViewer(), region, false);
- // because the protocol is missing, it should not show any hyperlinks
- assertNull(returned);
- }
+ editor = (SpecfileEditor) openEditor;
+ editor.doRevertToSaved();
+ SourcesFileHyperlinkDetector elementDetector = new SourcesFileHyperlinkDetector();
+ elementDetector.setEditor(editor);
+ // test source1 element
+ IRegion region = new Region(47, 0);
+ IHyperlink[] returned = elementDetector.detectHyperlinks(
+ editor.getSpecfileSourceViewer(), region, false);
+ // because the protocol is missing, it should not show any hyperlinks
+ assertNull(returned);
+ }
- @Test
- public void testDetectHyperlinksValidURL() throws PartInitException {
- IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage(), testFile,
- "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
+ @Test
+ public void testDetectHyperlinksValidURL() throws PartInitException {
+ IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage(), testFile,
+ "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
- editor = (SpecfileEditor) openEditor;
- editor.doRevertToSaved();
- SourcesFileHyperlinkDetector elementDetector = new SourcesFileHyperlinkDetector();
- elementDetector.setEditor(editor);
- // test source2 element
- IRegion region = new Region(82, 0);
- IHyperlink[] returned = elementDetector.detectHyperlinks(
- editor.getSpecfileSourceViewer(), region, false);
- // 1 = Download from URL (Open in browser should not show up because URLHyperlinkWithMacroDetector detects that)
- assertEquals(1, returned.length);
- }
+ editor = (SpecfileEditor) openEditor;
+ editor.doRevertToSaved();
+ SourcesFileHyperlinkDetector elementDetector = new SourcesFileHyperlinkDetector();
+ elementDetector.setEditor(editor);
+ // test source2 element
+ IRegion region = new Region(82, 0);
+ IHyperlink[] returned = elementDetector.detectHyperlinks(
+ editor.getSpecfileSourceViewer(), region, false);
+ // 1 = Download from URL (Open in browser should not show up because URLHyperlinkWithMacroDetector detects that)
+ assertEquals(1, returned.length);
+ }
- @Test
- public void testDetectNoPatchInProject() throws PartInitException {
- IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage(), testFile,
- "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
+ @Test
+ public void testDetectNoPatchInProject() throws PartInitException {
+ IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage(), testFile,
+ "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
- editor = (SpecfileEditor) openEditor;
- editor.doRevertToSaved();
- SourcesFileHyperlinkDetector elementDetector = new SourcesFileHyperlinkDetector();
- elementDetector.setEditor(editor);
- // test patch element
- IRegion region = new Region(27, 0);
- IHyperlink[] returned = elementDetector.detectHyperlinks(
- editor.getSpecfileSourceViewer(), region, false);
- // 1 = Create test.patch because test.patch doesn't exist in current project
- assertEquals(1, returned.length);
- }
+ editor = (SpecfileEditor) openEditor;
+ editor.doRevertToSaved();
+ SourcesFileHyperlinkDetector elementDetector = new SourcesFileHyperlinkDetector();
+ elementDetector.setEditor(editor);
+ // test patch element
+ IRegion region = new Region(27, 0);
+ IHyperlink[] returned = elementDetector.detectHyperlinks(
+ editor.getSpecfileSourceViewer(), region, false);
+ // 1 = Create test.patch because test.patch doesn't exist in current project
+ assertEquals(1, returned.length);
+ }
- @Test
- public void testDetectHyperlinksNoRegionAndTextViewer() {
- SourcesFileHyperlinkDetector elementDetector = new SourcesFileHyperlinkDetector();
- elementDetector.setEditor(editor);
- IHyperlink[] returned = elementDetector.detectHyperlinks(null, null,
- false);
- assertNull(returned);
- }
+ @Test
+ public void testDetectHyperlinksNoRegionAndTextViewer() {
+ SourcesFileHyperlinkDetector elementDetector = new SourcesFileHyperlinkDetector();
+ elementDetector.setEditor(editor);
+ IHyperlink[] returned = elementDetector.detectHyperlinks(null, null,
+ false);
+ assertNull(returned);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SpecfileElementHyperlinkDetectorTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SpecfileElementHyperlinkDetectorTest.java
index 3adcadd940..44fca4737d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SpecfileElementHyperlinkDetectorTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/SpecfileElementHyperlinkDetectorTest.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -31,57 +31,57 @@ import org.junit.Test;
public class SpecfileElementHyperlinkDetectorTest extends FileTestCase {
- @Test
- public void testDetectHyperlinks() throws PartInitException {
- String testText = "%define smth other\nSource0: test.zip\nPatch0: first.patch\n"
- + "%build\n %{SOURCE0}\n%patch0\n%{smth}\n";
- newFile(testText);
- SpecfileElementHyperlinkDetector elementDetector = new SpecfileElementHyperlinkDetector();
- elementDetector.setSpecfile(specfile);
+ @Test
+ public void testDetectHyperlinks() throws PartInitException {
+ String testText = "%define smth other\nSource0: test.zip\nPatch0: first.patch\n"
+ + "%build\n %{SOURCE0}\n%patch0\n%{smth}\n";
+ newFile(testText);
+ SpecfileElementHyperlinkDetector elementDetector = new SpecfileElementHyperlinkDetector();
+ elementDetector.setSpecfile(specfile);
- IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage(), testFile,
- "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
+ IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage(), testFile,
+ "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
- editor = (SpecfileEditor) openEditor;
- editor.doRevertToSaved();
- // test source element
- IRegion region = new Region(74, 0);
- IHyperlink[] returned = elementDetector.detectHyperlinks(
- editor.getSpecfileSourceViewer(), region, false);
- SpecfileElementHyperlink element = (SpecfileElementHyperlink) returned[0];
- assertTrue(element.getSource() instanceof SpecfileSource);
- SpecfileSource source = (SpecfileSource) element.getSource();
- assertEquals(source.getSourceType(), SpecfileSource.SourceType.SOURCE);
- assertEquals(source.getFileName(), "test.zip");
+ editor = (SpecfileEditor) openEditor;
+ editor.doRevertToSaved();
+ // test source element
+ IRegion region = new Region(74, 0);
+ IHyperlink[] returned = elementDetector.detectHyperlinks(
+ editor.getSpecfileSourceViewer(), region, false);
+ SpecfileElementHyperlink element = (SpecfileElementHyperlink) returned[0];
+ assertTrue(element.getSource() instanceof SpecfileSource);
+ SpecfileSource source = (SpecfileSource) element.getSource();
+ assertEquals(source.getSourceType(), SpecfileSource.SourceType.SOURCE);
+ assertEquals(source.getFileName(), "test.zip");
- // test patch element
- region = new Region(83, 0);
- returned = elementDetector.detectHyperlinks(
- editor.getSpecfileSourceViewer(), region, false);
- element = (SpecfileElementHyperlink) returned[0];
- assertTrue(element.getSource() instanceof SpecfileSource);
- source = (SpecfileSource) element.getSource();
- assertEquals(source.getSourceType(), SpecfileSource.SourceType.PATCH);
- assertEquals(source.getFileName(), "first.patch");
+ // test patch element
+ region = new Region(83, 0);
+ returned = elementDetector.detectHyperlinks(
+ editor.getSpecfileSourceViewer(), region, false);
+ element = (SpecfileElementHyperlink) returned[0];
+ assertTrue(element.getSource() instanceof SpecfileSource);
+ source = (SpecfileSource) element.getSource();
+ assertEquals(source.getSourceType(), SpecfileSource.SourceType.PATCH);
+ assertEquals(source.getFileName(), "first.patch");
- // test define
- region = new Region(89, 0);
- returned = elementDetector.detectHyperlinks(
- editor.getSpecfileSourceViewer(), region, false);
- element = (SpecfileElementHyperlink) returned[0];
- assertTrue(element.getSource() instanceof SpecfileDefine);
- SpecfileDefine define = (SpecfileDefine) element.getSource();
- assertEquals(define.getName(), "smth");
- assertEquals(define.getStringValue(), "other");
- }
+ // test define
+ region = new Region(89, 0);
+ returned = elementDetector.detectHyperlinks(
+ editor.getSpecfileSourceViewer(), region, false);
+ element = (SpecfileElementHyperlink) returned[0];
+ assertTrue(element.getSource() instanceof SpecfileDefine);
+ SpecfileDefine define = (SpecfileDefine) element.getSource();
+ assertEquals(define.getName(), "smth");
+ assertEquals(define.getStringValue(), "other");
+ }
- @Test
- public void testDetectHyperlinksNoRegionAndTextViewer() {
- SpecfileElementHyperlinkDetector elementDetector = new SpecfileElementHyperlinkDetector();
- elementDetector.setSpecfile(specfile);
- IHyperlink[] returned = elementDetector.detectHyperlinks(null, null,
- false);
- assertNull(returned);
- }
+ @Test
+ public void testDetectHyperlinksNoRegionAndTextViewer() {
+ SpecfileElementHyperlinkDetector elementDetector = new SpecfileElementHyperlinkDetector();
+ elementDetector.setSpecfile(specfile);
+ IHyperlink[] returned = elementDetector.detectHyperlinks(null, null,
+ false);
+ assertNull(returned);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/URLHyperlinkWithMacroDetectorTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/URLHyperlinkWithMacroDetectorTest.java
index c497b97755..7e5dc467db 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/URLHyperlinkWithMacroDetectorTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/tests/URLHyperlinkWithMacroDetectorTest.java
@@ -27,22 +27,22 @@ import org.junit.Test;
public class URLHyperlinkWithMacroDetectorTest extends FileTestCase {
- @Test
- public void testDetectHyperlinks() throws PartInitException {
- String testText = "Name: eclipse\nURL: http://www.%{name}.org/";
- newFile(testText);
- URLHyperlinkWithMacroDetector macroDetector = new URLHyperlinkWithMacroDetector();
- macroDetector.setSpecfile(specfile);
- IRegion region = new Region(20, 0);
- IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage(), testFile,
- "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
+ @Test
+ public void testDetectHyperlinks() throws PartInitException {
+ String testText = "Name: eclipse\nURL: http://www.%{name}.org/";
+ newFile(testText);
+ URLHyperlinkWithMacroDetector macroDetector = new URLHyperlinkWithMacroDetector();
+ macroDetector.setSpecfile(specfile);
+ IRegion region = new Region(20, 0);
+ IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage(), testFile,
+ "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
- editor = (SpecfileEditor) openEditor;
- editor.doRevertToSaved();
- IHyperlink[] returned = macroDetector.detectHyperlinks(
- editor.getSpecfileSourceViewer(), region, false);
- URLHyperlink url = (URLHyperlink) returned[0];
- assertEquals("http://www.eclipse.org/", url.getURLString());
- }
+ editor = (SpecfileEditor) openEditor;
+ editor.doRevertToSaved();
+ IHyperlink[] returned = macroDetector.detectHyperlinks(
+ editor.getSpecfileSourceViewer(), region, false);
+ URLHyperlink url = (URLHyperlink) returned[0];
+ assertEquals("http://www.eclipse.org/", url.getURLString());
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/ScannersAllTests.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/ScannersAllTests.java
index 72201ec764..5bd9ee55dd 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/ScannersAllTests.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/ScannersAllTests.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -15,6 +15,6 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ SpecfileChangelogScannerTest.class,
- SpecfilePackagesScannerTest.class, SpecfileScannerTest.class })
+ SpecfilePackagesScannerTest.class, SpecfileScannerTest.class })
public class ScannersAllTests {
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfileChangelogScannerTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfileChangelogScannerTest.java
index 5c6f9dcdfc..7b4920c1fd 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfileChangelogScannerTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfileChangelogScannerTest.java
@@ -26,68 +26,68 @@ import org.junit.Test;
public class SpecfileChangelogScannerTest extends AScannerTest {
- private IToken token;
+ private IToken token;
- private TextAttribute ta;
+ private TextAttribute ta;
- private static SpecfileChangelogScanner scanner;
-
- @BeforeClass
- public static void init() {
- scanner = new SpecfileChangelogScanner(new ColorManager());
- }
+ private static SpecfileChangelogScanner scanner;
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getContents()
- */
- @Override
- protected String getContents() {
- return "%changelog <toto@test.com> - 1.1-4";
- }
+ @BeforeClass
+ public static void init() {
+ scanner = new SpecfileChangelogScanner(new ColorManager());
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getScanner()
- */
- @Override
- protected RuleBasedScanner getScanner() {
- return scanner;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getContents()
+ */
+ @Override
+ protected String getContents() {
+ return "%changelog <toto@test.com> - 1.1-4";
+ }
- @Test
- public void testSection() {
- token = getNextToken();
- assertTrue(token instanceof Token);
- assertEquals(10, rulesBasedScanner.getTokenLength());
- assertEquals(0, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals(ta.getForeground().getRGB(),
- ISpecfileColorConstants.SECTIONS);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getScanner()
+ */
+ @Override
+ protected RuleBasedScanner getScanner() {
+ return scanner;
+ }
- @Test
- public void testMail() {
- token = getToken(3);
- assertTrue(token instanceof Token);
- assertEquals(15, rulesBasedScanner.getTokenLength());
- assertEquals(11, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals(ta.getForeground().getRGB(),
- ISpecfileColorConstants.AUTHOR_MAIL);
- }
+ @Test
+ public void testSection() {
+ token = getNextToken();
+ assertTrue(token instanceof Token);
+ assertEquals(10, rulesBasedScanner.getTokenLength());
+ assertEquals(0, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals(ta.getForeground().getRGB(),
+ ISpecfileColorConstants.SECTIONS);
+ }
- @Test
- public void testVerRel() {
- token = getToken(4);
- assertTrue(token instanceof Token);
- assertEquals(8, rulesBasedScanner.getTokenLength());
- assertEquals(26, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals(ta.getForeground().getRGB(),
- ISpecfileColorConstants.VER_REL);
- }
+ @Test
+ public void testMail() {
+ token = getToken(3);
+ assertTrue(token instanceof Token);
+ assertEquals(15, rulesBasedScanner.getTokenLength());
+ assertEquals(11, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals(ta.getForeground().getRGB(),
+ ISpecfileColorConstants.AUTHOR_MAIL);
+ }
+
+ @Test
+ public void testVerRel() {
+ token = getToken(4);
+ assertTrue(token instanceof Token);
+ assertEquals(8, rulesBasedScanner.getTokenLength());
+ assertEquals(26, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals(ta.getForeground().getRGB(),
+ ISpecfileColorConstants.VER_REL);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfilePackagesScannerTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfilePackagesScannerTest.java
index da78802c03..22f2325899 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfilePackagesScannerTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfilePackagesScannerTest.java
@@ -36,106 +36,106 @@ import org.junit.Test;
public class SpecfilePackagesScannerTest extends AScannerTest {
- private IToken token;
+ private IToken token;
- private TextAttribute ta;
+ private TextAttribute ta;
- private static SpecfilePackagesScanner scanner;
- private static final String P_RPM_LIST_FILEPATH = "/tmp/pkglist1";
+ private static SpecfilePackagesScanner scanner;
+ private static final String P_RPM_LIST_FILEPATH = "/tmp/pkglist1";
- @BeforeClass
- public static void init() {
- Activator.getDefault().getPreferenceStore().setValue(
- PreferenceConstants.P_RPM_LIST_FILEPATH, P_RPM_LIST_FILEPATH);
- Activator.getDefault().getPreferenceStore().setValue(
- PreferenceConstants.P_RPM_LIST_BACKGROUND_BUILD, false);
+ @BeforeClass
+ public static void init() {
+ Activator.getDefault().getPreferenceStore().setValue(
+ PreferenceConstants.P_RPM_LIST_FILEPATH, P_RPM_LIST_FILEPATH);
+ Activator.getDefault().getPreferenceStore().setValue(
+ PreferenceConstants.P_RPM_LIST_BACKGROUND_BUILD, false);
- try (BufferedWriter out = new BufferedWriter(new FileWriter(
- P_RPM_LIST_FILEPATH))) {
- out.write("setup\ntest_underscore\n");
- out.close();
- } catch (IOException e) {
- fail(e.getMessage());
- }
- // we ensure that proposals are rebuild
- Activator.packagesList = null;
- scanner = new SpecfilePackagesScanner(new ColorManager());
- }
+ try (BufferedWriter out = new BufferedWriter(new FileWriter(
+ P_RPM_LIST_FILEPATH))) {
+ out.write("setup\ntest_underscore\n");
+ out.close();
+ } catch (IOException e) {
+ fail(e.getMessage());
+ }
+ // we ensure that proposals are rebuild
+ Activator.packagesList = null;
+ scanner = new SpecfilePackagesScanner(new ColorManager());
+ }
- @AfterClass
- public static void cleanUp() {
- File file = new File(P_RPM_LIST_FILEPATH);
- if (file.exists()) {
- file.delete();
- }
- }
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getContents()
- */
- @Override
- protected String getContents() {
- return "Requires: test_underscore\n%{name}\n# Requires:\n";
- }
+ @AfterClass
+ public static void cleanUp() {
+ File file = new File(P_RPM_LIST_FILEPATH);
+ if (file.exists()) {
+ file.delete();
+ }
+ }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getContents()
+ */
+ @Override
+ protected String getContents() {
+ return "Requires: test_underscore\n%{name}\n# Requires:\n";
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getScanner()
- */
- @Override
- protected RuleBasedScanner getScanner() {
- return scanner;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getScanner()
+ */
+ @Override
+ protected RuleBasedScanner getScanner() {
+ return scanner;
+ }
- @Test
- public void testPackageTag() {
- token = getNextToken();
- assertTrue(token instanceof Token);
- assertEquals(9, rulesBasedScanner.getTokenLength());
- assertEquals(0, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals(ta.getForeground().getRGB(), ISpecfileColorConstants.TAGS);
- }
+ @Test
+ public void testPackageTag() {
+ token = getNextToken();
+ assertTrue(token instanceof Token);
+ assertEquals(9, rulesBasedScanner.getTokenLength());
+ assertEquals(0, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals(ta.getForeground().getRGB(), ISpecfileColorConstants.TAGS);
+ }
- /**
- * We test a package with a underscore. see bug:
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=182302
- */
- @Test
- public void testPackage() {
- token = getToken(2);
- assertTrue(token instanceof Token);
- assertEquals(16, rulesBasedScanner.getTokenLength());
- assertEquals(9, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals((ta.getForeground()).getRGB(),
- ISpecfileColorConstants.PACKAGES);
- }
+ /**
+ * We test a package with a underscore. see bug:
+ * https://bugs.eclipse.org/bugs/show_bug.cgi?id=182302
+ */
+ @Test
+ public void testPackage() {
+ token = getToken(2);
+ assertTrue(token instanceof Token);
+ assertEquals(16, rulesBasedScanner.getTokenLength());
+ assertEquals(9, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals((ta.getForeground()).getRGB(),
+ ISpecfileColorConstants.PACKAGES);
+ }
- @Test
- public void testMacro() {
- token = getToken(4);
- assertTrue(token instanceof Token);
- assertEquals(7, rulesBasedScanner.getTokenLength());
- assertEquals(26, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals((ta.getForeground()).getRGB(),
- ISpecfileColorConstants.MACROS);
- }
- /**
- * Check that comments are not handle with the package scanner. See bug:
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=182302
- */
- @Test
- public void testComment() {
- token = getToken(6);
- assertTrue(token instanceof Token);
- assertEquals(1, rulesBasedScanner.getTokenLength());
- ta = (TextAttribute) token.getData();
- assertNull(ta);
- }
+ @Test
+ public void testMacro() {
+ token = getToken(4);
+ assertTrue(token instanceof Token);
+ assertEquals(7, rulesBasedScanner.getTokenLength());
+ assertEquals(26, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals((ta.getForeground()).getRGB(),
+ ISpecfileColorConstants.MACROS);
+ }
+ /**
+ * Check that comments are not handle with the package scanner. See bug:
+ * https://bugs.eclipse.org/bugs/show_bug.cgi?id=182302
+ */
+ @Test
+ public void testComment() {
+ token = getToken(6);
+ assertTrue(token instanceof Token);
+ assertEquals(1, rulesBasedScanner.getTokenLength());
+ ta = (TextAttribute) token.getData();
+ assertNull(ta);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfileScannerTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfileScannerTest.java
index bdd1990da1..d9c675ab55 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfileScannerTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/tests/SpecfileScannerTest.java
@@ -26,108 +26,108 @@ import org.junit.Test;
public class SpecfileScannerTest extends AScannerTest {
- private IToken token;
-
- private TextAttribute ta;
-
- private static SpecfileScanner scanner;
-
- @BeforeClass
- public static void init() {
- scanner = new SpecfileScanner(new ColorManager());
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getContents()
- */
- @Override
- protected String getContents() {
- return "# This is a comment\nName: test\n%prep\n%{name}\n%define\n%if\nName=test";
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getScanner()
- */
- @Override
- protected RuleBasedScanner getScanner() {
- return scanner;
- }
-
- @Test
- public void testComment() {
- token = getNextToken();
- assertTrue(token instanceof Token);
- assertEquals(20, rulesBasedScanner.getTokenLength());
- assertEquals(0, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals(ISpecfileColorConstants.COMMENT, ta.getForeground().getRGB());
- }
-
- @Test
- public void testTag() {
- token = getToken(2);
- assertTrue(token instanceof Token);
- assertEquals(5, rulesBasedScanner.getTokenLength());
- assertEquals(20, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals(ISpecfileColorConstants.TAGS, ta.getForeground().getRGB());
- }
-
- @Test
- public void testSection() {
- token = getToken(9);
- assertTrue(token instanceof Token);
- assertEquals(5, rulesBasedScanner.getTokenLength());
- assertEquals(31, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals(ISpecfileColorConstants.SECTIONS, ta.getForeground().getRGB());
- }
-
- @Test
- public void testMacro() {
- token = getToken(11);
- assertTrue(token instanceof Token);
- assertEquals(7, rulesBasedScanner.getTokenLength());
- assertEquals(37, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals(ISpecfileColorConstants.MACROS, ta.getForeground().getRGB());
- }
-
- @Test
- public void testDefinedMacro() {
- token = getToken(13);
- assertTrue(token instanceof Token);
- assertEquals(7, rulesBasedScanner.getTokenLength());
- assertEquals(45, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals(ISpecfileColorConstants.MACROS, ta.getForeground().getRGB());
- }
-
- @Test
- public void testKeyword() {
- token = getToken(15);
- assertTrue(token instanceof Token);
- assertEquals(3, rulesBasedScanner.getTokenLength());
- assertEquals(53, rulesBasedScanner.getTokenOffset());
- ta = (TextAttribute) token.getData();
- assertEquals(ISpecfileColorConstants.KEYWORDS, ta.getForeground().getRGB());
- }
-
- /**
- * Check that defines are correctly scanned. See bug:
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=182302 printscreen:
- * https://bugs.eclipse.org/bugs/attachment.cgi?id=63722
- */
- @Test
- public void testDefineCorreclyScanned() {
- token = getToken(17);
- assertTrue(token instanceof Token);
- assertEquals(1, rulesBasedScanner.getTokenLength());
- }
+ private IToken token;
+
+ private TextAttribute ta;
+
+ private static SpecfileScanner scanner;
+
+ @BeforeClass
+ public static void init() {
+ scanner = new SpecfileScanner(new ColorManager());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getContents()
+ */
+ @Override
+ protected String getContents() {
+ return "# This is a comment\nName: test\n%prep\n%{name}\n%define\n%if\nName=test";
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.linuxtools.rpm.ui.editor.tests.AScannerTest#getScanner()
+ */
+ @Override
+ protected RuleBasedScanner getScanner() {
+ return scanner;
+ }
+
+ @Test
+ public void testComment() {
+ token = getNextToken();
+ assertTrue(token instanceof Token);
+ assertEquals(20, rulesBasedScanner.getTokenLength());
+ assertEquals(0, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals(ISpecfileColorConstants.COMMENT, ta.getForeground().getRGB());
+ }
+
+ @Test
+ public void testTag() {
+ token = getToken(2);
+ assertTrue(token instanceof Token);
+ assertEquals(5, rulesBasedScanner.getTokenLength());
+ assertEquals(20, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals(ISpecfileColorConstants.TAGS, ta.getForeground().getRGB());
+ }
+
+ @Test
+ public void testSection() {
+ token = getToken(9);
+ assertTrue(token instanceof Token);
+ assertEquals(5, rulesBasedScanner.getTokenLength());
+ assertEquals(31, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals(ISpecfileColorConstants.SECTIONS, ta.getForeground().getRGB());
+ }
+
+ @Test
+ public void testMacro() {
+ token = getToken(11);
+ assertTrue(token instanceof Token);
+ assertEquals(7, rulesBasedScanner.getTokenLength());
+ assertEquals(37, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals(ISpecfileColorConstants.MACROS, ta.getForeground().getRGB());
+ }
+
+ @Test
+ public void testDefinedMacro() {
+ token = getToken(13);
+ assertTrue(token instanceof Token);
+ assertEquals(7, rulesBasedScanner.getTokenLength());
+ assertEquals(45, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals(ISpecfileColorConstants.MACROS, ta.getForeground().getRGB());
+ }
+
+ @Test
+ public void testKeyword() {
+ token = getToken(15);
+ assertTrue(token instanceof Token);
+ assertEquals(3, rulesBasedScanner.getTokenLength());
+ assertEquals(53, rulesBasedScanner.getTokenOffset());
+ ta = (TextAttribute) token.getData();
+ assertEquals(ISpecfileColorConstants.KEYWORDS, ta.getForeground().getRGB());
+ }
+
+ /**
+ * Check that defines are correctly scanned. See bug:
+ * https://bugs.eclipse.org/bugs/show_bug.cgi?id=182302 printscreen:
+ * https://bugs.eclipse.org/bugs/attachment.cgi?id=63722
+ */
+ @Test
+ public void testDefineCorreclyScanned() {
+ token = getToken(17);
+ assertTrue(token instanceof Token);
+ assertEquals(1, rulesBasedScanner.getTokenLength());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/AScannerTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/AScannerTest.java
index c15429cde9..52b0d5ad72 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/AScannerTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/AScannerTest.java
@@ -21,37 +21,37 @@ import org.junit.Before;
public abstract class AScannerTest extends FileTestCase {
- protected RuleBasedScanner rulesBasedScanner;
-
- protected abstract String getContents();
-
- protected abstract RuleBasedScanner getScanner();
-
- public SpecfileEditor editor;
-
- @Override
- @Before
- public void setUp() throws CoreException {
- super.setUp();
- newFile(getContents());
- testProject.refresh();
- IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage(), testFile,
- "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
- editor = (SpecfileEditor) openEditor;
- editor.doRevertToSaved();
- rulesBasedScanner = getScanner();
- rulesBasedScanner.setRange(testDocument, 0, getContents().length());
- }
-
- protected IToken getNextToken() {
- return rulesBasedScanner.nextToken();
- }
-
- protected IToken getToken(int nbrOfToken) {
- for (int i = 0; i < nbrOfToken - 1; i++) {
- rulesBasedScanner.nextToken();
- }
- return rulesBasedScanner.nextToken();
- }
+ protected RuleBasedScanner rulesBasedScanner;
+
+ protected abstract String getContents();
+
+ protected abstract RuleBasedScanner getScanner();
+
+ public SpecfileEditor editor;
+
+ @Override
+ @Before
+ public void setUp() throws CoreException {
+ super.setUp();
+ newFile(getContents());
+ testProject.refresh();
+ IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage(), testFile,
+ "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor");
+ editor = (SpecfileEditor) openEditor;
+ editor.doRevertToSaved();
+ rulesBasedScanner = getScanner();
+ rulesBasedScanner.setRange(testDocument, 0, getContents().length());
+ }
+
+ protected IToken getNextToken() {
+ return rulesBasedScanner.nextToken();
+ }
+
+ protected IToken getToken(int nbrOfToken) {
+ for (int i = 0; i < nbrOfToken - 1; i++) {
+ rulesBasedScanner.nextToken();
+ }
+ return rulesBasedScanner.nextToken();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/AllTests.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/AllTests.java
index d9208db2c7..3f25a7081c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/AllTests.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/AllTests.java
@@ -20,11 +20,11 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ EpochTagTest.class, ReleaseTagTest.class,
- NameTagTest.class, VersionTagTest.class, HeaderRecognitionTest.class,
- LicenseTagTest.class, PatchApplicationTest.class,
- LinePositionTest.class, RpmMacroProposalsListTest.class,
- RpmPackageProposalsListTest.class, ActionsAllTests.class,
- ScannersAllTests.class, ParserAllTests.class, HyperlinkAllTests.class,
- SpecfileCompletionProcessorTest.class, LabelProviderTest.class })
+ NameTagTest.class, VersionTagTest.class, HeaderRecognitionTest.class,
+ LicenseTagTest.class, PatchApplicationTest.class,
+ LinePositionTest.class, RpmMacroProposalsListTest.class,
+ RpmPackageProposalsListTest.class, ActionsAllTests.class,
+ ScannersAllTests.class, ParserAllTests.class, HyperlinkAllTests.class,
+ SpecfileCompletionProcessorTest.class, LabelProviderTest.class })
public class AllTests {
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/EpochTagTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/EpochTagTest.java
index 0cce1f3747..504b36f853 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/EpochTagTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/EpochTagTest.java
@@ -18,95 +18,95 @@ import org.junit.Test;
public class EpochTagTest extends FileTestCase {
- @Test
- public void testEpochTag() {
- String testText = "Epoch: 1";
- newFile(testText);
- assertEquals(1, specfile.getEpoch());
- }
+ @Test
+ public void testEpochTag() {
+ String testText = "Epoch: 1";
+ newFile(testText);
+ assertEquals(1, specfile.getEpoch());
+ }
- @Test
- public void testEpochTag2() {
- String testText = "Epoch: 1";
- newFile(testText);
- assertEquals(1, specfile.getEpoch());
- }
+ @Test
+ public void testEpochTag2() {
+ String testText = "Epoch:\t1";
+ newFile(testText);
+ assertEquals(1, specfile.getEpoch());
+ }
- @Test
- public void testNullEpochTag() {
- String testText = "Epoch:";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(6, failure.getPosition().getLength());
- assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
- .getAnnotation().getType());
- assertEquals("Epoch declaration without value.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testNullEpochTag() {
+ String testText = "Epoch:";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(6, failure.getPosition().getLength());
+ assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
+ .getAnnotation().getType());
+ assertEquals("Epoch declaration without value.", failure
+ .getAnnotation().getText());
+ }
- @Test
- public void testNullEpochTag2() {
- String testText = "Epoch: ";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(7, failure.getPosition().getLength());
- assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
- .getAnnotation().getType());
- assertEquals("Epoch declaration without value.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testNullEpochTag2() {
+ String testText = "Epoch:\t";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(7, failure.getPosition().getLength());
+ assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
+ .getAnnotation().getType());
+ assertEquals("Epoch declaration without value.", failure
+ .getAnnotation().getText());
+ }
- @Test
- public void testMultipleEpochsTag() {
- String testText = "Epoch: 1 2";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(10, failure.getPosition().getLength());
- assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
- .getAnnotation().getType());
- assertEquals("Epoch cannot have multiple values.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testMultipleEpochsTag() {
+ String testText = "Epoch: 1 2";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(10, failure.getPosition().getLength());
+ assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
+ .getAnnotation().getType());
+ assertEquals("Epoch cannot have multiple values.", failure
+ .getAnnotation().getText());
+ }
- @Test
- public void testMultipleEpochsTag2() {
- String testText = "Epoch: 1 2";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(11, failure.getPosition().getLength());
- assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
- .getAnnotation().getType());
- assertEquals("Epoch cannot have multiple values.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testMultipleEpochsTag2() {
+ String testText = "Epoch: \t1 2";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(11, failure.getPosition().getLength());
+ assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
+ .getAnnotation().getType());
+ assertEquals("Epoch cannot have multiple values.", failure
+ .getAnnotation().getText());
+ }
- @Test
- public void testNonIntegerEpoch() {
- String testText = "Epoch: blah";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(11, failure.getPosition().getLength());
- assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
- .getAnnotation().getType());
- assertEquals("Epoch cannot have non-integer value.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testNonIntegerEpoch() {
+ String testText = "Epoch: blah";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(11, failure.getPosition().getLength());
+ assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
+ .getAnnotation().getType());
+ assertEquals("Epoch cannot have non-integer value.", failure
+ .getAnnotation().getText());
+ }
- @Test
- public void testNonIntegerEpoch2() {
- String testText = "Epoch: blah";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(11, failure.getPosition().getLength());
- assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
- .getAnnotation().getType());
- assertEquals("Epoch cannot have non-integer value.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testNonIntegerEpoch2() {
+ String testText = "Epoch:\tblah";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(11, failure.getPosition().getLength());
+ assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR, failure
+ .getAnnotation().getType());
+ assertEquals("Epoch cannot have non-integer value.", failure
+ .getAnnotation().getText());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/FileTestCase.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/FileTestCase.java
index b8437e29d6..19321249d9 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/FileTestCase.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/FileTestCase.java
@@ -38,74 +38,74 @@ import org.junit.Before;
*/
public abstract class FileTestCase {
- protected SpecfileParser parser;
- protected Specfile specfile;
- protected IFile testFile;
- protected Document testDocument;
- SpecfileErrorHandler errorHandler;
- SpecfileTestProject testProject;
+ protected SpecfileParser parser;
+ protected Specfile specfile;
+ protected IFile testFile;
+ protected Document testDocument;
+ SpecfileErrorHandler errorHandler;
+ SpecfileTestProject testProject;
FileEditorInput fei;
protected SpecfileEditor editor;
- @Before
- public void setUp() throws CoreException {
- testProject = new SpecfileTestProject();
- String fileName = "test" + this.getClass().getSimpleName() + ".spec";
- testFile = testProject.createFile(fileName);
- editor = new SpecfileEditor();
- parser = new SpecfileParser();
- specfile = new Specfile();
- }
+ @Before
+ public void setUp() throws CoreException {
+ testProject = new SpecfileTestProject();
+ String fileName = "test" + this.getClass().getSimpleName() + ".spec";
+ testFile = testProject.createFile(fileName);
+ editor = new SpecfileEditor();
+ parser = new SpecfileParser();
+ specfile = new Specfile();
+ }
- @After
- public void tearDown() throws CoreException {
- testProject.dispose();
- }
+ @After
+ public void tearDown() throws CoreException {
+ testProject.dispose();
+ }
- public static void closeEditor(final IEditorPart editor) {
- if (editor.getSite().getWorkbenchWindow().getActivePage() != null) {
- PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
- @Override
- public void run() {
- // close editor
- editor.getSite().getWorkbenchWindow().getActivePage()
- .closeEditor(editor, false);
- }
- });
- }
- }
+ public static void closeEditor(final IEditorPart editor) {
+ if (editor.getSite().getWorkbenchWindow().getActivePage() != null) {
+ PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ // close editor
+ editor.getSite().getWorkbenchWindow().getActivePage()
+ .closeEditor(editor, false);
+ }
+ });
+ }
+ }
- protected ArrayList<SpecfileTestFailure> getFailures() {
- ArrayList<SpecfileTestFailure> failures = new ArrayList<>();
- IAnnotationModel model = SpecfileEditor.getSpecfileDocumentProvider()
- .getAnnotationModel(fei);
- for (Iterator<Annotation> i = model.getAnnotationIterator(); i
- .hasNext();) {
- Annotation annotation = i.next();
- Position p = model.getPosition(annotation);
- SpecfileTestFailure t = new SpecfileTestFailure(annotation, p);
- failures.add(t);
- }
- return failures;
- }
+ protected ArrayList<SpecfileTestFailure> getFailures() {
+ ArrayList<SpecfileTestFailure> failures = new ArrayList<>();
+ IAnnotationModel model = SpecfileEditor.getSpecfileDocumentProvider()
+ .getAnnotationModel(fei);
+ for (Iterator<Annotation> i = model.getAnnotationIterator(); i
+ .hasNext();) {
+ Annotation annotation = i.next();
+ Position p = model.getPosition(annotation);
+ SpecfileTestFailure t = new SpecfileTestFailure(annotation, p);
+ failures.add(t);
+ }
+ return failures;
+ }
- protected void newFile(String contents) {
- try {
- testFile.setContents(new ByteArrayInputStream(contents.getBytes()),
- false, false, null);
- } catch (CoreException e) {
- fail(e.getMessage());
- }
- testDocument = new Document(contents);
- fei = new FileEditorInput(testFile);
- try {
- SpecfileEditor.getSpecfileDocumentProvider().disconnect(fei);
- SpecfileEditor.getSpecfileDocumentProvider().connect(fei);
- } catch (CoreException e) {
- // let failures occur
- }
- errorHandler = new SpecfileErrorHandler(fei, testDocument);
- parser.setErrorHandler(errorHandler);
- specfile = parser.parse(testDocument);
- }
+ protected void newFile(String contents) {
+ try {
+ testFile.setContents(new ByteArrayInputStream(contents.getBytes()),
+ false, false, null);
+ } catch (CoreException e) {
+ fail(e.getMessage());
+ }
+ testDocument = new Document(contents);
+ fei = new FileEditorInput(testFile);
+ try {
+ SpecfileEditor.getSpecfileDocumentProvider().disconnect(fei);
+ SpecfileEditor.getSpecfileDocumentProvider().connect(fei);
+ } catch (CoreException e) {
+ // let failures occur
+ }
+ errorHandler = new SpecfileErrorHandler(fei, testDocument);
+ parser.setErrorHandler(errorHandler);
+ specfile = parser.parse(testDocument);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/HeaderRecognitionTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/HeaderRecognitionTest.java
index ea2cd272af..f5a6c237c4 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/HeaderRecognitionTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/HeaderRecognitionTest.java
@@ -24,113 +24,113 @@ import org.junit.Test;
*/
public class HeaderRecognitionTest extends FileTestCase {
- @Test
- public void testGetSimpleSectionName() {
- String testText = "%prep";
- SpecfileElement element;
+ @Test
+ public void testGetSimpleSectionName() {
+ String testText = "%prep";
+ SpecfileElement element;
- newFile(testText);
- element = parser.parseLine(testText, specfile, 0);
- assertEquals(SpecfileSection.class, element.getClass());
- assertEquals(testText.substring(1), ((SpecfileSection) element)
- .getName());
- }
- @Test
- public void testGetComplexSectionName1() {
- String testText = "%post";
- SpecfileElement element;
+ newFile(testText);
+ element = parser.parseLine(testText, specfile, 0);
+ assertEquals(SpecfileSection.class, element.getClass());
+ assertEquals(testText.substring(1), ((SpecfileSection) element)
+ .getName());
+ }
+ @Test
+ public void testGetComplexSectionName1() {
+ String testText = "%post";
+ SpecfileElement element;
- newFile(testText);
- element = parser.parseLine(testText, specfile, 0);
- assertEquals(SpecfileSection.class, element.getClass());
- SpecfileSection section = (SpecfileSection) element;
- assertEquals(testText.substring(1), section.getName());
- assertNull(section.getPackage());
- }
- @Test
- public void testGetComplexSectionName2() {
- String testText = "%post -n";
- newFile(testText);
- specfile = parser.parse(testDocument);
+ newFile(testText);
+ element = parser.parseLine(testText, specfile, 0);
+ assertEquals(SpecfileSection.class, element.getClass());
+ SpecfileSection section = (SpecfileSection) element;
+ assertEquals(testText.substring(1), section.getName());
+ assertNull(section.getPackage());
+ }
+ @Test
+ public void testGetComplexSectionName2() {
+ String testText = "%post -n";
+ newFile(testText);
+ specfile = parser.parse(testDocument);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals("No package name after -n in post section.",
- failure.getAnnotation().getText());
- assertEquals(testText.length(),
- failure.getPosition().getLength());
- }
- @Test
- public void testGetComplexSectionName3() {
- String testText = "%post -n name";
- String[] tokens = testText.split("\\s+");
- SpecfileElement element;
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals("No package name after -n in post section.",
+ failure.getAnnotation().getText());
+ assertEquals(testText.length(),
+ failure.getPosition().getLength());
+ }
+ @Test
+ public void testGetComplexSectionName3() {
+ String testText = "%post -n name";
+ String[] tokens = testText.split("\\s+");
+ SpecfileElement element;
- newFile(testText);
- element = parser.parseLine(testText, specfile, 0);
- assertEquals(SpecfileSection.class, element.getClass());
- SpecfileSection section = (SpecfileSection) element;
- assertEquals(tokens[0].substring(1), section.getName());
- assertEquals(tokens[2], section.getPackage().getPackageName());
- }
- @Test
- public void testGetComplexSectionName4() {
- // FIXME: check for rest of line when -p is implemented
- // this should be an error case
- String testText = "%post -n name -p";
- String[] tokens = testText.split("\\s+");
- SpecfileElement element;
+ newFile(testText);
+ element = parser.parseLine(testText, specfile, 0);
+ assertEquals(SpecfileSection.class, element.getClass());
+ SpecfileSection section = (SpecfileSection) element;
+ assertEquals(tokens[0].substring(1), section.getName());
+ assertEquals(tokens[2], section.getPackage().getPackageName());
+ }
+ @Test
+ public void testGetComplexSectionName4() {
+ // FIXME: check for rest of line when -p is implemented
+ // this should be an error case
+ String testText = "%post -n name -p";
+ String[] tokens = testText.split("\\s+");
+ SpecfileElement element;
- newFile(testText);
- element = parser.parseLine(testText, specfile, 0);
- assertEquals(SpecfileSection.class, element.getClass());
- SpecfileSection section = (SpecfileSection) element;
- assertEquals(tokens[0].substring(1), section.getName());
- assertEquals(tokens[2], section.getPackage().getPackageName());
- }
- @Test
- public void testGetComplexSectionName5() {
- // FIXME: check for rest of line when -p is implemented
- // "blah bleh" should become the actual text of the section
- String testText = "%post -n name -p blah bleh";
- String[] tokens = testText.split("\\s+");
- SpecfileElement element;
+ newFile(testText);
+ element = parser.parseLine(testText, specfile, 0);
+ assertEquals(SpecfileSection.class, element.getClass());
+ SpecfileSection section = (SpecfileSection) element;
+ assertEquals(tokens[0].substring(1), section.getName());
+ assertEquals(tokens[2], section.getPackage().getPackageName());
+ }
+ @Test
+ public void testGetComplexSectionName5() {
+ // FIXME: check for rest of line when -p is implemented
+ // "blah bleh" should become the actual text of the section
+ String testText = "%post -n name -p blah bleh";
+ String[] tokens = testText.split("\\s+");
+ SpecfileElement element;
- newFile(testText);
- element = parser.parseLine(testText, specfile, 0);
- assertEquals(SpecfileSection.class, element.getClass());
- SpecfileSection section = (SpecfileSection) element;
- assertEquals(tokens[0].substring(1), section.getName());
- assertEquals(tokens[2], section.getPackage().getPackageName());
- }
- @Test
- public void testGetComplexSectionName6() {
- String testText = "%post -p blah bleh";
- // FIXME: check for rest of line when -p is implemented
- // "blah bleh" should become the actual text of the section
+ newFile(testText);
+ element = parser.parseLine(testText, specfile, 0);
+ assertEquals(SpecfileSection.class, element.getClass());
+ SpecfileSection section = (SpecfileSection) element;
+ assertEquals(tokens[0].substring(1), section.getName());
+ assertEquals(tokens[2], section.getPackage().getPackageName());
+ }
+ @Test
+ public void testGetComplexSectionName6() {
+ String testText = "%post -p blah bleh";
+ // FIXME: check for rest of line when -p is implemented
+ // "blah bleh" should become the actual text of the section
- String[] tokens = testText.split("\\s+");
- SpecfileElement element;
+ String[] tokens = testText.split("\\s+");
+ SpecfileElement element;
- newFile(testText);
- element = parser.parseLine(testText, specfile, 0);
- assertEquals(SpecfileSection.class, element.getClass());
- SpecfileSection section = (SpecfileSection) element;
- assertEquals(tokens[0].substring(1), section.getName());
- assertNull(section.getPackage());
- }
- @Test
- public void testGetComplexSectionName7() {
- String testText = "%post -n -p blah";
+ newFile(testText);
+ element = parser.parseLine(testText, specfile, 0);
+ assertEquals(SpecfileSection.class, element.getClass());
+ SpecfileSection section = (SpecfileSection) element;
+ assertEquals(tokens[0].substring(1), section.getName());
+ assertNull(section.getPackage());
+ }
+ @Test
+ public void testGetComplexSectionName7() {
+ String testText = "%post -n -p blah";
- newFile(testText);
- specfile = parser.parse(testDocument);
+ newFile(testText);
+ specfile = parser.parse(testDocument);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals("Package name must not start with '-': -p.",
- failure.getAnnotation().getText());
- assertEquals(testText.length(),
- failure.getPosition().getLength());
- }
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals("Package name must not start with '-': -p.",
+ failure.getAnnotation().getText());
+ assertEquals(testText.length(),
+ failure.getPosition().getLength());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LabelProviderTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LabelProviderTest.java
index 0ea2beee15..422516267f 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LabelProviderTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LabelProviderTest.java
@@ -24,47 +24,47 @@ import org.junit.Test;
*/
public class LabelProviderTest extends FileTestCase {
- private SpecfileLabelProvider labelProvider;
- private String correctResult = "eclipse-plugin";
+ private SpecfileLabelProvider labelProvider;
+ private String correctResult = "eclipse-plugin";
- @Before
- public void initialize() {
- labelProvider = new SpecfileLabelProvider();
- }
+ @Before
+ public void initialize() {
+ labelProvider = new SpecfileLabelProvider();
+ }
- /**
- * Test to see if %{?...} macros will be shown. They should not.
- */
- @Test
- public void testLabelForUnresolvedMacro() {
- String testText = "%{?some_macro}eclipse-plugin";
- String result = labelProvider.getText(testText);
- assertEquals(result, correctResult);
+ /**
+ * Test to see if %{?...} macros will be shown. They should not.
+ */
+ @Test
+ public void testLabelForUnresolvedMacro() {
+ String testText = "%{?some_macro}eclipse-plugin";
+ String result = labelProvider.getText(testText);
+ assertEquals(result, correctResult);
- testText = "eclipse-plugin%{?some_macro}";
- result = labelProvider.getText(testText);
- assertEquals(result, correctResult);
+ testText = "eclipse-plugin%{?some_macro}";
+ result = labelProvider.getText(testText);
+ assertEquals(result, correctResult);
- testText = "%{?some_macro}eclipse-plugin%{?some_macro}";
- result = labelProvider.getText(testText);
- assertEquals(result, correctResult);
- }
+ testText = "%{?some_macro}eclipse-plugin%{?some_macro}";
+ result = labelProvider.getText(testText);
+ assertEquals(result, correctResult);
+ }
- /**
- * Test for incorrect labels.
- */
- @Test
- public void testLabelForIncorrectString() {
- // for sake of test, this is just to show that the filterMacros
- // method would not filter %{...} regular macros.
- // It is the job of SpecfileDefine to do that.
- String testText = "%{no_question_mark}eclipse-plugin";
- String result = labelProvider.getText(testText);
- assertNotEquals(result, correctResult);
+ /**
+ * Test for incorrect labels.
+ */
+ @Test
+ public void testLabelForIncorrectString() {
+ // for sake of test, this is just to show that the filterMacros
+ // method would not filter %{...} regular macros.
+ // It is the job of SpecfileDefine to do that.
+ String testText = "%{no_question_mark}eclipse-plugin";
+ String result = labelProvider.getText(testText);
+ assertNotEquals(result, correctResult);
- testText = "{?no_percent_sign}eclipse-plugin";
- result = labelProvider.getText(testText);
- assertNotEquals(result, correctResult);
- }
+ testText = "{?no_percent_sign}eclipse-plugin";
+ result = labelProvider.getText(testText);
+ assertNotEquals(result, correctResult);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LicenseTagTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LicenseTagTest.java
index 39208ea707..f1bcb637ac 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LicenseTagTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LicenseTagTest.java
@@ -15,10 +15,10 @@ import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class LicenseTagTest extends FileTestCase {
- @Test
- public void testSingleLicenseTag() {
- String testText = "License: EPL";
- newFile(testText);
- assertEquals("EPL", specfile.getLicense());
- }
+ @Test
+ public void testSingleLicenseTag() {
+ String testText = "License: EPL";
+ newFile(testText);
+ assertEquals("EPL", specfile.getLicense());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LinePositionTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LinePositionTest.java
index ebdd9e0712..a373a36e5e 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LinePositionTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/LinePositionTest.java
@@ -20,35 +20,35 @@ import org.eclipse.linuxtools.internal.rpm.ui.editor.parser.SpecfileSource;
import org.junit.Test;
public class LinePositionTest extends FileTestCase {
- @Test
- public void testLineNumber() {
- String specText = "Patch3: somefilesomewhere.patch" + "\n"
- + "Patch2: someotherfile.patch";
-
- newFile(specText);
- Collection<SpecfileSource> patches = specfile.getPatches();
- for (SpecfileSource patch : patches) {
- if (patch.getNumber() == 2)
- assertEquals(1, patch.getLineNumber());
- else if (patch.getNumber() == 3)
- assertEquals(0, patch.getLineNumber());
- else
- fail("Found patch with number different from the expected numbers (2 or 3).");
- }
- }
- @Test
- public void testLineNumber2() {
- String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
-
- newFile(specText);
- Collection<SpecfileSource> patches = specfile.getPatches();
- for (SpecfileSource patch : patches) {
- if (patch.getNumber() == 3) {
- assertEquals(0, patch.getLineNumber());
- assertEquals(1, patch.getLinesUsed().get(0).intValue());
- } else
- fail("Found patch with number different from the expected 3.");
- }
- }
+ @Test
+ public void testLineNumber() {
+ String specText = "Patch3: somefilesomewhere.patch" + "\n"
+ + "Patch2: someotherfile.patch";
+
+ newFile(specText);
+ Collection<SpecfileSource> patches = specfile.getPatches();
+ for (SpecfileSource patch : patches) {
+ if (patch.getNumber() == 2)
+ assertEquals(1, patch.getLineNumber());
+ else if (patch.getNumber() == 3)
+ assertEquals(0, patch.getLineNumber());
+ else
+ fail("Found patch with number different from the expected numbers (2 or 3).");
+ }
+ }
+ @Test
+ public void testLineNumber2() {
+ String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
+
+ newFile(specText);
+ Collection<SpecfileSource> patches = specfile.getPatches();
+ for (SpecfileSource patch : patches) {
+ if (patch.getNumber() == 3) {
+ assertEquals(0, patch.getLineNumber());
+ assertEquals(1, patch.getLinesUsed().get(0).intValue());
+ } else
+ fail("Found patch with number different from the expected 3.");
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/NameTagTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/NameTagTest.java
index ff3b09def9..5f4aa9a1cd 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/NameTagTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/NameTagTest.java
@@ -16,75 +16,75 @@ import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class NameTagTest extends FileTestCase {
- @Test
- public void testResolvedNameTag() {
- String testText = "%define blah notblah\nName: %{blah}";
- newFile(testText);
- assertEquals("notblah", specfile.getName());
- }
+ @Test
+ public void testResolvedNameTag() {
+ String testText = "%define blah notblah\nName: %{blah}";
+ newFile(testText);
+ assertEquals("notblah", specfile.getName());
+ }
- @Test
- public void testResolvedSetName() {
- String testText = "%define blah notblah\nName: %{blah}";
- newFile(testText);
- assertEquals("notblah", specfile.getName());
- }
+ @Test
+ public void testResolvedSetName() {
+ String testText = "%define blah notblah\nName: %{blah}";
+ newFile(testText);
+ assertEquals("notblah", specfile.getName());
+ }
- @Test
- public void testNameTag() {
- String testText = "Name: blah";
- newFile(testText);
- assertEquals("blah", specfile.getName());
- }
+ @Test
+ public void testNameTag() {
+ String testText = "Name: blah";
+ newFile(testText);
+ assertEquals("blah", specfile.getName());
+ }
- @Test
- public void testNameTag2() {
- String testText = "Name: blah";
- newFile(testText);
- assertEquals("blah", specfile.getName());
- }
+ @Test
+ public void testNameTag2() {
+ String testText = "Name: blah";
+ newFile(testText);
+ assertEquals("blah", specfile.getName());
+ }
- @Test
- public void testNullNameTag() {
- String testText = "Name: ";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Name declaration without value.", failure.getAnnotation()
- .getText());
- }
+ @Test
+ public void testNullNameTag() {
+ String testText = "Name: ";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Name declaration without value.", failure.getAnnotation()
+ .getText());
+ }
- @Test
- public void testNullNameTag2() {
- String testText = "Name: ";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Name declaration without value.", failure.getAnnotation()
- .getText());
- }
+ @Test
+ public void testNullNameTag2() {
+ String testText = "Name: ";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Name declaration without value.", failure.getAnnotation()
+ .getText());
+ }
- @Test
- public void testMultipleNamesTag() {
- String testText = "Name: blah bleh";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Name cannot have multiple values.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testMultipleNamesTag() {
+ String testText = "Name: blah bleh";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Name cannot have multiple values.", failure
+ .getAnnotation().getText());
+ }
- @Test
- public void testMultipleNamesTag2() {
- String testText = "Name: blah bleh";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Name cannot have multiple values.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testMultipleNamesTag2() {
+ String testText = "Name: blah bleh";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Name cannot have multiple values.", failure
+ .getAnnotation().getText());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/PatchApplicationTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/PatchApplicationTest.java
index ea3b9db47f..cefeb133ea 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/PatchApplicationTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/PatchApplicationTest.java
@@ -22,33 +22,33 @@ import org.eclipse.linuxtools.rpm.ui.editor.parser.SpecfileElement;
import org.junit.Test;
public class PatchApplicationTest extends FileTestCase {
- @Test
- public void testParsePatchApplication() {
- String specText = "Patch3: somefilesomewhere.patch\n%patch3";
- String testText = "%patch3";
- newFile(specText);
- SpecfileElement element = parser.parseLine(testText, specfile, 1);
- assertEquals(SpecfilePatchMacro.class, element.getClass());
- assertEquals(3, ((SpecfilePatchMacro) element).getPatchNumber());
- }
- @Test
- public void testPatchLineNumber() {
- String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
- newFile(specText);
- SpecfileSource thisPatch = specfile.getPatch(3);
- List<Integer> usedList = new ArrayList<>(1);
- usedList.add(Integer.valueOf(1));
- assertEquals(thisPatch.getLinesUsed(), usedList);
- }
- @Test
- public void testMultiplePatchLineNumbers() {
- String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3"
- + "\n" + "blah" + "\n" + "%patch3";
- newFile(specText);
- SpecfileSource thisPatch = specfile.getPatch(3);
- List<Integer> usedList = new ArrayList<>(2);
- usedList.add(Integer.valueOf(1));
- usedList.add(Integer.valueOf(3));
- assertEquals(thisPatch.getLinesUsed(), usedList);
- }
+ @Test
+ public void testParsePatchApplication() {
+ String specText = "Patch3: somefilesomewhere.patch\n%patch3";
+ String testText = "%patch3";
+ newFile(specText);
+ SpecfileElement element = parser.parseLine(testText, specfile, 1);
+ assertEquals(SpecfilePatchMacro.class, element.getClass());
+ assertEquals(3, ((SpecfilePatchMacro) element).getPatchNumber());
+ }
+ @Test
+ public void testPatchLineNumber() {
+ String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
+ newFile(specText);
+ SpecfileSource thisPatch = specfile.getPatch(3);
+ List<Integer> usedList = new ArrayList<>(1);
+ usedList.add(Integer.valueOf(1));
+ assertEquals(thisPatch.getLinesUsed(), usedList);
+ }
+ @Test
+ public void testMultiplePatchLineNumbers() {
+ String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3"
+ + "\n" + "blah" + "\n" + "%patch3";
+ newFile(specText);
+ SpecfileSource thisPatch = specfile.getPatch(3);
+ List<Integer> usedList = new ArrayList<>(2);
+ usedList.add(Integer.valueOf(1));
+ usedList.add(Integer.valueOf(3));
+ assertEquals(thisPatch.getLinesUsed(), usedList);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/ReleaseTagTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/ReleaseTagTest.java
index 29072f5ec1..ede3b28ec8 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/ReleaseTagTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/ReleaseTagTest.java
@@ -16,68 +16,68 @@ import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ReleaseTagTest extends FileTestCase {
- @Test
- public void testResolvedSetRelease() {
- String testText = "%define blah notblah\nRelease: %{blah}";
- newFile(testText);
- assertEquals("notblah", specfile.getRelease());
- }
+ @Test
+ public void testResolvedSetRelease() {
+ String testText = "%define blah notblah\nRelease: %{blah}";
+ newFile(testText);
+ assertEquals("notblah", specfile.getRelease());
+ }
- @Test
- public void testReleaseTag() {
- String testText = "Release: blah";
- newFile(testText);
- assertEquals("blah", specfile.getRelease());
- }
+ @Test
+ public void testReleaseTag() {
+ String testText = "Release: blah";
+ newFile(testText);
+ assertEquals("blah", specfile.getRelease());
+ }
- @Test
- public void testReleaseTag2() {
- String testText = "Release: blah";
- newFile(testText);
- assertEquals("blah", specfile.getRelease());
- }
+ @Test
+ public void testReleaseTag2() {
+ String testText = "Release: blah";
+ newFile(testText);
+ assertEquals("blah", specfile.getRelease());
+ }
- @Test
- public void testNullReleaseTag() {
- String testText = "Release: ";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Release declaration without value.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testNullReleaseTag() {
+ String testText = "Release: ";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Release declaration without value.", failure
+ .getAnnotation().getText());
+ }
- @Test
- public void testNullReleaseTag2() {
- String testText = "Release: ";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Release declaration without value.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testNullReleaseTag2() {
+ String testText = "Release: ";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Release declaration without value.", failure
+ .getAnnotation().getText());
+ }
- @Test
- public void testMultipleReleasesTag() {
- String testText = "Release: blah bleh";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Release cannot have multiple values.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testMultipleReleasesTag() {
+ String testText = "Release: blah bleh";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Release cannot have multiple values.", failure
+ .getAnnotation().getText());
+ }
- @Test
- public void testMultipleReleasesTag2() {
- String testText = "Release: blah bleh";
- newFile(testText);
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Release cannot have multiple values.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testMultipleReleasesTag2() {
+ String testText = "Release: blah bleh";
+ newFile(testText);
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Release cannot have multiple values.", failure
+ .getAnnotation().getText());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/RpmMacroProposalsListTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/RpmMacroProposalsListTest.java
index 861852fb07..ca595b847a 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/RpmMacroProposalsListTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/RpmMacroProposalsListTest.java
@@ -22,78 +22,78 @@ import org.junit.Test;
public class RpmMacroProposalsListTest {
- RpmMacroProposalsList macroProposalsList;
-
- @Before
- public void setUp() {
- macroProposalsList = new RpmMacroProposalsList();
- }
-
- @Test
- public final void testBuildMacroList() {
- macroProposalsList.buildMacroList();
- if (!macroProposalsList.findKey("%_libdir"))
- fail("buildMacroList faild, %_libdir macro was not found!");
- }
-
- /**
- * Configure is the most common macro that is multi-line so it tests our parsing of multiline macros.
- */
- @Test
- public final void buildMacroListMultiLineMacro() {
- macroProposalsList.buildMacroList();
- if (!macroProposalsList.findKey("%configure")) {
- fail("buildMacroList faild, %configure macro was not found!");
- }
- }
-
- @Test
- public final void testGetProposals() {
- Map<String, String> proposals = macroProposalsList
- .getProposals("%_libdir");
- if (proposals.size() != 1) {
- fail("getProposals faild, %_libdir macro was retrive as proposals");
- }
- }
-
- @Test
- public final void testGetProposals2() {
- Map<String, String> proposals = macroProposalsList
- .getProposals("%_unexistingmacro");
- if (proposals.size() != 0) {
- fail("getProposals faild, %_unexistingmacro don't can exist");
- }
- }
-
- @Test
- public final void testGetValue() {
- if (macroProposalsList.getValue("_libdir").indexOf("lib") == -1) {
- fail("getValue faild, %_libdir value don't end with '%{_lib}'");
- }
- }
-
- @Test
- public final void testGetValue2() {
- if (macroProposalsList.getValue("_unexistingmacro") != null) {
- fail("getValue faild, %_libdir value don't end with '%{_lib}'");
- }
- }
-
- @Test
- public final void testGetMacroEval() {
- if (Utils.fileExist("/bin/rpm")) {
- if (RpmMacroProposalsList.getMacroEval("%_libdir").indexOf("lib") == -1) {
- fail("getMacroEval faild, eval don't end with 'lib'");
- }
- }
- }
-
- @Test
- public final void testGetMacroEval2() {
- if (!RpmMacroProposalsList.getMacroEval("%_unexistingmacro").equals(
- "%_unexistingmacro")) {
- fail("getMacroEval faild, eval don't contain %_unexistingmacro macro name");
- }
- }
+ RpmMacroProposalsList macroProposalsList;
+
+ @Before
+ public void setUp() {
+ macroProposalsList = new RpmMacroProposalsList();
+ }
+
+ @Test
+ public final void testBuildMacroList() {
+ macroProposalsList.buildMacroList();
+ if (!macroProposalsList.findKey("%_libdir"))
+ fail("buildMacroList faild, %_libdir macro was not found!");
+ }
+
+ /**
+ * Configure is the most common macro that is multi-line so it tests our parsing of multiline macros.
+ */
+ @Test
+ public final void buildMacroListMultiLineMacro() {
+ macroProposalsList.buildMacroList();
+ if (!macroProposalsList.findKey("%configure")) {
+ fail("buildMacroList faild, %configure macro was not found!");
+ }
+ }
+
+ @Test
+ public final void testGetProposals() {
+ Map<String, String> proposals = macroProposalsList
+ .getProposals("%_libdir");
+ if (proposals.size() != 1) {
+ fail("getProposals faild, %_libdir macro was retrive as proposals");
+ }
+ }
+
+ @Test
+ public final void testGetProposals2() {
+ Map<String, String> proposals = macroProposalsList
+ .getProposals("%_unexistingmacro");
+ if (proposals.size() != 0) {
+ fail("getProposals faild, %_unexistingmacro don't can exist");
+ }
+ }
+
+ @Test
+ public final void testGetValue() {
+ if (macroProposalsList.getValue("_libdir").indexOf("lib") == -1) {
+ fail("getValue faild, %_libdir value don't end with '%{_lib}'");
+ }
+ }
+
+ @Test
+ public final void testGetValue2() {
+ if (macroProposalsList.getValue("_unexistingmacro") != null) {
+ fail("getValue faild, %_libdir value don't end with '%{_lib}'");
+ }
+ }
+
+ @Test
+ public final void testGetMacroEval() {
+ if (Utils.fileExist("/bin/rpm")) {
+ if (RpmMacroProposalsList.getMacroEval("%_libdir").indexOf("lib") == -1) {
+ fail("getMacroEval faild, eval don't end with 'lib'");
+ }
+ }
+ }
+
+ @Test
+ public final void testGetMacroEval2() {
+ if (!RpmMacroProposalsList.getMacroEval("%_unexistingmacro").equals(
+ "%_unexistingmacro")) {
+ fail("getMacroEval faild, eval don't contain %_unexistingmacro macro name");
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/RpmPackageProposalsListTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/RpmPackageProposalsListTest.java
index 694f8262a9..5489cec2da 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/RpmPackageProposalsListTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/RpmPackageProposalsListTest.java
@@ -27,61 +27,61 @@ import org.junit.Test;
public class RpmPackageProposalsListTest {
- private RpmPackageProposalsList packageProposalsList;
+ private RpmPackageProposalsList packageProposalsList;
- @Before
- public void setUp() {
- Activator.getDefault().getPreferenceStore().setValue(
- PreferenceConstants.P_RPM_LIST_FILEPATH, "/tmp/pkglist");
- try (BufferedWriter out = new BufferedWriter(new FileWriter(
- "/tmp/pkglist"))) {
- out.write("setup\ntest\nrpm\n");
- } catch (IOException e) {
- e.printStackTrace();
- }
- packageProposalsList = new RpmPackageProposalsList();
- }
+ @Before
+ public void setUp() {
+ Activator.getDefault().getPreferenceStore().setValue(
+ PreferenceConstants.P_RPM_LIST_FILEPATH, "/tmp/pkglist");
+ try (BufferedWriter out = new BufferedWriter(new FileWriter(
+ "/tmp/pkglist"))) {
+ out.write("setup\ntest\nrpm\n");
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ packageProposalsList = new RpmPackageProposalsList();
+ }
- @Test
- public final void testGetProposals() {
- List<String[]> proposals = packageProposalsList.getProposals("setup");
- if (!(proposals.size() == 1)) {
- fail("getProposals failed, setup package was retrieve as proposals!");
- }
- }
+ @Test
+ public final void testGetProposals() {
+ List<String[]> proposals = packageProposalsList.getProposals("setup");
+ if (!(proposals.size() == 1)) {
+ fail("getProposals failed, setup package was retrieve as proposals!");
+ }
+ }
- @Test
- public final void testGetValue() {
- if (Utils.fileExist("/bin/rpm")) {
- if (!packageProposalsList.getValue("rpm").startsWith(
- "<b>Name: </b>rpm")) {
- fail("getValue failed, rpm package info doesn't start with '<b>Name:<b> rpm'");
- }
- }
- }
+ @Test
+ public final void testGetValue() {
+ if (Utils.fileExist("/bin/rpm")) {
+ if (!packageProposalsList.getValue("rpm").startsWith(
+ "<b>Name: </b>rpm")) {
+ fail("getValue failed, rpm package info doesn't start with '<b>Name:<b> rpm'");
+ }
+ }
+ }
- @Test
- public final void testGetValue2() {
- if (packageProposalsList.getValue("test").indexOf("test") == -1) {
- fail("getValue failed, test package info doesn't contain 'test'");
- }
- }
+ @Test
+ public final void testGetValue2() {
+ if (packageProposalsList.getValue("test").indexOf("test") == -1) {
+ fail("getValue failed, test package info doesn't contain 'test'");
+ }
+ }
- @Test
- public final void testGetRpmInfo() {
- if (Utils.fileExist("/bin/rpm")) {
- if (!packageProposalsList.getRpmInfo("rpm").startsWith(
- "<b>Name: </b>rpm")) {
- fail("getRpmInfo failed, rpm package info doesn't start with '<b>Name:<b> rpm'");
- }
- }
- }
+ @Test
+ public final void testGetRpmInfo() {
+ if (Utils.fileExist("/bin/rpm")) {
+ if (!packageProposalsList.getRpmInfo("rpm").startsWith(
+ "<b>Name: </b>rpm")) {
+ fail("getRpmInfo failed, rpm package info doesn't start with '<b>Name:<b> rpm'");
+ }
+ }
+ }
- @Test
- public final void testGetRpmInfo2() {
- if (packageProposalsList.getValue("test").indexOf("test") == -1) {
- fail("getRpmInfo failed, test package info doesn't contain 'test'");
- }
- }
+ @Test
+ public final void testGetRpmInfo2() {
+ if (packageProposalsList.getValue("test").indexOf("test") == -1) {
+ fail("getRpmInfo failed, test package info doesn't contain 'test'");
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileCompletionProcessorTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileCompletionProcessorTest.java
index 189c86f9b6..b490214468 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileCompletionProcessorTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileCompletionProcessorTest.java
@@ -33,157 +33,157 @@ import org.junit.Test;
public class SpecfileCompletionProcessorTest extends FileTestCase {
- public static final String ONE_SOURCE = "Source0: text.zip\n";
- public static final String NO_SOURCE = "Patch3: somefilesomewhere.patch"
- + "\n" + "Patch2: someotherfile.patch\n";
- public static final String THREE_SOURCE_SEPARATED = "Source0: text.zip"
- + "\n" + "Patch0: first.patch" + "\n" + "Source2: ant.jar" + "\n"
- + "Source3: main.tar.gz";
-
- private static final String BUILD_REQUIRES = "BuildRequires: p";
-
- private static final String NON_ALPHA_DOT = "Requires: java-1.";
- private static final String NON_ALPHA_PLUS = "Requires: libstdc+";
-
- private SpecfileEditor initEditor(String contents) throws Exception {
- newFile(contents);
- IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage(), testFile);
-
- return (SpecfileEditor) openEditor;
- }
-
- private synchronized void computeCompletionProposals(String specContent,
- int occurances) throws Exception {
- SpecfileEditor editor = initEditor(specContent);
- testProject.refresh();
- // This is needed so the changes in the testFile are loaded in the
- // editor
- editor.doRevertToSaved();
- SpecfileCompletionProcessor complProcessor = new SpecfileCompletionProcessor(
- editor);
- assertNotNull(complProcessor);
- editor.getSpecfileSourceViewer().setSelectedRange(0, 0);
- ICompletionProposal[] proposals = complProcessor
- .computeCompletionProposals(editor.getSpecfileSourceViewer(), 0);
- int sourceComplCount = 0;
- for (ICompletionProposal proposal : proposals) {
- if (proposal.getDisplayString().startsWith("%{SOURCE")) {
- ++sourceComplCount;
- }
- }
- assertEquals(occurances, sourceComplCount);
- }
-
- @Test
- public void testComputeComplProposalsOneSource() throws Exception {
- computeCompletionProposals(ONE_SOURCE, 1);
- }
-
- @Test
- public void testComputeComplProposalsNoSource() throws Exception {
- computeCompletionProposals(NO_SOURCE, 0);
- }
-
- @Test
- public void testComputeComplProposalsThreeSourceSeparated()
- throws Exception {
- computeCompletionProposals(THREE_SOURCE_SEPARATED, 3);
- }
-
- @Test
- public void testBRCompletionOrder() throws Exception {
- setPackageList(new String[]{"package3", "package2", "package4", "package1"});
- SpecfileEditor editor = initEditor(BUILD_REQUIRES);
- testProject.refresh();
- editor.doRevertToSaved();
-
- editor.getSpecfileSourceViewer().setSelectedRange(BUILD_REQUIRES.length(), 0);
- SpecfileCompletionProcessor processor = new SpecfileCompletionProcessor(
- editor);
-
- ICompletionProposal[] proposals = processor.computeCompletionProposals(
- editor.getSpecfileSourceViewer(), BUILD_REQUIRES.length());
-
- assertTrue("Cannot perform test; not enough proposals", proposals.length > 1);
-
- ICompletionProposal previous = proposals[0];
-
- for (int i = 1; i < proposals.length; i++){
- ICompletionProposal current = proposals[i];
- assertTrue("Proposals are not in alphabetical order",
- previous.getDisplayString().compareToIgnoreCase (current.getDisplayString()) < 0);
- previous = current;
- }
-
- }
-
- @Test
- public void testBRCompletionNonAlphaDot() throws Exception {
- setPackageList(new String[]{"java-1.5.0-gcj", "java-1.7.0-openjdk", "java-1.7.0-openjdk-devel", "java-1.7.0-openjdk-javadoc"});
- SpecfileEditor editor = initEditor(NON_ALPHA_DOT);
- testProject.refresh();
- // This is needed so the changes in the testFile are loaded in the
- // editor
- editor.doRevertToSaved();
- SpecfileCompletionProcessor complProcessor = new SpecfileCompletionProcessor(
- editor);
- assertNotNull(complProcessor);
- editor.getSpecfileSourceViewer().setSelectedRange(NON_ALPHA_DOT.length(), 0);
- ICompletionProposal[] proposals = complProcessor
- .computeCompletionProposals(editor.getSpecfileSourceViewer(), NON_ALPHA_DOT.length());
- int sourceComplCount = 0;
- for (ICompletionProposal proposal : proposals) {
- if (proposal.getDisplayString().startsWith("java-1.")) {
- ++sourceComplCount;
- }
- }
- assertEquals(4, sourceComplCount);
- }
-
- @Test
- public void testBRCompletionNonAlphaPlus() throws Exception {
- setPackageList(new String[]{"libstdc++", "libstdc++-devel"});
- SpecfileEditor editor = initEditor(NON_ALPHA_PLUS);
- testProject.refresh();
- // This is needed so the changes in the testFile are loaded in the
- // editor
- editor.doRevertToSaved();
- SpecfileCompletionProcessor complProcessor = new SpecfileCompletionProcessor(
- editor);
- assertNotNull(complProcessor);
- editor.getSpecfileSourceViewer().setSelectedRange(NON_ALPHA_PLUS.length(), 0);
- ICompletionProposal[] proposals = complProcessor
- .computeCompletionProposals(editor.getSpecfileSourceViewer(), NON_ALPHA_PLUS.length());
- int sourceComplCount = 0;
- for (ICompletionProposal proposal : proposals) {
- if (proposal.getDisplayString().startsWith("libstdc+")) {
- ++sourceComplCount;
- }
- }
- assertEquals(2, sourceComplCount);
- }
-
- /**
- * Set the potential rpm package list to the given list. Useful for
- * testing package proposals.
- * @param packages
- */
- private void setPackageList(String[] packages) {
- ScopedPreferenceStore prefStore = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
- prefStore.setValue(PreferenceConstants.P_RPM_LIST_FILEPATH,
- "/tmp/pkglist1");
- prefStore.setValue(PreferenceConstants.P_RPM_LIST_BACKGROUND_BUILD,
- false);
-
- try (BufferedWriter out = new BufferedWriter(new FileWriter(
- "/tmp/pkglist1"))) {
- for (String packageName : packages){
- out.write(packageName + "\n");
- }
- } catch (IOException e) {
- fail(e.getMessage());
- }
- Activator.packagesList = null;
- }
+ public static final String ONE_SOURCE = "Source0: text.zip\n";
+ public static final String NO_SOURCE = "Patch3: somefilesomewhere.patch"
+ + "\n" + "Patch2: someotherfile.patch\n";
+ public static final String THREE_SOURCE_SEPARATED = "Source0: text.zip"
+ + "\n" + "Patch0: first.patch" + "\n" + "Source2: ant.jar" + "\n"
+ + "Source3: main.tar.gz";
+
+ private static final String BUILD_REQUIRES = "BuildRequires: p";
+
+ private static final String NON_ALPHA_DOT = "Requires: java-1.";
+ private static final String NON_ALPHA_PLUS = "Requires: libstdc+";
+
+ private SpecfileEditor initEditor(String contents) throws Exception {
+ newFile(contents);
+ IEditorPart openEditor = IDE.openEditor(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage(), testFile);
+
+ return (SpecfileEditor) openEditor;
+ }
+
+ private synchronized void computeCompletionProposals(String specContent,
+ int occurances) throws Exception {
+ SpecfileEditor editor = initEditor(specContent);
+ testProject.refresh();
+ // This is needed so the changes in the testFile are loaded in the
+ // editor
+ editor.doRevertToSaved();
+ SpecfileCompletionProcessor complProcessor = new SpecfileCompletionProcessor(
+ editor);
+ assertNotNull(complProcessor);
+ editor.getSpecfileSourceViewer().setSelectedRange(0, 0);
+ ICompletionProposal[] proposals = complProcessor
+ .computeCompletionProposals(editor.getSpecfileSourceViewer(), 0);
+ int sourceComplCount = 0;
+ for (ICompletionProposal proposal : proposals) {
+ if (proposal.getDisplayString().startsWith("%{SOURCE")) {
+ ++sourceComplCount;
+ }
+ }
+ assertEquals(occurances, sourceComplCount);
+ }
+
+ @Test
+ public void testComputeComplProposalsOneSource() throws Exception {
+ computeCompletionProposals(ONE_SOURCE, 1);
+ }
+
+ @Test
+ public void testComputeComplProposalsNoSource() throws Exception {
+ computeCompletionProposals(NO_SOURCE, 0);
+ }
+
+ @Test
+ public void testComputeComplProposalsThreeSourceSeparated()
+ throws Exception {
+ computeCompletionProposals(THREE_SOURCE_SEPARATED, 3);
+ }
+
+ @Test
+ public void testBRCompletionOrder() throws Exception {
+ setPackageList(new String[]{"package3", "package2", "package4", "package1"});
+ SpecfileEditor editor = initEditor(BUILD_REQUIRES);
+ testProject.refresh();
+ editor.doRevertToSaved();
+
+ editor.getSpecfileSourceViewer().setSelectedRange(BUILD_REQUIRES.length(), 0);
+ SpecfileCompletionProcessor processor = new SpecfileCompletionProcessor(
+ editor);
+
+ ICompletionProposal[] proposals = processor.computeCompletionProposals(
+ editor.getSpecfileSourceViewer(), BUILD_REQUIRES.length());
+
+ assertTrue("Cannot perform test; not enough proposals", proposals.length > 1);
+
+ ICompletionProposal previous = proposals[0];
+
+ for (int i = 1; i < proposals.length; i++){
+ ICompletionProposal current = proposals[i];
+ assertTrue("Proposals are not in alphabetical order",
+ previous.getDisplayString().compareToIgnoreCase (current.getDisplayString()) < 0);
+ previous = current;
+ }
+
+ }
+
+ @Test
+ public void testBRCompletionNonAlphaDot() throws Exception {
+ setPackageList(new String[]{"java-1.5.0-gcj", "java-1.7.0-openjdk", "java-1.7.0-openjdk-devel", "java-1.7.0-openjdk-javadoc"});
+ SpecfileEditor editor = initEditor(NON_ALPHA_DOT);
+ testProject.refresh();
+ // This is needed so the changes in the testFile are loaded in the
+ // editor
+ editor.doRevertToSaved();
+ SpecfileCompletionProcessor complProcessor = new SpecfileCompletionProcessor(
+ editor);
+ assertNotNull(complProcessor);
+ editor.getSpecfileSourceViewer().setSelectedRange(NON_ALPHA_DOT.length(), 0);
+ ICompletionProposal[] proposals = complProcessor
+ .computeCompletionProposals(editor.getSpecfileSourceViewer(), NON_ALPHA_DOT.length());
+ int sourceComplCount = 0;
+ for (ICompletionProposal proposal : proposals) {
+ if (proposal.getDisplayString().startsWith("java-1.")) {
+ ++sourceComplCount;
+ }
+ }
+ assertEquals(4, sourceComplCount);
+ }
+
+ @Test
+ public void testBRCompletionNonAlphaPlus() throws Exception {
+ setPackageList(new String[]{"libstdc++", "libstdc++-devel"});
+ SpecfileEditor editor = initEditor(NON_ALPHA_PLUS);
+ testProject.refresh();
+ // This is needed so the changes in the testFile are loaded in the
+ // editor
+ editor.doRevertToSaved();
+ SpecfileCompletionProcessor complProcessor = new SpecfileCompletionProcessor(
+ editor);
+ assertNotNull(complProcessor);
+ editor.getSpecfileSourceViewer().setSelectedRange(NON_ALPHA_PLUS.length(), 0);
+ ICompletionProposal[] proposals = complProcessor
+ .computeCompletionProposals(editor.getSpecfileSourceViewer(), NON_ALPHA_PLUS.length());
+ int sourceComplCount = 0;
+ for (ICompletionProposal proposal : proposals) {
+ if (proposal.getDisplayString().startsWith("libstdc+")) {
+ ++sourceComplCount;
+ }
+ }
+ assertEquals(2, sourceComplCount);
+ }
+
+ /**
+ * Set the potential rpm package list to the given list. Useful for
+ * testing package proposals.
+ * @param packages
+ */
+ private void setPackageList(String[] packages) {
+ ScopedPreferenceStore prefStore = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
+ prefStore.setValue(PreferenceConstants.P_RPM_LIST_FILEPATH,
+ "/tmp/pkglist1");
+ prefStore.setValue(PreferenceConstants.P_RPM_LIST_BACKGROUND_BUILD,
+ false);
+
+ try (BufferedWriter out = new BufferedWriter(new FileWriter(
+ "/tmp/pkglist1"))) {
+ for (String packageName : packages){
+ out.write(packageName + "\n");
+ }
+ } catch (IOException e) {
+ fail(e.getMessage());
+ }
+ Activator.packagesList = null;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileTestFailure.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileTestFailure.java
index 8df9e3a716..8436b6c646 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileTestFailure.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileTestFailure.java
@@ -13,20 +13,20 @@ import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
public class SpecfileTestFailure {
-
- private Position position;
- private Annotation annotation;
-
- public SpecfileTestFailure(Annotation annotation, Position position) {
- this.annotation = annotation;
- this.position = position;
- }
- public Annotation getAnnotation() {
- return annotation;
- }
-
- public Position getPosition() {
- return position;
- }
+ private Position position;
+ private Annotation annotation;
+
+ public SpecfileTestFailure(Annotation annotation, Position position) {
+ this.annotation = annotation;
+ this.position = position;
+ }
+
+ public Annotation getAnnotation() {
+ return annotation;
+ }
+
+ public Position getPosition() {
+ return position;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileTestProject.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileTestProject.java
index 0d71153a4e..cfc144f218 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileTestProject.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/SpecfileTestProject.java
@@ -23,41 +23,41 @@ import org.eclipse.core.runtime.CoreException;
import org.eclipse.linuxtools.rpm.core.utils.Utils;
public class SpecfileTestProject {
- private IProject project;
-
- public SpecfileTestProject() throws CoreException {
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- project = workspaceRoot.getProject("TestSpecfileProject");
- if (!project.exists()) {
- project.create(null);
- }
- project.open(null);
- }
-
- public void dispose() throws CoreException {
- project.delete(true, true, null);
- try {
- Utils.runCommandToInputStream("rm", "-f", "/tmp/pkglist");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- public IFile createFile(String filename) throws CoreException {
- IFile testSpecfile = project.getFile(filename);
- if (!testSpecfile.exists()) {
- testSpecfile.create(null, true, null);
- }
- return testSpecfile;
- }
-
- protected IMarker[] getFailureMarkers() throws CoreException {
- return project.findMarkers(
- "org.eclipse.linuxtools.rpm.ui.editor.specfileerror", false,
- IResource.DEPTH_INFINITE);
- }
-
- public void refresh() throws CoreException {
- project.refreshLocal(IResource.DEPTH_INFINITE, null);
- }
+ private IProject project;
+
+ public SpecfileTestProject() throws CoreException {
+ IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
+ project = workspaceRoot.getProject("TestSpecfileProject");
+ if (!project.exists()) {
+ project.create(null);
+ }
+ project.open(null);
+ }
+
+ public void dispose() throws CoreException {
+ project.delete(true, true, null);
+ try {
+ Utils.runCommandToInputStream("rm", "-f", "/tmp/pkglist");
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public IFile createFile(String filename) throws CoreException {
+ IFile testSpecfile = project.getFile(filename);
+ if (!testSpecfile.exists()) {
+ testSpecfile.create(null, true, null);
+ }
+ return testSpecfile;
+ }
+
+ protected IMarker[] getFailureMarkers() throws CoreException {
+ return project.findMarkers(
+ "org.eclipse.linuxtools.rpm.ui.editor.specfileerror", false,
+ IResource.DEPTH_INFINITE);
+ }
+
+ public void refresh() throws CoreException {
+ project.refreshLocal(IResource.DEPTH_INFINITE, null);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/VersionTagTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/VersionTagTest.java
index a948b1f41c..977f87f666 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/VersionTagTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/VersionTagTest.java
@@ -16,75 +16,75 @@ import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class VersionTagTest extends FileTestCase {
- @Test
- public void testResolvedSetVersion() {
- String testText = "%define blah notblah\nVersion: %{blah}";
- newFile(testText);
- assertEquals("notblah", specfile.getVersion());
- }
-
- @Test
- public void testVersionTag() {
- String testText = "Version: blah";
- newFile(testText);
- assertEquals("blah", specfile.getVersion());
- }
-
- @Test
- public void testVersionTag2() {
- String testText = "Version: blah";
- newFile(testText);
- assertEquals("blah", specfile.getVersion());
- }
-
- @Test
- public void testNullVersionTag() {
- String testText = "Version: ";
- newFile(testText);
-
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Version declaration without value.", failure
- .getAnnotation().getText());
- }
-
- @Test
- public void testNullVersionTag2() {
- String testText = "Version: ";
-
- newFile(testText);
-
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Version declaration without value.", failure
- .getAnnotation().getText());
- }
-
- @Test
- public void testMultipleVersionsTag() {
- String testText = "Version: blah bleh";
- newFile(testText);
-
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Version cannot have multiple values.", failure
- .getAnnotation().getText());
- }
-
- @Test
- public void testMultipleVersionsTag2() {
- String testText = "Version: blah bleh";
-
- newFile(testText);
-
- SpecfileTestFailure failure = getFailures().get(0);
- assertEquals(0, failure.getPosition().getOffset());
- assertEquals(testText.length(), failure.getPosition().getLength());
- assertEquals("Version cannot have multiple values.", failure
- .getAnnotation().getText());
- }
+ @Test
+ public void testResolvedSetVersion() {
+ String testText = "%define blah notblah\nVersion: %{blah}";
+ newFile(testText);
+ assertEquals("notblah", specfile.getVersion());
+ }
+
+ @Test
+ public void testVersionTag() {
+ String testText = "Version: blah";
+ newFile(testText);
+ assertEquals("blah", specfile.getVersion());
+ }
+
+ @Test
+ public void testVersionTag2() {
+ String testText = "Version: blah";
+ newFile(testText);
+ assertEquals("blah", specfile.getVersion());
+ }
+
+ @Test
+ public void testNullVersionTag() {
+ String testText = "Version: ";
+ newFile(testText);
+
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Version declaration without value.", failure
+ .getAnnotation().getText());
+ }
+
+ @Test
+ public void testNullVersionTag2() {
+ String testText = "Version: ";
+
+ newFile(testText);
+
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Version declaration without value.", failure
+ .getAnnotation().getText());
+ }
+
+ @Test
+ public void testMultipleVersionsTag() {
+ String testText = "Version: blah bleh";
+ newFile(testText);
+
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Version cannot have multiple values.", failure
+ .getAnnotation().getText());
+ }
+
+ @Test
+ public void testMultipleVersionsTag2() {
+ String testText = "Version: blah bleh";
+
+ newFile(testText);
+
+ SpecfileTestFailure failure = getFailures().get(0);
+ assertEquals(0, failure.getPosition().getOffset());
+ assertEquals(testText.length(), failure.getPosition().getLength());
+ assertEquals("Version cannot have multiple values.", failure
+ .getAnnotation().getText());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/ParserAllTests.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/ParserAllTests.java
index fbea64cb5f..79d7869093 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/ParserAllTests.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/ParserAllTests.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -15,6 +15,6 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ SourceComparatorTest.class, SpecfileDefineTest.class,
- SpecfileTest.class })
+ SpecfileTest.class })
public class ParserAllTests {
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SourceComparatorTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SourceComparatorTest.java
index b34ded6ecd..b04d575b8b 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SourceComparatorTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SourceComparatorTest.java
@@ -23,34 +23,34 @@ import org.junit.Test;
public class SourceComparatorTest extends FileTestCase {
- @Test
- public void testPatchComparator() {
- String specText = "Patch3: somefilesomewhere.patch" + "\n"
- + "Patch2: someotherfile.patch";
-
- newFile(specText);
- Collection<SpecfileSource> patches = specfile.getPatches();
- int i = 1;
- for (SpecfileSource patch : patches) {
- i++;
- if (i == 2) {
- assertEquals(2, patch.getNumber());
- } else if (i == 3) {
- assertEquals(3, patch.getNumber());
- } else {
- fail();
- }
- }
- }
-
- @Test
- public void testPatchComparator2() {
- String specText = "Patch3: somefilesomewhere.patch" + "\n"
- + "Patch2: someotherfile.patch";
-
- newFile(specText);
- List<SpecfileSource> patches = specfile.getPatches();
- assertEquals(2, patches.get(0).getNumber());
- assertEquals(3, patches.get(1).getNumber());
- }
+ @Test
+ public void testPatchComparator() {
+ String specText = "Patch3: somefilesomewhere.patch" + "\n"
+ + "Patch2: someotherfile.patch";
+
+ newFile(specText);
+ Collection<SpecfileSource> patches = specfile.getPatches();
+ int i = 1;
+ for (SpecfileSource patch : patches) {
+ i++;
+ if (i == 2) {
+ assertEquals(2, patch.getNumber());
+ } else if (i == 3) {
+ assertEquals(3, patch.getNumber());
+ } else {
+ fail();
+ }
+ }
+ }
+
+ @Test
+ public void testPatchComparator2() {
+ String specText = "Patch3: somefilesomewhere.patch" + "\n"
+ + "Patch2: someotherfile.patch";
+
+ newFile(specText);
+ List<SpecfileSource> patches = specfile.getPatches();
+ assertEquals(2, patches.get(0).getNumber());
+ assertEquals(3, patches.get(1).getNumber());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SpecfileDefineTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SpecfileDefineTest.java
index f0fdd939af..099cf5d21c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SpecfileDefineTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SpecfileDefineTest.java
@@ -27,132 +27,132 @@ import org.junit.Test;
public class SpecfileDefineTest extends FileTestCase {
- private String testSpec =
- // Characters 0 through 17
- "%define blah bleh" + "\n" +
- // Characters 18 through 36
- "%define blah2 bleh" + "\n" +
- // Characters 37 through 52
- "%define blah3 1" + "\n" +
- // Characters 53 through 69
- "%define blah4 1" + "\n" +
- // Characters 70 through 83
- "%define blah5" + "\n" +
- // Characters 84 through 95
- "%define 1 2" + "\n" +
- // Characters 96 through 109
- "%define -n -p" + "\n" +
- // Characters 110 through 144
- "%define __find_requires %{SOURCE3}" + "\n" +
- // Characters 145 through 180
- "%global version_suffix 201302130906" + "\n" +
- // Characters 181 through 195
- "Version: 2.3.0" + "\n";
-
- @Override
- @Before
- public void setUp() throws CoreException {
- super.setUp();
- newFile(testSpec);
- specfile = parser.parse(testDocument);
- }
-
- @Test
- public void testResolve() {
- SpecfileDefine define1 = new SpecfileDefine("name", "testspec",
- specfile, specfile.getPackages().getPackage(specfile.getName()));
- specfile.addDefine(define1);
- assertEquals("testspec", ((SpecfileElement) define1).resolve("%{name}"));
- }
-
- @Test
- public void testDefine() {
- SpecfileDefine blahDefine = specfile.getDefine("blah");
- assertEquals(SpecfileDefine.class, blahDefine.getClass());
- assertEquals("blah", blahDefine.getName());
- assertEquals("bleh", blahDefine.getStringValue());
- }
-
- @Test
- public void testDefine2() {
- SpecfileDefine blahDefine = specfile.getDefine("blah2");
- assertEquals(SpecfileDefine.class, blahDefine.getClass());
- assertEquals("blah2", blahDefine.getName());
- assertEquals("bleh", blahDefine.getStringValue());
- }
-
- @Test
- public void testDefine3() {
- SpecfileDefine blahDefine = specfile.getDefine("blah3");
- assertEquals(SpecfileDefine.class, blahDefine.getClass());
- assertEquals("blah3", blahDefine.getName());
- assertEquals(1, blahDefine.getIntValue());
- }
-
- @Test
- public void testDefine4() {
- SpecfileDefine blahDefine = specfile.getDefine("blah4");
- assertEquals(SpecfileDefine.class, blahDefine.getClass());
- assertEquals("blah4", blahDefine.getName());
- assertEquals(1, blahDefine.getIntValue());
- }
-
- @Test
- public void testNonLetterDefinitionName() {
- boolean fail = true;
- for (SpecfileTestFailure failure : getFailures()) {
- if ((failure.getPosition().getOffset() == 84)
- && (failure.getPosition().getLength() == 11)) {
- assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR,
- failure.getAnnotation().getType());
- assertEquals(
- "Definition lvalue must begin with a letter or an underscore.",
- failure.getAnnotation().getText());
- fail = false;
- }
- }
- if (fail) {
- fail();
- }
- }
- @Test
- public void testNonLetterDefinitionName2() {
- boolean fail = true;
- for (SpecfileTestFailure failure : getFailures()) {
- if ((failure.getPosition().getOffset() == 96)
- && (failure.getPosition().getLength() == 13)) {
- assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR,
- failure.getAnnotation().getType());
- assertEquals(
- "Definition lvalue must begin with a letter or an underscore.",
- failure.getAnnotation().getText());
- fail = false;
- }
- }
- if (fail) {
- fail();
- }
- }
-
- @Test
- public void testUnderscoreDefine() {
- SpecfileDefine blahDefine = specfile.getDefine("__find_requires");
- assertEquals(SpecfileDefine.class, blahDefine.getClass());
- assertEquals("__find_requires", blahDefine.getName());
- assertEquals("%{SOURCE3}", blahDefine.getStringValue());
- }
-
- @Test
- public void testWholeWordResolveDefine() {
- String testResolve = UiUtils.resolveDefines(specfile, "%{version}.%{version_suffix}");
- assertEquals(testResolve, "2.3.0.201302130906");
- }
-
- @Test
- public void testResolveSCLMacro() throws CoreException {
- String specText = "Name: %{?scl_prefix}eclipse-jgit" + "\n" + "%{name}";
- newFile(specText);
- assertEquals("eclipse-jgit", RPMQuery.eval(specfile.getName()).trim());
- }
+ private String testSpec =
+ // Characters 0 through 17
+ "%define blah bleh" + "\n" +
+ // Characters 18 through 36
+ "%define blah2\tbleh\n" +
+ // Characters 37 through 52
+ "%define blah3\t1\n" +
+ // Characters 53 through 69
+ "%define blah4\t\t1\n" +
+ // Characters 70 through 83
+ "%define blah5" + "\n" +
+ // Characters 84 through 95
+ "%define 1 2" + "\n" +
+ // Characters 96 through 109
+ "%define -n -p" + "\n" +
+ // Characters 110 through 144
+ "%define __find_requires %{SOURCE3}" + "\n" +
+ // Characters 145 through 180
+ "%global version_suffix 201302130906" + "\n" +
+ // Characters 181 through 195
+ "Version: 2.3.0" + "\n";
+
+ @Override
+ @Before
+ public void setUp() throws CoreException {
+ super.setUp();
+ newFile(testSpec);
+ specfile = parser.parse(testDocument);
+ }
+
+ @Test
+ public void testResolve() {
+ SpecfileDefine define1 = new SpecfileDefine("name", "testspec",
+ specfile, specfile.getPackages().getPackage(specfile.getName()));
+ specfile.addDefine(define1);
+ assertEquals("testspec", ((SpecfileElement) define1).resolve("%{name}"));
+ }
+
+ @Test
+ public void testDefine() {
+ SpecfileDefine blahDefine = specfile.getDefine("blah");
+ assertEquals(SpecfileDefine.class, blahDefine.getClass());
+ assertEquals("blah", blahDefine.getName());
+ assertEquals("bleh", blahDefine.getStringValue());
+ }
+
+ @Test
+ public void testDefine2() {
+ SpecfileDefine blahDefine = specfile.getDefine("blah2");
+ assertEquals(SpecfileDefine.class, blahDefine.getClass());
+ assertEquals("blah2", blahDefine.getName());
+ assertEquals("bleh", blahDefine.getStringValue());
+ }
+
+ @Test
+ public void testDefine3() {
+ SpecfileDefine blahDefine = specfile.getDefine("blah3");
+ assertEquals(SpecfileDefine.class, blahDefine.getClass());
+ assertEquals("blah3", blahDefine.getName());
+ assertEquals(1, blahDefine.getIntValue());
+ }
+
+ @Test
+ public void testDefine4() {
+ SpecfileDefine blahDefine = specfile.getDefine("blah4");
+ assertEquals(SpecfileDefine.class, blahDefine.getClass());
+ assertEquals("blah4", blahDefine.getName());
+ assertEquals(1, blahDefine.getIntValue());
+ }
+
+ @Test
+ public void testNonLetterDefinitionName() {
+ boolean fail = true;
+ for (SpecfileTestFailure failure : getFailures()) {
+ if ((failure.getPosition().getOffset() == 84)
+ && (failure.getPosition().getLength() == 11)) {
+ assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR,
+ failure.getAnnotation().getType());
+ assertEquals(
+ "Definition lvalue must begin with a letter or an underscore.",
+ failure.getAnnotation().getText());
+ fail = false;
+ }
+ }
+ if (fail) {
+ fail();
+ }
+ }
+ @Test
+ public void testNonLetterDefinitionName2() {
+ boolean fail = true;
+ for (SpecfileTestFailure failure : getFailures()) {
+ if ((failure.getPosition().getOffset() == 96)
+ && (failure.getPosition().getLength() == 13)) {
+ assertEquals(SpecfileErrorHandler.ANNOTATION_ERROR,
+ failure.getAnnotation().getType());
+ assertEquals(
+ "Definition lvalue must begin with a letter or an underscore.",
+ failure.getAnnotation().getText());
+ fail = false;
+ }
+ }
+ if (fail) {
+ fail();
+ }
+ }
+
+ @Test
+ public void testUnderscoreDefine() {
+ SpecfileDefine blahDefine = specfile.getDefine("__find_requires");
+ assertEquals(SpecfileDefine.class, blahDefine.getClass());
+ assertEquals("__find_requires", blahDefine.getName());
+ assertEquals("%{SOURCE3}", blahDefine.getStringValue());
+ }
+
+ @Test
+ public void testWholeWordResolveDefine() {
+ String testResolve = UiUtils.resolveDefines(specfile, "%{version}.%{version_suffix}");
+ assertEquals(testResolve, "2.3.0.201302130906");
+ }
+
+ @Test
+ public void testResolveSCLMacro() throws CoreException {
+ String specText = "Name: %{?scl_prefix}eclipse-jgit" + "\n" + "%{name}";
+ newFile(specText);
+ assertEquals("eclipse-jgit", RPMQuery.eval(specfile.getName()).trim());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SpecfileTest.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SpecfileTest.java
index 396a1520da..b18d82c82f 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SpecfileTest.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor.tests/src/org/eclipse/linuxtools/rpm/ui/editor/tests/parser/SpecfileTest.java
@@ -22,60 +22,60 @@ import org.eclipse.linuxtools.rpm.ui.editor.tests.FileTestCase;
import org.junit.Test;
public class SpecfileTest extends FileTestCase {
- @Test
- public void testGetLine() throws BadLocationException {
- String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
- newFile(specText);
- assertEquals("%patch3", specfile.getLine(1));
- }
- @Test
- public void testChangeLine() throws BadLocationException {
- String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
- newFile(specText);
- assertEquals("%patch3", specfile.getLine(1));
- specfile.changeLine(1, "%patch4");
- assertEquals("%patch4", specfile.getLine(1));
- }
- @Test
- public void testChangeLine2() throws BadLocationException {
- String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
- newFile(specText);
- assertEquals("Patch3: somefilesomewhere.patch", specfile.getLine(0));
- specfile.changeLine(0, "Patch4: somefilesomewhere.patch");
- assertEquals("Patch4: somefilesomewhere.patch", specfile.getLine(0));
- }
- @Test
- public void testChangeLine3() throws BadLocationException {
- String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
- newFile(specText);
- assertEquals("Patch3: somefilesomewhere.patch", specfile.getLine(0));
- specfile.changeLine(0, "andrew");
- assertEquals("andrew", specfile.getLine(0));
- }
- @Test
- public void testOrganizePatches() throws BadLocationException {
- String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
- newFile(specText);
- assertEquals("Patch3: somefilesomewhere.patch", specfile.getLine(0));
- assertEquals("%patch3", specfile.getLine(1));
- assertEquals(0, specfile.getPatch(3).getLineNumber());
- SpecfileSource patch = specfile.getPatch(3);
- List<Integer> linesUsed = patch.getLinesUsed();
- assertEquals(1, linesUsed.size());
- Integer lineUsedNumber = linesUsed.get(0);
- assertEquals(1, lineUsedNumber.intValue());
- specfile.organizePatches();
- assertEquals("Patch0: somefilesomewhere.patch", specfile.getLine(0));
- assertEquals("%patch0", specfile.getLine(1));
- assertEquals(0, specfile.getPatch(0).getLineNumber());
- patch = specfile.getPatch(3);
- assertNull(patch);
- patch = specfile.getPatch(0);
- assertEquals(0, patch.getNumber());
- linesUsed = patch.getLinesUsed();
- assertEquals(1, linesUsed.size());
- lineUsedNumber = linesUsed.get(0);
- assertEquals(1, lineUsedNumber.intValue());
- }
+ @Test
+ public void testGetLine() throws BadLocationException {
+ String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
+ newFile(specText);
+ assertEquals("%patch3", specfile.getLine(1));
+ }
+ @Test
+ public void testChangeLine() throws BadLocationException {
+ String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
+ newFile(specText);
+ assertEquals("%patch3", specfile.getLine(1));
+ specfile.changeLine(1, "%patch4");
+ assertEquals("%patch4", specfile.getLine(1));
+ }
+ @Test
+ public void testChangeLine2() throws BadLocationException {
+ String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
+ newFile(specText);
+ assertEquals("Patch3: somefilesomewhere.patch", specfile.getLine(0));
+ specfile.changeLine(0, "Patch4: somefilesomewhere.patch");
+ assertEquals("Patch4: somefilesomewhere.patch", specfile.getLine(0));
+ }
+ @Test
+ public void testChangeLine3() throws BadLocationException {
+ String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
+ newFile(specText);
+ assertEquals("Patch3: somefilesomewhere.patch", specfile.getLine(0));
+ specfile.changeLine(0, "andrew");
+ assertEquals("andrew", specfile.getLine(0));
+ }
+ @Test
+ public void testOrganizePatches() throws BadLocationException {
+ String specText = "Patch3: somefilesomewhere.patch" + "\n" + "%patch3";
+ newFile(specText);
+ assertEquals("Patch3: somefilesomewhere.patch", specfile.getLine(0));
+ assertEquals("%patch3", specfile.getLine(1));
+ assertEquals(0, specfile.getPatch(3).getLineNumber());
+ SpecfileSource patch = specfile.getPatch(3);
+ List<Integer> linesUsed = patch.getLinesUsed();
+ assertEquals(1, linesUsed.size());
+ Integer lineUsedNumber = linesUsed.get(0);
+ assertEquals(1, lineUsedNumber.intValue());
+ specfile.organizePatches();
+ assertEquals("Patch0: somefilesomewhere.patch", specfile.getLine(0));
+ assertEquals("%patch0", specfile.getLine(1));
+ assertEquals(0, specfile.getPatch(0).getLineNumber());
+ patch = specfile.getPatch(3);
+ assertNull(patch);
+ patch = specfile.getPatch(0);
+ assertEquals(0, patch.getNumber());
+ linesUsed = patch.getLinesUsed();
+ assertEquals(1, linesUsed.size());
+ lineUsedNumber = linesUsed.get(0);
+ assertEquals(1, lineUsedNumber.intValue());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/plugin.xml b/rpm/org.eclipse.linuxtools.rpm.ui.editor/plugin.xml
index 1b90a0d0ef..2cd2c70860 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/plugin.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/plugin.xml
@@ -5,7 +5,7 @@
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-
+
Contributors:
Red Hat - initial API and implementation
-->
@@ -19,7 +19,7 @@
parentId="org.eclipse.ui.textEditorScope">
</context>
</extension>
-
+
<extension
point="org.eclipse.ui.editors">
<editor
@@ -39,12 +39,12 @@
id="org.eclipse.linuxtools.rpm.ui.editor.forms.SpecfileFormEditor">
</editor>
</extension>
-
- <!-- Hyperlink targets and detectors -->
- <extension
- point="org.eclipse.ui.workbench.texteditor.hyperlinkDetectorTargets">
-<target id="org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditorTarget"
- name="RPM Editor Target">
+
+ <!-- Hyperlink targets and detectors -->
+ <extension
+ point="org.eclipse.ui.workbench.texteditor.hyperlinkDetectorTargets">
+<target id="org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditorTarget"
+ name="RPM Editor Target">
<context type="org.eclipse.ui.texteditor.ITextEditor"/>
</target>
</extension>
@@ -77,20 +77,20 @@
</extension>
<extension
- id="specfileerror"
- point="org.eclipse.core.resources.markers"
- name="%extension.name">
- <super type="org.eclipse.core.resources.problemmarker"/>
- <super type="org.eclipse.core.resources.textmarker"/>
- <persistent value="true"/>
- </extension>
- <extension
- id="specfiletask"
- point="org.eclipse.core.resources.markers"
- name="%extension.name.0">
- <super type="org.eclipse.core.resources.taskmarker"/>
- <persistent value="true"/>
- </extension>
+ id="specfileerror"
+ point="org.eclipse.core.resources.markers"
+ name="%extension.name">
+ <super type="org.eclipse.core.resources.problemmarker"/>
+ <super type="org.eclipse.core.resources.textmarker"/>
+ <persistent value="true"/>
+ </extension>
+ <extension
+ id="specfiletask"
+ point="org.eclipse.core.resources.markers"
+ name="%extension.name.0">
+ <super type="org.eclipse.core.resources.taskmarker"/>
+ <persistent value="true"/>
+ </extension>
<extension
point="org.eclipse.ui.editors.documentProviders">
<provider
@@ -116,7 +116,7 @@
<filePattern pattern=".*\.spec"/>
</formatter>
</extension>
-
+
<extension
point="org.eclipse.ui.editors.templates">
<contextType
@@ -187,7 +187,7 @@
<!--markerSeverity="0"-->
</type>
</extension>
-
+
<extension
point="org.eclipse.ui.editors.markerAnnotationSpecification">
<specification
@@ -239,7 +239,7 @@
name="%command.name.0"
id="rpmEditor.organizePatches.command"/>
<command
- categoryId="rpmEditor.category"
+ categoryId="rpmEditor.category"
id="rpmEditor.showOutline.command"
name="%command.name.1"/>
<command
@@ -254,15 +254,15 @@
</command>
</extension>
<extension point="org.eclipse.ui.handlers">
- <handler
- class="org.eclipse.linuxtools.internal.rpm.ui.editor.actions.SpecfileEditorToggleCommentActionDelegate"
- commandId="rpmEditor.toggleComment.command" />
- <handler
- class="org.eclipse.linuxtools.internal.rpm.ui.editor.actions.SpecfileEditorOrganizePatchesActionDelegate"
- commandId="rpmEditor.organizePatches.command" />
- <handler
- class="org.eclipse.linuxtools.internal.rpm.ui.editor.actions.SpecfileEditorShowOutlineActionDelegate"
- commandId="rpmEditor.showOutline.command" />
+ <handler
+ class="org.eclipse.linuxtools.internal.rpm.ui.editor.actions.SpecfileEditorToggleCommentActionDelegate"
+ commandId="rpmEditor.toggleComment.command" />
+ <handler
+ class="org.eclipse.linuxtools.internal.rpm.ui.editor.actions.SpecfileEditorOrganizePatchesActionDelegate"
+ commandId="rpmEditor.organizePatches.command" />
+ <handler
+ class="org.eclipse.linuxtools.internal.rpm.ui.editor.actions.SpecfileEditorShowOutlineActionDelegate"
+ commandId="rpmEditor.showOutline.command" />
<handler
class="org.eclipse.linuxtools.internal.rpm.ui.editor.actions.SpecfileEditorDownloadSourcesActionDelegate"
commandId="rpmEditor.downloadSources.command">
@@ -286,7 +286,7 @@
contextId="org.eclipse.linuxtools.rpm.ui.specEditorScope"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"/>
<key
- sequence="Ctrl+O"
+ sequence="Ctrl+O"
commandId="rpmEditor.showOutline.command"
contextId="org.eclipse.linuxtools.rpm.ui.specEditorScope"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"/>
@@ -425,21 +425,21 @@
</extension>
<!-- Compare support-->
<extension point="org.eclipse.compare.contentMergeViewers">
- <viewer
- id="org.eclipse.linuxtools.rpm.ui.editor.SpecMergeViewer"
- extensions="spec,spec2"
- class="org.eclipse.linuxtools.internal.rpm.ui.editor.compare.SpecMergeViewerCreator">
- </viewer>
+ <viewer
+ id="org.eclipse.linuxtools.rpm.ui.editor.SpecMergeViewer"
+ extensions="spec,spec2"
+ class="org.eclipse.linuxtools.internal.rpm.ui.editor.compare.SpecMergeViewerCreator">
+ </viewer>
</extension>
<extension point="org.eclipse.compare.structureMergeViewers">
- <viewer
- id="org.eclipse.linuxtools.rpm.ui.editor.SpecStructureMergeViewer"
- extensions="spec"
- class="org.eclipse.linuxtools.internal.rpm.ui.editor.compare.SpecStructureMergeViewerCreator">
- </viewer>
+ <viewer
+ id="org.eclipse.linuxtools.rpm.ui.editor.SpecStructureMergeViewer"
+ extensions="spec"
+ class="org.eclipse.linuxtools.internal.rpm.ui.editor.compare.SpecStructureMergeViewerCreator">
+ </viewer>
</extension>
<extension point ="org.eclipse.compare.structureCreators">
- <structureCreator id="org.eclipse.linuxtools.rpm.ui.editor.SpecStructureCreator"
- class="org.eclipse.linuxtools.internal.rpm.ui.editor.compare.SpecStructureCreator" extensions="spec"/>
+ <structureCreator id="org.eclipse.linuxtools.rpm.ui.editor.SpecStructureCreator"
+ class="org.eclipse.linuxtools.internal.rpm.ui.editor.compare.SpecStructureCreator" extensions="spec"/>
</extension>
</plugin>
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/Activator.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/Activator.java
index 409326b5ca..80c4c61002 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/Activator.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/Activator.java
@@ -35,166 +35,166 @@ import org.osgi.framework.BundleContext;
*/
public class Activator extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.rpm.ui.editor"; //$NON-NLS-1$
-
- // The shared instance
- private static Activator plugin;
-
- private ContributionTemplateStore fTemplateStore;
- private ContributionContextTypeRegistry fContextTypeRegistry;
-
- // RPM macros list
- private RpmMacroProposalsList macrosList ;
-
- // RPM Groups
- private List<String> rpmGroups = new ArrayList<>() ;
-
- // RPM package list
- public static RpmPackageProposalsList packagesList ;
-
- /**
- * The constructor
- */
- public Activator() {
- super();
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- RpmPackageBuildProposalsJob.setPropertyChangeListener(true);
- RpmPackageBuildProposalsJob.update();
- // Do some sanity checks.
- UiUtils.pluginSanityCheck();
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- RpmPackageBuildProposalsJob.setPropertyChangeListener(false);
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
-
- public TemplateStore getTemplateStore() {
- if (fTemplateStore == null) {
- fTemplateStore= new ContributionTemplateStore(getContextTypeRegistry(), getPreferenceStore(), "templates"); //$NON-NLS-1$
- try {
- fTemplateStore.load();
- } catch (IOException e) {
- SpecfileLog.logError(e);
- }
- }
-
- return fTemplateStore;
- }
-
- public RpmMacroProposalsList getRpmMacroList() {
- macrosList = new RpmMacroProposalsList();
- return macrosList;
- }
-
-
- public RpmPackageProposalsList getRpmPackageList() {
- if (packagesList == null){
- packagesList = new RpmPackageProposalsList();
- } else if (packagesList.getProposals("").size() == 0) { //$NON-NLS-1$
- packagesList = new RpmPackageProposalsList();
- }
- return packagesList;
- }
-
- public List<String> getRpmGroups() {
- if (rpmGroups.isEmpty()) {
- // FIXME: Can we assume that all distros place
- // documentations files in the below path?
- String docDir = "/usr/share/doc/"; //$NON-NLS-1$
- File dir = new File(docDir);
- if (dir.exists()) {
- File files[] = dir.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return name.startsWith("rpm-"); //$NON-NLS-1$
- }
- });
- try {
- // We can not be sure that there is only one directory here
- // starting with rpm-
- // (e.g. rpm-apidocs is the wrong directory.)
- for (File file : files) {
- File groupsFile = new File(file, "GROUPS"); //$NON-NLS-1$
- if (groupsFile.exists()) {
-
- LineNumberReader reader = null;
- try {
- reader = new LineNumberReader(new FileReader(
- groupsFile));
- String line;
- while ((line = reader.readLine()) != null) {
- rpmGroups.add(line);
- }
- } finally {
- if (reader != null) {
- reader.close();
- }
- }
- break;
- }
- }
- } catch (IOException e) {
- SpecfileLog.logError(e);
- }
- }
- }
- return rpmGroups;
- }
-
- public ContextTypeRegistry getContextTypeRegistry() {
- if (fContextTypeRegistry == null) {
- fContextTypeRegistry = new ContributionContextTypeRegistry();
- fContextTypeRegistry.addContextType("org.eclipse.linuxtools.rpm.ui.editor.preambleSection"); //$NON-NLS-1$
- fContextTypeRegistry.addContextType("org.eclipse.linuxtools.rpm.ui.editor.preSection"); //$NON-NLS-1$
- fContextTypeRegistry.addContextType("org.eclipse.linuxtools.rpm.ui.editor.buildSection"); //$NON-NLS-1$
- fContextTypeRegistry.addContextType("org.eclipse.linuxtools.rpm.ui.editor.installSection"); //$NON-NLS-1$
- fContextTypeRegistry.addContextType("org.eclipse.linuxtools.rpm.ui.editor.changelogSection"); //$NON-NLS-1$
- }
- return fContextTypeRegistry;
- }
-
- /**
- * Get a <code>Image</code> object for the given relative path.
- *
- * @param imageRelativePath The relative path to the image.
- * @return
- * a <code>Image</code>
- */
- public Image getImage(String imageRelativePath) {
- ImageRegistry registry = getImageRegistry();
- Image image = registry.get(imageRelativePath);
- if (image == null) {
- ImageDescriptor desc = AbstractUIPlugin.imageDescriptorFromPlugin(PLUGIN_ID, imageRelativePath);
- registry.put(imageRelativePath, desc);
- image = registry.get(imageRelativePath);
- }
- return image;
- }
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.rpm.ui.editor"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ private ContributionTemplateStore fTemplateStore;
+ private ContributionContextTypeRegistry fContextTypeRegistry;
+
+ // RPM macros list
+ private RpmMacroProposalsList macrosList ;
+
+ // RPM Groups
+ private List<String> rpmGroups = new ArrayList<>() ;
+
+ // RPM package list
+ public static RpmPackageProposalsList packagesList ;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ super();
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ RpmPackageBuildProposalsJob.setPropertyChangeListener(true);
+ RpmPackageBuildProposalsJob.update();
+ // Do some sanity checks.
+ UiUtils.pluginSanityCheck();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ RpmPackageBuildProposalsJob.setPropertyChangeListener(false);
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+ public TemplateStore getTemplateStore() {
+ if (fTemplateStore == null) {
+ fTemplateStore= new ContributionTemplateStore(getContextTypeRegistry(), getPreferenceStore(), "templates"); //$NON-NLS-1$
+ try {
+ fTemplateStore.load();
+ } catch (IOException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+
+ return fTemplateStore;
+ }
+
+ public RpmMacroProposalsList getRpmMacroList() {
+ macrosList = new RpmMacroProposalsList();
+ return macrosList;
+ }
+
+
+ public RpmPackageProposalsList getRpmPackageList() {
+ if (packagesList == null){
+ packagesList = new RpmPackageProposalsList();
+ } else if (packagesList.getProposals("").size() == 0) { //$NON-NLS-1$
+ packagesList = new RpmPackageProposalsList();
+ }
+ return packagesList;
+ }
+
+ public List<String> getRpmGroups() {
+ if (rpmGroups.isEmpty()) {
+ // FIXME: Can we assume that all distros place
+ // documentations files in the below path?
+ String docDir = "/usr/share/doc/"; //$NON-NLS-1$
+ File dir = new File(docDir);
+ if (dir.exists()) {
+ File files[] = dir.listFiles(new FilenameFilter() {
+ @Override
+ public boolean accept(File dir, String name) {
+ return name.startsWith("rpm-"); //$NON-NLS-1$
+ }
+ });
+ try {
+ // We can not be sure that there is only one directory here
+ // starting with rpm-
+ // (e.g. rpm-apidocs is the wrong directory.)
+ for (File file : files) {
+ File groupsFile = new File(file, "GROUPS"); //$NON-NLS-1$
+ if (groupsFile.exists()) {
+
+ LineNumberReader reader = null;
+ try {
+ reader = new LineNumberReader(new FileReader(
+ groupsFile));
+ String line;
+ while ((line = reader.readLine()) != null) {
+ rpmGroups.add(line);
+ }
+ } finally {
+ if (reader != null) {
+ reader.close();
+ }
+ }
+ break;
+ }
+ }
+ } catch (IOException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+ }
+ return rpmGroups;
+ }
+
+ public ContextTypeRegistry getContextTypeRegistry() {
+ if (fContextTypeRegistry == null) {
+ fContextTypeRegistry = new ContributionContextTypeRegistry();
+ fContextTypeRegistry.addContextType("org.eclipse.linuxtools.rpm.ui.editor.preambleSection"); //$NON-NLS-1$
+ fContextTypeRegistry.addContextType("org.eclipse.linuxtools.rpm.ui.editor.preSection"); //$NON-NLS-1$
+ fContextTypeRegistry.addContextType("org.eclipse.linuxtools.rpm.ui.editor.buildSection"); //$NON-NLS-1$
+ fContextTypeRegistry.addContextType("org.eclipse.linuxtools.rpm.ui.editor.installSection"); //$NON-NLS-1$
+ fContextTypeRegistry.addContextType("org.eclipse.linuxtools.rpm.ui.editor.changelogSection"); //$NON-NLS-1$
+ }
+ return fContextTypeRegistry;
+ }
+
+ /**
+ * Get a <code>Image</code> object for the given relative path.
+ *
+ * @param imageRelativePath The relative path to the image.
+ * @return
+ * a <code>Image</code>
+ */
+ public Image getImage(String imageRelativePath) {
+ ImageRegistry registry = getImageRegistry();
+ Image image = registry.get(imageRelativePath);
+ if (image == null) {
+ ImageDescriptor desc = AbstractUIPlugin.imageDescriptorFromPlugin(PLUGIN_ID, imageRelativePath);
+ registry.put(imageRelativePath, desc);
+ image = registry.get(imageRelativePath);
+ }
+ return image;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ColorManager.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ColorManager.java
index 84a1329316..f6def9f72b 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ColorManager.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ColorManager.java
@@ -20,19 +20,19 @@ import org.eclipse.swt.widgets.Display;
public class ColorManager {
- private Map<RGB, Color> fColorTable = new HashMap<>(10);
+ private Map<RGB, Color> fColorTable = new HashMap<>(10);
- public void dispose() {
- for (Map.Entry<RGB, Color> entry:fColorTable.entrySet()){
- entry.getValue().dispose();
- }
- }
- public Color getColor(RGB rgb) {
- Color color = fColorTable.get(rgb);
- if (color == null) {
- color = new Color(Display.getCurrent(), rgb);
- fColorTable.put(rgb, color);
- }
- return color;
- }
+ public void dispose() {
+ for (Map.Entry<RGB, Color> entry:fColorTable.entrySet()){
+ entry.getValue().dispose();
+ }
+ }
+ public Color getColor(RGB rgb) {
+ Color color = fColorTable.get(rgb);
+ if (color == null) {
+ color = new Color(Display.getCurrent(), rgb);
+ fColorTable.put(rgb, color);
+ }
+ return color;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ISpecfileColorConstants.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ISpecfileColorConstants.java
index d94192ca37..ff1166b76d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ISpecfileColorConstants.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ISpecfileColorConstants.java
@@ -14,19 +14,19 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor;
import org.eclipse.swt.graphics.RGB;
public interface ISpecfileColorConstants {
- // general constants
- RGB DEFAULT = new RGB(0, 0, 0);
- RGB SECTIONS = new RGB(128, 0, 0);
- RGB MACROS = new RGB(0, 0, 128);
- RGB KEYWORDS = new RGB(127, 0, 85);
- RGB DEFINES = new RGB(0, 128, 0);
- RGB TAGS = new RGB(255, 101, 52);
- RGB COMMENT = new RGB(63, 95, 191);
- RGB PACKAGES = new RGB(0, 0, 128);
-
- // changelog section specific constants
- RGB AUTHOR_MAIL = new RGB(10, 20, 175);
- RGB VER_REL = new RGB(255, 101, 52);
-
-
+ // general constants
+ RGB DEFAULT = new RGB(0, 0, 0);
+ RGB SECTIONS = new RGB(128, 0, 0);
+ RGB MACROS = new RGB(0, 0, 128);
+ RGB KEYWORDS = new RGB(127, 0, 85);
+ RGB DEFINES = new RGB(0, 128, 0);
+ RGB TAGS = new RGB(255, 101, 52);
+ RGB COMMENT = new RGB(63, 95, 191);
+ RGB PACKAGES = new RGB(0, 0, 128);
+
+ // changelog section specific constants
+ RGB AUTHOR_MAIL = new RGB(10, 20, 175);
+ RGB VER_REL = new RGB(255, 101, 52);
+
+
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ISpecfileSpecialSymbols.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ISpecfileSpecialSymbols.java
index cd619616df..d462aeb295 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ISpecfileSpecialSymbols.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/ISpecfileSpecialSymbols.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -12,25 +12,25 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor;
/**
* Constants for all the special symbols in spec file.
- *
+ *
*/
public interface ISpecfileSpecialSymbols {
- /**
- * Identifier for macro start - long one.
- */
- String MACRO_START_LONG = "%{"; //$NON-NLS-1$
- /**
- * Identifier for macro end - long one.
- */
- String MACRO_END_LONG = "}"; //$NON-NLS-1$
-
- /**
- * Identifier for macro start - short one.
- */
- String MACRO_START_SHORT = "%"; //$NON-NLS-1$
- /**
- * Identifier for comment start. Comment is from this symbol till the line
- * end.
- */
- String COMMENT_START = "#"; //$NON-NLS-1$
+ /**
+ * Identifier for macro start - long one.
+ */
+ String MACRO_START_LONG = "%{"; //$NON-NLS-1$
+ /**
+ * Identifier for macro end - long one.
+ */
+ String MACRO_END_LONG = "}"; //$NON-NLS-1$
+
+ /**
+ * Identifier for macro start - short one.
+ */
+ String MACRO_START_SHORT = "%"; //$NON-NLS-1$
+ /**
+ * Identifier for comment start. Comment is from this symbol till the line
+ * end.
+ */
+ String COMMENT_START = "#"; //$NON-NLS-1$
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/Messages.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/Messages.java
index 55d07b0135..027a3c0704 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/Messages.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -13,28 +13,28 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor;
import org.eclipse.osgi.util.NLS;
public final class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.messages"; //$NON-NLS-1$
- public static String RpmMacroProposalsList_0;
- public static String RpmPackageBuildProposalsJob_0;
- public static String RpmPackageBuildProposalsJob_1;
- public static String RpmPackageBuildProposalsJob_2;
- public static String RpmPackageBuildProposalsJob_3;
- public static String RpmPackageBuildProposalsJob_NonZeroReturn;
- public static String RpmPackageProposalsList_0;
- public static String RpmPackageProposalsList_1;
- public static String RpmPackageProposalsList_2;
- public static String RpmPackageProposalsList_3;
- public static String SpecfileConfiguration_0;
- public static String SpecfileEditor_0;
- public static String SpecfileEditor_1;
- public static String SpecfileEditor_2;
- public static String SpecfileLog_0;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.messages"; //$NON-NLS-1$
+ public static String RpmMacroProposalsList_0;
+ public static String RpmPackageBuildProposalsJob_0;
+ public static String RpmPackageBuildProposalsJob_1;
+ public static String RpmPackageBuildProposalsJob_2;
+ public static String RpmPackageBuildProposalsJob_3;
+ public static String RpmPackageBuildProposalsJob_NonZeroReturn;
+ public static String RpmPackageProposalsList_0;
+ public static String RpmPackageProposalsList_1;
+ public static String RpmPackageProposalsList_2;
+ public static String RpmPackageProposalsList_3;
+ public static String SpecfileConfiguration_0;
+ public static String SpecfileEditor_0;
+ public static String SpecfileEditor_1;
+ public static String SpecfileEditor_2;
+ public static String SpecfileLog_0;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- super();
- }
+ private Messages() {
+ super();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/NonRuleBasedDamagerRepairer.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/NonRuleBasedDamagerRepairer.java
index ef322ba6d5..71652aec07 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/NonRuleBasedDamagerRepairer.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/NonRuleBasedDamagerRepairer.java
@@ -24,131 +24,131 @@ import org.eclipse.jface.text.presentation.IPresentationRepairer;
import org.eclipse.swt.custom.StyleRange;
public class NonRuleBasedDamagerRepairer
- implements IPresentationDamager, IPresentationRepairer {
-
- /** The document this object works on */
- protected IDocument fDocument;
- /** The default text attribute if non is returned as data by the current token */
- protected TextAttribute fDefaultTextAttribute;
-
- /**
- * Constructor for NonRuleBasedDamagerRepairer.
- */
- public NonRuleBasedDamagerRepairer(TextAttribute defaultTextAttribute) {
- Assert.isNotNull(defaultTextAttribute);
-
- fDefaultTextAttribute = defaultTextAttribute;
- }
-
- /**
- * @see IPresentationRepairer#setDocument(IDocument)
- */
- @Override
- public void setDocument(IDocument document) {
- fDocument = document;
- }
-
- /**
- * Returns the end offset of the line that contains the specified offset or
- * if the offset is inside a line delimiter, the end offset of the next line.
- *
- * @param offset the offset whose line end offset must be computed
- * @return the line end offset for the given offset
- * @exception BadLocationException if offset is invalid in the current document
- */
- protected int endOfLineOf(int offset) throws BadLocationException {
-
- IRegion info = fDocument.getLineInformationOfOffset(offset);
- if (offset <= info.getOffset() + info.getLength()) {
- return info.getOffset() + info.getLength();
- }
-
- int line = fDocument.getLineOfOffset(offset);
- try {
- info = fDocument.getLineInformation(line + 1);
- return info.getOffset() + info.getLength();
- } catch (BadLocationException x) {
- return fDocument.getLength();
- }
- }
-
- /**
- * @see IPresentationDamager#getDamageRegion(ITypedRegion, DocumentEvent, boolean)
- */
- @Override
- public IRegion getDamageRegion(
- ITypedRegion partition,
- DocumentEvent event,
- boolean documentPartitioningChanged) {
- if (!documentPartitioningChanged) {
- try {
-
- IRegion info =
- fDocument.getLineInformationOfOffset(event.getOffset());
- int start = Math.max(partition.getOffset(), info.getOffset());
-
- int end =
- event.getOffset()
- + (event.getText() == null
- ? event.getLength()
- : event.getText().length());
-
- if (info.getOffset() <= end
- && end <= info.getOffset() + info.getLength()) {
- // optimize the case of the same line
- end = info.getOffset() + info.getLength();
- } else {
- end = endOfLineOf(end);
- }
-
- end =
- Math.min(
- partition.getOffset() + partition.getLength(),
- end);
- return new Region(start, end - start);
-
- } catch (BadLocationException x) {
- }
- }
-
- return partition;
- }
-
- /**
- * @see IPresentationRepairer#createPresentation(TextPresentation, ITypedRegion)
- */
- @Override
- public void createPresentation(
- TextPresentation presentation,
- ITypedRegion region) {
- addRange(
- presentation,
- region.getOffset(),
- region.getLength(),
- fDefaultTextAttribute);
- }
-
- /**
- * Adds style information to the given text presentation.
- *
- * @param presentation the text presentation to be extended
- * @param offset the offset of the range to be styled
- * @param length the length of the range to be styled
- * @param attr the attribute describing the style of the range to be styled
- */
- protected void addRange(
- TextPresentation presentation,
- int offset,
- int length,
- TextAttribute attr) {
- if (attr != null) {
- presentation.addStyleRange(
- new StyleRange(
- offset,
- length,
- attr.getForeground(),
- attr.getBackground(),
- attr.getStyle()));
- }
- }
+ implements IPresentationDamager, IPresentationRepairer {
+
+ /** The document this object works on */
+ protected IDocument fDocument;
+ /** The default text attribute if non is returned as data by the current token */
+ protected TextAttribute fDefaultTextAttribute;
+
+ /**
+ * Constructor for NonRuleBasedDamagerRepairer.
+ */
+ public NonRuleBasedDamagerRepairer(TextAttribute defaultTextAttribute) {
+ Assert.isNotNull(defaultTextAttribute);
+
+ fDefaultTextAttribute = defaultTextAttribute;
+ }
+
+ /**
+ * @see IPresentationRepairer#setDocument(IDocument)
+ */
+ @Override
+ public void setDocument(IDocument document) {
+ fDocument = document;
+ }
+
+ /**
+ * Returns the end offset of the line that contains the specified offset or
+ * if the offset is inside a line delimiter, the end offset of the next line.
+ *
+ * @param offset the offset whose line end offset must be computed
+ * @return the line end offset for the given offset
+ * @exception BadLocationException if offset is invalid in the current document
+ */
+ protected int endOfLineOf(int offset) throws BadLocationException {
+
+ IRegion info = fDocument.getLineInformationOfOffset(offset);
+ if (offset <= info.getOffset() + info.getLength()) {
+ return info.getOffset() + info.getLength();
+ }
+
+ int line = fDocument.getLineOfOffset(offset);
+ try {
+ info = fDocument.getLineInformation(line + 1);
+ return info.getOffset() + info.getLength();
+ } catch (BadLocationException x) {
+ return fDocument.getLength();
+ }
+ }
+
+ /**
+ * @see IPresentationDamager#getDamageRegion(ITypedRegion, DocumentEvent, boolean)
+ */
+ @Override
+ public IRegion getDamageRegion(
+ ITypedRegion partition,
+ DocumentEvent event,
+ boolean documentPartitioningChanged) {
+ if (!documentPartitioningChanged) {
+ try {
+
+ IRegion info =
+ fDocument.getLineInformationOfOffset(event.getOffset());
+ int start = Math.max(partition.getOffset(), info.getOffset());
+
+ int end =
+ event.getOffset()
+ + (event.getText() == null
+ ? event.getLength()
+ : event.getText().length());
+
+ if (info.getOffset() <= end
+ && end <= info.getOffset() + info.getLength()) {
+ // optimize the case of the same line
+ end = info.getOffset() + info.getLength();
+ } else {
+ end = endOfLineOf(end);
+ }
+
+ end =
+ Math.min(
+ partition.getOffset() + partition.getLength(),
+ end);
+ return new Region(start, end - start);
+
+ } catch (BadLocationException x) {
+ }
+ }
+
+ return partition;
+ }
+
+ /**
+ * @see IPresentationRepairer#createPresentation(TextPresentation, ITypedRegion)
+ */
+ @Override
+ public void createPresentation(
+ TextPresentation presentation,
+ ITypedRegion region) {
+ addRange(
+ presentation,
+ region.getOffset(),
+ region.getLength(),
+ fDefaultTextAttribute);
+ }
+
+ /**
+ * Adds style information to the given text presentation.
+ *
+ * @param presentation the text presentation to be extended
+ * @param offset the offset of the range to be styled
+ * @param length the length of the range to be styled
+ * @param attr the attribute describing the style of the range to be styled
+ */
+ protected void addRange(
+ TextPresentation presentation,
+ int offset,
+ int length,
+ TextAttribute attr) {
+ if (attr != null) {
+ presentation.addStyleRange(
+ new StyleRange(
+ offset,
+ length,
+ attr.getForeground(),
+ attr.getBackground(),
+ attr.getStyle()));
+ }
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RPMHandlerUtils.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RPMHandlerUtils.java
index 4d527c3cc5..5cbacf7d7c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RPMHandlerUtils.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RPMHandlerUtils.java
@@ -36,76 +36,76 @@ import org.eclipse.ui.part.EditorPart;
*/
public class RPMHandlerUtils {
- /**
- * Utility classes should not have a public or default constructor.
- */
- private RPMHandlerUtils() {}
+ /**
+ * Utility classes should not have a public or default constructor.
+ */
+ private RPMHandlerUtils() {}
- /**
- * Extract the IResource that was selected when the event was fired.
- * @param event The fired execution event.
- * @return The resource that was selected.
- */
- public static IResource getResource(ExecutionEvent event) {
- IWorkbenchPart part = HandlerUtil.getActivePart(event);
- if (part == null) {
- return null;
- }
- if (part instanceof EditorPart) {
- IEditorInput input = ((EditorPart) part).getEditorInput();
- if (input instanceof IFileEditorInput) {
- return ((IFileEditorInput) input).getFile();
- }
- return null;
- }
- IWorkbenchSite site = part.getSite();
- if (site == null) {
- return null;
- }
- ISelectionProvider provider = site.getSelectionProvider();
- if (provider == null) {
- return null;
- }
- ISelection selection = provider.getSelection();
- if (selection instanceof IStructuredSelection) {
- Object element = ((IStructuredSelection) selection)
- .getFirstElement();
- if (element instanceof IResource) {
- return (IResource) element;
- } else if (element instanceof IAdaptable) {
- IAdaptable adaptable = (IAdaptable) element;
- return (IResource) adaptable.getAdapter(IResource.class);
- } else {
- return null;
- }
- }
- return null;
- }
+ /**
+ * Extract the IResource that was selected when the event was fired.
+ * @param event The fired execution event.
+ * @return The resource that was selected.
+ */
+ public static IResource getResource(ExecutionEvent event) {
+ IWorkbenchPart part = HandlerUtil.getActivePart(event);
+ if (part == null) {
+ return null;
+ }
+ if (part instanceof EditorPart) {
+ IEditorInput input = ((EditorPart) part).getEditorInput();
+ if (input instanceof IFileEditorInput) {
+ return ((IFileEditorInput) input).getFile();
+ }
+ return null;
+ }
+ IWorkbenchSite site = part.getSite();
+ if (site == null) {
+ return null;
+ }
+ ISelectionProvider provider = site.getSelectionProvider();
+ if (provider == null) {
+ return null;
+ }
+ ISelection selection = provider.getSelection();
+ if (selection instanceof IStructuredSelection) {
+ Object element = ((IStructuredSelection) selection)
+ .getFirstElement();
+ if (element instanceof IResource) {
+ return (IResource) element;
+ } else if (element instanceof IAdaptable) {
+ IAdaptable adaptable = (IAdaptable) element;
+ return (IResource) adaptable.getAdapter(IResource.class);
+ } else {
+ return null;
+ }
+ }
+ return null;
+ }
- /**
- * Get an RPMProject for the resource creating a new instance to an RPMProject.
- * @param resource The resource to check its parent project.
- * @return The RPMProject of the resource passed in.
- */
- public static RPMProject getRPMProject(IResource resource) {
- RPMProject rc = null;
+ /**
+ * Get an RPMProject for the resource creating a new instance to an RPMProject.
+ * @param resource The resource to check its parent project.
+ * @return The RPMProject of the resource passed in.
+ */
+ public static RPMProject getRPMProject(IResource resource) {
+ RPMProject rc = null;
- try {
- IProject parentProject = resource.getProject();
+ try {
+ IProject parentProject = resource.getProject();
- // determine if project selected is an RPMProject
- if (parentProject.hasNature(IRPMConstants.RPM_NATURE_ID)) {
- if (parentProject.getPersistentProperty(new QualifiedName(IRPMConstants.RPM_CORE_ID, IRPMConstants.SPECS_FOLDER)) != null){
- rc = new RPMProject(parentProject, RPMProjectLayout.RPMBUILD);
- } else {
- rc = new RPMProject(parentProject, RPMProjectLayout.FLAT);
- }
- } else {
- rc = new RPMProject(parentProject, RPMProjectLayout.FLAT);
- }
- } catch (CoreException e) {
- SpecfileLog.logError(Messages.RPMHandlerUtils_cannotCreateRPMProject, e);
- }
- return rc;
- }
+ // determine if project selected is an RPMProject
+ if (parentProject.hasNature(IRPMConstants.RPM_NATURE_ID)) {
+ if (parentProject.getPersistentProperty(new QualifiedName(IRPMConstants.RPM_CORE_ID, IRPMConstants.SPECS_FOLDER)) != null){
+ rc = new RPMProject(parentProject, RPMProjectLayout.RPMBUILD);
+ } else {
+ rc = new RPMProject(parentProject, RPMProjectLayout.FLAT);
+ }
+ } else {
+ rc = new RPMProject(parentProject, RPMProjectLayout.FLAT);
+ }
+ } catch (CoreException e) {
+ SpecfileLog.logError(Messages.RPMHandlerUtils_cannotCreateRPMProject, e);
+ }
+ return rc;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmMacroOccurrencesUpdater.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmMacroOccurrencesUpdater.java
index d620eefbc4..2d9681ef5f 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmMacroOccurrencesUpdater.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmMacroOccurrencesUpdater.java
@@ -31,216 +31,216 @@ import org.eclipse.linuxtools.rpm.ui.editor.parser.SpecfileDefine;
public class RpmMacroOccurrencesUpdater implements ISelectionChangedListener {
- private static final String ANNOTATION_TYPE = Activator.PLUGIN_ID + ".highlightannotation"; //$NON-NLS-1$
-
- private final SpecfileEditor fEditor;
-
- private final List<Annotation> fOldAnnotations = new LinkedList<>();
-
- /**
- * Creates a new instance on editor <code>specfileEditor</code>.
- *
- * @param specfileEditor The editor to mark occurrences on.
- */
- public RpmMacroOccurrencesUpdater(SpecfileEditor specfileEditor) {
- ((IPostSelectionProvider) specfileEditor.getSelectionProvider())
- .addPostSelectionChangedListener(this);
- fEditor = specfileEditor;
- }
-
- /*
- * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
- */
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- update((ISourceViewer) event.getSource());
- }
-
- /**
- * Updates the drawn annotations.
- *
- * @param viewer The viewer to get the document and annotation model from
- */
- public void update(ISourceViewer viewer) {
- try {
- IDocument document = viewer.getDocument();
- IAnnotationModel model = viewer.getAnnotationModel();
- if (document == null || model == null) {
- return;
- }
- removeOldAnnotations(model);
- String currentSelectedWord = getWordAtSelection(fEditor.getSelectionProvider()
- .getSelection(), document);
- if (isMacro(currentSelectedWord)) {
- Specfile spec = fEditor.getSpecfile();
- SpecfileDefine define = spec.getDefine(currentSelectedWord);
- String word = currentSelectedWord + ": "; //$NON-NLS-1$
+ private static final String ANNOTATION_TYPE = Activator.PLUGIN_ID + ".highlightannotation"; //$NON-NLS-1$
+
+ private final SpecfileEditor fEditor;
+
+ private final List<Annotation> fOldAnnotations = new LinkedList<>();
+
+ /**
+ * Creates a new instance on editor <code>specfileEditor</code>.
+ *
+ * @param specfileEditor The editor to mark occurrences on.
+ */
+ public RpmMacroOccurrencesUpdater(SpecfileEditor specfileEditor) {
+ ((IPostSelectionProvider) specfileEditor.getSelectionProvider())
+ .addPostSelectionChangedListener(this);
+ fEditor = specfileEditor;
+ }
+
+ /*
+ * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
+ */
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ update((ISourceViewer) event.getSource());
+ }
+
+ /**
+ * Updates the drawn annotations.
+ *
+ * @param viewer The viewer to get the document and annotation model from
+ */
+ public void update(ISourceViewer viewer) {
+ try {
+ IDocument document = viewer.getDocument();
+ IAnnotationModel model = viewer.getAnnotationModel();
+ if (document == null || model == null) {
+ return;
+ }
+ removeOldAnnotations(model);
+ String currentSelectedWord = getWordAtSelection(fEditor.getSelectionProvider()
+ .getSelection(), document);
+ if (isMacro(currentSelectedWord)) {
+ Specfile spec = fEditor.getSpecfile();
+ SpecfileDefine define = spec.getDefine(currentSelectedWord);
+ String word = currentSelectedWord + ": "; //$NON-NLS-1$
if (define != null) {
- word += define.getStringValue();
+ word += define.getStringValue();
} else {
- // If there's no such define we try to see if it corresponds to
- // a Source or Patch declaration
- String retrivedValue = SpecfileHover.getSourceOrPatchValue(spec, currentSelectedWord.toLowerCase());
- if (retrivedValue != null) {
- word += retrivedValue;
- } else {
- // If it does not correspond to a Patch or Source macro, try to find it
- // in the macro proposals list.
- retrivedValue = SpecfileHover.getMacroValueFromMacroList(currentSelectedWord);
- if (retrivedValue != null) {
- word += retrivedValue;
- }
- }
+ // If there's no such define we try to see if it corresponds to
+ // a Source or Patch declaration
+ String retrivedValue = SpecfileHover.getSourceOrPatchValue(spec, currentSelectedWord.toLowerCase());
+ if (retrivedValue != null) {
+ word += retrivedValue;
+ } else {
+ // If it does not correspond to a Patch or Source macro, try to find it
+ // in the macro proposals list.
+ retrivedValue = SpecfileHover.getMacroValueFromMacroList(currentSelectedWord);
+ if (retrivedValue != null) {
+ word += retrivedValue;
+ }
+ }
}
createNewAnnotations(currentSelectedWord, word, document, model);
- }
- } catch (BadLocationException e) {
- SpecfileLog.logError(e);
- }
- }
-
- /**
- * Removes the previous set of annotations from the annotation model.
- *
- * @param model
- * the annotation model
- */
- private void removeOldAnnotations(IAnnotationModel model) {
- for (Annotation annotation: fOldAnnotations) {
- model.removeAnnotation(annotation);
- }
- fOldAnnotations.clear();
- }
-
- /**
- * Checks if <code>word</code> is an macro.
- *
- * @param word
- * the word to check
- *
- * @return <code>true</code> if <code>word</code> is an macro,
- * <code>false</code> otherwise
- */
- private boolean isMacro(String word) {
- List<SpecfileDefine> defines = getMacros();
- if (word.length() > 0) {
- for (SpecfileDefine define: defines) {
- if (containsWord(define, word)) {
- return true;
- }
- }
- if (Activator.getDefault().getRpmMacroList().getProposals(
- "%" + word).size() > 0) {//$NON-NLS-1$
- return true;
- }
- }
- return false;
- }
-
- /**
- * Retrieves the macros from the editor's specfile.
- *
- * @return the macros from the editor's specfile
- */
- private List<SpecfileDefine> getMacros() {
- Specfile specfile = fEditor.getSpecfile();
- if (specfile != null) {
- List<SpecfileDefine> macros = specfile.getDefines();
- if (macros != null) {
- return macros;
- }
- }
- return new ArrayList<>();
- }
-
- /**
- * Returns <code>true</code> if <code>macro</code> equals the word
- * <code>current</code>.
- *
- * @param macro
- * the <code>macro</code> to check
- * @param current
- * the word to look for
- *
- * @return <code>true</code> if <code>macro</code> contains the word
- * <code>current</code>,<code>false</code> if not
- */
- private boolean containsWord(SpecfileDefine macro, String current) {
- return macro.getName().equalsIgnoreCase(current);
- }
-
- /**
- * Returns the word at the current selection / caret position.
- *
- * @param selection
- * the selection
- * @param document
- * the document
- * @return the currently selected text, or the word at the caret if the
- * selection has length 0
- * @throws BadLocationException
- * if accessing the document fails
- */
- private String getWordAtSelection(ISelection selection, IDocument document)
- throws BadLocationException {
- String word;
- if (selection instanceof ITextSelection) {
- ITextSelection ts = (ITextSelection) selection;
- int offset = ts.getOffset();
- int end = offset + ts.getLength();
-
- // non-empty selections
- if (end != offset) {
- word = ts.getText();
- } else {
- while (offset > 0 && isDefineChar(document.getChar(offset - 1))) {
- offset--;
- }
- while (end < document.getLength()
- && isDefineChar(document.getChar(end))) {
- end++;
- }
-
- word = document.get(offset, end - offset);
- }
- } else {
- word = ""; //$NON-NLS-1$
- }
- return word.toLowerCase();
- }
-
- private boolean isDefineChar(char c) {
- return c != '{' && c != '}' && c != '?' && !Character.isWhitespace(c);
- }
-
- /**
- * Adds an annotation for every occurrence of <code>macro</code> in the
- * document. Also stores the created annotations in
- * <code>fOldAnnotations</code>.
- *
- * @param macro
- * the word to look for
- * @param document
- * the document
- * @param model
- * the annotation model
- */
- private void createNewAnnotations(String macro, String hoverContent, IDocument document,
- IAnnotationModel model) {
- String content = document.get().toLowerCase();
- int idx = content.indexOf(macro.toLowerCase());
- while (idx != -1) {
- Annotation annotation = new Annotation(ANNOTATION_TYPE, false,
- hoverContent);
- Position position = new Position(idx, macro.length());
- model.addAnnotation(annotation, position);
- fOldAnnotations.add(annotation);
- idx = content.indexOf(macro, idx + 1);
- }
- }
-
- public void dispose() {
- ((IPostSelectionProvider) fEditor.getSelectionProvider())
- .removePostSelectionChangedListener(this);
- }
+ }
+ } catch (BadLocationException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+
+ /**
+ * Removes the previous set of annotations from the annotation model.
+ *
+ * @param model
+ * the annotation model
+ */
+ private void removeOldAnnotations(IAnnotationModel model) {
+ for (Annotation annotation: fOldAnnotations) {
+ model.removeAnnotation(annotation);
+ }
+ fOldAnnotations.clear();
+ }
+
+ /**
+ * Checks if <code>word</code> is an macro.
+ *
+ * @param word
+ * the word to check
+ *
+ * @return <code>true</code> if <code>word</code> is an macro,
+ * <code>false</code> otherwise
+ */
+ private boolean isMacro(String word) {
+ List<SpecfileDefine> defines = getMacros();
+ if (word.length() > 0) {
+ for (SpecfileDefine define: defines) {
+ if (containsWord(define, word)) {
+ return true;
+ }
+ }
+ if (Activator.getDefault().getRpmMacroList().getProposals(
+ "%" + word).size() > 0) {//$NON-NLS-1$
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Retrieves the macros from the editor's specfile.
+ *
+ * @return the macros from the editor's specfile
+ */
+ private List<SpecfileDefine> getMacros() {
+ Specfile specfile = fEditor.getSpecfile();
+ if (specfile != null) {
+ List<SpecfileDefine> macros = specfile.getDefines();
+ if (macros != null) {
+ return macros;
+ }
+ }
+ return new ArrayList<>();
+ }
+
+ /**
+ * Returns <code>true</code> if <code>macro</code> equals the word
+ * <code>current</code>.
+ *
+ * @param macro
+ * the <code>macro</code> to check
+ * @param current
+ * the word to look for
+ *
+ * @return <code>true</code> if <code>macro</code> contains the word
+ * <code>current</code>,<code>false</code> if not
+ */
+ private boolean containsWord(SpecfileDefine macro, String current) {
+ return macro.getName().equalsIgnoreCase(current);
+ }
+
+ /**
+ * Returns the word at the current selection / caret position.
+ *
+ * @param selection
+ * the selection
+ * @param document
+ * the document
+ * @return the currently selected text, or the word at the caret if the
+ * selection has length 0
+ * @throws BadLocationException
+ * if accessing the document fails
+ */
+ private String getWordAtSelection(ISelection selection, IDocument document)
+ throws BadLocationException {
+ String word;
+ if (selection instanceof ITextSelection) {
+ ITextSelection ts = (ITextSelection) selection;
+ int offset = ts.getOffset();
+ int end = offset + ts.getLength();
+
+ // non-empty selections
+ if (end != offset) {
+ word = ts.getText();
+ } else {
+ while (offset > 0 && isDefineChar(document.getChar(offset - 1))) {
+ offset--;
+ }
+ while (end < document.getLength()
+ && isDefineChar(document.getChar(end))) {
+ end++;
+ }
+
+ word = document.get(offset, end - offset);
+ }
+ } else {
+ word = ""; //$NON-NLS-1$
+ }
+ return word.toLowerCase();
+ }
+
+ private boolean isDefineChar(char c) {
+ return c != '{' && c != '}' && c != '?' && !Character.isWhitespace(c);
+ }
+
+ /**
+ * Adds an annotation for every occurrence of <code>macro</code> in the
+ * document. Also stores the created annotations in
+ * <code>fOldAnnotations</code>.
+ *
+ * @param macro
+ * the word to look for
+ * @param document
+ * the document
+ * @param model
+ * the annotation model
+ */
+ private void createNewAnnotations(String macro, String hoverContent, IDocument document,
+ IAnnotationModel model) {
+ String content = document.get().toLowerCase();
+ int idx = content.indexOf(macro.toLowerCase());
+ while (idx != -1) {
+ Annotation annotation = new Annotation(ANNOTATION_TYPE, false,
+ hoverContent);
+ Position position = new Position(idx, macro.length());
+ model.addAnnotation(annotation, position);
+ fOldAnnotations.add(annotation);
+ idx = content.indexOf(macro, idx + 1);
+ }
+ }
+
+ public void dispose() {
+ ((IPostSelectionProvider) fEditor.getSelectionProvider())
+ .removePostSelectionChangedListener(this);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmMacroProposalsList.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmMacroProposalsList.java
index 44d93bb376..cc9976007b 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmMacroProposalsList.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmMacroProposalsList.java
@@ -31,195 +31,195 @@ import org.eclipse.linuxtools.rpm.core.utils.Utils;
*/
public class RpmMacroProposalsList {
- private static final String EMPTY_STRING = ""; //$NON-NLS-1$
-
- private Map<String, String> macroMap = new HashMap<>();
-
- private String toStringStr;
-
- /**
- * Default contructor
- */
- public RpmMacroProposalsList() {
- buildMacroList();
- }
-
- /**
- * Build the macro list.
- */
- public final void buildMacroList() {
- for (String definedMacro: SpecfileScanner.DEFINED_MACROS){
- macroMap.put(definedMacro, Messages.RpmMacroProposalsList_0);
- //TODO find way to provide info about buildin macros.
- }
- String macroProposalsPaths = Activator.getDefault()
- .getPreferenceStore().getString(
- PreferenceConstants.P_MACRO_PROPOSALS_FILESPATH);
- String[] paths = macroProposalsPaths.split(";"); //$NON-NLS-1$
- // paths must be reversed because the last value added
- // into a Map overwrites the first.
- paths = reverseStringArray(paths);
- for (String path : paths) {
- if (!path.equals(EMPTY_STRING)) {
- File pathFile = new File(path);
- if (pathFile.exists()) {
- if (pathFile.isDirectory()) {
- File[] macrosFiles = pathFile.listFiles();
- for (File macrosFile : macrosFiles) {
- addMacroToMap(macrosFile.getAbsolutePath());
- }
- } else {
- addMacroToMap(path);
- }
- }
- }
- }
- }
-
- /**
- * Add macro definition to the map
- *
- * @param filename
- * macro file definition.
- */
- private void addMacroToMap(String filename) {
- String line = EMPTY_STRING;
- try (BufferedReader reader = new BufferedReader(new InputStreamReader(
- new FileInputStream(filename)))){
- line = reader.readLine();
- String key = EMPTY_STRING, value = EMPTY_STRING;
- while (line != null) {
- if (line.startsWith("%")) { //$NON-NLS-1$
- String[] item = line.split("\t+| ", 2); //$NON-NLS-1$
- try {
- // Get values on more than one line
- if (line.trim().endsWith("\\")) { //$NON-NLS-1$
- value = "\n"; //$NON-NLS-1$
- boolean isKeyLine = true;
- while (line.trim().endsWith("\\")) { //$NON-NLS-1$
- if (isKeyLine) {
- isKeyLine = false;
- key = item[0];
- if (item.length > 1) {
- value += item[1].replaceAll("\\\\", "\n\n"); //$NON-NLS-1$//$NON-NLS-2$
- }
- } else {
- value += line.substring(0,
- line.length() - 1).trim()
- + "\n\t"; //$NON-NLS-1$
- }
- line = reader.readLine();
- }
- } else {
- key = item[0];
- value = item[1];
- }
- key = key.trim();
- value = value.trim();
- macroMap.put(key, value);
- toStringStr += key + ": " + value + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
- } catch (Exception e) {
- line = reader.readLine();
- continue;
- }
- value = EMPTY_STRING;
- key = EMPTY_STRING;
- }
- line = reader.readLine();
- }
- } catch (IOException e) {
- SpecfileLog.logError(e);
- }
- }
-
- /**
- * Reverse a <code>String</code> array.
- *
- * @param stringArrayToReverse
- * the string array to reverse.
- * @return the reversed <code>String</code> array.
- */
- private String[] reverseStringArray(String[] stringArrayToReverse) {
- int left = 0;
- int right = stringArrayToReverse.length - 1;
- while (left < right) {
- String tmp = stringArrayToReverse[left];
- stringArrayToReverse[left] = stringArrayToReverse[right];
- stringArrayToReverse[right] = tmp;
- left++;
- right--;
- }
- return stringArrayToReverse;
- }
-
- /**
- * Get proposals for a given prefix
- *
- * @param prefix The prefix to search.
- * @return a <code>Map</code> of proposals.
- */
- public Map<String, String> getProposals(String prefix) {
- Map<String, String> proposalsMap = new HashMap<>(macroMap.size());
- for (Map.Entry<String, String> entry: macroMap.entrySet()) {
- // Get proposals for macro begin with { char too.
- if (entry.getKey().startsWith(prefix.replaceFirst("\\{", EMPTY_STRING))) { //$NON-NLS-1$
- proposalsMap.put(entry.getKey(), entry.getValue());
- }
- }
- // Sort proposals
- return new TreeMap<>(proposalsMap);
- }
-
- /**
- * Get the value for a given macro.
- *
- * @param key Key to retrieve value.
- * @return a string representation of the value
- */
- public String getValue(String key) {
- String value = macroMap.get("%" + key); //$NON-NLS-1$
- // get proposals for macro contain ? too.
- if (value == null) {
- value = macroMap.get(("%" + key).replaceFirst("\\?", EMPTY_STRING)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return value;
- }
-
- /**
- * Find a key in the macroMap
- *
- * @param keyToFind The key to find.
- * @return return the value
- */
- public boolean findKey(String keyToFind) {
- return macroMap.containsKey(keyToFind);
- }
-
- /**
- * Return the ouput of the <code>rpm --eval</code> command for a given
- * macro.
- *
- * @param macroName The macro name to eval.
- * @return the resolved macro content.
- */
- public static String getMacroEval(String macroName) {
- String eval = EMPTY_STRING;
- try {
- eval = Utils.runCommandToString( "rpm", "--eval", macroName); //$NON-NLS-1$//$NON-NLS-2$
- } catch (IOException e) {
- SpecfileLog.logError(e);
- }
- return eval.trim();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return toStringStr;
- }
+ private static final String EMPTY_STRING = ""; //$NON-NLS-1$
+
+ private Map<String, String> macroMap = new HashMap<>();
+
+ private String toStringStr;
+
+ /**
+ * Default contructor
+ */
+ public RpmMacroProposalsList() {
+ buildMacroList();
+ }
+
+ /**
+ * Build the macro list.
+ */
+ public final void buildMacroList() {
+ for (String definedMacro: SpecfileScanner.DEFINED_MACROS){
+ macroMap.put(definedMacro, Messages.RpmMacroProposalsList_0);
+ //TODO find way to provide info about buildin macros.
+ }
+ String macroProposalsPaths = Activator.getDefault()
+ .getPreferenceStore().getString(
+ PreferenceConstants.P_MACRO_PROPOSALS_FILESPATH);
+ String[] paths = macroProposalsPaths.split(";"); //$NON-NLS-1$
+ // paths must be reversed because the last value added
+ // into a Map overwrites the first.
+ paths = reverseStringArray(paths);
+ for (String path : paths) {
+ if (!path.equals(EMPTY_STRING)) {
+ File pathFile = new File(path);
+ if (pathFile.exists()) {
+ if (pathFile.isDirectory()) {
+ File[] macrosFiles = pathFile.listFiles();
+ for (File macrosFile : macrosFiles) {
+ addMacroToMap(macrosFile.getAbsolutePath());
+ }
+ } else {
+ addMacroToMap(path);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Add macro definition to the map
+ *
+ * @param filename
+ * macro file definition.
+ */
+ private void addMacroToMap(String filename) {
+ String line = EMPTY_STRING;
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(
+ new FileInputStream(filename)))){
+ line = reader.readLine();
+ String key = EMPTY_STRING, value = EMPTY_STRING;
+ while (line != null) {
+ if (line.startsWith("%")) { //$NON-NLS-1$
+ String[] item = line.split("\t+| ", 2); //$NON-NLS-1$
+ try {
+ // Get values on more than one line
+ if (line.trim().endsWith("\\")) { //$NON-NLS-1$
+ value = "\n"; //$NON-NLS-1$
+ boolean isKeyLine = true;
+ while (line.trim().endsWith("\\")) { //$NON-NLS-1$
+ if (isKeyLine) {
+ isKeyLine = false;
+ key = item[0];
+ if (item.length > 1) {
+ value += item[1].replaceAll("\\\\", "\n\n"); //$NON-NLS-1$//$NON-NLS-2$
+ }
+ } else {
+ value += line.substring(0,
+ line.length() - 1).trim()
+ + "\n\t"; //$NON-NLS-1$
+ }
+ line = reader.readLine();
+ }
+ } else {
+ key = item[0];
+ value = item[1];
+ }
+ key = key.trim();
+ value = value.trim();
+ macroMap.put(key, value);
+ toStringStr += key + ": " + value + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
+ } catch (Exception e) {
+ line = reader.readLine();
+ continue;
+ }
+ value = EMPTY_STRING;
+ key = EMPTY_STRING;
+ }
+ line = reader.readLine();
+ }
+ } catch (IOException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+
+ /**
+ * Reverse a <code>String</code> array.
+ *
+ * @param stringArrayToReverse
+ * the string array to reverse.
+ * @return the reversed <code>String</code> array.
+ */
+ private String[] reverseStringArray(String[] stringArrayToReverse) {
+ int left = 0;
+ int right = stringArrayToReverse.length - 1;
+ while (left < right) {
+ String tmp = stringArrayToReverse[left];
+ stringArrayToReverse[left] = stringArrayToReverse[right];
+ stringArrayToReverse[right] = tmp;
+ left++;
+ right--;
+ }
+ return stringArrayToReverse;
+ }
+
+ /**
+ * Get proposals for a given prefix
+ *
+ * @param prefix The prefix to search.
+ * @return a <code>Map</code> of proposals.
+ */
+ public Map<String, String> getProposals(String prefix) {
+ Map<String, String> proposalsMap = new HashMap<>(macroMap.size());
+ for (Map.Entry<String, String> entry: macroMap.entrySet()) {
+ // Get proposals for macro begin with { char too.
+ if (entry.getKey().startsWith(prefix.replaceFirst("\\{", EMPTY_STRING))) { //$NON-NLS-1$
+ proposalsMap.put(entry.getKey(), entry.getValue());
+ }
+ }
+ // Sort proposals
+ return new TreeMap<>(proposalsMap);
+ }
+
+ /**
+ * Get the value for a given macro.
+ *
+ * @param key Key to retrieve value.
+ * @return a string representation of the value
+ */
+ public String getValue(String key) {
+ String value = macroMap.get("%" + key); //$NON-NLS-1$
+ // get proposals for macro contain ? too.
+ if (value == null) {
+ value = macroMap.get(("%" + key).replaceFirst("\\?", EMPTY_STRING)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return value;
+ }
+
+ /**
+ * Find a key in the macroMap
+ *
+ * @param keyToFind The key to find.
+ * @return return the value
+ */
+ public boolean findKey(String keyToFind) {
+ return macroMap.containsKey(keyToFind);
+ }
+
+ /**
+ * Return the ouput of the <code>rpm --eval</code> command for a given
+ * macro.
+ *
+ * @param macroName The macro name to eval.
+ * @return the resolved macro content.
+ */
+ public static String getMacroEval(String macroName) {
+ String eval = EMPTY_STRING;
+ try {
+ eval = Utils.runCommandToString( "rpm", "--eval", macroName); //$NON-NLS-1$//$NON-NLS-2$
+ } catch (IOException e) {
+ SpecfileLog.logError(e);
+ }
+ return eval.trim();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return toStringStr;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmPackageBuildProposalsJob.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmPackageBuildProposalsJob.java
index ee6523e51e..892658bcc2 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmPackageBuildProposalsJob.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmPackageBuildProposalsJob.java
@@ -35,229 +35,229 @@ import org.eclipse.osgi.util.NLS;
public final class RpmPackageBuildProposalsJob extends Job {
- private RpmPackageBuildProposalsJob(String name) {
- super(name);
- this.addJobChangeListener(updateFinishedListener);
- }
+ private RpmPackageBuildProposalsJob(String name) {
+ super(name);
+ this.addJobChangeListener(updateFinishedListener);
+ }
- private static RpmPackageBuildProposalsJob job = null;
+ private static RpmPackageBuildProposalsJob job = null;
- private Object updatingLock = false;
- private boolean updating = false;
+ private Object updatingLock = false;
+ private boolean updating = false;
- private IJobChangeListener updateFinishedListener = new JobChangeAdapter(){
+ private IJobChangeListener updateFinishedListener = new JobChangeAdapter(){
- @Override
- public void done(IJobChangeEvent event) {
- synchronized (updatingLock) {
- updating = false;
- updatingLock.notifyAll();
- }
- }
- };
+ @Override
+ public void done(IJobChangeEvent event) {
+ synchronized (updatingLock) {
+ updating = false;
+ updatingLock.notifyAll();
+ }
+ }
+ };
- /**
- * If the updates thread has not finished updating this function blocks
- * the current thread until that job is done.
- */
- public static void waitForUpdates (){
- if (job != null){
- try {
- synchronized (job.updatingLock){
- if (job.updating){
- job.updatingLock.wait();
- }
- }
- } catch (InterruptedException e) {}
- }
- }
+ /**
+ * If the updates thread has not finished updating this function blocks
+ * the current thread until that job is done.
+ */
+ public static void waitForUpdates (){
+ if (job != null){
+ try {
+ synchronized (job.updatingLock){
+ if (job.updating){
+ job.updatingLock.wait();
+ }
+ }
+ } catch (InterruptedException e) {}
+ }
+ }
- protected static final IEclipsePreferences.IPreferenceChangeListener PROPERTY_LISTENER = new IEclipsePreferences.IPreferenceChangeListener() {
- @Override
- public void preferenceChange(PreferenceChangeEvent event) {
- if (event.getKey().equals(PreferenceConstants.P_CURRENT_RPMTOOLS)) {
- update();
- }
- }
- };
+ protected static final IEclipsePreferences.IPreferenceChangeListener PROPERTY_LISTENER = new IEclipsePreferences.IPreferenceChangeListener() {
+ @Override
+ public void preferenceChange(PreferenceChangeEvent event) {
+ if (event.getKey().equals(PreferenceConstants.P_CURRENT_RPMTOOLS)) {
+ update();
+ }
+ }
+ };
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- return retrievePackageList(monitor);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ return retrievePackageList(monitor);
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.runtime.jobs.Job#shouldSchedule()
- */
- @Override
- public boolean shouldSchedule() {
- return equals(job);
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.core.runtime.jobs.Job#shouldSchedule()
+ */
+ @Override
+ public boolean shouldSchedule() {
+ return equals(job);
+ }
- /**
- * Run the Job if it's needed according with the configuration set in the
- * preference page.
- */
- public static void update() {
- boolean runJob = false;
- // Today's date
- Date today = new Date();
- IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(Activator.PLUGIN_ID);
- if (preferences
- .getBoolean(PreferenceConstants.P_RPM_LIST_BACKGROUND_BUILD, PreferenceConstants.DP_RPM_LIST_BACKGROUND_BUILD)) {
- int period = preferences
- .getInt(PreferenceConstants.P_RPM_LIST_BUILD_PERIOD, PreferenceConstants.DP_RPM_LIST_BUILD_PERIOD);
- // each time that the plugin is loaded.
- if (period == 1) {
- runJob = true;
- } else {
- long lastBuildTime = preferences
- .getLong(PreferenceConstants.P_RPM_LIST_LAST_BUILD, PreferenceConstants.DP_RPM_LIST_LAST_BUILD);
- if (lastBuildTime == 0) {
- runJob = true;
- } else {
- long interval = (today.getTime() - lastBuildTime)
- / (1000 * 60 * 60 * 24);
- // run the job once a week
- if (period == 2 && interval >= 7) {
- runJob = true;
- // run the job once a month
- } else if (period == 3 && interval >= 30) {
- runJob = true;
- }
- }
- }
- if (runJob) {
- if (job == null) {
- job = new RpmPackageBuildProposalsJob(Messages.RpmPackageBuildProposalsJob_0);
- job.lockAndSchedule();
- preferences.putLong(PreferenceConstants.P_RPM_LIST_LAST_BUILD, today
- .getTime());
- } else {
- job.cancel();
- job.lockAndSchedule();
- preferences.putLong(
- PreferenceConstants.P_RPM_LIST_LAST_BUILD, today
- .getTime());
- }
- }
- } else {
- if (job != null) {
- job.cancel();
- job = null;
- }
- }
- }
+ /**
+ * Run the Job if it's needed according with the configuration set in the
+ * preference page.
+ */
+ public static void update() {
+ boolean runJob = false;
+ // Today's date
+ Date today = new Date();
+ IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(Activator.PLUGIN_ID);
+ if (preferences
+ .getBoolean(PreferenceConstants.P_RPM_LIST_BACKGROUND_BUILD, PreferenceConstants.DP_RPM_LIST_BACKGROUND_BUILD)) {
+ int period = preferences
+ .getInt(PreferenceConstants.P_RPM_LIST_BUILD_PERIOD, PreferenceConstants.DP_RPM_LIST_BUILD_PERIOD);
+ // each time that the plugin is loaded.
+ if (period == 1) {
+ runJob = true;
+ } else {
+ long lastBuildTime = preferences
+ .getLong(PreferenceConstants.P_RPM_LIST_LAST_BUILD, PreferenceConstants.DP_RPM_LIST_LAST_BUILD);
+ if (lastBuildTime == 0) {
+ runJob = true;
+ } else {
+ long interval = (today.getTime() - lastBuildTime)
+ / (1000 * 60 * 60 * 24);
+ // run the job once a week
+ if (period == 2 && interval >= 7) {
+ runJob = true;
+ // run the job once a month
+ } else if (period == 3 && interval >= 30) {
+ runJob = true;
+ }
+ }
+ }
+ if (runJob) {
+ if (job == null) {
+ job = new RpmPackageBuildProposalsJob(Messages.RpmPackageBuildProposalsJob_0);
+ job.lockAndSchedule();
+ preferences.putLong(PreferenceConstants.P_RPM_LIST_LAST_BUILD, today
+ .getTime());
+ } else {
+ job.cancel();
+ job.lockAndSchedule();
+ preferences.putLong(
+ PreferenceConstants.P_RPM_LIST_LAST_BUILD, today
+ .getTime());
+ }
+ }
+ } else {
+ if (job != null) {
+ job.cancel();
+ job = null;
+ }
+ }
+ }
- /**
- * Puts the object in the updating state so that any objets
- * requesting information will be made to wait until the update
- * is complete.
- */
- private void lockAndSchedule() {
- synchronized(this.updatingLock){
- this.updating = true;
- }
- this.schedule();
- }
+ /**
+ * Puts the object in the updating state so that any objets
+ * requesting information will be made to wait until the update
+ * is complete.
+ */
+ private void lockAndSchedule() {
+ synchronized(this.updatingLock){
+ this.updating = true;
+ }
+ this.schedule();
+ }
- /**
- * Retrieve the package list
- *
- * @param monitor
- * to update
- * @return a <code>IStatus</code>
- */
- private IStatus retrievePackageList(IProgressMonitor monitor) {
- String rpmListCmd = Activator.getDefault().getPreferenceStore()
- .getString(PreferenceConstants.P_CURRENT_RPMTOOLS);
- String rpmListFilepath = Activator.getDefault().getPreferenceStore()
- .getString(PreferenceConstants.P_RPM_LIST_FILEPATH);
- File bkupFile = new File(rpmListFilepath + ".bkup"); //$NON-NLS-1$
- try {
- monitor.beginTask(Messages.RpmPackageBuildProposalsJob_1,
- IProgressMonitor.UNKNOWN);
- if (Utils.fileExist("/bin/sh")) { //$NON-NLS-1$
- BufferedProcessInputStream in = Utils.runCommandToInputStream(
- "/bin/sh", "-c", rpmListCmd); //$NON-NLS-1$ //$NON-NLS-2$
- // backup pkg list file
- File rpmListFile = new File(rpmListFilepath);
- if (rpmListFile.exists()) {
- Utils.copyFile(new File(rpmListFilepath), bkupFile);
- }
+ /**
+ * Retrieve the package list
+ *
+ * @param monitor
+ * to update
+ * @return a <code>IStatus</code>
+ */
+ private IStatus retrievePackageList(IProgressMonitor monitor) {
+ String rpmListCmd = Activator.getDefault().getPreferenceStore()
+ .getString(PreferenceConstants.P_CURRENT_RPMTOOLS);
+ String rpmListFilepath = Activator.getDefault().getPreferenceStore()
+ .getString(PreferenceConstants.P_RPM_LIST_FILEPATH);
+ File bkupFile = new File(rpmListFilepath + ".bkup"); //$NON-NLS-1$
+ try {
+ monitor.beginTask(Messages.RpmPackageBuildProposalsJob_1,
+ IProgressMonitor.UNKNOWN);
+ if (Utils.fileExist("/bin/sh")) { //$NON-NLS-1$
+ BufferedProcessInputStream in = Utils.runCommandToInputStream(
+ "/bin/sh", "-c", rpmListCmd); //$NON-NLS-1$ //$NON-NLS-2$
+ // backup pkg list file
+ File rpmListFile = new File(rpmListFilepath);
+ if (rpmListFile.exists()) {
+ Utils.copyFile(new File(rpmListFilepath), bkupFile);
+ }
- BufferedWriter out = new BufferedWriter(new FileWriter(
- rpmListFile, false));
- BufferedReader reader = new BufferedReader(
- new InputStreamReader(in));
- monitor.subTask(Messages.RpmPackageBuildProposalsJob_2
- + rpmListCmd + Messages.RpmPackageBuildProposalsJob_3);
- String line;
- while ((line = reader.readLine()) != null) {
- monitor.subTask(line);
- out.write(line + "\n"); //$NON-NLS-1$
- if (monitor.isCanceled()) {
- in.destroyProcess();
- in.close();
- out.close();
- // restore backup
- if (rpmListFile.exists() && bkupFile.exists()) {
- Utils.copyFile(bkupFile, rpmListFile);
- bkupFile.delete();
- }
- Activator.packagesList = new RpmPackageProposalsList();
- return Status.CANCEL_STATUS;
- }
- }
- in.close();
- out.close();
- bkupFile.delete();
- int processExitValue = 0;
- try {
- processExitValue = in.getExitValue();
- } catch (InterruptedException e) {
- return Status.CANCEL_STATUS;
- }
- if (processExitValue != 0){
- SpecfileLog
- .log(IStatus.WARNING,
- processExitValue,
- NLS.bind(
- Messages.RpmPackageBuildProposalsJob_NonZeroReturn,
- processExitValue), null);
- }
- }
- } catch (IOException e) {
- SpecfileLog.logError(e);
- return Status.CANCEL_STATUS;
- } finally {
- monitor.done();
- }
- // Update package list
- Activator.packagesList = new RpmPackageProposalsList();
- return Status.OK_STATUS;
- }
+ BufferedWriter out = new BufferedWriter(new FileWriter(
+ rpmListFile, false));
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(in));
+ monitor.subTask(Messages.RpmPackageBuildProposalsJob_2
+ + rpmListCmd + Messages.RpmPackageBuildProposalsJob_3);
+ String line;
+ while ((line = reader.readLine()) != null) {
+ monitor.subTask(line);
+ out.write(line + "\n"); //$NON-NLS-1$
+ if (monitor.isCanceled()) {
+ in.destroyProcess();
+ in.close();
+ out.close();
+ // restore backup
+ if (rpmListFile.exists() && bkupFile.exists()) {
+ Utils.copyFile(bkupFile, rpmListFile);
+ bkupFile.delete();
+ }
+ Activator.packagesList = new RpmPackageProposalsList();
+ return Status.CANCEL_STATUS;
+ }
+ }
+ in.close();
+ out.close();
+ bkupFile.delete();
+ int processExitValue = 0;
+ try {
+ processExitValue = in.getExitValue();
+ } catch (InterruptedException e) {
+ return Status.CANCEL_STATUS;
+ }
+ if (processExitValue != 0){
+ SpecfileLog
+ .log(IStatus.WARNING,
+ processExitValue,
+ NLS.bind(
+ Messages.RpmPackageBuildProposalsJob_NonZeroReturn,
+ processExitValue), null);
+ }
+ }
+ } catch (IOException e) {
+ SpecfileLog.logError(e);
+ return Status.CANCEL_STATUS;
+ } finally {
+ monitor.done();
+ }
+ // Update package list
+ Activator.packagesList = new RpmPackageProposalsList();
+ return Status.OK_STATUS;
+ }
- /**
- * Enable and disable the property change listener.
- *
- * @param activated Flag indicating whether the listener to be enabled or disabled.
- */
- public static void setPropertyChangeListener(boolean activated) {
- IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(Activator.PLUGIN_ID);
- if (activated) {
- preferences.addPreferenceChangeListener(PROPERTY_LISTENER);
- } else {
- preferences.removePreferenceChangeListener(PROPERTY_LISTENER);
- }
- }
+ /**
+ * Enable and disable the property change listener.
+ *
+ * @param activated Flag indicating whether the listener to be enabled or disabled.
+ */
+ public static void setPropertyChangeListener(boolean activated) {
+ IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(Activator.PLUGIN_ID);
+ if (activated) {
+ preferences.addPreferenceChangeListener(PROPERTY_LISTENER);
+ } else {
+ preferences.removePreferenceChangeListener(PROPERTY_LISTENER);
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmPackageProposalsList.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmPackageProposalsList.java
index bade7aaf50..62f42a8193 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmPackageProposalsList.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmPackageProposalsList.java
@@ -35,159 +35,159 @@ import org.eclipse.linuxtools.rpm.core.utils.Utils;
*
*/
public class RpmPackageProposalsList {
- private Set<String> list = new HashSet<>();
+ private Set<String> list = new HashSet<>();
- public RpmPackageProposalsList() {
- setPackagesList();
- }
+ public RpmPackageProposalsList() {
+ setPackagesList();
+ }
- private void setPackagesList() {
- String rpmpkgsFile = Activator.getDefault().getPreferenceStore()
- .getString(PreferenceConstants.P_RPM_LIST_FILEPATH);
- try {
- if (Utils.fileExist(rpmpkgsFile)) {
- try (BufferedReader reader = new BufferedReader(
- new InputStreamReader(new FileInputStream(rpmpkgsFile)))) {
- String line = reader.readLine();
- while (line != null) {
- list.add(line.trim());
- line = reader.readLine();
- }
- }
- } else {
- RpmPackageBuildProposalsJob.update();
- }
- } catch (IOException e) {
- RpmPackageBuildProposalsJob.update();
- SpecfileLog.logError(e);
- }
- }
+ private void setPackagesList() {
+ String rpmpkgsFile = Activator.getDefault().getPreferenceStore()
+ .getString(PreferenceConstants.P_RPM_LIST_FILEPATH);
+ try {
+ if (Utils.fileExist(rpmpkgsFile)) {
+ try (BufferedReader reader = new BufferedReader(
+ new InputStreamReader(new FileInputStream(rpmpkgsFile)))) {
+ String line = reader.readLine();
+ while (line != null) {
+ list.add(line.trim());
+ line = reader.readLine();
+ }
+ }
+ } else {
+ RpmPackageBuildProposalsJob.update();
+ }
+ } catch (IOException e) {
+ RpmPackageBuildProposalsJob.update();
+ SpecfileLog.logError(e);
+ }
+ }
- public List<String[]> getProposals(String prefix) {
- this.waitForUpdates();
- int rpmpkgsMaxProposals = Activator.getDefault().getPreferenceStore()
- .getInt(PreferenceConstants.P_RPM_LIST_MAX_PROPOSALS);
- List<String[]> proposalsList = new ArrayList<>(list.size());
- for (String listValue:list){
- String item[] = new String[2];
- item[0] = listValue;
- String message = Messages.RpmPackageProposalsList_0
- + rpmpkgsMaxProposals
- + Messages.RpmPackageProposalsList_1;
- item[1] = message;
- if (item[0].startsWith(prefix)) {
- proposalsList.add(item);
- }
- }
- /*
- * Show RPM informations only if the proposal list is less than the
- * limit set in the RPM proposals preference page.
- */
- if (proposalsList.size() < rpmpkgsMaxProposals) {
- List<String[]> proposalsListWithInfo = new ArrayList<>(proposalsList.size());
- for (String[] proposals: proposalsList){
- proposals[1] = getRpmInfo(proposals[0]);
- proposalsListWithInfo.add(proposals);
- }
- return proposalsListWithInfo;
- } else {
- return proposalsList;
- }
- }
+ public List<String[]> getProposals(String prefix) {
+ this.waitForUpdates();
+ int rpmpkgsMaxProposals = Activator.getDefault().getPreferenceStore()
+ .getInt(PreferenceConstants.P_RPM_LIST_MAX_PROPOSALS);
+ List<String[]> proposalsList = new ArrayList<>(list.size());
+ for (String listValue:list){
+ String item[] = new String[2];
+ item[0] = listValue;
+ String message = Messages.RpmPackageProposalsList_0
+ + rpmpkgsMaxProposals
+ + Messages.RpmPackageProposalsList_1;
+ item[1] = message;
+ if (item[0].startsWith(prefix)) {
+ proposalsList.add(item);
+ }
+ }
+ /*
+ * Show RPM informations only if the proposal list is less than the
+ * limit set in the RPM proposals preference page.
+ */
+ if (proposalsList.size() < rpmpkgsMaxProposals) {
+ List<String[]> proposalsListWithInfo = new ArrayList<>(proposalsList.size());
+ for (String[] proposals: proposalsList){
+ proposals[1] = getRpmInfo(proposals[0]);
+ proposalsListWithInfo.add(proposals);
+ }
+ return proposalsListWithInfo;
+ } else {
+ return proposalsList;
+ }
+ }
- public String getValue(String key) {
- for (String item :list){
- if (item.equals(key.trim())) {
- return getRpmInfo(item);
- }
- }
- return null;
+ public String getValue(String key) {
+ for (String item :list){
+ if (item.equals(key.trim())) {
+ return getRpmInfo(item);
+ }
+ }
+ return null;
- }
+ }
- public String getRpmInfo(String pkgName) {
- String ret = ""; //$NON-NLS-1$
- try {
- ret = org.eclipse.linuxtools.rpm.core.utils.Utils.runCommandToString("rpm", "-q", pkgName, "--qf", //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
- getformattedRpmInformations());
- } catch (IOException e) {
- SpecfileLog.logError(e);
- return Messages.RpmPackageProposalsList_2
- + Messages.RpmPackageProposalsList_3;
- }
- // Create encoder and decoder
- CharsetDecoder decoder = Charset.forName(System.getProperty("file.encoding")).newDecoder(); //$NON-NLS-1$
- /*
- * TODO: Jcharset may be used to detect the inputstream encoding if it's required?
- * http://jchardet.sourceforge.net
- */
- CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder(); //$NON-NLS-1$
- try {
- ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(ret));
- CharBuffer cbuf = decoder.decode(bbuf);
- ret = cbuf.toString();
- } catch (CharacterCodingException e) {
- // If an error occurs when re-encoding the output, the original
- // output is returned.
- }
- return ret;
- }
+ public String getRpmInfo(String pkgName) {
+ String ret = ""; //$NON-NLS-1$
+ try {
+ ret = org.eclipse.linuxtools.rpm.core.utils.Utils.runCommandToString("rpm", "-q", pkgName, "--qf", //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
+ getformattedRpmInformations());
+ } catch (IOException e) {
+ SpecfileLog.logError(e);
+ return Messages.RpmPackageProposalsList_2
+ + Messages.RpmPackageProposalsList_3;
+ }
+ // Create encoder and decoder
+ CharsetDecoder decoder = Charset.forName(System.getProperty("file.encoding")).newDecoder(); //$NON-NLS-1$
+ /*
+ * TODO: Jcharset may be used to detect the inputstream encoding if it's required?
+ * http://jchardet.sourceforge.net
+ */
+ CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder(); //$NON-NLS-1$
+ try {
+ ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(ret));
+ CharBuffer cbuf = decoder.decode(bbuf);
+ ret = cbuf.toString();
+ } catch (CharacterCodingException e) {
+ // If an error occurs when re-encoding the output, the original
+ // output is returned.
+ }
+ return ret;
+ }
- private String getformattedRpmInformations() {
- StringBuilder formatedInfoString = new StringBuilder();
- IPreferenceStore store = Activator.getDefault().getPreferenceStore();
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_NAME)) {
- formatedInfoString.append("<b>Name: </b>%{NAME}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_VERSION)) {
- formatedInfoString.append("<b>Version: </b>%{VERSION}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_RELEASE)) {
- formatedInfoString.append("<b>Release: </b>%{Release}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_SUMMARY)) {
- formatedInfoString.append("<b>Summary: </b>%{SUMMARY}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_LICENSE)) {
- formatedInfoString.append("<b>License: </b>%{LICENSE}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_GROUP)) {
- formatedInfoString.append("<b>Group: </b>%{GROUP}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_URL)) {
- formatedInfoString.append("<b>URL: </b>%{URL}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_INSTALLTIME)) {
- formatedInfoString.append("<b>Installation Date: </b>%{INSTALLTIME:date}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_DESCRIPTION)) {
- formatedInfoString.append("<b>Description: </b>%{DESCRIPTION}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_PACKAGER)) {
- formatedInfoString.append("<b>Packager: </b>%{PACKAGER}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_VENDOR)) {
- formatedInfoString.append("<b>Vendor: </b>%{VENDOR}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_SIZE)) {
- formatedInfoString.append("<b>Size: </b>%{SIZE} bytes<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_BUILDTIME)) {
- formatedInfoString.append("<b>Build Date: </b>%{BUILDTIME:date}<br>"); //$NON-NLS-1$
- }
- if (store.getBoolean(PreferenceConstants.P_RPMINFO_SOURCERPM)) {
- formatedInfoString.append("<b>SRPM: </b>%{SOURCERPM}<br>"); //$NON-NLS-1$
- }
- return formatedInfoString.toString();
+ private String getformattedRpmInformations() {
+ StringBuilder formatedInfoString = new StringBuilder();
+ IPreferenceStore store = Activator.getDefault().getPreferenceStore();
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_NAME)) {
+ formatedInfoString.append("<b>Name: </b>%{NAME}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_VERSION)) {
+ formatedInfoString.append("<b>Version: </b>%{VERSION}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_RELEASE)) {
+ formatedInfoString.append("<b>Release: </b>%{Release}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_SUMMARY)) {
+ formatedInfoString.append("<b>Summary: </b>%{SUMMARY}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_LICENSE)) {
+ formatedInfoString.append("<b>License: </b>%{LICENSE}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_GROUP)) {
+ formatedInfoString.append("<b>Group: </b>%{GROUP}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_URL)) {
+ formatedInfoString.append("<b>URL: </b>%{URL}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_INSTALLTIME)) {
+ formatedInfoString.append("<b>Installation Date: </b>%{INSTALLTIME:date}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_DESCRIPTION)) {
+ formatedInfoString.append("<b>Description: </b>%{DESCRIPTION}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_PACKAGER)) {
+ formatedInfoString.append("<b>Packager: </b>%{PACKAGER}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_VENDOR)) {
+ formatedInfoString.append("<b>Vendor: </b>%{VENDOR}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_SIZE)) {
+ formatedInfoString.append("<b>Size: </b>%{SIZE} bytes<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_BUILDTIME)) {
+ formatedInfoString.append("<b>Build Date: </b>%{BUILDTIME:date}<br>"); //$NON-NLS-1$
+ }
+ if (store.getBoolean(PreferenceConstants.P_RPMINFO_SOURCERPM)) {
+ formatedInfoString.append("<b>SRPM: </b>%{SOURCERPM}<br>"); //$NON-NLS-1$
+ }
+ return formatedInfoString.toString();
- }
+ }
- /**
- * If the rpm package proposals list is being updated
- * block this thread
- */
- private void waitForUpdates() {
- RpmPackageBuildProposalsJob.waitForUpdates();
- }
+ /**
+ * If the rpm package proposals list is being updated
+ * block this thread
+ */
+ private void waitForUpdates() {
+ RpmPackageBuildProposalsJob.waitForUpdates();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmSections.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmSections.java
index 4dc581d9f3..dad300d4ab 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmSections.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmSections.java
@@ -14,21 +14,21 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor;
* Definitions of all the rpm sections.
*/
public interface RpmSections {
-
- String PREP_SECTION = "%prep"; //$NON-NLS-1$
- String BUILD_SECTION = "%build"; //$NON-NLS-1$
- String INSTALL_SECTION = "%install"; //$NON-NLS-1$
- String PRETRANS_SECTION = "%pretrans"; //$NON-NLS-1$
- String PRE_SECTION = "%pre"; //$NON-NLS-1$
- String PREUN_SECTION = "%preun"; //$NON-NLS-1$
- String POST_SECTION = "%post"; //$NON-NLS-1$
- String POSTUN_SECTION = "%postun"; //$NON-NLS-1$
- String POSTTRANS_SECTION = "%posttrans"; //$NON-NLS-1$
- String CLEAN_SECTION = "%clean"; //$NON-NLS-1$
- String FILES_SECTION = "%files"; //$NON-NLS-1$
- String CHECK_SECTION = "%check"; //$NON-NLS-1$
- String CHANGELOG_SECTION = "%changelog"; //$NON-NLS-1$
- String PACKAGE_SECTION = "%package"; //$NON-NLS-1$
- String DESCRIPTION_SECTION = "%description"; //$NON-NLS-1$
+
+ String PREP_SECTION = "%prep"; //$NON-NLS-1$
+ String BUILD_SECTION = "%build"; //$NON-NLS-1$
+ String INSTALL_SECTION = "%install"; //$NON-NLS-1$
+ String PRETRANS_SECTION = "%pretrans"; //$NON-NLS-1$
+ String PRE_SECTION = "%pre"; //$NON-NLS-1$
+ String PREUN_SECTION = "%preun"; //$NON-NLS-1$
+ String POST_SECTION = "%post"; //$NON-NLS-1$
+ String POSTUN_SECTION = "%postun"; //$NON-NLS-1$
+ String POSTTRANS_SECTION = "%posttrans"; //$NON-NLS-1$
+ String CLEAN_SECTION = "%clean"; //$NON-NLS-1$
+ String FILES_SECTION = "%files"; //$NON-NLS-1$
+ String CHECK_SECTION = "%check"; //$NON-NLS-1$
+ String CHANGELOG_SECTION = "%changelog"; //$NON-NLS-1$
+ String PACKAGE_SECTION = "%package"; //$NON-NLS-1$
+ String DESCRIPTION_SECTION = "%description"; //$NON-NLS-1$
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmTags.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmTags.java
index 0f8167545f..5f95106589 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmTags.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/RpmTags.java
@@ -16,33 +16,33 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor;
*
*/
public interface RpmTags {
- String SUMMARY = "Summary"; //$NON-NLS-1$
- String NAME = "Name"; //$NON-NLS-1$
- String VERSION = "Version"; //$NON-NLS-1$
- String PACKAGER = "Packager"; //$NON-NLS-1$
- String ICON = "Icon"; //$NON-NLS-1$
- String URL = "URL"; //$NON-NLS-1$
- String PREFIX = "Prefix"; //$NON-NLS-1$
- String GROUP = "Group"; //$NON-NLS-1$
- String LICENSE = "License"; //$NON-NLS-1$
- String RELEASE = "Release"; //$NON-NLS-1$
- String BUILD_ROOT = "BuildRoot"; //$NON-NLS-1$
- String DISTRIBUTION = "Distribution"; //$NON-NLS-1$
- String VENDOR = "Vendor"; //$NON-NLS-1$
- String PROVIDES = "Provides"; //$NON-NLS-1$
- String EXCLUSIVE_ARCH = "ExclusiveArch"; //$NON-NLS-1$
- String EXCLUDE_ARCH = "ExcludeArch"; //$NON-NLS-1$
- String EXCLUDE_OS = "ExclusiveOS"; //$NON-NLS-1$
- String BUILD_ARCH = "BuildArch"; //$NON-NLS-1$
- String BUILD_ARCHITECTURES = "BuildArchitectures"; //$NON-NLS-1$
- String AUTO_REQUIRES = "AutoRequires"; //$NON-NLS-1$
- String AUTO_REQ = "AutoReq"; //$NON-NLS-1$
- String AUTO_REQ_PROV = "AutoReqProv"; //$NON-NLS-1$
- String AUTO_PROV = "AutoProv"; //$NON-NLS-1$
- String EPOCH = "Epoch"; //$NON-NLS-1$
- String OBSOLETES = "Obsoletes"; //$NON-NLS-1$
- String REQUIRES = "Requires"; //$NON-NLS-1$
- String REQUIRES_PRE = "Requires(pre)"; //$NON-NLS-1$
- String REQUIRES_POST = "Requires(post)"; //$NON-NLS-1$
- String REQUIRES_POSTUN = "Requires(postun)"; //$NON-NLS-1$
+ String SUMMARY = "Summary"; //$NON-NLS-1$
+ String NAME = "Name"; //$NON-NLS-1$
+ String VERSION = "Version"; //$NON-NLS-1$
+ String PACKAGER = "Packager"; //$NON-NLS-1$
+ String ICON = "Icon"; //$NON-NLS-1$
+ String URL = "URL"; //$NON-NLS-1$
+ String PREFIX = "Prefix"; //$NON-NLS-1$
+ String GROUP = "Group"; //$NON-NLS-1$
+ String LICENSE = "License"; //$NON-NLS-1$
+ String RELEASE = "Release"; //$NON-NLS-1$
+ String BUILD_ROOT = "BuildRoot"; //$NON-NLS-1$
+ String DISTRIBUTION = "Distribution"; //$NON-NLS-1$
+ String VENDOR = "Vendor"; //$NON-NLS-1$
+ String PROVIDES = "Provides"; //$NON-NLS-1$
+ String EXCLUSIVE_ARCH = "ExclusiveArch"; //$NON-NLS-1$
+ String EXCLUDE_ARCH = "ExcludeArch"; //$NON-NLS-1$
+ String EXCLUDE_OS = "ExclusiveOS"; //$NON-NLS-1$
+ String BUILD_ARCH = "BuildArch"; //$NON-NLS-1$
+ String BUILD_ARCHITECTURES = "BuildArchitectures"; //$NON-NLS-1$
+ String AUTO_REQUIRES = "AutoRequires"; //$NON-NLS-1$
+ String AUTO_REQ = "AutoReq"; //$NON-NLS-1$
+ String AUTO_REQ_PROV = "AutoReqProv"; //$NON-NLS-1$
+ String AUTO_PROV = "AutoProv"; //$NON-NLS-1$
+ String EPOCH = "Epoch"; //$NON-NLS-1$
+ String OBSOLETES = "Obsoletes"; //$NON-NLS-1$
+ String REQUIRES = "Requires"; //$NON-NLS-1$
+ String REQUIRES_PRE = "Requires(pre)"; //$NON-NLS-1$
+ String REQUIRES_POST = "Requires(post)"; //$NON-NLS-1$
+ String REQUIRES_POSTUN = "Requires(postun)"; //$NON-NLS-1$
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileCompletionProcessor.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileCompletionProcessor.java
index a176abd2c0..2111ee104d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileCompletionProcessor.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileCompletionProcessor.java
@@ -53,570 +53,570 @@ import org.eclipse.linuxtools.rpm.ui.editor.parser.SpecfileSection;
*/
public class SpecfileCompletionProcessor implements IContentAssistProcessor {
- private static final String SOURCE = "SOURCE"; //$NON-NLS-1$
-
- private static final String EMPTY_STRING = ""; //$NON-NLS-1$
-
- /**
- * <code>Comparator</code> implementation used to sort template proposals
- * @author Van Assche Alphonse
- */
- private static final class TemplateProposalComparator implements Comparator<TemplateProposal>, Serializable {
- private static final long serialVersionUID = 1L;
- @Override
- public int compare(TemplateProposal t1, TemplateProposal t2) {
- return (t2.getRelevance() - t1.getRelevance());
- }
- }
-
- /**
- * Comparator implementation for a generic proposal
- * @author Sami Wagiaalla
- */
- private static final class ProposalComparator implements Comparator<ICompletionProposal>{
- @Override
- public int compare(ICompletionProposal a, ICompletionProposal b){
- return a.getDisplayString().compareToIgnoreCase(b.getDisplayString());
- }
- }
-
- private static final String TEMPLATE_ICON = "icons/template_obj.gif"; //$NON-NLS-1$
-
- private static final String MACRO_ICON = "icons/macro_obj.gif"; //$NON-NLS-1$
-
- private static final String PATCH_ICON = "icons/macro_obj.gif"; //$NON-NLS-1$
-
- private static final String PACKAGE_ICON = "icons/rpm.gif"; //$NON-NLS-1$
-
- private static final String PREAMBLE_SECTION_TEMPLATE = "org.eclipse.linuxtools.rpm.ui.editor.preambleSection"; //$NON-NLS-1$
-
- private static final String PRE_SECTION_TEMPLATE = "org.eclipse.linuxtools.rpm.ui.editor.preSection"; //$NON-NLS-1$
-
- private static final String BUILD_SECTION_TEMPLATE = "org.eclipse.linuxtools.rpm.ui.editor.buildSection"; //$NON-NLS-1$
-
- private static final String INSTALL_SECTION_TEMPLATE = "org.eclipse.linuxtools.rpm.ui.editor.installSection"; //$NON-NLS-1$
-
- private static final String CHANGELOG_SECTION_TEMPLATE = "org.eclipse.linuxtools.rpm.ui.editor.changelogSection"; //$NON-NLS-1$
-
- private final SpecfileEditor editor;
-
- private static final Comparator<ICompletionProposal> PROPOSAL_COMPARATOR = new ProposalComparator();
- private static final Comparator<TemplateProposal> TEMPLATE_PROPOSAL_COMPARATOR = new TemplateProposalComparator();
-
- /**
- * Default constructor
- */
- public SpecfileCompletionProcessor(SpecfileEditor editor) {
- this.editor = editor;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
- */
- @Override
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
- int offset) {
- List<ICompletionProposal> result = new ArrayList<>();
- Specfile specfile = editor.getSpecfile();
- if (specfile == null) {
- return null;
- }
- ITextSelection selection = (ITextSelection) viewer
- .getSelectionProvider().getSelection();
- // adjust offset to start of normalized selection
- if (selection.getOffset() != offset) {
- offset = selection.getOffset();
- }
- String prefix = getPrefix(viewer, offset);
- Region region = new Region(offset - prefix.length(), prefix.length()
- + selection.getLength());
- // RPM macro's are useful in the whole specfile.
- List<ICompletionProposal> rpmMacroProposals = computeRpmMacroProposals(
- region, specfile, prefix);
- // Sources completion
- List<ICompletionProposal> sourcesProposals = computeSourcesProposals(
- region, specfile, prefix);
- result.addAll(sourcesProposals);
- // Get the current content type
- String currentContentType = ((IDocument)editor.getAdapter(IDocument.class)).getDocumentPartitioner().getContentType(region.getOffset());
- if (currentContentType.equals(SpecfilePartitionScanner.SPEC_PREP)){
- List<ICompletionProposal> patchesProposals = computePatchesProposals(
- region, specfile, prefix);
- result.addAll(patchesProposals);
- }
-
- if (currentContentType.equals(SpecfilePartitionScanner.SPEC_PACKAGES)) {
- // don't show template in the RPM packages content type.
- // (when the line begin with Requires, BuildRequires etc...)
- List<ICompletionProposal> rpmPackageProposals = computeRpmPackageProposals(
- region, prefix);
- result.addAll(rpmPackageProposals);
- result.addAll(rpmMacroProposals);
- } else {
- // don't show RPM packages proposals in all others content type.
- List<? extends ICompletionProposal> templateProposals = computeTemplateProposals(
- viewer, region, specfile, prefix);
- result.addAll(templateProposals);
- result.addAll(rpmMacroProposals);
- }
- if (currentContentType.equals(SpecfilePartitionScanner.SPEC_GROUP)){
- IDocument document = viewer.getDocument();
- try {
- int lineNumber = document.getLineOfOffset(region.getOffset());
- int lineOffset = document.getLineOffset(lineNumber);
- if (region.getOffset() - lineOffset > 5){
- result.clear();
- String groupPrefix = getGroupPrefix(viewer, offset);
- result.addAll(computeRpmGroupProposals(region, groupPrefix));
- }
- } catch (BadLocationException e) {
- SpecfileLog.logError(e);
- }
- }
-
- return result
- .toArray(new ICompletionProposal[result.size()]);
- }
-
- /**
- * Compute the templates proposals, these proposals are contextual on sections.
- * Return an array of template proposals for the given viewer, region, specfile, prefix.
- *
- * @param viewer
- * the viewer for which the context is created
- * @param region
- * the region into <code>document</code> for which the context
- * is created
- * @param specfile
- * the specfile element
- * @param prefix
- * the prefix string
- * @return
- * a ICompletionProposal[]
- */
- private List<? extends ICompletionProposal> computeTemplateProposals(ITextViewer viewer,
- IRegion region, Specfile specfile, String prefix) {
- TemplateContext context = createContext(viewer, region, specfile);
- List<TemplateProposal> matches = new ArrayList<>();
- if (context == null) {
- return matches;
- }
- ITextSelection selection = (ITextSelection) viewer
- .getSelectionProvider().getSelection();
- context.setVariable("selection", selection.getText()); //$NON-NLS-1$
- String id = context.getContextType().getId();
- Template[] templates = Activator.getDefault().getTemplateStore()
- .getTemplates(id);
- for (Template template : templates) {
- try {
- context.getContextType().validate(template.getPattern());
- } catch (TemplateException e) {
- continue;
- }
- int relevance = getRelevance(template, prefix);
- if (relevance > 0) {
- matches.add(new TemplateProposal(template, context, region,
- Activator.getDefault().getImage(TEMPLATE_ICON), relevance));
- }
- }
- Collections.sort(matches, TEMPLATE_PROPOSAL_COMPARATOR);
- return matches;
- }
-
- /**
- * Compute RPM macro proposals, these proposals are usable in the whole document.
- * Return an array of RPM macro proposals for the given viewer, region, prefix.
- *
- * @param viewer
- * the viewer for which the context is created
- * @param region
- * the region into <code>document</code> for which the context
- * is created
- * @param prefix
- * the prefix string to find
- * @return
- * a ICompletionProposal[]
- */
- private List<ICompletionProposal> computeRpmMacroProposals(IRegion region,
- Specfile specfile, String prefix) {
- Map<String, String> rpmMacroProposalsMap = Activator.getDefault().getRpmMacroList().getProposals(prefix);
-
- // grab defines and put them into the proposals map
- rpmMacroProposalsMap.putAll(getDefines(specfile, prefix));
-
- ArrayList<ICompletionProposal> proposals = new ArrayList<>();
- if (rpmMacroProposalsMap != null) {
- for (Map.Entry<String, String> entry : rpmMacroProposalsMap
- .entrySet()) {
- proposals.add(new CompletionProposal(
- ISpecfileSpecialSymbols.MACRO_START_LONG
- + entry.getKey().substring(1)
- + ISpecfileSpecialSymbols.MACRO_END_LONG,
- region.getOffset(), region.getLength(), entry.getKey()
- .length() + 2, Activator.getDefault().getImage(
- MACRO_ICON), entry.getKey(), null, entry
- .getValue()));
- }
- }
- return proposals;
- }
-
- /**
- * Compute patches proposals, these proposals are usable in the whole document.
- * Return an array of patches proposals for the given viewer, region, prefix.
- *
- * @param viewer
- * the viewer for which the context is created
- * @param region
- * the region into <code>document</code> for which the context
- * is created
- * @param prefix
- * the prefix string to find
- * @return
- * a ICompletionProposal[]
- */
- private List<ICompletionProposal> computePatchesProposals(IRegion region,
- Specfile specfile, String prefix) {
- // grab patches and put them into the proposals map
- Map<String, String> patchesProposalsMap = getPatches(specfile, prefix);
- ArrayList<ICompletionProposal> proposals = new ArrayList<>();
- if (patchesProposalsMap != null) {
- for (Map.Entry<String, String> entry : patchesProposalsMap
- .entrySet()) {
- proposals.add(new CompletionProposal(entry.getKey(), region
- .getOffset(), region.getLength(), entry.getKey()
- .length(), Activator.getDefault().getImage(PATCH_ICON),
- entry.getKey(), null, entry.getValue()));
- }
- }
- return proposals;
- }
-
- /**
- * Compute sources proposals, these proposals are usable in the whole document.
- * Return an array of sources proposals for the given viewer, region, prefix.
- *
- * @param viewer
- * the viewer for which the context is created
- * @param region
- * the region into <code>document</code> for which the context
- * is created
- * @param prefix
- * the prefix string to find
- * @return
- * a ICompletionProposal[]
- */
- private List<ICompletionProposal> computeSourcesProposals(IRegion region,
- Specfile specfile, String prefix) {
- // grab patches and put them into the proposals map
- Map<String, String> sourcesProposalsMap = getSources(specfile, prefix);
- ArrayList<ICompletionProposal> proposals = new ArrayList<>();
- if (sourcesProposalsMap != null) {
- for (Map.Entry<String, String> entry : sourcesProposalsMap
- .entrySet()) {
- proposals.add(new CompletionProposal(entry.getKey(), region
- .getOffset(), region.getLength(), entry.getKey()
- .length(), Activator.getDefault().getImage(PATCH_ICON),
- entry.getKey(), null, entry.getValue()));
- }
- }
- return proposals;
- }
-
- /**
- * Compute RPM package proposals, these proposals are usable only in the preambule section.
- * Return an array of RPM macro proposals for the given viewer, region, specfile, prefix.
- *
- * @param viewer
- * the viewer for which the context is created
- * @param region
- * the region into <code>document</code> for which the context
- * is created
- * @param prefix
- * the prefix string
- * @return
- * a ICompletionProposal[]
- */
- private List<ICompletionProposal> computeRpmPackageProposals(IRegion region,
- String prefix) {
- List<String[]> rpmPkgProposalsList = Activator.getDefault().getRpmPackageList().getProposals(prefix);
- ArrayList<ICompletionProposal> proposals = new ArrayList<>();
- if (rpmPkgProposalsList != null) {
- for (String[] item : rpmPkgProposalsList) {
- proposals.add(new CompletionProposal(item[0], region
- .getOffset(), region.getLength(), item[0].length(),
- Activator.getDefault().getImage(PACKAGE_ICON), item[0],
- null, item[1]));
- }
- }
-
- Collections.sort(proposals, PROPOSAL_COMPARATOR);
- return proposals;
- }
-
- private List<ICompletionProposal> computeRpmGroupProposals(IRegion region,
- String prefix) {
- List<String> rpmGroupProposalsList = Activator.getDefault()
- .getRpmGroups();
- ArrayList<ICompletionProposal> proposals = new ArrayList<>();
- for (String item : rpmGroupProposalsList) {
- if (item.startsWith(prefix)) {
- proposals.add(new CompletionProposal(item, region.getOffset(),
- region.getLength(), item.length(), Activator
- .getDefault().getImage(PACKAGE_ICON), item,
- null, item));
- }
- }
- return proposals;
- }
-
- /**
- * Create a template context for the givens Specfile, offset.
- *
- * @param specfile
- * the sepcfile element
- * @param offset
- * the offset of the <code>documment</code>
- * @return a TemplateContextType
- */
- private TemplateContextType getContextType(Specfile specfile, int offset) {
- List<SpecfileSection> elements = specfile.getSections();
- if (elements.size() == 0 || offset < elements.get(0).getLineEndPosition()) {
- return Activator.getDefault().getContextTypeRegistry()
- .getContextType(PREAMBLE_SECTION_TEMPLATE);
- } else if (elements.size() == 1 || offset < elements.get(1).getLineEndPosition()) {
- return Activator.getDefault().getContextTypeRegistry()
- .getContextType(PRE_SECTION_TEMPLATE);
- } else if (elements.size() == 2 || offset < elements.get(2).getLineEndPosition()) {
- return Activator.getDefault().getContextTypeRegistry()
- .getContextType(BUILD_SECTION_TEMPLATE);
- } else if (elements.size() == 3 || offset < elements.get(3).getLineEndPosition()) {
- return Activator.getDefault().getContextTypeRegistry()
- .getContextType(INSTALL_SECTION_TEMPLATE);
- } else {
- return Activator.getDefault().getContextTypeRegistry()
- .getContextType(CHANGELOG_SECTION_TEMPLATE);
- }
-
- }
-
- /**
- * Create a template context for the given Specfile and offset.
- *
- * @param viewer
- * the viewer for which the context is created
- * @param region
- * the region into <code>document</code> for which the context
- * is created
- * @param specfile
- * the specfile element
- * @return a TemplateContextType
- */
- private TemplateContext createContext(ITextViewer viewer, IRegion region,
- Specfile specfile) {
- TemplateContextType contextType = getContextType(specfile, region
- .getOffset());
- if (contextType != null) {
- IDocument document = viewer.getDocument();
- return new DocumentTemplateContext(contextType, document, region
- .getOffset(), region.getLength());
- }
- return null;
- }
-
- /**
- * Get relevance on templates for the given template and prefix.
- * @param template
- * the <code>Template</code> to get relevance
- * @param prefix
- * the prefix <code>String</code> to check.
- * @return
- * a relevant code (90 if <code>true</code> and 0 if not)
- */
- private int getRelevance(Template template, String prefix) {
- if (template.getName().startsWith(prefix)) {
- return 90;
- }
- return 0;
- }
-
- /**
- * Get the prefix for a given viewer, offset.
- *
- * @param viewer
- * the viewer for which the context is created
- * @param offset
- * the offset into <code>document</code> for which the prefix
- * is research
- * @return the prefix
- */
- private String getPrefix(ITextViewer viewer, int offset) {
- int i = offset;
- IDocument document = viewer.getDocument();
- if (i > document.getLength()) {
- return EMPTY_STRING;
- }
-
- try {
- while (i > 0) {
- char ch = document.getChar(i - 1);
- if (!Character.isLetterOrDigit(ch) && (ch != '%') && (ch != '_') && (ch != '-') && (ch != '{') && (ch != '.') && (ch != '+')) {
- break;
- }
- i--;
- }
- return document.get(i, offset - i);
- } catch (BadLocationException e) {
- return EMPTY_STRING;
- }
- }
-
- /**
- * Get the prefix for a given viewer, offset.
- *
- * @param viewer
- * the viewer for which the context is created
- * @param offset
- * the offset into <code>document</code> for which the prefix
- * is research
- * @return the prefix
- */
- private String getGroupPrefix(ITextViewer viewer, int offset) {
- int i = offset;
- IDocument document = viewer.getDocument();
- if (i > document.getLength()) {
- return EMPTY_STRING;
- }
-
- try {
- while (i > 0) {
- char ch = document.getChar(i - 1);
- if (!Character.isLetterOrDigit(ch) && (ch != '/')) {
- break;
- }
- i--;
- }
- return document.get(i, offset - i);
- } catch (BadLocationException e) {
- return EMPTY_STRING;
- }
- }
-
- /**
- * Get defines as a String key->value pair for a given specfile
- * and prefix.
- *
- * @param specfile
- * to get defines from.
- * @param prefix
- * used to find defines.
- * @return a <code>HashMap</code> of defines.
- *
- */
- private Map<String, String> getDefines(Specfile specfile, String prefix) {
- Collection<SpecfileDefine> defines = specfile.getDefines();
- Map<String, String> ret = new HashMap<>();
- String defineName;
- for (SpecfileDefine define: defines) {
- defineName = "%" + define.getName(); //$NON-NLS-1$
- if (defineName.startsWith(prefix.replaceFirst("\\{", EMPTY_STRING))) {//$NON-NLS-1$
- ret.put(defineName, define.getStringValue());
- }
- }
- return ret;
- }
-
- /**
- * Get patches as a String key->value pair for a given specfile
- * and prefix.
- *
- * @param specfile
- * to get defines from.
- * @param prefix
- * used to find defines.
- * @return a <code>HashMap</code> of defines.
- *
- */
- private Map<String, String> getPatches(Specfile specfile, String prefix) {
- Collection<SpecfileSource> patches = specfile.getPatches();
- Map<String, String> ret = new HashMap<>();
- String patchName;
- for (SpecfileSource patch: patches) {
- patchName = "%patch" + patch.getNumber(); //$NON-NLS-1$
- if (patchName.startsWith(prefix)) {
- ret.put(patchName.toLowerCase(), SpecfileHover
- .getSourceOrPatchValue(specfile, "patch" //$NON-NLS-1$
- + patch.getNumber()));
- }
- }
- return ret;
- }
-
- /**
- * Get sources as a String key->value pair for a given specfile
- * and prefix.
- *
- * @param specfile
- * to get defines from.
- * @param prefix
- * used to find defines.
- * @return a <code>HashMap</code> of defines.
- *
- */
- private Map<String, String> getSources(Specfile specfile, String prefix) {
- Collection<SpecfileSource> sources = specfile.getSources();
- Map<String, String> ret = new HashMap<>();
- String sourceName;
- for (SpecfileSource source : sources) {
- sourceName = ISpecfileSpecialSymbols.MACRO_START_LONG + SOURCE
- + source.getNumber()
- + ISpecfileSpecialSymbols.MACRO_END_LONG;
- if (sourceName.startsWith(prefix)) {
- ret.put(sourceName, SpecfileHover.getSourceOrPatchValue(
- specfile, SOURCE + source.getNumber()));
- }
- }
- return ret;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
- */
- @Override
- public IContextInformation[] computeContextInformation(ITextViewer viewer,
- int offset) {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
- */
- @Override
- public char[] getCompletionProposalAutoActivationCharacters() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
- */
- @Override
- public char[] getContextInformationAutoActivationCharacters() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
- */
- @Override
- public String getErrorMessage() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
- */
- @Override
- public IContextInformationValidator getContextInformationValidator() {
- return null;
- }
+ private static final String SOURCE = "SOURCE"; //$NON-NLS-1$
+
+ private static final String EMPTY_STRING = ""; //$NON-NLS-1$
+
+ /**
+ * <code>Comparator</code> implementation used to sort template proposals
+ * @author Van Assche Alphonse
+ */
+ private static final class TemplateProposalComparator implements Comparator<TemplateProposal>, Serializable {
+ private static final long serialVersionUID = 1L;
+ @Override
+ public int compare(TemplateProposal t1, TemplateProposal t2) {
+ return (t2.getRelevance() - t1.getRelevance());
+ }
+ }
+
+ /**
+ * Comparator implementation for a generic proposal
+ * @author Sami Wagiaalla
+ */
+ private static final class ProposalComparator implements Comparator<ICompletionProposal>{
+ @Override
+ public int compare(ICompletionProposal a, ICompletionProposal b){
+ return a.getDisplayString().compareToIgnoreCase(b.getDisplayString());
+ }
+ }
+
+ private static final String TEMPLATE_ICON = "icons/template_obj.gif"; //$NON-NLS-1$
+
+ private static final String MACRO_ICON = "icons/macro_obj.gif"; //$NON-NLS-1$
+
+ private static final String PATCH_ICON = "icons/macro_obj.gif"; //$NON-NLS-1$
+
+ private static final String PACKAGE_ICON = "icons/rpm.gif"; //$NON-NLS-1$
+
+ private static final String PREAMBLE_SECTION_TEMPLATE = "org.eclipse.linuxtools.rpm.ui.editor.preambleSection"; //$NON-NLS-1$
+
+ private static final String PRE_SECTION_TEMPLATE = "org.eclipse.linuxtools.rpm.ui.editor.preSection"; //$NON-NLS-1$
+
+ private static final String BUILD_SECTION_TEMPLATE = "org.eclipse.linuxtools.rpm.ui.editor.buildSection"; //$NON-NLS-1$
+
+ private static final String INSTALL_SECTION_TEMPLATE = "org.eclipse.linuxtools.rpm.ui.editor.installSection"; //$NON-NLS-1$
+
+ private static final String CHANGELOG_SECTION_TEMPLATE = "org.eclipse.linuxtools.rpm.ui.editor.changelogSection"; //$NON-NLS-1$
+
+ private final SpecfileEditor editor;
+
+ private static final Comparator<ICompletionProposal> PROPOSAL_COMPARATOR = new ProposalComparator();
+ private static final Comparator<TemplateProposal> TEMPLATE_PROPOSAL_COMPARATOR = new TemplateProposalComparator();
+
+ /**
+ * Default constructor
+ */
+ public SpecfileCompletionProcessor(SpecfileEditor editor) {
+ this.editor = editor;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
+ */
+ @Override
+ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
+ int offset) {
+ List<ICompletionProposal> result = new ArrayList<>();
+ Specfile specfile = editor.getSpecfile();
+ if (specfile == null) {
+ return null;
+ }
+ ITextSelection selection = (ITextSelection) viewer
+ .getSelectionProvider().getSelection();
+ // adjust offset to start of normalized selection
+ if (selection.getOffset() != offset) {
+ offset = selection.getOffset();
+ }
+ String prefix = getPrefix(viewer, offset);
+ Region region = new Region(offset - prefix.length(), prefix.length()
+ + selection.getLength());
+ // RPM macro's are useful in the whole specfile.
+ List<ICompletionProposal> rpmMacroProposals = computeRpmMacroProposals(
+ region, specfile, prefix);
+ // Sources completion
+ List<ICompletionProposal> sourcesProposals = computeSourcesProposals(
+ region, specfile, prefix);
+ result.addAll(sourcesProposals);
+ // Get the current content type
+ String currentContentType = ((IDocument)editor.getAdapter(IDocument.class)).getDocumentPartitioner().getContentType(region.getOffset());
+ if (currentContentType.equals(SpecfilePartitionScanner.SPEC_PREP)){
+ List<ICompletionProposal> patchesProposals = computePatchesProposals(
+ region, specfile, prefix);
+ result.addAll(patchesProposals);
+ }
+
+ if (currentContentType.equals(SpecfilePartitionScanner.SPEC_PACKAGES)) {
+ // don't show template in the RPM packages content type.
+ // (when the line begin with Requires, BuildRequires etc...)
+ List<ICompletionProposal> rpmPackageProposals = computeRpmPackageProposals(
+ region, prefix);
+ result.addAll(rpmPackageProposals);
+ result.addAll(rpmMacroProposals);
+ } else {
+ // don't show RPM packages proposals in all others content type.
+ List<? extends ICompletionProposal> templateProposals = computeTemplateProposals(
+ viewer, region, specfile, prefix);
+ result.addAll(templateProposals);
+ result.addAll(rpmMacroProposals);
+ }
+ if (currentContentType.equals(SpecfilePartitionScanner.SPEC_GROUP)){
+ IDocument document = viewer.getDocument();
+ try {
+ int lineNumber = document.getLineOfOffset(region.getOffset());
+ int lineOffset = document.getLineOffset(lineNumber);
+ if (region.getOffset() - lineOffset > 5){
+ result.clear();
+ String groupPrefix = getGroupPrefix(viewer, offset);
+ result.addAll(computeRpmGroupProposals(region, groupPrefix));
+ }
+ } catch (BadLocationException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+
+ return result
+ .toArray(new ICompletionProposal[result.size()]);
+ }
+
+ /**
+ * Compute the templates proposals, these proposals are contextual on sections.
+ * Return an array of template proposals for the given viewer, region, specfile, prefix.
+ *
+ * @param viewer
+ * the viewer for which the context is created
+ * @param region
+ * the region into <code>document</code> for which the context
+ * is created
+ * @param specfile
+ * the specfile element
+ * @param prefix
+ * the prefix string
+ * @return
+ * a ICompletionProposal[]
+ */
+ private List<? extends ICompletionProposal> computeTemplateProposals(ITextViewer viewer,
+ IRegion region, Specfile specfile, String prefix) {
+ TemplateContext context = createContext(viewer, region, specfile);
+ List<TemplateProposal> matches = new ArrayList<>();
+ if (context == null) {
+ return matches;
+ }
+ ITextSelection selection = (ITextSelection) viewer
+ .getSelectionProvider().getSelection();
+ context.setVariable("selection", selection.getText()); //$NON-NLS-1$
+ String id = context.getContextType().getId();
+ Template[] templates = Activator.getDefault().getTemplateStore()
+ .getTemplates(id);
+ for (Template template : templates) {
+ try {
+ context.getContextType().validate(template.getPattern());
+ } catch (TemplateException e) {
+ continue;
+ }
+ int relevance = getRelevance(template, prefix);
+ if (relevance > 0) {
+ matches.add(new TemplateProposal(template, context, region,
+ Activator.getDefault().getImage(TEMPLATE_ICON), relevance));
+ }
+ }
+ Collections.sort(matches, TEMPLATE_PROPOSAL_COMPARATOR);
+ return matches;
+ }
+
+ /**
+ * Compute RPM macro proposals, these proposals are usable in the whole document.
+ * Return an array of RPM macro proposals for the given viewer, region, prefix.
+ *
+ * @param viewer
+ * the viewer for which the context is created
+ * @param region
+ * the region into <code>document</code> for which the context
+ * is created
+ * @param prefix
+ * the prefix string to find
+ * @return
+ * a ICompletionProposal[]
+ */
+ private List<ICompletionProposal> computeRpmMacroProposals(IRegion region,
+ Specfile specfile, String prefix) {
+ Map<String, String> rpmMacroProposalsMap = Activator.getDefault().getRpmMacroList().getProposals(prefix);
+
+ // grab defines and put them into the proposals map
+ rpmMacroProposalsMap.putAll(getDefines(specfile, prefix));
+
+ ArrayList<ICompletionProposal> proposals = new ArrayList<>();
+ if (rpmMacroProposalsMap != null) {
+ for (Map.Entry<String, String> entry : rpmMacroProposalsMap
+ .entrySet()) {
+ proposals.add(new CompletionProposal(
+ ISpecfileSpecialSymbols.MACRO_START_LONG
+ + entry.getKey().substring(1)
+ + ISpecfileSpecialSymbols.MACRO_END_LONG,
+ region.getOffset(), region.getLength(), entry.getKey()
+ .length() + 2, Activator.getDefault().getImage(
+ MACRO_ICON), entry.getKey(), null, entry
+ .getValue()));
+ }
+ }
+ return proposals;
+ }
+
+ /**
+ * Compute patches proposals, these proposals are usable in the whole document.
+ * Return an array of patches proposals for the given viewer, region, prefix.
+ *
+ * @param viewer
+ * the viewer for which the context is created
+ * @param region
+ * the region into <code>document</code> for which the context
+ * is created
+ * @param prefix
+ * the prefix string to find
+ * @return
+ * a ICompletionProposal[]
+ */
+ private List<ICompletionProposal> computePatchesProposals(IRegion region,
+ Specfile specfile, String prefix) {
+ // grab patches and put them into the proposals map
+ Map<String, String> patchesProposalsMap = getPatches(specfile, prefix);
+ ArrayList<ICompletionProposal> proposals = new ArrayList<>();
+ if (patchesProposalsMap != null) {
+ for (Map.Entry<String, String> entry : patchesProposalsMap
+ .entrySet()) {
+ proposals.add(new CompletionProposal(entry.getKey(), region
+ .getOffset(), region.getLength(), entry.getKey()
+ .length(), Activator.getDefault().getImage(PATCH_ICON),
+ entry.getKey(), null, entry.getValue()));
+ }
+ }
+ return proposals;
+ }
+
+ /**
+ * Compute sources proposals, these proposals are usable in the whole document.
+ * Return an array of sources proposals for the given viewer, region, prefix.
+ *
+ * @param viewer
+ * the viewer for which the context is created
+ * @param region
+ * the region into <code>document</code> for which the context
+ * is created
+ * @param prefix
+ * the prefix string to find
+ * @return
+ * a ICompletionProposal[]
+ */
+ private List<ICompletionProposal> computeSourcesProposals(IRegion region,
+ Specfile specfile, String prefix) {
+ // grab patches and put them into the proposals map
+ Map<String, String> sourcesProposalsMap = getSources(specfile, prefix);
+ ArrayList<ICompletionProposal> proposals = new ArrayList<>();
+ if (sourcesProposalsMap != null) {
+ for (Map.Entry<String, String> entry : sourcesProposalsMap
+ .entrySet()) {
+ proposals.add(new CompletionProposal(entry.getKey(), region
+ .getOffset(), region.getLength(), entry.getKey()
+ .length(), Activator.getDefault().getImage(PATCH_ICON),
+ entry.getKey(), null, entry.getValue()));
+ }
+ }
+ return proposals;
+ }
+
+ /**
+ * Compute RPM package proposals, these proposals are usable only in the preambule section.
+ * Return an array of RPM macro proposals for the given viewer, region, specfile, prefix.
+ *
+ * @param viewer
+ * the viewer for which the context is created
+ * @param region
+ * the region into <code>document</code> for which the context
+ * is created
+ * @param prefix
+ * the prefix string
+ * @return
+ * a ICompletionProposal[]
+ */
+ private List<ICompletionProposal> computeRpmPackageProposals(IRegion region,
+ String prefix) {
+ List<String[]> rpmPkgProposalsList = Activator.getDefault().getRpmPackageList().getProposals(prefix);
+ ArrayList<ICompletionProposal> proposals = new ArrayList<>();
+ if (rpmPkgProposalsList != null) {
+ for (String[] item : rpmPkgProposalsList) {
+ proposals.add(new CompletionProposal(item[0], region
+ .getOffset(), region.getLength(), item[0].length(),
+ Activator.getDefault().getImage(PACKAGE_ICON), item[0],
+ null, item[1]));
+ }
+ }
+
+ Collections.sort(proposals, PROPOSAL_COMPARATOR);
+ return proposals;
+ }
+
+ private List<ICompletionProposal> computeRpmGroupProposals(IRegion region,
+ String prefix) {
+ List<String> rpmGroupProposalsList = Activator.getDefault()
+ .getRpmGroups();
+ ArrayList<ICompletionProposal> proposals = new ArrayList<>();
+ for (String item : rpmGroupProposalsList) {
+ if (item.startsWith(prefix)) {
+ proposals.add(new CompletionProposal(item, region.getOffset(),
+ region.getLength(), item.length(), Activator
+ .getDefault().getImage(PACKAGE_ICON), item,
+ null, item));
+ }
+ }
+ return proposals;
+ }
+
+ /**
+ * Create a template context for the givens Specfile, offset.
+ *
+ * @param specfile
+ * the sepcfile element
+ * @param offset
+ * the offset of the <code>documment</code>
+ * @return a TemplateContextType
+ */
+ private TemplateContextType getContextType(Specfile specfile, int offset) {
+ List<SpecfileSection> elements = specfile.getSections();
+ if (elements.size() == 0 || offset < elements.get(0).getLineEndPosition()) {
+ return Activator.getDefault().getContextTypeRegistry()
+ .getContextType(PREAMBLE_SECTION_TEMPLATE);
+ } else if (elements.size() == 1 || offset < elements.get(1).getLineEndPosition()) {
+ return Activator.getDefault().getContextTypeRegistry()
+ .getContextType(PRE_SECTION_TEMPLATE);
+ } else if (elements.size() == 2 || offset < elements.get(2).getLineEndPosition()) {
+ return Activator.getDefault().getContextTypeRegistry()
+ .getContextType(BUILD_SECTION_TEMPLATE);
+ } else if (elements.size() == 3 || offset < elements.get(3).getLineEndPosition()) {
+ return Activator.getDefault().getContextTypeRegistry()
+ .getContextType(INSTALL_SECTION_TEMPLATE);
+ } else {
+ return Activator.getDefault().getContextTypeRegistry()
+ .getContextType(CHANGELOG_SECTION_TEMPLATE);
+ }
+
+ }
+
+ /**
+ * Create a template context for the given Specfile and offset.
+ *
+ * @param viewer
+ * the viewer for which the context is created
+ * @param region
+ * the region into <code>document</code> for which the context
+ * is created
+ * @param specfile
+ * the specfile element
+ * @return a TemplateContextType
+ */
+ private TemplateContext createContext(ITextViewer viewer, IRegion region,
+ Specfile specfile) {
+ TemplateContextType contextType = getContextType(specfile, region
+ .getOffset());
+ if (contextType != null) {
+ IDocument document = viewer.getDocument();
+ return new DocumentTemplateContext(contextType, document, region
+ .getOffset(), region.getLength());
+ }
+ return null;
+ }
+
+ /**
+ * Get relevance on templates for the given template and prefix.
+ * @param template
+ * the <code>Template</code> to get relevance
+ * @param prefix
+ * the prefix <code>String</code> to check.
+ * @return
+ * a relevant code (90 if <code>true</code> and 0 if not)
+ */
+ private int getRelevance(Template template, String prefix) {
+ if (template.getName().startsWith(prefix)) {
+ return 90;
+ }
+ return 0;
+ }
+
+ /**
+ * Get the prefix for a given viewer, offset.
+ *
+ * @param viewer
+ * the viewer for which the context is created
+ * @param offset
+ * the offset into <code>document</code> for which the prefix
+ * is research
+ * @return the prefix
+ */
+ private String getPrefix(ITextViewer viewer, int offset) {
+ int i = offset;
+ IDocument document = viewer.getDocument();
+ if (i > document.getLength()) {
+ return EMPTY_STRING;
+ }
+
+ try {
+ while (i > 0) {
+ char ch = document.getChar(i - 1);
+ if (!Character.isLetterOrDigit(ch) && (ch != '%') && (ch != '_') && (ch != '-') && (ch != '{') && (ch != '.') && (ch != '+')) {
+ break;
+ }
+ i--;
+ }
+ return document.get(i, offset - i);
+ } catch (BadLocationException e) {
+ return EMPTY_STRING;
+ }
+ }
+
+ /**
+ * Get the prefix for a given viewer, offset.
+ *
+ * @param viewer
+ * the viewer for which the context is created
+ * @param offset
+ * the offset into <code>document</code> for which the prefix
+ * is research
+ * @return the prefix
+ */
+ private String getGroupPrefix(ITextViewer viewer, int offset) {
+ int i = offset;
+ IDocument document = viewer.getDocument();
+ if (i > document.getLength()) {
+ return EMPTY_STRING;
+ }
+
+ try {
+ while (i > 0) {
+ char ch = document.getChar(i - 1);
+ if (!Character.isLetterOrDigit(ch) && (ch != '/')) {
+ break;
+ }
+ i--;
+ }
+ return document.get(i, offset - i);
+ } catch (BadLocationException e) {
+ return EMPTY_STRING;
+ }
+ }
+
+ /**
+ * Get defines as a String key->value pair for a given specfile
+ * and prefix.
+ *
+ * @param specfile
+ * to get defines from.
+ * @param prefix
+ * used to find defines.
+ * @return a <code>HashMap</code> of defines.
+ *
+ */
+ private Map<String, String> getDefines(Specfile specfile, String prefix) {
+ Collection<SpecfileDefine> defines = specfile.getDefines();
+ Map<String, String> ret = new HashMap<>();
+ String defineName;
+ for (SpecfileDefine define: defines) {
+ defineName = "%" + define.getName(); //$NON-NLS-1$
+ if (defineName.startsWith(prefix.replaceFirst("\\{", EMPTY_STRING))) {//$NON-NLS-1$
+ ret.put(defineName, define.getStringValue());
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Get patches as a String key->value pair for a given specfile
+ * and prefix.
+ *
+ * @param specfile
+ * to get defines from.
+ * @param prefix
+ * used to find defines.
+ * @return a <code>HashMap</code> of defines.
+ *
+ */
+ private Map<String, String> getPatches(Specfile specfile, String prefix) {
+ Collection<SpecfileSource> patches = specfile.getPatches();
+ Map<String, String> ret = new HashMap<>();
+ String patchName;
+ for (SpecfileSource patch: patches) {
+ patchName = "%patch" + patch.getNumber(); //$NON-NLS-1$
+ if (patchName.startsWith(prefix)) {
+ ret.put(patchName.toLowerCase(), SpecfileHover
+ .getSourceOrPatchValue(specfile, "patch" //$NON-NLS-1$
+ + patch.getNumber()));
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Get sources as a String key->value pair for a given specfile
+ * and prefix.
+ *
+ * @param specfile
+ * to get defines from.
+ * @param prefix
+ * used to find defines.
+ * @return a <code>HashMap</code> of defines.
+ *
+ */
+ private Map<String, String> getSources(Specfile specfile, String prefix) {
+ Collection<SpecfileSource> sources = specfile.getSources();
+ Map<String, String> ret = new HashMap<>();
+ String sourceName;
+ for (SpecfileSource source : sources) {
+ sourceName = ISpecfileSpecialSymbols.MACRO_START_LONG + SOURCE
+ + source.getNumber()
+ + ISpecfileSpecialSymbols.MACRO_END_LONG;
+ if (sourceName.startsWith(prefix)) {
+ ret.put(sourceName, SpecfileHover.getSourceOrPatchValue(
+ specfile, SOURCE + source.getNumber()));
+ }
+ }
+ return ret;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
+ */
+ @Override
+ public IContextInformation[] computeContextInformation(ITextViewer viewer,
+ int offset) {
+ return null;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
+ */
+ @Override
+ public char[] getCompletionProposalAutoActivationCharacters() {
+ return null;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
+ */
+ @Override
+ public char[] getContextInformationAutoActivationCharacters() {
+ return null;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
+ */
+ @Override
+ public String getErrorMessage() {
+ return null;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
+ */
+ @Override
+ public IContextInformationValidator getContextInformationValidator() {
+ return null;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileConfiguration.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileConfiguration.java
index 85ed5cc5ea..2dddd90570 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileConfiguration.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileConfiguration.java
@@ -55,250 +55,250 @@ import org.eclipse.ui.texteditor.HyperlinkDetectorDescriptor;
import org.eclipse.ui.texteditor.HyperlinkDetectorRegistry;
public class SpecfileConfiguration extends TextSourceViewerConfiguration {
- private SpecfileDoubleClickStrategy doubleClickStrategy;
- private SpecfileScanner scanner;
- private SpecfileChangelogScanner changelogScanner;
- private SpecfilePackagesScanner packagesScanner;
- private ColorManager colorManager;
- private SpecfileHover specfileHover;
- private SpecfileEditor editor;
-
- public SpecfileConfiguration(ColorManager colorManager, SpecfileEditor editor) {
- super();
- this.colorManager = colorManager;
- this.editor = editor;
- }
-
- /**
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredContentTypes(org.eclipse.jface.text.source.ISourceViewer)
- */
- @Override
- public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
- return SpecfilePartitionScanner.SPEC_PARTITION_TYPES;
- }
-
- /**
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getDoubleClickStrategy(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
- */
- @Override
- public ITextDoubleClickStrategy getDoubleClickStrategy(
- ISourceViewer sourceViewer,
- String contentType) {
- if (doubleClickStrategy == null) {
- doubleClickStrategy = new SpecfileDoubleClickStrategy();
- }
- return doubleClickStrategy;
- }
-
- protected SpecfileScanner getSpecfileScanner() {
- if (scanner == null) {
- scanner = new SpecfileScanner(colorManager);
- scanner.setDefaultReturnToken(
- new Token(
- new TextAttribute(
- colorManager.getColor(ISpecfileColorConstants.DEFAULT))));
- }
- return scanner;
- }
-
- protected SpecfileChangelogScanner getSpecfileChangelogScanner() {
- if (changelogScanner == null) {
- changelogScanner = new SpecfileChangelogScanner(colorManager);
- changelogScanner.setDefaultReturnToken(
- new Token(
- new TextAttribute(
- colorManager.getColor(ISpecfileColorConstants.DEFAULT))));
- }
- return changelogScanner;
- }
-
- protected SpecfilePackagesScanner getSpecfilePackagesScanner() {
- if (packagesScanner == null) {
- packagesScanner = new SpecfilePackagesScanner(colorManager);
- packagesScanner.setDefaultReturnToken(
- new Token(
- new TextAttribute(
- colorManager.getColor(ISpecfileColorConstants.DEFAULT))));
- }
- return packagesScanner;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.editors.text.TextSourceViewerConfiguration#getTextHover(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
- */
- @Override
- public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
- if (specfileHover == null) {
- specfileHover = new SpecfileHover(this.editor);
- }
- return specfileHover;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(org.eclipse.jface.text.source.ISourceViewer)
- */
- @Override
- public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
- PresentationReconciler reconciler = new PresentationReconciler();
-
- DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getSpecfileScanner());
- reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
- reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
-
- dr = new DefaultDamagerRepairer(getSpecfilePackagesScanner());
- reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_PACKAGES);
- reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_PACKAGES);
-
- dr = new DefaultDamagerRepairer(getSpecfileScanner());
- reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_PREP);
- reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_PREP);
-
- dr = new DefaultDamagerRepairer(getSpecfileScanner());
- reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_SCRIPT);
- reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_SCRIPT);
-
- dr = new DefaultDamagerRepairer(getSpecfileScanner());
- reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_FILES);
- reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_FILES);
-
- dr = new DefaultDamagerRepairer(getSpecfileScanner());
- reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_GROUP);
- reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_GROUP);
-
- dr = new DefaultDamagerRepairer(getSpecfileChangelogScanner());
- reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_CHANGELOG);
- reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_CHANGELOG);
-
- return reconciler;
- }
-
- /*
- * @see SourceViewerConfiguration#getReconciler(ISourceViewer)
- */
- @Override
- public IReconciler getReconciler(ISourceViewer sourceViewer) {
- if (editor != null && editor.isEditable()) {
- SpecfileReconcilingStrategy strategy= new SpecfileReconcilingStrategy(editor);
- MonoReconciler reconciler= new MonoReconciler(strategy, false);
- reconciler.setProgressMonitor(new NullProgressMonitor());
- reconciler.setDelay(500);
- return reconciler;
- }
- return null;
- }
-
- /*
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getContentAssistant(org.eclipse.jface.text.source.ISourceViewer)
- */
- @Override
- public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
- ContentAssistant assistant= new ContentAssistant();
- IContentAssistProcessor processor= new SpecfileCompletionProcessor(editor);
- // add content assistance to all the supported contentType
- assistant.setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE);
- assistant.setContentAssistProcessor(processor, SpecfilePartitionScanner.SPEC_PREP);
- assistant.setContentAssistProcessor(processor, SpecfilePartitionScanner.SPEC_SCRIPT);
- assistant.setContentAssistProcessor(processor,SpecfilePartitionScanner.SPEC_FILES);
- assistant.setContentAssistProcessor(processor,SpecfilePartitionScanner.SPEC_CHANGELOG);
- assistant.setContentAssistProcessor(processor,SpecfilePartitionScanner.SPEC_PACKAGES);
- assistant.setContentAssistProcessor(processor,
- SpecfilePartitionScanner.SPEC_GROUP);
- // configure content assistance
- assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
+ private SpecfileDoubleClickStrategy doubleClickStrategy;
+ private SpecfileScanner scanner;
+ private SpecfileChangelogScanner changelogScanner;
+ private SpecfilePackagesScanner packagesScanner;
+ private ColorManager colorManager;
+ private SpecfileHover specfileHover;
+ private SpecfileEditor editor;
+
+ public SpecfileConfiguration(ColorManager colorManager, SpecfileEditor editor) {
+ super();
+ this.colorManager = colorManager;
+ this.editor = editor;
+ }
+
+ /**
+ * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredContentTypes(org.eclipse.jface.text.source.ISourceViewer)
+ */
+ @Override
+ public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
+ return SpecfilePartitionScanner.SPEC_PARTITION_TYPES;
+ }
+
+ /**
+ * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getDoubleClickStrategy(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
+ */
+ @Override
+ public ITextDoubleClickStrategy getDoubleClickStrategy(
+ ISourceViewer sourceViewer,
+ String contentType) {
+ if (doubleClickStrategy == null) {
+ doubleClickStrategy = new SpecfileDoubleClickStrategy();
+ }
+ return doubleClickStrategy;
+ }
+
+ protected SpecfileScanner getSpecfileScanner() {
+ if (scanner == null) {
+ scanner = new SpecfileScanner(colorManager);
+ scanner.setDefaultReturnToken(
+ new Token(
+ new TextAttribute(
+ colorManager.getColor(ISpecfileColorConstants.DEFAULT))));
+ }
+ return scanner;
+ }
+
+ protected SpecfileChangelogScanner getSpecfileChangelogScanner() {
+ if (changelogScanner == null) {
+ changelogScanner = new SpecfileChangelogScanner(colorManager);
+ changelogScanner.setDefaultReturnToken(
+ new Token(
+ new TextAttribute(
+ colorManager.getColor(ISpecfileColorConstants.DEFAULT))));
+ }
+ return changelogScanner;
+ }
+
+ protected SpecfilePackagesScanner getSpecfilePackagesScanner() {
+ if (packagesScanner == null) {
+ packagesScanner = new SpecfilePackagesScanner(colorManager);
+ packagesScanner.setDefaultReturnToken(
+ new Token(
+ new TextAttribute(
+ colorManager.getColor(ISpecfileColorConstants.DEFAULT))));
+ }
+ return packagesScanner;
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.editors.text.TextSourceViewerConfiguration#getTextHover(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
+ */
+ @Override
+ public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
+ if (specfileHover == null) {
+ specfileHover = new SpecfileHover(this.editor);
+ }
+ return specfileHover;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(org.eclipse.jface.text.source.ISourceViewer)
+ */
+ @Override
+ public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
+ PresentationReconciler reconciler = new PresentationReconciler();
+
+ DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getSpecfileScanner());
+ reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
+ reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
+
+ dr = new DefaultDamagerRepairer(getSpecfilePackagesScanner());
+ reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_PACKAGES);
+ reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_PACKAGES);
+
+ dr = new DefaultDamagerRepairer(getSpecfileScanner());
+ reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_PREP);
+ reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_PREP);
+
+ dr = new DefaultDamagerRepairer(getSpecfileScanner());
+ reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_SCRIPT);
+ reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_SCRIPT);
+
+ dr = new DefaultDamagerRepairer(getSpecfileScanner());
+ reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_FILES);
+ reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_FILES);
+
+ dr = new DefaultDamagerRepairer(getSpecfileScanner());
+ reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_GROUP);
+ reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_GROUP);
+
+ dr = new DefaultDamagerRepairer(getSpecfileChangelogScanner());
+ reconciler.setDamager(dr, SpecfilePartitionScanner.SPEC_CHANGELOG);
+ reconciler.setRepairer(dr, SpecfilePartitionScanner.SPEC_CHANGELOG);
+
+ return reconciler;
+ }
+
+ /*
+ * @see SourceViewerConfiguration#getReconciler(ISourceViewer)
+ */
+ @Override
+ public IReconciler getReconciler(ISourceViewer sourceViewer) {
+ if (editor != null && editor.isEditable()) {
+ SpecfileReconcilingStrategy strategy= new SpecfileReconcilingStrategy(editor);
+ MonoReconciler reconciler= new MonoReconciler(strategy, false);
+ reconciler.setProgressMonitor(new NullProgressMonitor());
+ reconciler.setDelay(500);
+ return reconciler;
+ }
+ return null;
+ }
+
+ /*
+ * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getContentAssistant(org.eclipse.jface.text.source.ISourceViewer)
+ */
+ @Override
+ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
+ ContentAssistant assistant= new ContentAssistant();
+ IContentAssistProcessor processor= new SpecfileCompletionProcessor(editor);
+ // add content assistance to all the supported contentType
+ assistant.setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE);
+ assistant.setContentAssistProcessor(processor, SpecfilePartitionScanner.SPEC_PREP);
+ assistant.setContentAssistProcessor(processor, SpecfilePartitionScanner.SPEC_SCRIPT);
+ assistant.setContentAssistProcessor(processor,SpecfilePartitionScanner.SPEC_FILES);
+ assistant.setContentAssistProcessor(processor,SpecfilePartitionScanner.SPEC_CHANGELOG);
+ assistant.setContentAssistProcessor(processor,SpecfilePartitionScanner.SPEC_PACKAGES);
+ assistant.setContentAssistProcessor(processor,
+ SpecfilePartitionScanner.SPEC_GROUP);
+ // configure content assistance
+ assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
IInformationControlCreator controlCreator= getInformationControlCreator();
- assistant.setInformationControlCreator(controlCreator);
- assistant.enableAutoInsert(true);
- assistant.setStatusLineVisible(true);
- assistant.setStatusMessage(Messages.SpecfileConfiguration_0);
- return assistant;
- }
-
- private IInformationControlCreator getInformationControlCreator() {
- return new IInformationControlCreator() {
- @Override
- public IInformationControl createInformationControl(Shell parent) {
- return new DefaultInformationControl(parent, false);
- }
- };
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getHyperlinkDetectors(org.eclipse.jface.text.source.ISourceViewer)
- */
- @Override
- public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) {
- if (sourceViewer == null) {
- return null;
- }
- Map<?, ?> targets = getHyperlinkDetectorTargets(sourceViewer);
- HyperlinkDetectorRegistry hlDetectorRegistry = EditorsUI.getHyperlinkDetectorRegistry();
- HyperlinkDetectorDescriptor[] hlDetectorDescriptor = hlDetectorRegistry.getHyperlinkDetectorDescriptors();
- List<IHyperlinkDetector> tempHDList = new ArrayList<>();
-
- for (Map.Entry<?, ?> entry : targets.entrySet()) {
- for (HyperlinkDetectorDescriptor hdd : hlDetectorDescriptor) {
- try {
- AbstractHyperlinkDetector ahld = (AbstractHyperlinkDetector) hdd.createHyperlinkDetectorImplementation();
- // filter using target id and not instance of URLHyperlinkDetector
- // so that an option to open url with unresolved macros won't show
- // however, allow URLHyperlinkWithMacroDetector
- if (hdd.getTargetId().equals(entry.getKey()) &&
- (!(ahld instanceof URLHyperlinkDetector) || ahld instanceof URLHyperlinkWithMacroDetector)) {
- ahld.setContext((IAdaptable)entry.getValue());
- tempHDList.add(ahld);
- }
- } catch (CoreException e) {
- SpecfileLog.logError(e);
- }
- }
- }
-
- if (!tempHDList.isEmpty()) {
- return tempHDList.toArray(new IHyperlinkDetector[tempHDList.size()]);
- } else {
- return null;
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.editors.text.TextSourceViewerConfiguration#getHyperlinkDetectorTargets(org.eclipse.jface.text.source.ISourceViewer)
- */
- @Override
- protected Map getHyperlinkDetectorTargets(ISourceViewer sourceViewer) {
+ assistant.setInformationControlCreator(controlCreator);
+ assistant.enableAutoInsert(true);
+ assistant.setStatusLineVisible(true);
+ assistant.setStatusMessage(Messages.SpecfileConfiguration_0);
+ return assistant;
+ }
+
+ private IInformationControlCreator getInformationControlCreator() {
+ return new IInformationControlCreator() {
+ @Override
+ public IInformationControl createInformationControl(Shell parent) {
+ return new DefaultInformationControl(parent, false);
+ }
+ };
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getHyperlinkDetectors(org.eclipse.jface.text.source.ISourceViewer)
+ */
+ @Override
+ public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) {
+ if (sourceViewer == null) {
+ return null;
+ }
+ Map<?, ?> targets = getHyperlinkDetectorTargets(sourceViewer);
+ HyperlinkDetectorRegistry hlDetectorRegistry = EditorsUI.getHyperlinkDetectorRegistry();
+ HyperlinkDetectorDescriptor[] hlDetectorDescriptor = hlDetectorRegistry.getHyperlinkDetectorDescriptors();
+ List<IHyperlinkDetector> tempHDList = new ArrayList<>();
+
+ for (Map.Entry<?, ?> entry : targets.entrySet()) {
+ for (HyperlinkDetectorDescriptor hdd : hlDetectorDescriptor) {
+ try {
+ AbstractHyperlinkDetector ahld = (AbstractHyperlinkDetector) hdd.createHyperlinkDetectorImplementation();
+ // filter using target id and not instance of URLHyperlinkDetector
+ // so that an option to open url with unresolved macros won't show
+ // however, allow URLHyperlinkWithMacroDetector
+ if (hdd.getTargetId().equals(entry.getKey()) &&
+ (!(ahld instanceof URLHyperlinkDetector) || ahld instanceof URLHyperlinkWithMacroDetector)) {
+ ahld.setContext((IAdaptable)entry.getValue());
+ tempHDList.add(ahld);
+ }
+ } catch (CoreException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+ }
+
+ if (!tempHDList.isEmpty()) {
+ return tempHDList.toArray(new IHyperlinkDetector[tempHDList.size()]);
+ } else {
+ return null;
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.editors.text.TextSourceViewerConfiguration#getHyperlinkDetectorTargets(org.eclipse.jface.text.source.ISourceViewer)
+ */
+ @Override
+ protected Map getHyperlinkDetectorTargets(ISourceViewer sourceViewer) {
Map<String, Object> targets= super.getHyperlinkDetectorTargets(sourceViewer);
targets.put("org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditorTarget", editor); //$NON-NLS-1$
targets.put("org.eclipse.ui.DefaultTextEditor", editor); //$NON-NLS-1$
return targets;
}
- private int getTabSize() {
- return Activator.getDefault().getPreferenceStore().getInt(
- PreferenceConstants.P_NBR_OF_SPACES_FOR_TAB);
- }
-
- private boolean isTabConversionEnabled() {
- return Activator.getDefault().getPreferenceStore().getBoolean(
- PreferenceConstants.P_SPACES_FOR_TABS);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.jface.text.source.SourceViewerConfiguration#getAutoEditStrategies
- * (org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
- */
- @Override
- public IAutoEditStrategy[] getAutoEditStrategies(
- ISourceViewer sourceViewer, String contentType) {
- if (isTabConversionEnabled()) {
- TabsToSpacesConverter tabsConverter = new TabsToSpacesConverter();
- tabsConverter.setLineTracker(new DefaultLineTracker());
- tabsConverter.setNumberOfSpacesPerTab(getTabSize());
- return new IAutoEditStrategy[] { tabsConverter };
- }
- return null;
- }
+ private int getTabSize() {
+ return Activator.getDefault().getPreferenceStore().getInt(
+ PreferenceConstants.P_NBR_OF_SPACES_FOR_TAB);
+ }
+
+ private boolean isTabConversionEnabled() {
+ return Activator.getDefault().getPreferenceStore().getBoolean(
+ PreferenceConstants.P_SPACES_FOR_TABS);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.jface.text.source.SourceViewerConfiguration#getAutoEditStrategies
+ * (org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
+ */
+ @Override
+ public IAutoEditStrategy[] getAutoEditStrategies(
+ ISourceViewer sourceViewer, String contentType) {
+ if (isTabConversionEnabled()) {
+ TabsToSpacesConverter tabsConverter = new TabsToSpacesConverter();
+ tabsConverter.setLineTracker(new DefaultLineTracker());
+ tabsConverter.setNumberOfSpacesPerTab(getTabSize());
+ return new IAutoEditStrategy[] { tabsConverter };
+ }
+ return null;
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileDocumentProvider.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileDocumentProvider.java
index e85b5e45d7..739d85fd3b 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileDocumentProvider.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileDocumentProvider.java
@@ -30,119 +30,119 @@ import org.eclipse.ui.ide.FileStoreEditorInput;
public class SpecfileDocumentProvider extends TextFileDocumentProvider {
- private int originalLength;
+ private int originalLength;
- private void setDocumentLength(Object element) {
- IDocument doc = getDocument(element);
- if (doc == null) {
- originalLength = 0;
- } else {
- originalLength = doc.getLength();
- }
- }
+ private void setDocumentLength(Object element) {
+ IDocument doc = getDocument(element);
+ if (doc == null) {
+ originalLength = 0;
+ } else {
+ originalLength = doc.getLength();
+ }
+ }
- @Override
- public IDocument getDocument(Object element) {
- IDocument document = super.getDocument(element);
- if (document != null && document.getDocumentPartitioner() == null) {
- FastPartitioner partitioner = new FastPartitioner(
- new SpecfilePartitionScanner(),
- SpecfilePartitionScanner.SPEC_PARTITION_TYPES);
- partitioner.connect(document, false);
- document.setDocumentPartitioner(partitioner);
- }
- return document;
- }
- /*
- * @see org.eclipse.ui.texteditor.IDocumentProvider#connect(java.lang.Object)
- */
- @Override
- public void connect(Object element) throws CoreException {
- super.connect(element);
- setDocumentLength(element);
- }
+ @Override
+ public IDocument getDocument(Object element) {
+ IDocument document = super.getDocument(element);
+ if (document != null && document.getDocumentPartitioner() == null) {
+ FastPartitioner partitioner = new FastPartitioner(
+ new SpecfilePartitionScanner(),
+ SpecfilePartitionScanner.SPEC_PARTITION_TYPES);
+ partitioner.connect(document, false);
+ document.setDocumentPartitioner(partitioner);
+ }
+ return document;
+ }
+ /*
+ * @see org.eclipse.ui.texteditor.IDocumentProvider#connect(java.lang.Object)
+ */
+ @Override
+ public void connect(Object element) throws CoreException {
+ super.connect(element);
+ setDocumentLength(element);
+ }
- /*
- * @see org.eclipse.ui.texteditor.IDocumentProvider#canSaveDocument(java.lang.Object)
- */
- @Override
- public boolean canSaveDocument(Object element) {
- if (element instanceof FileStoreEditorInput) {
- FileStoreEditorInput fei = (FileStoreEditorInput) element;
- IDocument doc = getDocument(element);
- if (!super.canSaveDocument(element)) {
- return false;
- }
- if (doc.getLength() != originalLength) {
- return true;
- }
- URI uri = fei.getURI();
- File f = URIUtil.toFile(uri);
- if (originalLength != 0) {
- try (BufferedReader input = new BufferedReader(
- new FileReader(f))) {
- boolean finished = false;
- char[] buffer = new char[100];
- int curoffset = 0;
- while (!finished) {
- int len = input.read(buffer);
- if (len <= 0) {
- break;
- }
- String origbytes = new String(buffer, 0, len);
- String curbytes = doc.get(curoffset, len);
- if (!curbytes.equals(origbytes)) {
- return true;
- }
- curoffset += len;
- }
- resetDocument(element);
- return false;
- } catch (Exception e) {
- return true;
- }
- }
- }
- return super.canSaveDocument(element);
- }
+ /*
+ * @see org.eclipse.ui.texteditor.IDocumentProvider#canSaveDocument(java.lang.Object)
+ */
+ @Override
+ public boolean canSaveDocument(Object element) {
+ if (element instanceof FileStoreEditorInput) {
+ FileStoreEditorInput fei = (FileStoreEditorInput) element;
+ IDocument doc = getDocument(element);
+ if (!super.canSaveDocument(element)) {
+ return false;
+ }
+ if (doc.getLength() != originalLength) {
+ return true;
+ }
+ URI uri = fei.getURI();
+ File f = URIUtil.toFile(uri);
+ if (originalLength != 0) {
+ try (BufferedReader input = new BufferedReader(
+ new FileReader(f))) {
+ boolean finished = false;
+ char[] buffer = new char[100];
+ int curoffset = 0;
+ while (!finished) {
+ int len = input.read(buffer);
+ if (len <= 0) {
+ break;
+ }
+ String origbytes = new String(buffer, 0, len);
+ String curbytes = doc.get(curoffset, len);
+ if (!curbytes.equals(origbytes)) {
+ return true;
+ }
+ curoffset += len;
+ }
+ resetDocument(element);
+ return false;
+ } catch (Exception e) {
+ return true;
+ }
+ }
+ }
+ return super.canSaveDocument(element);
+ }
- /*
- * @see org.eclipse.ui.texteditor.IDocumentProvider#createSaveOperation(java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
- */
+ /*
+ * @see org.eclipse.ui.texteditor.IDocumentProvider#createSaveOperation(java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
+ */
- @Override
- protected DocumentProviderOperation createSaveOperation(final Object element, final IDocument document, final boolean overwrite) throws CoreException {
- final DocumentProviderOperation saveOperation = super.createSaveOperation(element, document, overwrite);
+ @Override
+ protected DocumentProviderOperation createSaveOperation(final Object element, final IDocument document, final boolean overwrite) throws CoreException {
+ final DocumentProviderOperation saveOperation = super.createSaveOperation(element, document, overwrite);
- if (element instanceof IURIEditorInput) {
- return new DocumentProviderOperation() {
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
- */
- @Override
- public void execute(IProgressMonitor monitor) throws CoreException {
- }
+ if (element instanceof IURIEditorInput) {
+ return new DocumentProviderOperation() {
+ /*
+ * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ @Override
+ public void execute(IProgressMonitor monitor) throws CoreException {
+ }
- /*
- * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- @Override
- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
- saveOperation.run(monitor);
- // Here's where we sneak in resetting the original document length
- setDocumentLength(element);
- }
+ /*
+ * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ @Override
+ public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
+ saveOperation.run(monitor);
+ // Here's where we sneak in resetting the original document length
+ setDocumentLength(element);
+ }
- /*
- * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule()
- */
- @Override
- public ISchedulingRule getSchedulingRule() {
- return saveOperation.getSchedulingRule();
- }
- };
- }
+ /*
+ * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule()
+ */
+ @Override
+ public ISchedulingRule getSchedulingRule() {
+ return saveOperation.getSchedulingRule();
+ }
+ };
+ }
- return saveOperation;
- }
+ return saveOperation;
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileDoubleClickStrategy.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileDoubleClickStrategy.java
index 2a57d54f41..1a0f383b30 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileDoubleClickStrategy.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileDoubleClickStrategy.java
@@ -17,117 +17,117 @@ import org.eclipse.jface.text.ITextDoubleClickStrategy;
import org.eclipse.jface.text.ITextViewer;
public class SpecfileDoubleClickStrategy implements ITextDoubleClickStrategy {
- protected ITextViewer fText;
- //lTerminator should be either '\r' or '\n' depending on the OS
- final char lTerminator = System.getProperty("line.separator").charAt(0); //$NON-NLS-1$
-
- @Override
- public void doubleClicked(ITextViewer part) {
- int pos = part.getSelectedRange().x;
-
- if (pos < 0) {
- return;
- }
-
- fText = part;
-
- if (!selectComment(pos)) {
- selectWord(pos);
- }
- }
- protected boolean selectComment(int caretPos) {
- IDocument doc = fText.getDocument();
- int startPos, endPos;
- try {
- int pos = caretPos;
- char c = ' ';
-
- while (pos >= 0) {
- c = doc.getChar(pos);
- if (c == '\\') {
- pos -= 2;
- continue;
- }
- if ( c == lTerminator || c == '\"') {
- break;
- }
- --pos;
- }
- if (c != '\"') {
- return false;
- }
-
- startPos = pos;
-
- pos = caretPos;
- int length = doc.getLength();
- c = ' ';
-
- while (pos < length) {
- c = doc.getChar(pos);
- if ( c == lTerminator || c == '\"' ) {
- break;
- }
- ++pos;
- }
- if (c != '\"')
- return false;
-
- endPos = pos;
-
- int offset = startPos + 1;
- int len = endPos - offset;
- fText.setSelectedRange(offset, len);
- return true;
- } catch (BadLocationException x) {
- }
-
- return false;
- }
- protected boolean selectWord(int caretPos) {
-
- IDocument doc = fText.getDocument();
- int startPos, endPos;
-
- try {
-
- int pos = caretPos;
- char c;
-
- while (pos >= 0) {
- c = doc.getChar(pos);
- if (!Character.isJavaIdentifierPart(c)) {
- break;
- }
- --pos;
- }
-
- startPos = pos;
-
- pos = caretPos;
- int length = doc.getLength();
-
- while (pos < length) {
- c = doc.getChar(pos);
- if (!Character.isJavaIdentifierPart(c)) {
- break;
- }
- ++pos;
- }
-
- endPos = pos;
- selectRange(startPos, endPos);
- return true;
-
- } catch (BadLocationException x) {
- }
-
- return false;
- }
-
- private void selectRange(int startPos, int stopPos) {
- int offset = startPos + 1;
- int length = stopPos - offset;
- fText.setSelectedRange(offset, length);
- }
+ protected ITextViewer fText;
+ //lTerminator should be either '\r' or '\n' depending on the OS
+ final char lTerminator = System.getProperty("line.separator").charAt(0); //$NON-NLS-1$
+
+ @Override
+ public void doubleClicked(ITextViewer part) {
+ int pos = part.getSelectedRange().x;
+
+ if (pos < 0) {
+ return;
+ }
+
+ fText = part;
+
+ if (!selectComment(pos)) {
+ selectWord(pos);
+ }
+ }
+ protected boolean selectComment(int caretPos) {
+ IDocument doc = fText.getDocument();
+ int startPos, endPos;
+ try {
+ int pos = caretPos;
+ char c = ' ';
+
+ while (pos >= 0) {
+ c = doc.getChar(pos);
+ if (c == '\\') {
+ pos -= 2;
+ continue;
+ }
+ if ( c == lTerminator || c == '\"') {
+ break;
+ }
+ --pos;
+ }
+ if (c != '\"') {
+ return false;
+ }
+
+ startPos = pos;
+
+ pos = caretPos;
+ int length = doc.getLength();
+ c = ' ';
+
+ while (pos < length) {
+ c = doc.getChar(pos);
+ if ( c == lTerminator || c == '\"' ) {
+ break;
+ }
+ ++pos;
+ }
+ if (c != '\"')
+ return false;
+
+ endPos = pos;
+
+ int offset = startPos + 1;
+ int len = endPos - offset;
+ fText.setSelectedRange(offset, len);
+ return true;
+ } catch (BadLocationException x) {
+ }
+
+ return false;
+ }
+ protected boolean selectWord(int caretPos) {
+
+ IDocument doc = fText.getDocument();
+ int startPos, endPos;
+
+ try {
+
+ int pos = caretPos;
+ char c;
+
+ while (pos >= 0) {
+ c = doc.getChar(pos);
+ if (!Character.isJavaIdentifierPart(c)) {
+ break;
+ }
+ --pos;
+ }
+
+ startPos = pos;
+
+ pos = caretPos;
+ int length = doc.getLength();
+
+ while (pos < length) {
+ c = doc.getChar(pos);
+ if (!Character.isJavaIdentifierPart(c)) {
+ break;
+ }
+ ++pos;
+ }
+
+ endPos = pos;
+ selectRange(startPos, endPos);
+ return true;
+
+ } catch (BadLocationException x) {
+ }
+
+ return false;
+ }
+
+ private void selectRange(int startPos, int stopPos) {
+ int offset = startPos + 1;
+ int length = stopPos - offset;
+ fText.setSelectedRange(offset, length);
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileFoldingStructureProvider.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileFoldingStructureProvider.java
index 583742879a..95bb9272c8 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileFoldingStructureProvider.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileFoldingStructureProvider.java
@@ -34,106 +34,106 @@ import org.eclipse.linuxtools.rpm.ui.editor.parser.SpecfileElement;
public class SpecfileFoldingStructureProvider {
- private static class ElementByLineNbrComparator implements Comparator<SpecfileElement> {
- @Override
- public int compare(SpecfileElement element1, SpecfileElement element2) {
- Integer lineNbr1 = element1.getLineNumber();
- Integer lineNbr2 = element2.getLineNumber();
- return lineNbr1.compareTo(lineNbr2);
- }
- }
-
- private static final Annotation[] EMPTY = new Annotation[] {};
- private SpecfileEditor sEditor;
- private IDocument sDocument;
- private IProgressMonitor sProgressMonitor;
-
- public SpecfileFoldingStructureProvider(SpecfileEditor editor) {
- sEditor = editor;
- }
-
- public void setProgressMonitor(IProgressMonitor progressMonitor) {
- sProgressMonitor = progressMonitor;
- }
-
- public void setDocument(IDocument document) {
- sDocument = document;
- }
-
- public void updateFoldingRegions() {
- ProjectionAnnotationModel model = (ProjectionAnnotationModel) sEditor
- .getAdapter(ProjectionAnnotationModel.class);
- if (model != null) {
- updateFoldingRegions(model);
- }
- }
-
- void updateFoldingRegions(ProjectionAnnotationModel model) {
- Set<Position> structure = createFoldingStructure(sEditor.getSpecfile());
- Annotation[] deletions = computeDifferences(model, structure);
- Map<Annotation,Position> additions = computeAdditions(structure);
- if ((deletions.length != 0 || !additions.isEmpty())
- && (sProgressMonitor == null || !sProgressMonitor.isCanceled())) {
- model.modifyAnnotations(deletions, additions, EMPTY);
- }
- }
-
- private Map<Annotation,Position> computeAdditions(Set<Position> currentRegions) {
- Map<Annotation,Position> additionsMap = new HashMap<>();
- for (Position position: currentRegions) {
- additionsMap.put(new ProjectionAnnotation(), position);
- }
- return additionsMap;
- }
-
- private Annotation[] computeDifferences(ProjectionAnnotationModel model,
- Set<Position> current) {
- List<Annotation> deletions = new ArrayList<>();
- for (Iterator<Annotation> iter = model.getAnnotationIterator(); iter.hasNext();) {
- Annotation annotation = iter.next();
- if (annotation instanceof ProjectionAnnotation) {
- Position position = model.getPosition(annotation);
- if (current.contains(position)) {
- current.remove(position);
- } else {
- deletions.add(annotation);
- }
- }
- }
- return deletions.toArray(new Annotation[deletions.size()]);
- }
-
- private Set<Position> createFoldingStructure(Specfile specfile) {
- List<SpecfileElement> elements = new ArrayList<>();
- elements.addAll(specfile.getSections());
- elements.addAll(specfile.getComplexSections());
- Collections.sort(elements, new ElementByLineNbrComparator());
- return addFoldingRegions(elements);
- }
-
- private Set<Position> addFoldingRegions(List<SpecfileElement> elements) {
- Set<Position> regions = new HashSet<>();
- // add folding on the preamble section
- Position position;
- if (elements.size() > 0) {
- SpecfileElement element = elements.get(0);
- position = new Position(0, element.getLineStartPosition() - 1);
- regions.add(position);
- }
-
- for (int i = 0; i < elements.size(); i++) {
- SpecfileElement startElement = elements.get(i);
- int offsetPos = startElement.getLineStartPosition();
- int lenghtPos;
- if (i < elements.size() -1) {
- SpecfileElement endElement = elements.get(i+1);
- lenghtPos = endElement.getLineStartPosition() - startElement.getLineStartPosition() - 1;
- } else {
- lenghtPos = sDocument.getLength() - startElement.getLineStartPosition();
- }
- position = new Position(offsetPos, lenghtPos);
- regions.add(position);
- }
- return regions;
- }
+ private static class ElementByLineNbrComparator implements Comparator<SpecfileElement> {
+ @Override
+ public int compare(SpecfileElement element1, SpecfileElement element2) {
+ Integer lineNbr1 = element1.getLineNumber();
+ Integer lineNbr2 = element2.getLineNumber();
+ return lineNbr1.compareTo(lineNbr2);
+ }
+ }
+
+ private static final Annotation[] EMPTY = new Annotation[] {};
+ private SpecfileEditor sEditor;
+ private IDocument sDocument;
+ private IProgressMonitor sProgressMonitor;
+
+ public SpecfileFoldingStructureProvider(SpecfileEditor editor) {
+ sEditor = editor;
+ }
+
+ public void setProgressMonitor(IProgressMonitor progressMonitor) {
+ sProgressMonitor = progressMonitor;
+ }
+
+ public void setDocument(IDocument document) {
+ sDocument = document;
+ }
+
+ public void updateFoldingRegions() {
+ ProjectionAnnotationModel model = (ProjectionAnnotationModel) sEditor
+ .getAdapter(ProjectionAnnotationModel.class);
+ if (model != null) {
+ updateFoldingRegions(model);
+ }
+ }
+
+ void updateFoldingRegions(ProjectionAnnotationModel model) {
+ Set<Position> structure = createFoldingStructure(sEditor.getSpecfile());
+ Annotation[] deletions = computeDifferences(model, structure);
+ Map<Annotation,Position> additions = computeAdditions(structure);
+ if ((deletions.length != 0 || !additions.isEmpty())
+ && (sProgressMonitor == null || !sProgressMonitor.isCanceled())) {
+ model.modifyAnnotations(deletions, additions, EMPTY);
+ }
+ }
+
+ private Map<Annotation,Position> computeAdditions(Set<Position> currentRegions) {
+ Map<Annotation,Position> additionsMap = new HashMap<>();
+ for (Position position: currentRegions) {
+ additionsMap.put(new ProjectionAnnotation(), position);
+ }
+ return additionsMap;
+ }
+
+ private Annotation[] computeDifferences(ProjectionAnnotationModel model,
+ Set<Position> current) {
+ List<Annotation> deletions = new ArrayList<>();
+ for (Iterator<Annotation> iter = model.getAnnotationIterator(); iter.hasNext();) {
+ Annotation annotation = iter.next();
+ if (annotation instanceof ProjectionAnnotation) {
+ Position position = model.getPosition(annotation);
+ if (current.contains(position)) {
+ current.remove(position);
+ } else {
+ deletions.add(annotation);
+ }
+ }
+ }
+ return deletions.toArray(new Annotation[deletions.size()]);
+ }
+
+ private Set<Position> createFoldingStructure(Specfile specfile) {
+ List<SpecfileElement> elements = new ArrayList<>();
+ elements.addAll(specfile.getSections());
+ elements.addAll(specfile.getComplexSections());
+ Collections.sort(elements, new ElementByLineNbrComparator());
+ return addFoldingRegions(elements);
+ }
+
+ private Set<Position> addFoldingRegions(List<SpecfileElement> elements) {
+ Set<Position> regions = new HashSet<>();
+ // add folding on the preamble section
+ Position position;
+ if (elements.size() > 0) {
+ SpecfileElement element = elements.get(0);
+ position = new Position(0, element.getLineStartPosition() - 1);
+ regions.add(position);
+ }
+
+ for (int i = 0; i < elements.size(); i++) {
+ SpecfileElement startElement = elements.get(i);
+ int offsetPos = startElement.getLineStartPosition();
+ int lenghtPos;
+ if (i < elements.size() -1) {
+ SpecfileElement endElement = elements.get(i+1);
+ lenghtPos = endElement.getLineStartPosition() - startElement.getLineStartPosition() - 1;
+ } else {
+ lenghtPos = sDocument.getLength() - startElement.getLineStartPosition();
+ }
+ position = new Position(offsetPos, lenghtPos);
+ regions.add(position);
+ }
+ return regions;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileHover.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileHover.java
index c91ff52e63..b9f6c0c1ab 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileHover.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileHover.java
@@ -35,252 +35,252 @@ import org.eclipse.swt.widgets.Shell;
public class SpecfileHover implements ITextHover, ITextHoverExtension {
- private static final String EMPTY_STRING = ""; //$NON-NLS-1$
- private SpecfileEditor editor;
-
- public SpecfileHover(SpecfileEditor editor) {
- this.editor = editor;
- }
-
- @Override
- public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
- if (hoverRegion == null || hoverRegion.getLength() == 0) {
- return null;
- }
-
- Specfile spec = editor.getSpecfile();
- if (spec == null) {
- return null;
- }
-
- String currentSelection;
- try {
- currentSelection = textViewer.getDocument().get(hoverRegion.getOffset() + 1, hoverRegion.getLength() - 1);
- } catch (BadLocationException e) {
- return null;
- }
+ private static final String EMPTY_STRING = ""; //$NON-NLS-1$
+ private SpecfileEditor editor;
+
+ public SpecfileHover(SpecfileEditor editor) {
+ this.editor = editor;
+ }
+
+ @Override
+ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
+ if (hoverRegion == null || hoverRegion.getLength() == 0) {
+ return null;
+ }
+
+ Specfile spec = editor.getSpecfile();
+ if (spec == null) {
+ return null;
+ }
+
+ String currentSelection;
+ try {
+ currentSelection = textViewer.getDocument().get(hoverRegion.getOffset() + 1, hoverRegion.getLength() - 1);
+ } catch (BadLocationException e) {
+ return null;
+ }
// First we try to get a define based on the given name
- SpecfileDefine define = spec.getDefine(currentSelection);
+ SpecfileDefine define = spec.getDefine(currentSelection);
String value = currentSelection + ": "; //$NON-NLS-1$
- if (define != null) {
- return value + define.getStringValue();
- }
-
- String macroLower = currentSelection.toLowerCase();
-
- // If there's no such define we try to see if it corresponds to
- // a Source or Patch declaration
- String retrivedValue = getSourceOrPatchValue(spec, macroLower);
- if (retrivedValue != null) {
- return value + retrivedValue;
- } else {
- // If it does not correspond to a Patch or Source macro, try to find it
- // in the macro proposals list.
- retrivedValue = getMacroValueFromMacroList(currentSelection);
- if (retrivedValue != null) {
- return value + retrivedValue;
- } else {
- // If it does not correspond to a macro in the list, try to find it
- // in the RPM list.
- retrivedValue = Activator.getDefault().getRpmPackageList().getValue(currentSelection.replaceFirst(":",EMPTY_STRING)); //$NON-NLS-1$
- if (retrivedValue != null) {
- return retrivedValue;
- }
- }
- }
+ if (define != null) {
+ return value + define.getStringValue();
+ }
+
+ String macroLower = currentSelection.toLowerCase();
+
+ // If there's no such define we try to see if it corresponds to
+ // a Source or Patch declaration
+ String retrivedValue = getSourceOrPatchValue(spec, macroLower);
+ if (retrivedValue != null) {
+ return value + retrivedValue;
+ } else {
+ // If it does not correspond to a Patch or Source macro, try to find it
+ // in the macro proposals list.
+ retrivedValue = getMacroValueFromMacroList(currentSelection);
+ if (retrivedValue != null) {
+ return value + retrivedValue;
+ } else {
+ // If it does not correspond to a macro in the list, try to find it
+ // in the RPM list.
+ retrivedValue = Activator.getDefault().getRpmPackageList().getValue(currentSelection.replaceFirst(":",EMPTY_STRING)); //$NON-NLS-1$
+ if (retrivedValue != null) {
+ return retrivedValue;
+ }
+ }
+ }
// We return null in other cases, so we don't show hover information
// for unrecognized macros and RPM packages.
return null;
- }
-
- @Override
- public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
-
- if (textViewer != null) {
- /*
- * If the hover offset falls within the selection range return the
- * region for the whole selection.
- */
- Point selectedRange = textViewer.getSelectedRange();
- if (selectedRange.x >= 0 && selectedRange.y > 0
- && offset >= selectedRange.x
- && offset <= selectedRange.x + selectedRange.y) {
- return new Region(selectedRange.x, selectedRange.y);
- } else {
- IRegion region = findWord(textViewer.getDocument(), offset);
- if (region.equals(new Region(offset, 0))) {
- region = findPackages(textViewer.getDocument(), offset);
- }
- return region;
- }
- }
- return null;
- }
-
- @Override
- public IInformationControlCreator getHoverControlCreator() {
- return new IInformationControlCreator() {
- @Override
- public IInformationControl createInformationControl(Shell parent) {
- return new DefaultInformationControl(parent, false);
- }
- };
- }
-
-
- public static IRegion findWord(IDocument document, int offset) {
- int start = -1;
- int end = -1;
- boolean beginsWithBrace = false;
-
- try {
- int pos = offset;
- char c;
-
- while (pos >= 0) {
- c = document.getChar(pos);
- if (c == '%') {
- if (document.getChar(pos + 1) == '{') {
- beginsWithBrace = true;
- }
- break;
- }
- else if (c == '\n' || c == '}'){
- // if we hit the beginning of the line, it's not a macro
- return new Region(offset, 0);
- }
- --pos;
- }
-
- if (!beginsWithBrace) {
- --pos;
- }
-
- start = pos;
-
- pos = offset;
- int length = document.getLength();
-
- while (pos < length) {
- c = document.getChar(pos);
- if (beginsWithBrace && (c == '}')) {
- break;
- } else if (c == '\n' || c == '%' || c == '('){ // '(' is needed for the %deffatt( case
- break;
-// Do not return empty region here. We have a work.
-// return new Region(offset, 0);
- } else if (!beginsWithBrace && c == ' ') {
- break;
- }
- ++pos;
- }
-
- end = pos;
-
- } catch (BadLocationException x) {
- }
-
- if (start >= -1 && end > -1) {
- if (start == offset) {
- return new Region(start, end - start);
- } else {
- return new Region(start + 1, end - start - 1);
- }
- }
-
- return null;
- }
-
- public static IRegion findPackages(IDocument document, int offset) {
- int start = -1;
- int end = -1;
- boolean beginsWithSpace = false;
- try {
- int pos = offset;
- char c;
- while (pos >= 0) {
- c = document.getChar(pos);
- if (c == ' ' || c =='\t' || c==':') {
- if (Character.isLetter(document.getChar(pos + 1))) {
- beginsWithSpace = true;
- break;
- } else if (c == '\n'){
- return new Region(offset, 0);
- }
- }
- --pos;
- }
- --pos;
- start = pos;
- pos = offset;
- int length = document.getLength();
- while (pos < length) {
- c = document.getChar(pos);
- if (beginsWithSpace && (!Character.isLetter(c) && !Character.isDigit(c) && c != '-')) {
- break;
- } else if (c == '\n') {
- return new Region(offset, 0);
- }
- ++pos;
- }
- end = pos;
-
- } catch (BadLocationException x) {
- }
-
- if (start > -1 && end > -1) {
- return new Region(start, end - start);
- }
- return null;
- }
-
- public static String getSourceOrPatchValue(Specfile spec, String patchOrSourceName) {
- String value = null;
- Pattern p = Pattern.compile("(source|patch)(\\d*)"); //$NON-NLS-1$
- Matcher m = p.matcher(patchOrSourceName);
-
- if (m.matches()) {
- String digits = m.group(2);
-
- SpecfileSource source = null;
- int number = -1;
-
- if (digits != null && digits.equals(EMPTY_STRING)) {
- number = 0;
- } else if (digits != null && !digits.equals(EMPTY_STRING)) {
- number = Integer.parseInt(digits);
- }
-
- if (number != -1) {
- if (m.group(1).equals("source")) {//$NON-NLS-1$
- source = spec.getSource(number);
- } else if (m.group(1).equals("patch")) {//$NON-NLS-1$
- source = spec.getPatch(number);
- }
-
- if (source != null) {
- value = source.getFileName();
- }
- }
- }
- return value;
- }
-
- public static String getMacroValueFromMacroList(String macroName) {
- String value = null;
- if (Activator.getDefault().getRpmMacroList().findKey("%" + macroName)) { //$NON-NLS-1$
- String currentConfig = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_MACRO_HOVER_CONTENT);
- // Show content of the macro according with the configuration set
- // in the macro preference page.
- if (currentConfig.equals(PreferenceConstants.P_MACRO_HOVER_CONTENT_VIEWDESCRIPTION)) {
- value = Activator.getDefault().getRpmMacroList().getValue(macroName);
- } else {
- value = RpmMacroProposalsList.getMacroEval("%" + macroName); //$NON-NLS-1$
- }
- }
- return value;
- }
+ }
+
+ @Override
+ public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
+
+ if (textViewer != null) {
+ /*
+ * If the hover offset falls within the selection range return the
+ * region for the whole selection.
+ */
+ Point selectedRange = textViewer.getSelectedRange();
+ if (selectedRange.x >= 0 && selectedRange.y > 0
+ && offset >= selectedRange.x
+ && offset <= selectedRange.x + selectedRange.y) {
+ return new Region(selectedRange.x, selectedRange.y);
+ } else {
+ IRegion region = findWord(textViewer.getDocument(), offset);
+ if (region.equals(new Region(offset, 0))) {
+ region = findPackages(textViewer.getDocument(), offset);
+ }
+ return region;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public IInformationControlCreator getHoverControlCreator() {
+ return new IInformationControlCreator() {
+ @Override
+ public IInformationControl createInformationControl(Shell parent) {
+ return new DefaultInformationControl(parent, false);
+ }
+ };
+ }
+
+
+ public static IRegion findWord(IDocument document, int offset) {
+ int start = -1;
+ int end = -1;
+ boolean beginsWithBrace = false;
+
+ try {
+ int pos = offset;
+ char c;
+
+ while (pos >= 0) {
+ c = document.getChar(pos);
+ if (c == '%') {
+ if (document.getChar(pos + 1) == '{') {
+ beginsWithBrace = true;
+ }
+ break;
+ }
+ else if (c == '\n' || c == '}'){
+ // if we hit the beginning of the line, it's not a macro
+ return new Region(offset, 0);
+ }
+ --pos;
+ }
+
+ if (!beginsWithBrace) {
+ --pos;
+ }
+
+ start = pos;
+
+ pos = offset;
+ int length = document.getLength();
+
+ while (pos < length) {
+ c = document.getChar(pos);
+ if (beginsWithBrace && (c == '}')) {
+ break;
+ } else if (c == '\n' || c == '%' || c == '('){ // '(' is needed for the %deffatt( case
+ break;
+// Do not return empty region here. We have a work.
+// return new Region(offset, 0);
+ } else if (!beginsWithBrace && c == ' ') {
+ break;
+ }
+ ++pos;
+ }
+
+ end = pos;
+
+ } catch (BadLocationException x) {
+ }
+
+ if (start >= -1 && end > -1) {
+ if (start == offset) {
+ return new Region(start, end - start);
+ } else {
+ return new Region(start + 1, end - start - 1);
+ }
+ }
+
+ return null;
+ }
+
+ public static IRegion findPackages(IDocument document, int offset) {
+ int start = -1;
+ int end = -1;
+ boolean beginsWithSpace = false;
+ try {
+ int pos = offset;
+ char c;
+ while (pos >= 0) {
+ c = document.getChar(pos);
+ if (c == ' ' || c =='\t' || c==':') {
+ if (Character.isLetter(document.getChar(pos + 1))) {
+ beginsWithSpace = true;
+ break;
+ } else if (c == '\n'){
+ return new Region(offset, 0);
+ }
+ }
+ --pos;
+ }
+ --pos;
+ start = pos;
+ pos = offset;
+ int length = document.getLength();
+ while (pos < length) {
+ c = document.getChar(pos);
+ if (beginsWithSpace && (!Character.isLetter(c) && !Character.isDigit(c) && c != '-')) {
+ break;
+ } else if (c == '\n') {
+ return new Region(offset, 0);
+ }
+ ++pos;
+ }
+ end = pos;
+
+ } catch (BadLocationException x) {
+ }
+
+ if (start > -1 && end > -1) {
+ return new Region(start, end - start);
+ }
+ return null;
+ }
+
+ public static String getSourceOrPatchValue(Specfile spec, String patchOrSourceName) {
+ String value = null;
+ Pattern p = Pattern.compile("(source|patch)(\\d*)"); //$NON-NLS-1$
+ Matcher m = p.matcher(patchOrSourceName);
+
+ if (m.matches()) {
+ String digits = m.group(2);
+
+ SpecfileSource source = null;
+ int number = -1;
+
+ if (digits != null && digits.equals(EMPTY_STRING)) {
+ number = 0;
+ } else if (digits != null && !digits.equals(EMPTY_STRING)) {
+ number = Integer.parseInt(digits);
+ }
+
+ if (number != -1) {
+ if (m.group(1).equals("source")) {//$NON-NLS-1$
+ source = spec.getSource(number);
+ } else if (m.group(1).equals("patch")) {//$NON-NLS-1$
+ source = spec.getPatch(number);
+ }
+
+ if (source != null) {
+ value = source.getFileName();
+ }
+ }
+ }
+ return value;
+ }
+
+ public static String getMacroValueFromMacroList(String macroName) {
+ String value = null;
+ if (Activator.getDefault().getRpmMacroList().findKey("%" + macroName)) { //$NON-NLS-1$
+ String currentConfig = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_MACRO_HOVER_CONTENT);
+ // Show content of the macro according with the configuration set
+ // in the macro preference page.
+ if (currentConfig.equals(PreferenceConstants.P_MACRO_HOVER_CONTENT_VIEWDESCRIPTION)) {
+ value = Activator.getDefault().getRpmMacroList().getValue(macroName);
+ } else {
+ value = RpmMacroProposalsList.getMacroEval("%" + macroName); //$NON-NLS-1$
+ }
+ }
+ return value;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileLog.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileLog.java
index 4879fcf1ef..969efba5fc 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileLog.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileLog.java
@@ -18,14 +18,14 @@ import org.eclipse.core.runtime.Status;
* The logger of convenience for the Specfile Plug-In.
*/
public final class SpecfileLog {
-
- private SpecfileLog(){
- super();
- }
-
+
+ private SpecfileLog(){
+ super();
+ }
+
/**
* Log the specified information.
- *
+ *
* @param message A human-readable message, localized to the
* current locale.
*/
@@ -35,7 +35,7 @@ public final class SpecfileLog {
/**
* Log the specified error.
- *
+ *
* @param exception A low-level exception.
*/
public static void logError(Throwable exception) {
@@ -44,7 +44,7 @@ public final class SpecfileLog {
/**
* Log the specified error.
- *
+ *
* @param message A human-readable message, localized to the
* current locale.
* @param exception A low-level exception, or <code>null</code>
@@ -56,7 +56,7 @@ public final class SpecfileLog {
/**
* Log the specified information.
- *
+ *
* @param severity The severity; one of the following:
* <code>IStatus.OK</code>,
* <code>IStatus.ERROR</code>,
@@ -77,7 +77,7 @@ public final class SpecfileLog {
/**
* Create a status object representing the specified information.
- *
+ *
* @param severity The severity; one of the following:
* <code>IStatus.OK</code>,
* <code>IStatus.ERROR</code>,
@@ -100,10 +100,10 @@ public final class SpecfileLog {
/**
* Log the given status.
- *
+ *
* @param status The status to log.
*/
public static void log(IStatus status) {
- Activator.getDefault().getLog().log(status);
+ Activator.getDefault().getLog().log(status);
}
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileReconcilingStrategy.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileReconcilingStrategy.java
index d924e4fe0e..0f39de3a7c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileReconcilingStrategy.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/SpecfileReconcilingStrategy.java
@@ -27,70 +27,70 @@ import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
public class SpecfileReconcilingStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension {
- private SpecfileFoldingStructureProvider sFoldingStructureProvider;
+ private SpecfileFoldingStructureProvider sFoldingStructureProvider;
- SpecfileContentOutlinePage outline;
- SpecfileEditor editor;
- IDocumentProvider documentProvider;
+ SpecfileContentOutlinePage outline;
+ SpecfileEditor editor;
+ IDocumentProvider documentProvider;
- public SpecfileReconcilingStrategy(SpecfileEditor editor) {
- outline= (SpecfileContentOutlinePage) editor.getAdapter(IContentOutlinePage.class);
- this.editor = editor;
- documentProvider = editor.getDocumentProvider();
- sFoldingStructureProvider= new SpecfileFoldingStructureProvider(editor);
- }
+ public SpecfileReconcilingStrategy(SpecfileEditor editor) {
+ outline= (SpecfileContentOutlinePage) editor.getAdapter(IContentOutlinePage.class);
+ this.editor = editor;
+ documentProvider = editor.getDocumentProvider();
+ sFoldingStructureProvider= new SpecfileFoldingStructureProvider(editor);
+ }
- @Override
- public void setDocument(IDocument document) {
- sFoldingStructureProvider.setDocument(document);
- }
+ @Override
+ public void setDocument(IDocument document) {
+ sFoldingStructureProvider.setDocument(document);
+ }
- @Override
- public void setProgressMonitor(IProgressMonitor monitor) {
- sFoldingStructureProvider.setProgressMonitor(monitor);
- }
+ @Override
+ public void setProgressMonitor(IProgressMonitor monitor) {
+ sFoldingStructureProvider.setProgressMonitor(monitor);
+ }
- @Override
- public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
- reconcile();
- }
+ @Override
+ public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
+ reconcile();
+ }
- @Override
- public void initialReconcile() {
- reconcile();
- }
+ @Override
+ public void initialReconcile() {
+ reconcile();
+ }
- private void reconcile() {
- Specfile specfile = editor.getSpecfile();
- if (specfile != null) {
- editor.setSpecfile(editor.getParser().parse(documentProvider
- .getDocument(editor.getEditorInput())));
- outline.update();
- updateFolding();
- updateEditor();
- }
- }
+ private void reconcile() {
+ Specfile specfile = editor.getSpecfile();
+ if (specfile != null) {
+ editor.setSpecfile(editor.getParser().parse(documentProvider
+ .getDocument(editor.getEditorInput())));
+ outline.update();
+ updateFolding();
+ updateEditor();
+ }
+ }
- @Override
- public void reconcile(IRegion partition) {
- reconcile();
- }
+ @Override
+ public void reconcile(IRegion partition) {
+ reconcile();
+ }
- private void updateEditor() {
- Shell shell= editor.getSite().getShell();
- if (!(shell == null || shell.isDisposed())) {
- shell.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- editor.setSpecfile(editor.getParser().parse(documentProvider
- .getDocument(editor.getEditorInput())));
- }
- });
- }
- }
+ private void updateEditor() {
+ Shell shell= editor.getSite().getShell();
+ if (!(shell == null || shell.isDisposed())) {
+ shell.getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ editor.setSpecfile(editor.getParser().parse(documentProvider
+ .getDocument(editor.getEditorInput())));
+ }
+ });
+ }
+ }
- private void updateFolding() {
- sFoldingStructureProvider.updateFoldingRegions();
- }
+ private void updateFolding() {
+ sFoldingStructureProvider.updateFoldingRegions();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/UiUtils.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/UiUtils.java
index 16b97fb6ff..22e8cb9bd8 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/UiUtils.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/UiUtils.java
@@ -29,64 +29,64 @@ import org.eclipse.linuxtools.rpm.ui.editor.parser.SpecfilePackage;
public class UiUtils {
- public static void pluginSanityCheck() throws IOException {
- boolean exists = (new File(PreferenceConstants.RPMMACRO_FILE)).exists();
- // Check if ~/.rpmmacros exist, if the file don't exist we create
- // it with the appropriate command.
- if (!exists && Utils.fileExist("/usr/bin/rpmdev-setuptree")) { //$NON-NLS-1$
- org.eclipse.linuxtools.rpm.core.utils.Utils.runCommandToInputStream("rpmdev-setuptree"); //$NON-NLS-1$
- }
+ public static void pluginSanityCheck() throws IOException {
+ boolean exists = (new File(PreferenceConstants.RPMMACRO_FILE)).exists();
+ // Check if ~/.rpmmacros exist, if the file don't exist we create
+ // it with the appropriate command.
+ if (!exists && Utils.fileExist("/usr/bin/rpmdev-setuptree")) { //$NON-NLS-1$
+ org.eclipse.linuxtools.rpm.core.utils.Utils.runCommandToInputStream("rpmdev-setuptree"); //$NON-NLS-1$
+ }
- // Check RPM tool preference.
- String currentRpmTool = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_CURRENT_RPMTOOLS);
- if (!Utils.fileExist("/usr/bin/yum")) { //$NON-NLS-1$
- if (currentRpmTool.equals(PreferenceConstants.DP_RPMTOOLS_YUM)) {
- Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.P_CURRENT_RPMTOOLS, PreferenceConstants.DP_RPMTOOLS_RPM);
- }
- } else if (!Utils.fileExist("/usr/bin/urpmq")) { //$NON-NLS-1$
- if (currentRpmTool.equals(PreferenceConstants.DP_RPMTOOLS_URPM)) {
- Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.P_CURRENT_RPMTOOLS, PreferenceConstants.DP_RPMTOOLS_RPM);
- }
- }
- }
+ // Check RPM tool preference.
+ String currentRpmTool = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_CURRENT_RPMTOOLS);
+ if (!Utils.fileExist("/usr/bin/yum")) { //$NON-NLS-1$
+ if (currentRpmTool.equals(PreferenceConstants.DP_RPMTOOLS_YUM)) {
+ Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.P_CURRENT_RPMTOOLS, PreferenceConstants.DP_RPMTOOLS_RPM);
+ }
+ } else if (!Utils.fileExist("/usr/bin/urpmq")) { //$NON-NLS-1$
+ if (currentRpmTool.equals(PreferenceConstants.DP_RPMTOOLS_URPM)) {
+ Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.P_CURRENT_RPMTOOLS, PreferenceConstants.DP_RPMTOOLS_RPM);
+ }
+ }
+ }
- /**
- * Resolve defines for a give string, if a define is not found or if
- * there is some other error, the original string is returned.
- *
- * @param stringToResolve The string to resolve.
- * @return resolved string
- */
- public static String resolveDefines(Specfile specfile, String stringToResolve) {
- String originalString = stringToResolve;
- SpecfileDefine define;
- try {
- Pattern variablePattern = Pattern.compile("%\\{(\\S+?)\\}"); //$NON-NLS-1$
- Matcher variableMatcher = variablePattern.matcher(stringToResolve);
- while (variableMatcher.find()) {
- define = specfile.getDefine(variableMatcher.group(1));
- if (define != null) {
- stringToResolve = stringToResolve.replaceAll("\\b"+variableMatcher.group(1)+"\\b", define.getStringValue()); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- return originalString;
- }
- }
- if (!stringToResolve.equals(originalString)) {
- stringToResolve = stringToResolve.replaceAll("\\%\\{|\\}", ""); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return stringToResolve;
- } catch (Exception e) {
- return originalString;
- }
- }
+ /**
+ * Resolve defines for a give string, if a define is not found or if
+ * there is some other error, the original string is returned.
+ *
+ * @param stringToResolve The string to resolve.
+ * @return resolved string
+ */
+ public static String resolveDefines(Specfile specfile, String stringToResolve) {
+ String originalString = stringToResolve;
+ SpecfileDefine define;
+ try {
+ Pattern variablePattern = Pattern.compile("%\\{(\\S+?)\\}"); //$NON-NLS-1$
+ Matcher variableMatcher = variablePattern.matcher(stringToResolve);
+ while (variableMatcher.find()) {
+ define = specfile.getDefine(variableMatcher.group(1));
+ if (define != null) {
+ stringToResolve = stringToResolve.replaceAll("\\b"+variableMatcher.group(1)+"\\b", define.getStringValue()); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ return originalString;
+ }
+ }
+ if (!stringToResolve.equals(originalString)) {
+ stringToResolve = stringToResolve.replaceAll("\\%\\{|\\}", ""); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return stringToResolve;
+ } catch (Exception e) {
+ return originalString;
+ }
+ }
- public static String getPackageDefineId(SpecfileDefine define, SpecfilePackage rpmPackage){
- return getPackageDefineId(define.getName(),rpmPackage);
- }
+ public static String getPackageDefineId(SpecfileDefine define, SpecfilePackage rpmPackage){
+ return getPackageDefineId(define.getName(),rpmPackage);
+ }
- public static String getPackageDefineId(String defineName, SpecfilePackage rpmPackage){
- return defineName.toLowerCase() + ':' + rpmPackage.getPackageName();
- }
+ public static String getPackageDefineId(String defineName, SpecfilePackage rpmPackage){
+ return defineName.toLowerCase() + ':' + rpmPackage.getPackageName();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/Messages.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/Messages.java
index 14325e4ce0..e9681f7c7e 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/Messages.java
@@ -13,32 +13,32 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.actions;
import org.eclipse.osgi.util.NLS;
public final class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.actions.messages"; //$NON-NLS-1$
- public static String SpecfileChangelogFormatter_0;
- public static String SpecfileChangelogFormatter_1;
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.actions.messages"; //$NON-NLS-1$
+ public static String SpecfileChangelogFormatter_0;
+ public static String SpecfileChangelogFormatter_1;
- // SpecfileEditorDownloadSourcesActionDelegate
- public static String DownloadSources_malformedURL;
- public static String DownloadSources_cannotConnectToURL;
+ // SpecfileEditorDownloadSourcesActionDelegate
+ public static String DownloadSources_malformedURL;
+ public static String DownloadSources_cannotConnectToURL;
- // SpecfileEditorPrepareSourcesActionDelegate
- public static String PrepareSources_error;
- public static String PrepareSources_downloadSourcesMalformedURL;
- public static String PrepareSources_downloadCancelled;
- public static String PrepareSources_downloadConnectionFail;
- public static String PrepareSources_coreException;
- public static String PrepareSources_prepareSources;
- public static String PrepareSources_consoleName;
+ // SpecfileEditorPrepareSourcesActionDelegate
+ public static String PrepareSources_error;
+ public static String PrepareSources_downloadSourcesMalformedURL;
+ public static String PrepareSources_downloadCancelled;
+ public static String PrepareSources_downloadConnectionFail;
+ public static String PrepareSources_coreException;
+ public static String PrepareSources_prepareSources;
+ public static String PrepareSources_consoleName;
- // RPMHandlerUtils
- public static String RPMHandlerUtils_cannotCreateRPMProject;
+ // RPMHandlerUtils
+ public static String RPMHandlerUtils_cannotCreateRPMProject;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- super();
- }
+ private Messages() {
+ super();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileChangelogFormatter.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileChangelogFormatter.java
index 9a3d5fcba3..97801efed2 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileChangelogFormatter.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileChangelogFormatter.java
@@ -38,12 +38,12 @@ import org.eclipse.ui.PlatformUI;
public class SpecfileChangelogFormatter implements IFormatterChangeLogContrib {
public final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("EEE MMM d yyyy"); //$NON-NLS-1$
- private static final String EMPTY_STRING = ""; //$NON-NLS-1$
- private IEditorPart changelog;
+ private static final String EMPTY_STRING = ""; //$NON-NLS-1$
+ private IEditorPart changelog;
@Override
- public String formatDateLine(String authorName, String authorEmail) {
- String dateLine;
+ public String formatDateLine(String authorName, String authorEmail) {
+ String dateLine;
Specfile specfile = getParsedSpecfile();
SpecfileElement resolveElement = new SpecfileElement();
resolveElement.setSpecfile(specfile);
@@ -56,19 +56,19 @@ public class SpecfileChangelogFormatter implements IFormatterChangeLogContrib {
// default format
dateLine = MessageFormat.format("* {0} {1} <{2}> {3}{4}-{5}", formatTodaysDate(), authorName, //$NON-NLS-1$
- authorEmail, epoch, version, release);
+ authorEmail, epoch, version, release);
String format = Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT);
if (format.equals(PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT_VERSIONED_WITH_SEPARATOR)) {
- dateLine = MessageFormat.format("* {0} {1} <{2}> - {3}{4}-{5}", formatTodaysDate(), //$NON-NLS-1$
- authorName, authorEmail, epoch, version, release);
+ dateLine = MessageFormat.format("* {0} {1} <{2}> - {3}{4}-{5}", formatTodaysDate(), //$NON-NLS-1$
+ authorName, authorEmail, epoch, version, release);
} else if (format.equals(PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT_UNVERSIONED)) {
- dateLine = MessageFormat
- .format("* {0} {1} <{2}>", formatTodaysDate(), authorName, authorEmail); //$NON-NLS-1$
+ dateLine = MessageFormat
+ .format("* {0} {1} <{2}>", formatTodaysDate(), authorName, authorEmail); //$NON-NLS-1$
}
- dateLine = UiUtils.resolveDefines(specfile, dateLine);
+ dateLine = UiUtils.resolveDefines(specfile, dateLine);
return dateLine;
}
@@ -97,11 +97,11 @@ public class SpecfileChangelogFormatter implements IFormatterChangeLogContrib {
return date;
}
- @Override
- public String mergeChangelog(String dateLine, String functionGuess,
- String defaultContent, IEditorPart changelog,
- String changeLogLocation, String fileLocation) {
- if (changelog instanceof SpecfileEditor) {
+ @Override
+ public String mergeChangelog(String dateLine, String functionGuess,
+ String defaultContent, IEditorPart changelog,
+ String changeLogLocation, String fileLocation) {
+ if (changelog instanceof SpecfileEditor) {
SpecfileEditor specEditor = (SpecfileEditor) changelog;
IDocument doc = specEditor.getDocumentProvider().getDocument(
specEditor.getEditorInput());
@@ -187,13 +187,13 @@ public class SpecfileChangelogFormatter implements IFormatterChangeLogContrib {
specEditor.selectAndReveal(newCursorOffset, 0);
specEditor.setFocus();
} catch (BadPositionCategoryException e) {
- SpecfileLog.logError(e);
+ SpecfileLog.logError(e);
} catch (BadLocationException e) {
- SpecfileLog.logError(e);
+ SpecfileLog.logError(e);
}
}
}
return EMPTY_STRING;
- }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileChangelogParser.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileChangelogParser.java
index 3ffce59b14..e99c29da2d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileChangelogParser.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileChangelogParser.java
@@ -18,14 +18,14 @@ import org.eclipse.ui.IEditorPart;
public class SpecfileChangelogParser implements IParserChangeLogContrib {
- @Override
- public String parseCurrentFunction(IEditorPart editor) throws CoreException {
- return ""; //$NON-NLS-1$
- }
+ @Override
+ public String parseCurrentFunction(IEditorPart editor) throws CoreException {
+ return ""; //$NON-NLS-1$
+ }
- @Override
- public String parseCurrentFunction(IEditorInput input, int offset) throws CoreException {
- return ""; //$NON-NLS-1$
- }
+ @Override
+ public String parseCurrentFunction(IEditorInput input, int offset) throws CoreException {
+ return ""; //$NON-NLS-1$
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorDownloadSourcesActionDelegate.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorDownloadSourcesActionDelegate.java
index 0db5355f65..44af226eeb 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorDownloadSourcesActionDelegate.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorDownloadSourcesActionDelegate.java
@@ -39,58 +39,58 @@ import org.eclipse.ui.handlers.HandlerUtil;
public class SpecfileEditorDownloadSourcesActionDelegate extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- final Shell shell = HandlerUtil.getActiveShellChecked(event);
- final SpecfileParser specparser = new SpecfileParser();
- final IResource resource = RPMHandlerUtils.getResource(event);
- final RPMProject rpj = RPMHandlerUtils.getRPMProject(resource);
- final IFile workFile = (IFile) rpj.getSpecFile();
- final Specfile specfile = specparser.parse(workFile);
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ final Shell shell = HandlerUtil.getActiveShellChecked(event);
+ final SpecfileParser specparser = new SpecfileParser();
+ final IResource resource = RPMHandlerUtils.getResource(event);
+ final RPMProject rpj = RPMHandlerUtils.getRPMProject(resource);
+ final IFile workFile = (IFile) rpj.getSpecFile();
+ final Specfile specfile = specparser.parse(workFile);
- // retrieve source(s) from specfile
- final List<SpecfileSource> sourceURLList = specfile != null ? (List<SpecfileSource>) specfile
- .getSources() : null;
+ // retrieve source(s) from specfile
+ final List<SpecfileSource> sourceURLList = specfile != null ? (List<SpecfileSource>) specfile
+ .getSources() : null;
- // go through each source, resolve the defines, and then download the file
- // currently stops immediately once an invalid source URL is encountered
- for (final SpecfileSource sourceurls : sourceURLList) {
- try {
- String rawURL = sourceurls.getFileName();
- String resolvedURL = UiUtils.resolveDefines(specfile, rawURL);
- URL url = null;
- try {
- url = new URL(resolvedURL);
- } catch(MalformedURLException e) {
- SpecfileLog.logError(NLS.bind(Messages.DownloadSources_malformedURL, resolvedURL), e);
- RPMUtils.showErrorDialog(shell, "Error", //$NON-NLS-1$
- NLS.bind(Messages.DownloadSources_malformedURL, resolvedURL));
- return null;
- }
+ // go through each source, resolve the defines, and then download the file
+ // currently stops immediately once an invalid source URL is encountered
+ for (final SpecfileSource sourceurls : sourceURLList) {
+ try {
+ String rawURL = sourceurls.getFileName();
+ String resolvedURL = UiUtils.resolveDefines(specfile, rawURL);
+ URL url = null;
+ try {
+ url = new URL(resolvedURL);
+ } catch(MalformedURLException e) {
+ SpecfileLog.logError(NLS.bind(Messages.DownloadSources_malformedURL, resolvedURL), e);
+ RPMUtils.showErrorDialog(shell, "Error", //$NON-NLS-1$
+ NLS.bind(Messages.DownloadSources_malformedURL, resolvedURL));
+ return null;
+ }
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- if (connection.getResponseCode() != HttpURLConnection.HTTP_NOT_FOUND) {
- // grab the name of the file from the URL
- int offset = url.toString().lastIndexOf("/"); //$NON-NLS-1$
- String filename = url.toString().substring(offset + 1);
+ if (connection.getResponseCode() != HttpURLConnection.HTTP_NOT_FOUND) {
+ // grab the name of the file from the URL
+ int offset = url.toString().lastIndexOf("/"); //$NON-NLS-1$
+ String filename = url.toString().substring(offset + 1);
- // create the path to the "to be downloaded" file
- IFile file = rpj.getConfiguration().getSourcesFolder().getFile(new Path(filename));
+ // create the path to the "to be downloaded" file
+ IFile file = rpj.getConfiguration().getSourcesFolder().getFile(new Path(filename));
- Job downloadJob = new DownloadJob(file, connection);
- downloadJob.setUser(true);
- downloadJob.schedule();
- }
- } catch (IOException e) {
- SpecfileLog.logError(Messages.DownloadSources_cannotConnectToURL, e);
- RPMUtils.showErrorDialog(shell, "Error", //$NON-NLS-1$
- Messages.DownloadSources_cannotConnectToURL);
- return null;
- }
- }
+ Job downloadJob = new DownloadJob(file, connection);
+ downloadJob.setUser(true);
+ downloadJob.schedule();
+ }
+ } catch (IOException e) {
+ SpecfileLog.logError(Messages.DownloadSources_cannotConnectToURL, e);
+ RPMUtils.showErrorDialog(shell, "Error", //$NON-NLS-1$
+ Messages.DownloadSources_cannotConnectToURL);
+ return null;
+ }
+ }
- return null;
- }
+ return null;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorOrganizePatchesActionDelegate.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorOrganizePatchesActionDelegate.java
index c1c04cc049..7a689eb8d8 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorOrganizePatchesActionDelegate.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorOrganizePatchesActionDelegate.java
@@ -20,17 +20,17 @@ import org.eclipse.ui.handlers.HandlerUtil;
public class SpecfileEditorOrganizePatchesActionDelegate extends AbstractHandler {
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
- */
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- Specfile specfile = ((SpecfileEditor)HandlerUtil.getActiveEditor(event)).getSpecfile();
- if (specfile != null) {
- specfile.organizePatches();
- }
- return null;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
+ */
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ Specfile specfile = ((SpecfileEditor)HandlerUtil.getActiveEditor(event)).getSpecfile();
+ if (specfile != null) {
+ specfile.organizePatches();
+ }
+ return null;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorPrepareSourcesActionDelegate.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorPrepareSourcesActionDelegate.java
index 84bdfd39ed..b921fc9ddb 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorPrepareSourcesActionDelegate.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorPrepareSourcesActionDelegate.java
@@ -48,135 +48,135 @@ import org.eclipse.ui.handlers.HandlerUtil;
public class SpecfileEditorPrepareSourcesActionDelegate extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- final Shell shell = HandlerUtil.getActiveShellChecked(event);
- final SpecfileParser specparser = new SpecfileParser();
- final IResource resource = RPMHandlerUtils.getResource(event);
- final RPMProject rpj = RPMHandlerUtils.getRPMProject(resource);
- final IFile workFile = (IFile) rpj.getSpecFile();
- final Specfile specfile = specparser.parse(workFile);
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ final Shell shell = HandlerUtil.getActiveShellChecked(event);
+ final SpecfileParser specparser = new SpecfileParser();
+ final IResource resource = RPMHandlerUtils.getResource(event);
+ final RPMProject rpj = RPMHandlerUtils.getRPMProject(resource);
+ final IFile workFile = (IFile) rpj.getSpecFile();
+ final Specfile specfile = specparser.parse(workFile);
- if (!downloadFile(shell, rpj, specfile)) {
- return null;
- }
+ if (!downloadFile(shell, rpj, specfile)) {
+ return null;
+ }
- Job job = new Job("Preparing sources") { //$NON-NLS-1$
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- monitor.beginTask(
- NLS.bind(Messages.PrepareSources_prepareSources, rpj.getSpecFile().getName()), IProgressMonitor.UNKNOWN);
- int offset = rpj.getSpecFile().getName().lastIndexOf("."); //$NON-NLS-1$
- MessageConsoleStream out = getConsole(
- rpj.getSpecFile().getName().substring(0, offset))
- .newMessageStream();
- IStatus is = null;
- try {
- is = rpj.buildPrep(out);
- } catch (CoreException e) {
- SpecfileLog.logError(Messages.PrepareSources_coreException,
- e);
- RPMUtils.showErrorDialog(shell,
- Messages.PrepareSources_error,
- Messages.PrepareSources_coreException);
- return is;
- } finally {
- monitor.done();
- }
- return is;
- }
- };
- job.setUser(true); // suppress UI. That's done in encapsulated
- job.schedule();
- return null;
- }
+ Job job = new Job("Preparing sources") { //$NON-NLS-1$
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ monitor.beginTask(
+ NLS.bind(Messages.PrepareSources_prepareSources, rpj.getSpecFile().getName()), IProgressMonitor.UNKNOWN);
+ int offset = rpj.getSpecFile().getName().lastIndexOf("."); //$NON-NLS-1$
+ MessageConsoleStream out = getConsole(
+ rpj.getSpecFile().getName().substring(0, offset))
+ .newMessageStream();
+ IStatus is = null;
+ try {
+ is = rpj.buildPrep(out);
+ } catch (CoreException e) {
+ SpecfileLog.logError(Messages.PrepareSources_coreException,
+ e);
+ RPMUtils.showErrorDialog(shell,
+ Messages.PrepareSources_error,
+ Messages.PrepareSources_coreException);
+ return is;
+ } finally {
+ monitor.done();
+ }
+ return is;
+ }
+ };
+ job.setUser(true); // suppress UI. That's done in encapsulated
+ job.schedule();
+ return null;
+ }
- public boolean downloadFile(Shell shell, RPMProject rpj, Specfile specfile) {
- // retrieve source(s) from specfile
- final List<SpecfileSource> sourceURLList = specfile != null ? (List<SpecfileSource>) specfile
- .getSources() : null;
- for (final SpecfileSource sourceurls : sourceURLList) {
- try {
- String resolvedURL = UiUtils.resolveDefines(specfile, sourceurls.getFileName());
- URL url = null;
- try {
- url = new URL(resolvedURL);
- } catch (MalformedURLException e) {
- SpecfileLog.logError(
- NLS.bind(Messages.PrepareSources_downloadSourcesMalformedURL, resolvedURL), e);
- RPMUtils.showErrorDialog(shell,
- Messages.PrepareSources_error,
- NLS.bind(Messages.PrepareSources_downloadSourcesMalformedURL, resolvedURL));
- return false;
- }
+ public boolean downloadFile(Shell shell, RPMProject rpj, Specfile specfile) {
+ // retrieve source(s) from specfile
+ final List<SpecfileSource> sourceURLList = specfile != null ? (List<SpecfileSource>) specfile
+ .getSources() : null;
+ for (final SpecfileSource sourceurls : sourceURLList) {
+ try {
+ String resolvedURL = UiUtils.resolveDefines(specfile, sourceurls.getFileName());
+ URL url = null;
+ try {
+ url = new URL(resolvedURL);
+ } catch (MalformedURLException e) {
+ SpecfileLog.logError(
+ NLS.bind(Messages.PrepareSources_downloadSourcesMalformedURL, resolvedURL), e);
+ RPMUtils.showErrorDialog(shell,
+ Messages.PrepareSources_error,
+ NLS.bind(Messages.PrepareSources_downloadSourcesMalformedURL, resolvedURL));
+ return false;
+ }
- HttpURLConnection connection = (HttpURLConnection) url
- .openConnection();
+ HttpURLConnection connection = (HttpURLConnection) url
+ .openConnection();
- if (connection.getResponseCode() != HttpURLConnection.HTTP_NOT_FOUND) {
- // grab the name of the file from the URL
- int offset = url.toString().lastIndexOf("/"); //$NON-NLS-1$
- String filename = url.toString().substring(offset + 1);
+ if (connection.getResponseCode() != HttpURLConnection.HTTP_NOT_FOUND) {
+ // grab the name of the file from the URL
+ int offset = url.toString().lastIndexOf("/"); //$NON-NLS-1$
+ String filename = url.toString().substring(offset + 1);
- // create the path to the "to be downloaded" file
- IFile file = rpj.getConfiguration().getSourcesFolder()
- .getFile(new Path(filename));
+ // create the path to the "to be downloaded" file
+ IFile file = rpj.getConfiguration().getSourcesFolder()
+ .getFile(new Path(filename));
- Job downloadJob = new DownloadJob(file, connection);
- downloadJob.setUser(true);
- downloadJob.schedule();
- try {
- downloadJob.join();
- } catch (InterruptedException e1) {
- return false;
- }
- if (!downloadJob.getResult().isOK()) {
- return false;
- }
- }
- } catch (OperationCanceledException e) {
- SpecfileLog.logError(Messages.PrepareSources_downloadCancelled,
- e);
- RPMUtils.showErrorDialog(shell, Messages.PrepareSources_error,
- Messages.PrepareSources_downloadCancelled);
- return false;
- } catch (IOException e) {
- SpecfileLog.logError(
- Messages.PrepareSources_downloadConnectionFail, e);
- RPMUtils.showErrorDialog(shell, Messages.PrepareSources_error,
- Messages.PrepareSources_downloadConnectionFail);
- return false;
- }
- }
- return true;
- }
+ Job downloadJob = new DownloadJob(file, connection);
+ downloadJob.setUser(true);
+ downloadJob.schedule();
+ try {
+ downloadJob.join();
+ } catch (InterruptedException e1) {
+ return false;
+ }
+ if (!downloadJob.getResult().isOK()) {
+ return false;
+ }
+ }
+ } catch (OperationCanceledException e) {
+ SpecfileLog.logError(Messages.PrepareSources_downloadCancelled,
+ e);
+ RPMUtils.showErrorDialog(shell, Messages.PrepareSources_error,
+ Messages.PrepareSources_downloadCancelled);
+ return false;
+ } catch (IOException e) {
+ SpecfileLog.logError(
+ Messages.PrepareSources_downloadConnectionFail, e);
+ RPMUtils.showErrorDialog(shell, Messages.PrepareSources_error,
+ Messages.PrepareSources_downloadConnectionFail);
+ return false;
+ }
+ }
+ return true;
+ }
- /**
- * Get the console.
- *
- * @param packageName
- * The name of the package(RPM) this console will be for.
- * @return A console instance.
- */
- public MessageConsole getConsole(String packageName) {
- ConsolePlugin plugin = ConsolePlugin.getDefault();
- IConsoleManager conMan = plugin.getConsoleManager();
- String projectConsoleName = NLS.bind(Messages.PrepareSources_consoleName, packageName);
- MessageConsole ret = null;
- for (IConsole cons : ConsolePlugin.getDefault().getConsoleManager()
- .getConsoles()) {
- if (cons.getName().equals(projectConsoleName)) {
- ret = (MessageConsole) cons;
- }
- }
- // no existing console, create new one
- if (ret == null) {
- ret = new MessageConsole(projectConsoleName, null, null, true);
- }
- conMan.addConsoles(new IConsole[] { ret });
- ret.clearConsole();
- ret.activate();
- return ret;
- }
+ /**
+ * Get the console.
+ *
+ * @param packageName
+ * The name of the package(RPM) this console will be for.
+ * @return A console instance.
+ */
+ public MessageConsole getConsole(String packageName) {
+ ConsolePlugin plugin = ConsolePlugin.getDefault();
+ IConsoleManager conMan = plugin.getConsoleManager();
+ String projectConsoleName = NLS.bind(Messages.PrepareSources_consoleName, packageName);
+ MessageConsole ret = null;
+ for (IConsole cons : ConsolePlugin.getDefault().getConsoleManager()
+ .getConsoles()) {
+ if (cons.getName().equals(projectConsoleName)) {
+ ret = (MessageConsole) cons;
+ }
+ }
+ // no existing console, create new one
+ if (ret == null) {
+ ret = new MessageConsole(projectConsoleName, null, null, true);
+ }
+ conMan.addConsoles(new IConsole[] { ret });
+ ret.clearConsole();
+ ret.activate();
+ return ret;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorShowOutlineActionDelegate.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorShowOutlineActionDelegate.java
index d351b473c1..084eb3c4ce 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorShowOutlineActionDelegate.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorShowOutlineActionDelegate.java
@@ -20,15 +20,15 @@ import org.eclipse.ui.handlers.HandlerUtil;
public class SpecfileEditorShowOutlineActionDelegate extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- SpecfileEditor editor = (SpecfileEditor) HandlerUtil
- .getActiveEditor(event);
- SpecfileQuickOutlineDialog quickOutlinePopupDialog = new SpecfileQuickOutlineDialog(
- editor.getSite().getShell(), SWT.NONE, editor);
- quickOutlinePopupDialog.setSize(400, 200);
- quickOutlinePopupDialog.setVisible(true);
- return null;
- }
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ SpecfileEditor editor = (SpecfileEditor) HandlerUtil
+ .getActiveEditor(event);
+ SpecfileQuickOutlineDialog quickOutlinePopupDialog = new SpecfileQuickOutlineDialog(
+ editor.getSite().getShell(), SWT.NONE, editor);
+ quickOutlinePopupDialog.setSize(400, 200);
+ quickOutlinePopupDialog.setVisible(true);
+ return null;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorToggleCommentActionDelegate.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorToggleCommentActionDelegate.java
index cd12e1e3a6..ad89e53830 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorToggleCommentActionDelegate.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/actions/SpecfileEditorToggleCommentActionDelegate.java
@@ -29,75 +29,75 @@ import org.eclipse.ui.handlers.HandlerUtil;
public class SpecfileEditorToggleCommentActionDelegate extends AbstractHandler {
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
- */
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- SpecfileEditor editor = (SpecfileEditor) HandlerUtil.getActiveEditor(event);
- IDocument document = (IDocument) editor.getAdapter(IDocument.class);
- ISelection currentSelection = editor.getSpecfileSourceViewer()
- .getSelection();
- if (currentSelection instanceof ITextSelection) {
- ITextSelection selection = (ITextSelection) currentSelection;
- String selectedContent = ""; //$NON-NLS-1$
- try {
- int begin = document.getLineOffset(selection.getStartLine());
- StringBuilder sb = new StringBuilder(document.get().substring(0,
- begin));
- String content = document.get().substring(begin,
- selection.getOffset() + selection.getLength());
- if (linesContentCommentChar(content)) {
- if (selection.getStartLine() == selection.getEndLine()) {
- selectedContent = ISpecfileSpecialSymbols.COMMENT_START + content;
- } else {
- selectedContent = ISpecfileSpecialSymbols.COMMENT_START + content.replaceAll("\n", "\n#"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- selectedContent = content.replaceFirst(ISpecfileSpecialSymbols.COMMENT_START, "").replaceAll( //$NON-NLS-1$
- "\n#", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- sb.append(selectedContent);
- sb.append(document.get().substring(
- selection.getOffset() + selection.getLength(),
- document.get().length()));
- document.set(sb.toString());
- editor.setHighlightRange(selection.getOffset(), selection
- .getLength(), true);
- } catch (BadLocationException e) {
- SpecfileLog.logError(e);
- }
- }
- return null;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
+ */
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ SpecfileEditor editor = (SpecfileEditor) HandlerUtil.getActiveEditor(event);
+ IDocument document = (IDocument) editor.getAdapter(IDocument.class);
+ ISelection currentSelection = editor.getSpecfileSourceViewer()
+ .getSelection();
+ if (currentSelection instanceof ITextSelection) {
+ ITextSelection selection = (ITextSelection) currentSelection;
+ String selectedContent = ""; //$NON-NLS-1$
+ try {
+ int begin = document.getLineOffset(selection.getStartLine());
+ StringBuilder sb = new StringBuilder(document.get().substring(0,
+ begin));
+ String content = document.get().substring(begin,
+ selection.getOffset() + selection.getLength());
+ if (linesContentCommentChar(content)) {
+ if (selection.getStartLine() == selection.getEndLine()) {
+ selectedContent = ISpecfileSpecialSymbols.COMMENT_START + content;
+ } else {
+ selectedContent = ISpecfileSpecialSymbols.COMMENT_START + content.replaceAll("\n", "\n#"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ } else {
+ selectedContent = content.replaceFirst(ISpecfileSpecialSymbols.COMMENT_START, "").replaceAll( //$NON-NLS-1$
+ "\n#", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ sb.append(selectedContent);
+ sb.append(document.get().substring(
+ selection.getOffset() + selection.getLength(),
+ document.get().length()));
+ document.set(sb.toString());
+ editor.setHighlightRange(selection.getOffset(), selection
+ .getLength(), true);
+ } catch (BadLocationException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+ return null;
+ }
- /**
- * Check if all lines are commented
- *
- * @param content
- * to check
- * @return true if all lines begin with '#' char
- */
- private boolean linesContentCommentChar(String content) {
- LineNumberReader reader = new LineNumberReader(
- new StringReader(content));
- String line;
- boolean ret = false;
- try {
- while ((line = reader.readLine()) != null) {
- if (line.startsWith(ISpecfileSpecialSymbols.COMMENT_START)) {
- ret = false;
- } else {
- return true;
- }
- }
- } catch (IOException e) {
- SpecfileLog.logError(e);
- return false;
- }
- return ret;
- }
+ /**
+ * Check if all lines are commented
+ *
+ * @param content
+ * to check
+ * @return true if all lines begin with '#' char
+ */
+ private boolean linesContentCommentChar(String content) {
+ LineNumberReader reader = new LineNumberReader(
+ new StringReader(content));
+ String line;
+ boolean ret = false;
+ try {
+ while ((line = reader.readLine()) != null) {
+ if (line.startsWith(ISpecfileSpecialSymbols.COMMENT_START)) {
+ ret = false;
+ } else {
+ return true;
+ }
+ }
+ } catch (IOException e) {
+ SpecfileLog.logError(e);
+ return false;
+ }
+ return ret;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/Messages.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/Messages.java
index 36eb1f2e63..0bfed73c9a 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/Messages.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -13,15 +13,15 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.compare;
import org.eclipse.osgi.util.NLS;
public final class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.compare.messages"; //$NON-NLS-1$
- public static String SpecMergeViewer_0;
- public static String SpecStructureCreator_0;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.compare.messages"; //$NON-NLS-1$
+ public static String SpecMergeViewer_0;
+ public static String SpecStructureCreator_0;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- super();
- }
+ private Messages() {
+ super();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecMergeViewer.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecMergeViewer.java
index 342e7053fc..558f0eeb88 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecMergeViewer.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecMergeViewer.java
@@ -28,56 +28,56 @@ import org.eclipse.swt.widgets.Composite;
*
*/
public class SpecMergeViewer extends TextMergeViewer {
- private ColorManager colorManager;
+ private ColorManager colorManager;
- /**
- * Creates a new SpecMergeViewer.
- *
- * @param parent The parent control.
- * @param configuration The compare configuration.
- *
- * @see TextMergeViewer#TextMergeViewer(Composite, CompareConfiguration)
- */
- public SpecMergeViewer(Composite parent, CompareConfiguration configuration) {
- super(parent, configuration);
- }
+ /**
+ * Creates a new SpecMergeViewer.
+ *
+ * @param parent The parent control.
+ * @param configuration The compare configuration.
+ *
+ * @see TextMergeViewer#TextMergeViewer(Composite, CompareConfiguration)
+ */
+ public SpecMergeViewer(Composite parent, CompareConfiguration configuration) {
+ super(parent, configuration);
+ }
- @Override
- public String getTitle() {
- return Messages.SpecMergeViewer_0;
- }
+ @Override
+ public String getTitle() {
+ return Messages.SpecMergeViewer_0;
+ }
- @Override
- protected IDocumentPartitioner getDocumentPartitioner() {
- return new FastPartitioner(new SpecfilePartitionScanner(),
- SpecfilePartitionScanner.SPEC_PARTITION_TYPES);
- }
+ @Override
+ protected IDocumentPartitioner getDocumentPartitioner() {
+ return new FastPartitioner(new SpecfilePartitionScanner(),
+ SpecfilePartitionScanner.SPEC_PARTITION_TYPES);
+ }
- @Override
- protected String getDocumentPartitioning() {
- return SpecfilePartitionScanner.SPEC_FILE_PARTITIONING;
- }
+ @Override
+ protected String getDocumentPartitioning() {
+ return SpecfilePartitionScanner.SPEC_FILE_PARTITIONING;
+ }
- @Override
- protected void configureTextViewer(TextViewer textViewer) {
- if (textViewer instanceof SourceViewer) {
- this.colorManager = new ColorManager();
- SpecfileEditor editor = new SpecfileEditor();
- ((SourceViewer) textViewer).configure(new SpecfileConfiguration(
- colorManager, editor));
- }
- }
+ @Override
+ protected void configureTextViewer(TextViewer textViewer) {
+ if (textViewer instanceof SourceViewer) {
+ this.colorManager = new ColorManager();
+ SpecfileEditor editor = new SpecfileEditor();
+ ((SourceViewer) textViewer).configure(new SpecfileConfiguration(
+ colorManager, editor));
+ }
+ }
- /**
- * Dispose the color manager and invoke the super method.
- *
- * @see org.eclipse.compare.contentmergeviewer.TextMergeViewer#handleDispose(org.eclipse.swt.events.DisposeEvent)
- */
- @Override
- protected void handleDispose(DisposeEvent event) {
- if (colorManager != null) {
- colorManager.dispose();
- }
- super.handleDispose(event);
- }
+ /**
+ * Dispose the color manager and invoke the super method.
+ *
+ * @see org.eclipse.compare.contentmergeviewer.TextMergeViewer#handleDispose(org.eclipse.swt.events.DisposeEvent)
+ */
+ @Override
+ protected void handleDispose(DisposeEvent event) {
+ if (colorManager != null) {
+ colorManager.dispose();
+ }
+ super.handleDispose(event);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecMergeViewerCreator.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecMergeViewerCreator.java
index 3446733875..bec9c729bd 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecMergeViewerCreator.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecMergeViewerCreator.java
@@ -21,12 +21,12 @@ import org.eclipse.swt.widgets.Composite;
*/
public class SpecMergeViewerCreator implements IViewerCreator {
- /**
- * @see org.eclipse.compare.IViewerCreator#createViewer(org.eclipse.swt.widgets
- * .Composite, org.eclipse.compare.CompareConfiguration)
- */
- @Override
- public Viewer createViewer(Composite parent, CompareConfiguration config) {
- return new SpecMergeViewer(parent, config);
- }
+ /**
+ * @see org.eclipse.compare.IViewerCreator#createViewer(org.eclipse.swt.widgets
+ * .Composite, org.eclipse.compare.CompareConfiguration)
+ */
+ @Override
+ public Viewer createViewer(Composite parent, CompareConfiguration config) {
+ return new SpecMergeViewer(parent, config);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecStructureCreator.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecStructureCreator.java
index ab80560749..376cdfcc6c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecStructureCreator.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecStructureCreator.java
@@ -54,229 +54,229 @@ import org.eclipse.ui.part.FileEditorInput;
*
* <pre>
* ROOT_NODE
- * SECTIONS...N
+ * SECTIONS...N
* SPECFILE_NODE
- * SUB_PACKAGE...N
- * SUB_PACKAGE_SECTIONS...N
+ * SUB_PACKAGE...N
+ * SUB_PACKAGE_SECTIONS...N
* </pre>
*/
public class SpecStructureCreator extends StructureCreator {
- private static class SpecNode extends DocumentRangeNode implements ITypedElement {
-
- public SpecNode(DocumentRangeNode parent, int type, String id,
- IDocument doc, int start, int length) {
- super(parent, type, id, doc, start, length);
- if (parent != null) {
- parent.addChild(this);
- }
- }
-
- @Override
- public String getName() {
- return getId();
- }
-
- @Override
- public String getType() {
- return "spec2"; //$NON-NLS-1$
- }
-
- @Override
- public Image getImage() {
- return CompareUI.getImage(getType());
- }
- }
-
- private static final String SPECFILE_ROOT_NODE = "Specfile Sections"; //$NON-NLS-1$
-
- @Override
- public String getName() {
- return Messages.SpecStructureCreator_0;
- }
-
- @Override
- public IStructureComparator locate(Object path, Object input) {
- return null;
- }
-
- @Override
- public String getContents(Object node, boolean ignoreWhitespace) {
- if (node instanceof IStreamContentAccessor) {
- IStreamContentAccessor sca = (IStreamContentAccessor) node;
- try {
- return readString(sca);
- } catch (CoreException e) {
- SpecfileLog.logError(e);
- }
- }
- return null;
- }
-
- private void parseSpecfile(DocumentRangeNode root, IDocument doc, IFile file) {
- SpecfileParser parser = new SpecfileParser();
-
- // setup the error and task handlers
- // FIXME: error markers do not show
- if (file != null) {
- FileEditorInput fei = new FileEditorInput(file);
- // this allows compare editor to work with specfiles with errors
- // without it, the compare editor is blank
- try {
- SpecfileEditor.getSpecfileDocumentProvider().disconnect(fei);
- SpecfileEditor.getSpecfileDocumentProvider().connect(fei);
- } catch (CoreException e) {
- SpecfileLog.logError(e);
- }
- parser.setErrorHandler(new SpecfileErrorHandler(fei, doc));
- parser.setTaskHandler(new SpecfileTaskHandler(fei, doc));
-
- Specfile specfile = parser.parse(doc);
- String id = specfile.getName();
- // Be a child under parent node of specfileSectionRoot (would be rootNode)
- SpecNode fileNode = new SpecNode((DocumentRangeNode) root.getParentNode(), 1, id, doc, 0, doc.getLength());
- for (SpecfileSection sec : specfile.getSections()) {
- try {
- addNode(root, doc, sec.getName(),
- doc.getLineOffset(sec.getLineNumber()),
- doc.getLineOffset(sec.getSectionEndLine()) - doc.getLineOffset(sec.getLineNumber()),
- 2);
- } catch (BadLocationException e) {
- SpecfileLog.logError(e);
- }
- }
-
- // Be a child under the parent file node
- for (SpecfilePackage sPackage : specfile.getPackages()
- .getPackages()) {
- try {
- SpecNode pNode = addNode(fileNode, doc, sPackage.getPackageName(),
- doc.getLineOffset(sPackage.getLineNumber()),
- doc.getLineOffset(sPackage.getSectionEndLine()) - doc.getLineOffset(sPackage.getLineNumber()),
- 3);
- for (SpecfileSection section : sPackage.getSections()) {
- addNode(pNode, doc, section.getName(),
- doc.getLineOffset(section.getLineNumber()),
- doc.getLineOffset(section.getSectionEndLine()) - doc.getLineOffset(section.getLineNumber()),
- 4);
- }
- } catch (BadLocationException e) {
- SpecfileLog.logError(e);
- }
- }
-
- }
- }
-
- private IProgressMonitor beginWork(IProgressMonitor monitor) {
- if (monitor == null) {
- return new NullProgressMonitor();
- }
- return new SubProgressMonitor(monitor, IProgressMonitor.UNKNOWN);
- }
-
- private SpecNode addNode(DocumentRangeNode parent, IDocument doc,
- String name, int start, int end, int type) {
- return new SpecNode(parent, type, name, doc, start, end);
- }
-
- private static String readString(InputStream is, String encoding) {
- if (is == null) {
- return null;
- }
- BufferedReader reader = null;
- try {
- StringBuffer buffer = new StringBuffer();
- char[] part = new char[2048];
- int read = 0;
- reader = new BufferedReader(new InputStreamReader(is, encoding));
-
- while ((read = reader.read(part)) != -1) {
- buffer.append(part, 0, read);
- }
-
- return buffer.toString();
-
- } catch (IOException ex) {
- // NeedWork
- SpecfileLog.logError(ex);
- } finally {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException ex) {
- SpecfileLog.logError(ex);
- }
- }
- }
- return null;
- }
-
- public static String readString(IStreamContentAccessor sa)
- throws CoreException {
- InputStream is = sa.getContents();
- if (is != null) {
- String encoding = null;
- if (sa instanceof IEncodedStreamContentAccessor) {
- encoding = ((IEncodedStreamContentAccessor) sa)
- .getCharset();
- }
- if (encoding == null) {
- encoding = ResourcesPlugin.getEncoding();
- }
- return readString(is, encoding);
- }
- return null;
- }
-
- @Override
- protected IDocumentPartitioner getDocumentPartitioner() {
- return new FastPartitioner(new SpecfilePartitionScanner(),
- SpecfilePartitionScanner.SPEC_PARTITION_TYPES);
- }
-
- @Override
- protected String getDocumentPartitioning() {
- return SpecfilePartitionScanner.SPEC_FILE_PARTITIONING;
- }
-
- @Override
- protected IStructureComparator createStructureComparator(Object input,
- IDocument document, ISharedDocumentAdapter adapter,
- IProgressMonitor monitor) throws CoreException {
-
- final boolean isEditable;
- if (input instanceof IEditableContent) {
- isEditable = ((IEditableContent) input).isEditable();
- } else {
- isEditable = false;
- }
-
- // get the resource being compared, but treat compare with history as null resource
- IFile file = null;
- if (input instanceof IResourceProvider) {
- IResource res = ((IResourceProvider)input).getResource();
- file = (IFile) res.getAdapter(IFile.class);
- }
-
- DocumentRangeNode rootNode = new StructureRootNode(document, input, this, adapter) {
- @Override
- public boolean isEditable() {
- return isEditable;
- }
- };
-
- try {
- monitor = beginWork(monitor);
- // Section Root
- SpecNode specfileSectionRoot = new SpecNode(rootNode, 0, SPECFILE_ROOT_NODE, document, 0, document.getLength());
- parseSpecfile(specfileSectionRoot, document, file);
- } finally {
- if (monitor != null) {
- monitor.done();
- }
- }
-
- return rootNode;
- }
+ private static class SpecNode extends DocumentRangeNode implements ITypedElement {
+
+ public SpecNode(DocumentRangeNode parent, int type, String id,
+ IDocument doc, int start, int length) {
+ super(parent, type, id, doc, start, length);
+ if (parent != null) {
+ parent.addChild(this);
+ }
+ }
+
+ @Override
+ public String getName() {
+ return getId();
+ }
+
+ @Override
+ public String getType() {
+ return "spec2"; //$NON-NLS-1$
+ }
+
+ @Override
+ public Image getImage() {
+ return CompareUI.getImage(getType());
+ }
+ }
+
+ private static final String SPECFILE_ROOT_NODE = "Specfile Sections"; //$NON-NLS-1$
+
+ @Override
+ public String getName() {
+ return Messages.SpecStructureCreator_0;
+ }
+
+ @Override
+ public IStructureComparator locate(Object path, Object input) {
+ return null;
+ }
+
+ @Override
+ public String getContents(Object node, boolean ignoreWhitespace) {
+ if (node instanceof IStreamContentAccessor) {
+ IStreamContentAccessor sca = (IStreamContentAccessor) node;
+ try {
+ return readString(sca);
+ } catch (CoreException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+ return null;
+ }
+
+ private void parseSpecfile(DocumentRangeNode root, IDocument doc, IFile file) {
+ SpecfileParser parser = new SpecfileParser();
+
+ // setup the error and task handlers
+ // FIXME: error markers do not show
+ if (file != null) {
+ FileEditorInput fei = new FileEditorInput(file);
+ // this allows compare editor to work with specfiles with errors
+ // without it, the compare editor is blank
+ try {
+ SpecfileEditor.getSpecfileDocumentProvider().disconnect(fei);
+ SpecfileEditor.getSpecfileDocumentProvider().connect(fei);
+ } catch (CoreException e) {
+ SpecfileLog.logError(e);
+ }
+ parser.setErrorHandler(new SpecfileErrorHandler(fei, doc));
+ parser.setTaskHandler(new SpecfileTaskHandler(fei, doc));
+
+ Specfile specfile = parser.parse(doc);
+ String id = specfile.getName();
+ // Be a child under parent node of specfileSectionRoot (would be rootNode)
+ SpecNode fileNode = new SpecNode((DocumentRangeNode) root.getParentNode(), 1, id, doc, 0, doc.getLength());
+ for (SpecfileSection sec : specfile.getSections()) {
+ try {
+ addNode(root, doc, sec.getName(),
+ doc.getLineOffset(sec.getLineNumber()),
+ doc.getLineOffset(sec.getSectionEndLine()) - doc.getLineOffset(sec.getLineNumber()),
+ 2);
+ } catch (BadLocationException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+
+ // Be a child under the parent file node
+ for (SpecfilePackage sPackage : specfile.getPackages()
+ .getPackages()) {
+ try {
+ SpecNode pNode = addNode(fileNode, doc, sPackage.getPackageName(),
+ doc.getLineOffset(sPackage.getLineNumber()),
+ doc.getLineOffset(sPackage.getSectionEndLine()) - doc.getLineOffset(sPackage.getLineNumber()),
+ 3);
+ for (SpecfileSection section : sPackage.getSections()) {
+ addNode(pNode, doc, section.getName(),
+ doc.getLineOffset(section.getLineNumber()),
+ doc.getLineOffset(section.getSectionEndLine()) - doc.getLineOffset(section.getLineNumber()),
+ 4);
+ }
+ } catch (BadLocationException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+
+ }
+ }
+
+ private IProgressMonitor beginWork(IProgressMonitor monitor) {
+ if (monitor == null) {
+ return new NullProgressMonitor();
+ }
+ return new SubProgressMonitor(monitor, IProgressMonitor.UNKNOWN);
+ }
+
+ private SpecNode addNode(DocumentRangeNode parent, IDocument doc,
+ String name, int start, int end, int type) {
+ return new SpecNode(parent, type, name, doc, start, end);
+ }
+
+ private static String readString(InputStream is, String encoding) {
+ if (is == null) {
+ return null;
+ }
+ BufferedReader reader = null;
+ try {
+ StringBuffer buffer = new StringBuffer();
+ char[] part = new char[2048];
+ int read = 0;
+ reader = new BufferedReader(new InputStreamReader(is, encoding));
+
+ while ((read = reader.read(part)) != -1) {
+ buffer.append(part, 0, read);
+ }
+
+ return buffer.toString();
+
+ } catch (IOException ex) {
+ // NeedWork
+ SpecfileLog.logError(ex);
+ } finally {
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException ex) {
+ SpecfileLog.logError(ex);
+ }
+ }
+ }
+ return null;
+ }
+
+ public static String readString(IStreamContentAccessor sa)
+ throws CoreException {
+ InputStream is = sa.getContents();
+ if (is != null) {
+ String encoding = null;
+ if (sa instanceof IEncodedStreamContentAccessor) {
+ encoding = ((IEncodedStreamContentAccessor) sa)
+ .getCharset();
+ }
+ if (encoding == null) {
+ encoding = ResourcesPlugin.getEncoding();
+ }
+ return readString(is, encoding);
+ }
+ return null;
+ }
+
+ @Override
+ protected IDocumentPartitioner getDocumentPartitioner() {
+ return new FastPartitioner(new SpecfilePartitionScanner(),
+ SpecfilePartitionScanner.SPEC_PARTITION_TYPES);
+ }
+
+ @Override
+ protected String getDocumentPartitioning() {
+ return SpecfilePartitionScanner.SPEC_FILE_PARTITIONING;
+ }
+
+ @Override
+ protected IStructureComparator createStructureComparator(Object input,
+ IDocument document, ISharedDocumentAdapter adapter,
+ IProgressMonitor monitor) throws CoreException {
+
+ final boolean isEditable;
+ if (input instanceof IEditableContent) {
+ isEditable = ((IEditableContent) input).isEditable();
+ } else {
+ isEditable = false;
+ }
+
+ // get the resource being compared, but treat compare with history as null resource
+ IFile file = null;
+ if (input instanceof IResourceProvider) {
+ IResource res = ((IResourceProvider)input).getResource();
+ file = (IFile) res.getAdapter(IFile.class);
+ }
+
+ DocumentRangeNode rootNode = new StructureRootNode(document, input, this, adapter) {
+ @Override
+ public boolean isEditable() {
+ return isEditable;
+ }
+ };
+
+ try {
+ monitor = beginWork(monitor);
+ // Section Root
+ SpecNode specfileSectionRoot = new SpecNode(rootNode, 0, SPECFILE_ROOT_NODE, document, 0, document.getLength());
+ parseSpecfile(specfileSectionRoot, document, file);
+ } finally {
+ if (monitor != null) {
+ monitor.done();
+ }
+ }
+
+ return rootNode;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecStructureMergeViewerCreator.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecStructureMergeViewerCreator.java
index ffdec1a5b8..d39c483429 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecStructureMergeViewerCreator.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/compare/SpecStructureMergeViewerCreator.java
@@ -23,15 +23,15 @@ import org.eclipse.swt.widgets.Composite;
*/
public class SpecStructureMergeViewerCreator implements IViewerCreator {
- /**
- * @see org.eclipse.compare.IViewerCreator#createViewer(org.eclipse.swt.widgets.Composite,
- * org.eclipse.compare.CompareConfiguration)
- */
- @Override
- public Viewer createViewer(Composite parent, CompareConfiguration config) {
- StructureDiffViewer diffViewer = new StructureDiffViewer(parent, config);
- diffViewer.setStructureCreator(new SpecStructureCreator());
- return diffViewer;
- }
+ /**
+ * @see org.eclipse.compare.IViewerCreator#createViewer(org.eclipse.swt.widgets.Composite,
+ * org.eclipse.compare.CompareConfiguration)
+ */
+ @Override
+ public Viewer createViewer(Composite parent, CompareConfiguration config) {
+ StructureDiffViewer diffViewer = new StructureDiffViewer(parent, config);
+ diffViewer.setStructureCreator(new SpecStructureCreator());
+ return diffViewer;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/IStrictWordDetector.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/IStrictWordDetector.java
index fda37ff61a..848ea7ba8e 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/IStrictWordDetector.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/IStrictWordDetector.java
@@ -14,5 +14,5 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.detectors;
import org.eclipse.jface.text.rules.IWordDetector;
public interface IStrictWordDetector extends IWordDetector {
- boolean isEndingCharacter(char c);
+ boolean isEndingCharacter(char c);
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/KeywordWordDetector.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/KeywordWordDetector.java
index a753174f78..9f5dfbc005 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/KeywordWordDetector.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/KeywordWordDetector.java
@@ -15,14 +15,14 @@ import org.eclipse.jface.text.rules.IWordDetector;
public class KeywordWordDetector implements IWordDetector {
- @Override
- public boolean isWordPart(char c) {
- return Character.isLetterOrDigit(c);
- }
+ @Override
+ public boolean isWordPart(char c) {
+ return Character.isLetterOrDigit(c);
+ }
- @Override
- public boolean isWordStart(char c) {
- return (c == '%');
- }
+ @Override
+ public boolean isWordStart(char c) {
+ return (c == '%');
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/MacroWordDetector.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/MacroWordDetector.java
index def26ec5ea..b91be0e957 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/MacroWordDetector.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/MacroWordDetector.java
@@ -15,14 +15,14 @@ import org.eclipse.jface.text.rules.IWordDetector;
public class MacroWordDetector implements IWordDetector {
- @Override
- public boolean isWordPart(char c) {
- return (Character.isLetterOrDigit(c) || c == '%' || c == '{' || c == '}' || c == '_') ;
- }
+ @Override
+ public boolean isWordPart(char c) {
+ return (Character.isLetterOrDigit(c) || c == '%' || c == '{' || c == '}' || c == '_') ;
+ }
- @Override
- public boolean isWordStart(char c) {
- return (c == '%');
- }
+ @Override
+ public boolean isWordStart(char c) {
+ return (c == '%');
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/PackageWordDetector.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/PackageWordDetector.java
index 8de8a63f94..c98622d671 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/PackageWordDetector.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/PackageWordDetector.java
@@ -15,13 +15,13 @@ import org.eclipse.jface.text.rules.IWordDetector;
public class PackageWordDetector implements IWordDetector {
- @Override
- public boolean isWordPart(char c) {
- return Character.isLetterOrDigit(c) || (c == '-') || (c == '_') || (c == '+');
- }
+ @Override
+ public boolean isWordPart(char c) {
+ return Character.isLetterOrDigit(c) || (c == '-') || (c == '_') || (c == '+');
+ }
- @Override
- public boolean isWordStart(char c) {
- return (c == ' ') || (c == ',') || (c == '\t') || (c == ':');
- }
+ @Override
+ public boolean isWordStart(char c) {
+ return (c == ' ') || (c == ',') || (c == '\t') || (c == ':');
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/PatchNumberDetector.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/PatchNumberDetector.java
index f9c4c288bc..4ab59fe8b4 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/PatchNumberDetector.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/PatchNumberDetector.java
@@ -13,19 +13,19 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.detectors;
public class PatchNumberDetector implements IStrictWordDetector {
- @Override
- public boolean isWordPart(char c) {
- return Character.isDigit(c);
- }
+ @Override
+ public boolean isWordPart(char c) {
+ return Character.isDigit(c);
+ }
- @Override
- public boolean isWordStart(char c) {
- return Character.isDigit(c);
- }
+ @Override
+ public boolean isWordStart(char c) {
+ return Character.isDigit(c);
+ }
- @Override
- public boolean isEndingCharacter(char c) {
- return Character.isWhitespace(c);
- }
+ @Override
+ public boolean isEndingCharacter(char c) {
+ return Character.isWhitespace(c);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/SuffixNumberDetector.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/SuffixNumberDetector.java
index c641577d7d..cc1f401ccc 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/SuffixNumberDetector.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/SuffixNumberDetector.java
@@ -14,20 +14,20 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.detectors;
public class SuffixNumberDetector implements IStrictWordDetector {
- @Override
- public boolean isEndingCharacter(char c) {
- return (c == ':');
- }
+ @Override
+ public boolean isEndingCharacter(char c) {
+ return (c == ':');
+ }
- @Override
- public boolean isWordPart(char c) {
- return Character.isDigit(c);
- }
+ @Override
+ public boolean isWordPart(char c) {
+ return Character.isDigit(c);
+ }
- @Override
- public boolean isWordStart(char c) {
- // TODO Auto-generated method stub
- return Character.isDigit(c);
- }
+ @Override
+ public boolean isWordStart(char c) {
+ // TODO Auto-generated method stub
+ return Character.isDigit(c);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/TagWordDetector.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/TagWordDetector.java
index 7e8f28e4fe..ae2f39546a 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/TagWordDetector.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/detectors/TagWordDetector.java
@@ -15,13 +15,13 @@ import org.eclipse.jface.text.rules.IWordDetector;
public class TagWordDetector implements IWordDetector {
- @Override
- public boolean isWordPart(char c) {
- return Character.isLetterOrDigit(c) || (c == ':') || (c == '(') || (c == ')');
- }
+ @Override
+ public boolean isWordPart(char c) {
+ return Character.isLetterOrDigit(c) || (c == ':') || (c == '(') || (c == ')');
+ }
- @Override
- public boolean isWordStart(char c) {
- return Character.isLetter(c);
- }
+ @Override
+ public boolean isWordStart(char c) {
+ return Character.isLetter(c);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/MainPackagePage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/MainPackagePage.java
index c8ffa4e79c..4225f99a9f 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/MainPackagePage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/MainPackagePage.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -27,144 +27,144 @@ import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
public class MainPackagePage extends FormPage {
- private FormToolkit toolkit;
- private ScrolledForm form;
- private Specfile specfile;
+ private FormToolkit toolkit;
+ private ScrolledForm form;
+ private Specfile specfile;
- public MainPackagePage(SpecfileFormEditor editor, Specfile specfile) {
- super(editor, Messages.MainPackagePage_0, Messages.MainPackagePage_1);
- this.specfile = specfile;
- }
+ public MainPackagePage(SpecfileFormEditor editor, Specfile specfile) {
+ super(editor, Messages.MainPackagePage_0, Messages.MainPackagePage_1);
+ this.specfile = specfile;
+ }
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- super.createFormContent(managedForm);
- toolkit = managedForm.getToolkit();
- form = managedForm.getForm();
- form.setText(Messages.MainPackagePage_2);
- GridLayout layout = new GridLayout();
- layout.marginWidth = layout.marginHeight = 5;
- layout.numColumns = 2;
- RowLayout rowLayout = new RowLayout();
- rowLayout.type = SWT.VERTICAL;
- rowLayout.justify = true;
- rowLayout.fill = true;
-
- form.getBody().setLayout(rowLayout);
- form.getBody().setLayoutData(rowLayout);
- layout.numColumns = 2;
- GridData gd = new GridData();
- gd.horizontalSpan = 2;
- gd.horizontalAlignment = SWT.FILL;
- final Section mainPackageSection = toolkit.createSection(form.getBody(),
- ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
- | ExpandableComposite.EXPANDED);
- mainPackageSection.setText(Messages.MainPackagePage_3);
- mainPackageSection.setLayout(new GridLayout());
- Composite mainPackageClient = toolkit.createComposite(mainPackageSection);
- GridLayout gridLayout = new GridLayout();
- gridLayout.marginWidth = gridLayout.marginHeight = 5;
- gridLayout.numColumns = 2;
-
- mainPackageClient.setLayout(gridLayout);
- new RpmTagText(mainPackageClient, RpmTags.NAME, specfile);
- new RpmTagText(mainPackageClient, RpmTags.VERSION, specfile);
- new RpmTagText(mainPackageClient, RpmTags.RELEASE, specfile);
- new RpmTagText(mainPackageClient, RpmTags.URL, specfile);
- new RpmTagText(mainPackageClient, RpmTags.LICENSE, specfile);
- new RpmTagText(mainPackageClient, RpmTags.GROUP, specfile);
- new RpmTagText(mainPackageClient, RpmTags.EPOCH, specfile);
- new RpmTagText(mainPackageClient, RpmTags.BUILD_ROOT, specfile);
- new RpmTagText(mainPackageClient, RpmTags.BUILD_ARCH, specfile);
- new RpmTagText(mainPackageClient, RpmTags.SUMMARY, specfile, SWT.MULTI);
-
- // BuildRequires
- final Section buildRequiresSection = toolkit.createSection(mainPackageClient,
- ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
- | ExpandableComposite.EXPANDED);
- buildRequiresSection.setText(Messages.MainPackagePage_4);
- buildRequiresSection.setLayout(rowLayout);
- buildRequiresSection.setExpanded(false);
- Composite buildRequiresClient = toolkit.createComposite(buildRequiresSection);
- buildRequiresClient.setLayout(gridLayout);
- for (SpecfileTag buildRequire: specfile.getBuildRequires()) {
- new RpmTagText(buildRequiresClient, buildRequire, specfile);
- }
- buildRequiresSection.setClient(buildRequiresClient);
- toolkit.paintBordersFor(buildRequiresClient);
- toolkit.paintBordersFor(buildRequiresSection);
-
- // Requires
- final Section requiresSection = toolkit.createSection(mainPackageClient,
- ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
- | ExpandableComposite.EXPANDED);
- requiresSection.setText(Messages.MainPackagePage_5);
- requiresSection.setLayout(rowLayout);
- requiresSection.setExpanded(false);
- Composite requiresClient = toolkit.createComposite(requiresSection);
- requiresClient.setLayout(gridLayout);
- requiresClient.setLayoutData(gd);
- for (SpecfileTag require: specfile.getRequires()) {
- new RpmTagText(requiresClient, require, specfile);
- }
- requiresSection.setClient(requiresClient);
- toolkit.paintBordersFor(requiresClient);
- toolkit.paintBordersFor(requiresSection);
-
- mainPackageSection.setClient(mainPackageClient);
- toolkit.paintBordersFor(mainPackageClient);
- toolkit.paintBordersFor(mainPackageSection);
-
- // subpackages
- final Section packagesSection = toolkit.createSection(form.getBody(),
- ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
- | ExpandableComposite.EXPANDED);
- packagesSection.setText(Messages.MainPackagePage_6);
- packagesSection.setLayout(gridLayout);
- Composite packagesClient = toolkit.createComposite(packagesSection);
- packagesClient.setLayout(gridLayout);
- packagesClient.setLayoutData(gd);
- for (SpecfilePackage specfilePackage : specfile.getPackages()
- .getPackages()) {
- if (specfilePackage.isMainPackage()){
- continue;
- }
- final Section packageSection = toolkit.createSection(packagesClient,
- ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
- | ExpandableComposite.EXPANDED);
- packageSection.setText(specfilePackage.getFullPackageName());
- packageSection.setExpanded(false);
- packageSection.setLayout(rowLayout);
- Composite packageClient = toolkit.createComposite(packageSection);
- packageClient.setLayout(gridLayout);
- packageClient.setLayoutData(gd);
- new RpmTagText(packageClient, RpmTags.SUMMARY, specfile, specfilePackage, SWT.MULTI);
- new RpmTagText(packageClient, RpmTags.GROUP, specfile, specfilePackage, SWT.MULTI);
-
- final Section packageRequiresSection = toolkit.createSection(packageClient,
- ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
- | ExpandableComposite.EXPANDED);
- packageRequiresSection.setText(Messages.MainPackagePage_7);
- packageRequiresSection.setLayout(rowLayout);
- packageRequiresSection.setLayoutData(gd);
- Composite packageRequiresClient = toolkit.createComposite(packageRequiresSection);
- packageRequiresClient.setLayout(gridLayout);
- packageRequiresClient.setLayoutData(gd);
- for (SpecfileTag require: specfilePackage.getRequires()) {
- new RpmTagText(packageRequiresClient, require, specfile);
- }
- packageRequiresSection.setClient(packageRequiresClient);
-
- toolkit.paintBordersFor(packageRequiresClient);
- toolkit.paintBordersFor(packageRequiresSection);
-
- packageSection.setClient(packageClient);
- toolkit.paintBordersFor(packageClient);
- toolkit.paintBordersFor(packageSection);
- }
- packagesSection.setClient(packagesClient);
- toolkit.paintBordersFor(packagesClient);
- toolkit.paintBordersFor(packagesSection);
- managedForm.refresh();
- }
+ @Override
+ protected void createFormContent(IManagedForm managedForm) {
+ super.createFormContent(managedForm);
+ toolkit = managedForm.getToolkit();
+ form = managedForm.getForm();
+ form.setText(Messages.MainPackagePage_2);
+ GridLayout layout = new GridLayout();
+ layout.marginWidth = layout.marginHeight = 5;
+ layout.numColumns = 2;
+ RowLayout rowLayout = new RowLayout();
+ rowLayout.type = SWT.VERTICAL;
+ rowLayout.justify = true;
+ rowLayout.fill = true;
+
+ form.getBody().setLayout(rowLayout);
+ form.getBody().setLayoutData(rowLayout);
+ layout.numColumns = 2;
+ GridData gd = new GridData();
+ gd.horizontalSpan = 2;
+ gd.horizontalAlignment = SWT.FILL;
+ final Section mainPackageSection = toolkit.createSection(form.getBody(),
+ ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
+ | ExpandableComposite.EXPANDED);
+ mainPackageSection.setText(Messages.MainPackagePage_3);
+ mainPackageSection.setLayout(new GridLayout());
+ Composite mainPackageClient = toolkit.createComposite(mainPackageSection);
+ GridLayout gridLayout = new GridLayout();
+ gridLayout.marginWidth = gridLayout.marginHeight = 5;
+ gridLayout.numColumns = 2;
+
+ mainPackageClient.setLayout(gridLayout);
+ new RpmTagText(mainPackageClient, RpmTags.NAME, specfile);
+ new RpmTagText(mainPackageClient, RpmTags.VERSION, specfile);
+ new RpmTagText(mainPackageClient, RpmTags.RELEASE, specfile);
+ new RpmTagText(mainPackageClient, RpmTags.URL, specfile);
+ new RpmTagText(mainPackageClient, RpmTags.LICENSE, specfile);
+ new RpmTagText(mainPackageClient, RpmTags.GROUP, specfile);
+ new RpmTagText(mainPackageClient, RpmTags.EPOCH, specfile);
+ new RpmTagText(mainPackageClient, RpmTags.BUILD_ROOT, specfile);
+ new RpmTagText(mainPackageClient, RpmTags.BUILD_ARCH, specfile);
+ new RpmTagText(mainPackageClient, RpmTags.SUMMARY, specfile, SWT.MULTI);
+
+ // BuildRequires
+ final Section buildRequiresSection = toolkit.createSection(mainPackageClient,
+ ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
+ | ExpandableComposite.EXPANDED);
+ buildRequiresSection.setText(Messages.MainPackagePage_4);
+ buildRequiresSection.setLayout(rowLayout);
+ buildRequiresSection.setExpanded(false);
+ Composite buildRequiresClient = toolkit.createComposite(buildRequiresSection);
+ buildRequiresClient.setLayout(gridLayout);
+ for (SpecfileTag buildRequire: specfile.getBuildRequires()) {
+ new RpmTagText(buildRequiresClient, buildRequire, specfile);
+ }
+ buildRequiresSection.setClient(buildRequiresClient);
+ toolkit.paintBordersFor(buildRequiresClient);
+ toolkit.paintBordersFor(buildRequiresSection);
+
+ // Requires
+ final Section requiresSection = toolkit.createSection(mainPackageClient,
+ ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
+ | ExpandableComposite.EXPANDED);
+ requiresSection.setText(Messages.MainPackagePage_5);
+ requiresSection.setLayout(rowLayout);
+ requiresSection.setExpanded(false);
+ Composite requiresClient = toolkit.createComposite(requiresSection);
+ requiresClient.setLayout(gridLayout);
+ requiresClient.setLayoutData(gd);
+ for (SpecfileTag require: specfile.getRequires()) {
+ new RpmTagText(requiresClient, require, specfile);
+ }
+ requiresSection.setClient(requiresClient);
+ toolkit.paintBordersFor(requiresClient);
+ toolkit.paintBordersFor(requiresSection);
+
+ mainPackageSection.setClient(mainPackageClient);
+ toolkit.paintBordersFor(mainPackageClient);
+ toolkit.paintBordersFor(mainPackageSection);
+
+ // subpackages
+ final Section packagesSection = toolkit.createSection(form.getBody(),
+ ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
+ | ExpandableComposite.EXPANDED);
+ packagesSection.setText(Messages.MainPackagePage_6);
+ packagesSection.setLayout(gridLayout);
+ Composite packagesClient = toolkit.createComposite(packagesSection);
+ packagesClient.setLayout(gridLayout);
+ packagesClient.setLayoutData(gd);
+ for (SpecfilePackage specfilePackage : specfile.getPackages()
+ .getPackages()) {
+ if (specfilePackage.isMainPackage()){
+ continue;
+ }
+ final Section packageSection = toolkit.createSection(packagesClient,
+ ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
+ | ExpandableComposite.EXPANDED);
+ packageSection.setText(specfilePackage.getFullPackageName());
+ packageSection.setExpanded(false);
+ packageSection.setLayout(rowLayout);
+ Composite packageClient = toolkit.createComposite(packageSection);
+ packageClient.setLayout(gridLayout);
+ packageClient.setLayoutData(gd);
+ new RpmTagText(packageClient, RpmTags.SUMMARY, specfile, specfilePackage, SWT.MULTI);
+ new RpmTagText(packageClient, RpmTags.GROUP, specfile, specfilePackage, SWT.MULTI);
+
+ final Section packageRequiresSection = toolkit.createSection(packageClient,
+ ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
+ | ExpandableComposite.EXPANDED);
+ packageRequiresSection.setText(Messages.MainPackagePage_7);
+ packageRequiresSection.setLayout(rowLayout);
+ packageRequiresSection.setLayoutData(gd);
+ Composite packageRequiresClient = toolkit.createComposite(packageRequiresSection);
+ packageRequiresClient.setLayout(gridLayout);
+ packageRequiresClient.setLayoutData(gd);
+ for (SpecfileTag require: specfilePackage.getRequires()) {
+ new RpmTagText(packageRequiresClient, require, specfile);
+ }
+ packageRequiresSection.setClient(packageRequiresClient);
+
+ toolkit.paintBordersFor(packageRequiresClient);
+ toolkit.paintBordersFor(packageRequiresSection);
+
+ packageSection.setClient(packageClient);
+ toolkit.paintBordersFor(packageClient);
+ toolkit.paintBordersFor(packageSection);
+ }
+ packagesSection.setClient(packagesClient);
+ toolkit.paintBordersFor(packagesClient);
+ toolkit.paintBordersFor(packagesSection);
+ managedForm.refresh();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/Messages.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/Messages.java
index 4e510ddc6e..a35b645cdb 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/Messages.java
@@ -13,23 +13,23 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.forms;
import org.eclipse.osgi.util.NLS;
public final class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.forms.messages"; //$NON-NLS-1$
- public static String MainPackagePage_0;
- public static String MainPackagePage_1;
- public static String MainPackagePage_2;
- public static String MainPackagePage_3;
- public static String MainPackagePage_4;
- public static String MainPackagePage_5;
- public static String MainPackagePage_6;
- public static String MainPackagePage_7;
- public static String RpmTagText_0;
- public static String SpecfileFormEditor_0;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.forms.messages"; //$NON-NLS-1$
+ public static String MainPackagePage_0;
+ public static String MainPackagePage_1;
+ public static String MainPackagePage_2;
+ public static String MainPackagePage_3;
+ public static String MainPackagePage_4;
+ public static String MainPackagePage_5;
+ public static String MainPackagePage_6;
+ public static String MainPackagePage_7;
+ public static String RpmTagText_0;
+ public static String SpecfileFormEditor_0;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- super();
- }
+ private Messages() {
+ super();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/RpmSectionPage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/RpmSectionPage.java
index 420ddc6d07..1f37ab8646 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/RpmSectionPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/RpmSectionPage.java
@@ -22,34 +22,34 @@ import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
public class RpmSectionPage extends FormPage {
- private String rpmSection;
- private SpecfileSection section;
+ private String rpmSection;
+ private SpecfileSection section;
- public RpmSectionPage(SpecfileFormEditor editor, Specfile specfile,
- String rpmSection) {
- super(editor, rpmSection, rpmSection);
- this.rpmSection = rpmSection;
- this.section = specfile.getSection(rpmSection.substring(1));
- }
+ public RpmSectionPage(SpecfileFormEditor editor, Specfile specfile,
+ String rpmSection) {
+ super(editor, rpmSection, rpmSection);
+ this.rpmSection = rpmSection;
+ this.section = specfile.getSection(rpmSection.substring(1));
+ }
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- super.createFormContent(managedForm);
- FormToolkit toolkit = managedForm.getToolkit();
- ScrolledForm form = managedForm.getForm();
- form.setText(rpmSection);
- GridLayout layout = new GridLayout();
+ @Override
+ protected void createFormContent(IManagedForm managedForm) {
+ super.createFormContent(managedForm);
+ FormToolkit toolkit = managedForm.getToolkit();
+ ScrolledForm form = managedForm.getForm();
+ form.setText(rpmSection);
+ GridLayout layout = new GridLayout();
- form.getBody().setLayout(layout);
- layout.numColumns = 2;
- toolkit.createLabel(form.getBody(), rpmSection);
- final Text text = toolkit.createText(form.getBody(), section.getContents(),
- SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
- GridData gd = new GridData();
- gd.grabExcessHorizontalSpace = true;
- gd.grabExcessVerticalSpace = true;
- gd.horizontalAlignment = SWT.FILL;
- gd.verticalAlignment = SWT.FILL;
- text.setLayoutData(gd);
- }
+ form.getBody().setLayout(layout);
+ layout.numColumns = 2;
+ toolkit.createLabel(form.getBody(), rpmSection);
+ final Text text = toolkit.createText(form.getBody(), section.getContents(),
+ SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
+ GridData gd = new GridData();
+ gd.grabExcessHorizontalSpace = true;
+ gd.grabExcessVerticalSpace = true;
+ gd.horizontalAlignment = SWT.FILL;
+ gd.verticalAlignment = SWT.FILL;
+ text.setLayoutData(gd);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/RpmTagText.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/RpmTagText.java
index 509ea054f3..659d23c963 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/RpmTagText.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/RpmTagText.java
@@ -25,63 +25,63 @@ import org.eclipse.swt.widgets.Text;
public class RpmTagText {
- public RpmTagText(Composite parent, final String rpmTag,
- final Specfile specfile) {
- this(parent, rpmTag, specfile, SWT.SINGLE);
- }
+ public RpmTagText(Composite parent, final String rpmTag,
+ final Specfile specfile) {
+ this(parent, rpmTag, specfile, SWT.SINGLE);
+ }
- public RpmTagText(Composite parent, final String rpmTag,
- final Specfile specfile, int flag) {
- Label label = new Label(parent, SWT.SINGLE);
- label.setText(rpmTag);
- final Text text = new Text(parent, SWT.BORDER_SOLID | flag);
- SpecfileDefine define = specfile.getDefine(rpmTag);
- if (null != define) {
- if (define.getTagType().equals(TagType.INT)) {
- text.setText(String.valueOf(define.getIntValue()));
- } else {
- text.setText(define.getStringValue());
- }
- }
- text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- text.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- specfile.modifyDefine(rpmTag, text.getText());
- }
- });
- }
+ public RpmTagText(Composite parent, final String rpmTag,
+ final Specfile specfile, int flag) {
+ Label label = new Label(parent, SWT.SINGLE);
+ label.setText(rpmTag);
+ final Text text = new Text(parent, SWT.BORDER_SOLID | flag);
+ SpecfileDefine define = specfile.getDefine(rpmTag);
+ if (null != define) {
+ if (define.getTagType().equals(TagType.INT)) {
+ text.setText(String.valueOf(define.getIntValue()));
+ } else {
+ text.setText(define.getStringValue());
+ }
+ }
+ text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ text.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ specfile.modifyDefine(rpmTag, text.getText());
+ }
+ });
+ }
- public RpmTagText(Composite parent, final String rpmTag,
- final Specfile specfile, final SpecfilePackage rpmPackage, int flag) {
- Label label = new Label(parent, SWT.SINGLE);
- label.setText(rpmTag);
- final Text text = new Text(parent, SWT.BORDER_SOLID | flag);
- SpecfileDefine define = specfile.getDefine(rpmTag, rpmPackage);
- if (null != define) {
- text.setText(define.getStringValue());
- }
- text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- text.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- specfile.modifyDefine(rpmTag, rpmPackage, text.getText());
- }
- });
- }
+ public RpmTagText(Composite parent, final String rpmTag,
+ final Specfile specfile, final SpecfilePackage rpmPackage, int flag) {
+ Label label = new Label(parent, SWT.SINGLE);
+ label.setText(rpmTag);
+ final Text text = new Text(parent, SWT.BORDER_SOLID | flag);
+ SpecfileDefine define = specfile.getDefine(rpmTag, rpmPackage);
+ if (null != define) {
+ text.setText(define.getStringValue());
+ }
+ text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ text.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ specfile.modifyDefine(rpmTag, rpmPackage, text.getText());
+ }
+ });
+ }
- public RpmTagText(Composite parent, final SpecfileTag require, final Specfile specfile) {
- Label label = new Label(parent, SWT.SINGLE);
- label.setText(Messages.RpmTagText_0);
- final Text text = new Text(parent, SWT.BORDER_SOLID);
- text.setText(require.getStringValue());
- text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- text.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- specfile.modifyDefine(require, text.getText());
- }
- });
- }
+ public RpmTagText(Composite parent, final SpecfileTag require, final Specfile specfile) {
+ Label label = new Label(parent, SWT.SINGLE);
+ label.setText(Messages.RpmTagText_0);
+ final Text text = new Text(parent, SWT.BORDER_SOLID);
+ text.setText(require.getStringValue());
+ text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ text.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ specfile.modifyDefine(require, text.getText());
+ }
+ });
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/SpecfileFormEditor.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/SpecfileFormEditor.java
index e45425dfa3..b5b13f34f3 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/SpecfileFormEditor.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/forms/SpecfileFormEditor.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -22,54 +22,54 @@ import org.eclipse.ui.forms.widgets.FormToolkit;
public class SpecfileFormEditor extends FormEditor {
- FormPage mainPackage;
- SpecfileEditor editor;
- private Specfile specfile;
+ FormPage mainPackage;
+ SpecfileEditor editor;
+ private Specfile specfile;
- public SpecfileFormEditor() {
- super();
- editor = new SpecfileEditor();
- }
+ public SpecfileFormEditor() {
+ super();
+ editor = new SpecfileEditor();
+ }
- @Override
- protected FormToolkit createToolkit(Display display) {
- // Create a toolkit that shares colors between editors.
- return new FormToolkit(Display.getCurrent());
- }
+ @Override
+ protected FormToolkit createToolkit(Display display) {
+ // Create a toolkit that shares colors between editors.
+ return new FormToolkit(Display.getCurrent());
+ }
- @Override
- protected void addPages() {
- try {
- int index = addPage(editor, getEditorInput());
- setPageText(index, Messages.SpecfileFormEditor_0);
- specfile = editor.getSpecfile();
- mainPackage = new MainPackagePage(this, specfile);
- addPage(0, mainPackage);
- addPage(1, new RpmSectionPage(this, specfile, RpmSections.PREP_SECTION));
- addPage(2, new RpmSectionPage(this, specfile, RpmSections.BUILD_SECTION));
- addPage(3, new RpmSectionPage(this, specfile, RpmSections.INSTALL_SECTION));
- } catch (PartInitException e) {
- //
- }
- }
+ @Override
+ protected void addPages() {
+ try {
+ int index = addPage(editor, getEditorInput());
+ setPageText(index, Messages.SpecfileFormEditor_0);
+ specfile = editor.getSpecfile();
+ mainPackage = new MainPackagePage(this, specfile);
+ addPage(0, mainPackage);
+ addPage(1, new RpmSectionPage(this, specfile, RpmSections.PREP_SECTION));
+ addPage(2, new RpmSectionPage(this, specfile, RpmSections.BUILD_SECTION));
+ addPage(3, new RpmSectionPage(this, specfile, RpmSections.INSTALL_SECTION));
+ } catch (PartInitException e) {
+ //
+ }
+ }
- @Override
- public void doSave(IProgressMonitor monitor) {
- editor.doSave(monitor);
- }
+ @Override
+ public void doSave(IProgressMonitor monitor) {
+ editor.doSave(monitor);
+ }
- @Override
- public void doSaveAs() {
- //noop
- }
+ @Override
+ public void doSaveAs() {
+ //noop
+ }
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
+ @Override
+ public boolean isSaveAsAllowed() {
+ return false;
+ }
- @Override
- public boolean isDirty() {
- return editor.isDirty();
- }
+ @Override
+ public boolean isDirty() {
+ return editor.isDirty();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/MailHyperlink.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/MailHyperlink.java
index 6fafeaf05d..39607ae804 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/MailHyperlink.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/MailHyperlink.java
@@ -21,24 +21,24 @@ import org.eclipse.swt.program.Program;
public class MailHyperlink extends URLHyperlink {
- private String fURLString;
-
-
- public MailHyperlink(IRegion region, String urlString) {
- super(region, urlString);
- fURLString = urlString;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.hyperlink.URLHyperlink#open()
- */
- @Override
- public void open() {
- if (fURLString != null) {
- Program.launch(fURLString);
- fURLString= null;
- return;
- }
- }
+ private String fURLString;
+
+
+ public MailHyperlink(IRegion region, String urlString) {
+ super(region, urlString);
+ fURLString = urlString;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.hyperlink.URLHyperlink#open()
+ */
+ @Override
+ public void open() {
+ if (fURLString != null) {
+ Program.launch(fURLString);
+ fURLString= null;
+ return;
+ }
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/MailHyperlinkDetector.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/MailHyperlinkDetector.java
index b20ed254b2..05f81f50f3 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/MailHyperlinkDetector.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/MailHyperlinkDetector.java
@@ -34,202 +34,202 @@ import org.eclipse.linuxtools.rpm.ui.editor.parser.Specfile;
*/
public class MailHyperlinkDetector extends AbstractHyperlinkDetector {
- private SpecfileEditor editor;
-
- /*
- * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer,
- * org.eclipse.jface.text.IRegion, boolean)
- */
- @Override
- public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
- if (region == null || textViewer == null) {
- return null;
- }
- if (editor == null) {
- editor = ((SpecfileEditor) this.getAdapter(SpecfileEditor.class));
- if (editor == null) {
- return null;
- }
- }
-
- IDocument document= textViewer.getDocument();
-
- int offset= region.getOffset();
-
- String urlString= null;
- if (document == null) {
- return null;
- }
-
- IRegion lineInfo;
- String line;
- String mail;
- int mailLength = 0;
- int mailOffsetInLine;
- try {
- lineInfo= document.getLineInformationOfOffset(offset);
- line= document.get(lineInfo.getOffset(), lineInfo.getLength());
- } catch (BadLocationException ex) {
- ex.printStackTrace();
- return null;
- }
-
- int startSeparator= line.indexOf('<');
- mailOffsetInLine = startSeparator + 1;
-
- if (startSeparator != -1) {
- int endSeparator= line.indexOf('>');
-
- if (endSeparator < 5) {
- return null;
- }
-
- mail= line.substring(startSeparator + 1, endSeparator).trim();
- mailLength= mail.length();
-
- // Some cleanups, maybe we can add more.
- mail= mail.replaceAll("(?i) at ", "@"); //$NON-NLS-1$ //$NON-NLS-2$
- mail= mail.replaceAll("(?i) dot ", "."); //$NON-NLS-1$ //$NON-NLS-2$
- mail= mail.replaceAll("(?i)_at_", "@"); //$NON-NLS-1$ //$NON-NLS-2$
- mail= mail.replaceAll("(?i)_dot_", "."); //$NON-NLS-1$ //$NON-NLS-2$
-
- mail= mail.replaceAll(" +", " "); //$NON-NLS-1$ //$NON-NLS-2$
- if (mail.split(" ").length == 3) { //$NON-NLS-1$
- if (mail.indexOf('@') == -1) {
- mail = mail.replaceFirst(" ", "@").replaceFirst(" ", "."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
- }
- mail= mail.replaceAll(" ", ""); //$NON-NLS-1$ //$NON-NLS-2$
-
- } else {
-
- int offsetInLine= offset - lineInfo.getOffset();
-
- boolean startDoubleQuote= false;
- mailOffsetInLine= 0;
-
- int mailSeparatorOffset= line.indexOf('@');
- while (mailSeparatorOffset >= 0) {
-
- // (left to "@")
- mailOffsetInLine= mailSeparatorOffset;
- char ch;
- do {
- mailOffsetInLine--;
- ch= ' ';
- if (mailOffsetInLine > -1) {
- ch= line.charAt(mailOffsetInLine);
- }
- startDoubleQuote= ch == '"';
- } while (Character.isLetterOrDigit(ch) || ch == '.' || ch == '_' || ch == '-');
- mailOffsetInLine++;
-
- // a valid mail contain a left part.
- if (mailOffsetInLine == mailSeparatorOffset) {
- return null;
- }
-
- // Right to "@"
- StringTokenizer tokenizer= new StringTokenizer(line.substring(mailSeparatorOffset + 3), " \t\n\r\f<>", false); //$NON-NLS-1$
- if (!tokenizer.hasMoreTokens()) {
- return null;
- }
-
- mailLength= tokenizer.nextToken().length() + 3 + mailSeparatorOffset - mailOffsetInLine;
- if (offsetInLine >= mailOffsetInLine && offsetInLine <= mailOffsetInLine + mailLength) {
- break;
- }
-
- mailSeparatorOffset= line.indexOf('@', mailSeparatorOffset + 1);
- }
-
- if (mailSeparatorOffset < 0) {
- return null;
- }
-
- if (startDoubleQuote) {
- int endOffset= -1;
- int nextDoubleQuote= line.indexOf('"', mailOffsetInLine);
- int nextWhitespace= line.indexOf(' ', mailOffsetInLine);
- if (nextDoubleQuote != -1 && nextWhitespace != -1) {
- endOffset= Math.min(nextDoubleQuote, nextWhitespace);
- } else if (nextDoubleQuote != -1) {
- endOffset= nextDoubleQuote;
- } else if (nextWhitespace != -1) {
- endOffset= nextWhitespace;
- }
- if (endOffset != -1) {
- mailLength= endOffset - mailOffsetInLine;
- }
- }
- if (mailLength == 0) {
- return null;
- }
-
- mail= line.substring(mailOffsetInLine, mailOffsetInLine + mailLength);
- }
-
- try {
- // mail address contain at less one '@' and one '.' character.
- if (!mail.contains("@") || !mail.contains(".")) { //$NON-NLS-1$ //$NON-NLS-2$
- return null;
- }
-
- urlString= "mailto:" + mail; //$NON-NLS-1$
- char separator= '?';
- String subject= getSubject();
- if (subject != null) {
- urlString+= separator + "subject=" + subject; //$NON-NLS-1$
- separator= '&';
- }
- String body= getBody();
- if (body != null) {
- urlString+= separator + "body=" + body; //$NON-NLS-1$
- }
-
- // url don't like %
- urlString= urlString.replaceAll("\\%", "\\%25"); //$NON-NLS-1$ //$NON-NLS-2$
- new URL(urlString);
- } catch (MalformedURLException ex) {
- ex.printStackTrace();
- urlString= null;
- return null;
- }
-
- IRegion urlRegion= new Region(lineInfo.getOffset() + mailOffsetInLine, mailLength);
- return new IHyperlink[] {new MailHyperlink(urlRegion, urlString)};
- }
-
- private String getSubject() {
- Specfile specfile= editor.getSpecfile();
- return MessageFormat.format("[{0}.spec - {1}-{2}]", specfile.getName(), specfile.getVersion(), //$NON-NLS-1$
- specfile.getRelease());
- }
-
- private String getBody() {
- String body = null;
- // Get current selection
- IDocument document= (IDocument) editor.getAdapter(IDocument.class);
- ISelection currentSelection= editor.getSpecfileSourceViewer().getSelection();
- if (currentSelection instanceof ITextSelection) {
- ITextSelection selection= (ITextSelection) currentSelection;
- try {
- String txt= selection.getText();
- if (txt.trim().length() > 0) {
- int begin= document.getLineOffset(selection.getStartLine());
- body= document.get().substring(begin,
- selection.getOffset() + selection.getLength());
- // replace left spaces or tabs and add a space at the begin of each line.
- body= body.replaceAll("(?m)^[ \\t]+|[ \\t]+$|^", " "); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } catch (BadLocationException e) {
- }
-
- }
- return body;
- }
-
- public void setEditor(SpecfileEditor editor) {
- this.editor = editor;
- }
+ private SpecfileEditor editor;
+
+ /*
+ * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer,
+ * org.eclipse.jface.text.IRegion, boolean)
+ */
+ @Override
+ public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
+ if (region == null || textViewer == null) {
+ return null;
+ }
+ if (editor == null) {
+ editor = ((SpecfileEditor) this.getAdapter(SpecfileEditor.class));
+ if (editor == null) {
+ return null;
+ }
+ }
+
+ IDocument document= textViewer.getDocument();
+
+ int offset= region.getOffset();
+
+ String urlString= null;
+ if (document == null) {
+ return null;
+ }
+
+ IRegion lineInfo;
+ String line;
+ String mail;
+ int mailLength = 0;
+ int mailOffsetInLine;
+ try {
+ lineInfo= document.getLineInformationOfOffset(offset);
+ line= document.get(lineInfo.getOffset(), lineInfo.getLength());
+ } catch (BadLocationException ex) {
+ ex.printStackTrace();
+ return null;
+ }
+
+ int startSeparator= line.indexOf('<');
+ mailOffsetInLine = startSeparator + 1;
+
+ if (startSeparator != -1) {
+ int endSeparator= line.indexOf('>');
+
+ if (endSeparator < 5) {
+ return null;
+ }
+
+ mail= line.substring(startSeparator + 1, endSeparator).trim();
+ mailLength= mail.length();
+
+ // Some cleanups, maybe we can add more.
+ mail= mail.replaceAll("(?i) at ", "@"); //$NON-NLS-1$ //$NON-NLS-2$
+ mail= mail.replaceAll("(?i) dot ", "."); //$NON-NLS-1$ //$NON-NLS-2$
+ mail= mail.replaceAll("(?i)_at_", "@"); //$NON-NLS-1$ //$NON-NLS-2$
+ mail= mail.replaceAll("(?i)_dot_", "."); //$NON-NLS-1$ //$NON-NLS-2$
+
+ mail= mail.replaceAll(" +", " "); //$NON-NLS-1$ //$NON-NLS-2$
+ if (mail.split(" ").length == 3) { //$NON-NLS-1$
+ if (mail.indexOf('@') == -1) {
+ mail = mail.replaceFirst(" ", "@").replaceFirst(" ", "."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+ }
+ mail= mail.replaceAll(" ", ""); //$NON-NLS-1$ //$NON-NLS-2$
+
+ } else {
+
+ int offsetInLine= offset - lineInfo.getOffset();
+
+ boolean startDoubleQuote= false;
+ mailOffsetInLine= 0;
+
+ int mailSeparatorOffset= line.indexOf('@');
+ while (mailSeparatorOffset >= 0) {
+
+ // (left to "@")
+ mailOffsetInLine= mailSeparatorOffset;
+ char ch;
+ do {
+ mailOffsetInLine--;
+ ch= ' ';
+ if (mailOffsetInLine > -1) {
+ ch= line.charAt(mailOffsetInLine);
+ }
+ startDoubleQuote= ch == '"';
+ } while (Character.isLetterOrDigit(ch) || ch == '.' || ch == '_' || ch == '-');
+ mailOffsetInLine++;
+
+ // a valid mail contain a left part.
+ if (mailOffsetInLine == mailSeparatorOffset) {
+ return null;
+ }
+
+ // Right to "@"
+ StringTokenizer tokenizer= new StringTokenizer(line.substring(mailSeparatorOffset + 3), " \t\n\r\f<>", false); //$NON-NLS-1$
+ if (!tokenizer.hasMoreTokens()) {
+ return null;
+ }
+
+ mailLength= tokenizer.nextToken().length() + 3 + mailSeparatorOffset - mailOffsetInLine;
+ if (offsetInLine >= mailOffsetInLine && offsetInLine <= mailOffsetInLine + mailLength) {
+ break;
+ }
+
+ mailSeparatorOffset= line.indexOf('@', mailSeparatorOffset + 1);
+ }
+
+ if (mailSeparatorOffset < 0) {
+ return null;
+ }
+
+ if (startDoubleQuote) {
+ int endOffset= -1;
+ int nextDoubleQuote= line.indexOf('"', mailOffsetInLine);
+ int nextWhitespace= line.indexOf(' ', mailOffsetInLine);
+ if (nextDoubleQuote != -1 && nextWhitespace != -1) {
+ endOffset= Math.min(nextDoubleQuote, nextWhitespace);
+ } else if (nextDoubleQuote != -1) {
+ endOffset= nextDoubleQuote;
+ } else if (nextWhitespace != -1) {
+ endOffset= nextWhitespace;
+ }
+ if (endOffset != -1) {
+ mailLength= endOffset - mailOffsetInLine;
+ }
+ }
+ if (mailLength == 0) {
+ return null;
+ }
+
+ mail= line.substring(mailOffsetInLine, mailOffsetInLine + mailLength);
+ }
+
+ try {
+ // mail address contain at less one '@' and one '.' character.
+ if (!mail.contains("@") || !mail.contains(".")) { //$NON-NLS-1$ //$NON-NLS-2$
+ return null;
+ }
+
+ urlString= "mailto:" + mail; //$NON-NLS-1$
+ char separator= '?';
+ String subject= getSubject();
+ if (subject != null) {
+ urlString+= separator + "subject=" + subject; //$NON-NLS-1$
+ separator= '&';
+ }
+ String body= getBody();
+ if (body != null) {
+ urlString+= separator + "body=" + body; //$NON-NLS-1$
+ }
+
+ // url don't like %
+ urlString= urlString.replaceAll("\\%", "\\%25"); //$NON-NLS-1$ //$NON-NLS-2$
+ new URL(urlString);
+ } catch (MalformedURLException ex) {
+ ex.printStackTrace();
+ urlString= null;
+ return null;
+ }
+
+ IRegion urlRegion= new Region(lineInfo.getOffset() + mailOffsetInLine, mailLength);
+ return new IHyperlink[] {new MailHyperlink(urlRegion, urlString)};
+ }
+
+ private String getSubject() {
+ Specfile specfile= editor.getSpecfile();
+ return MessageFormat.format("[{0}.spec - {1}-{2}]", specfile.getName(), specfile.getVersion(), //$NON-NLS-1$
+ specfile.getRelease());
+ }
+
+ private String getBody() {
+ String body = null;
+ // Get current selection
+ IDocument document= (IDocument) editor.getAdapter(IDocument.class);
+ ISelection currentSelection= editor.getSpecfileSourceViewer().getSelection();
+ if (currentSelection instanceof ITextSelection) {
+ ITextSelection selection= (ITextSelection) currentSelection;
+ try {
+ String txt= selection.getText();
+ if (txt.trim().length() > 0) {
+ int begin= document.getLineOffset(selection.getStartLine());
+ body= document.get().substring(begin,
+ selection.getOffset() + selection.getLength());
+ // replace left spaces or tabs and add a space at the begin of each line.
+ body= body.replaceAll("(?m)^[ \\t]+|[ \\t]+$|^", " "); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ } catch (BadLocationException e) {
+ }
+
+ }
+ return body;
+ }
+
+ public void setEditor(SpecfileEditor editor) {
+ this.editor = editor;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/Messages.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/Messages.java
index 3e0789f309..e36b3690c9 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/Messages.java
@@ -13,23 +13,23 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.hyperlink;
import org.eclipse.osgi.util.NLS;
public final class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.hyperlink.messages"; //$NON-NLS-1$
- public static String SourcesFileDownloadHyperlink_0;
- public static String SourcesFileDownloadHyperlink_1;
- public static String SourcesFileDownloadHyperlink_2;
- public static String SourcesFileDownloadHyperlink_3;
- public static String SourcesFileDownloadHyperlink_4;
- public static String SourcesFileDownloadHyperlink_5;
- public static String SourcesFileHyperlink_0;
- public static String SourcesFileHyperlink_1;
- public static String SourcesFileHyperlink_2;
- public static String SourcesFileHyperlink_3;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.hyperlink.messages"; //$NON-NLS-1$
+ public static String SourcesFileDownloadHyperlink_0;
+ public static String SourcesFileDownloadHyperlink_1;
+ public static String SourcesFileDownloadHyperlink_2;
+ public static String SourcesFileDownloadHyperlink_3;
+ public static String SourcesFileDownloadHyperlink_4;
+ public static String SourcesFileDownloadHyperlink_5;
+ public static String SourcesFileHyperlink_0;
+ public static String SourcesFileHyperlink_1;
+ public static String SourcesFileHyperlink_2;
+ public static String SourcesFileHyperlink_3;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- super();
- }
+ private Messages() {
+ super();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileCreateHyperlink.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileCreateHyperlink.java
index 47a2d709b3..73fe444ff0 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileCreateHyperlink.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileCreateHyperlink.java
@@ -38,91 +38,91 @@ import org.eclipse.ui.ide.IDE;
*/
public class SourcesFileCreateHyperlink implements IHyperlink {
- private String fileName;
- private IFile original;
- private IRegion region;
+ private String fileName;
+ private IFile original;
+ private IRegion region;
- /**
- * Creates hyperlink for the following file name, region and file whether
- * the file name is found.
- *
- * @param original
- * The file where the reference to this file name is.
- * @param fileName
- * The name of the file to open.
- * @param region
- * The hyperlink region.
- */
- public SourcesFileCreateHyperlink(IFile original, String fileName,
- IRegion region) {
- this.fileName = fileName;
- this.original = original;
- this.region = region;
- }
+ /**
+ * Creates hyperlink for the following file name, region and file whether
+ * the file name is found.
+ *
+ * @param original
+ * The file where the reference to this file name is.
+ * @param fileName
+ * The name of the file to open.
+ * @param region
+ * The hyperlink region.
+ */
+ public SourcesFileCreateHyperlink(IFile original, String fileName,
+ IRegion region) {
+ this.fileName = fileName;
+ this.original = original;
+ this.region = region;
+ }
- /**
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkRegion()
- */
- @Override
- public IRegion getHyperlinkRegion() {
- return region;
- }
+ /**
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkRegion()
+ */
+ @Override
+ public IRegion getHyperlinkRegion() {
+ return region;
+ }
- /**
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkText()
- */
- @Override
- public String getHyperlinkText() {
- return NLS.bind(Messages.SourcesFileHyperlink_2, fileName);
- }
+ /**
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkText()
+ */
+ @Override
+ public String getHyperlinkText() {
+ return NLS.bind(Messages.SourcesFileHyperlink_2, fileName);
+ }
- /**
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#getTypeLabel()
- */
- @Override
- public String getTypeLabel() {
- return null;
- }
+ /**
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#getTypeLabel()
+ */
+ @Override
+ public String getTypeLabel() {
+ return null;
+ }
- /**
- * Tries to create the given file name looking for it in the current
- * directory and in ../SOURCES.
- *
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#open()
- */
- @Override
- public void open() {
- IContainer container = original.getParent();
- IResource resourceToOpen = container.findMember(fileName);
- final InputStream source = new ByteArrayInputStream("".getBytes()); //$NON-NLS-1$
- IFile file = null;
+ /**
+ * Tries to create the given file name looking for it in the current
+ * directory and in ../SOURCES.
+ *
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#open()
+ */
+ @Override
+ public void open() {
+ IContainer container = original.getParent();
+ IResource resourceToOpen = container.findMember(fileName);
+ final InputStream source = new ByteArrayInputStream("".getBytes()); //$NON-NLS-1$
+ IFile file = null;
- if (resourceToOpen == null) {
- IResource sourcesFolder = container.getProject().findMember(
- "SOURCES"); //$NON-NLS-1$
- file = container.getFile(new Path(fileName));
- if (sourcesFolder != null) {
- file = ((IFolder) sourcesFolder).getFile(new Path(fileName));
- }
- if (!file.exists()) {
- try {
- file.create(source, IResource.NONE, null);
- } catch (CoreException e) {
- SpecfileLog.logError(e);
- }
- }
- resourceToOpen = file;
- }
- if (resourceToOpen != null) {
- IWorkbenchPage page = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- try {
- if (resourceToOpen.getType() == IResource.FILE) {
- IDE.openEditor(page, (IFile) resourceToOpen);
- }
- } catch (PartInitException e) {
- SpecfileLog.logError(e);
- }
- }
- }
+ if (resourceToOpen == null) {
+ IResource sourcesFolder = container.getProject().findMember(
+ "SOURCES"); //$NON-NLS-1$
+ file = container.getFile(new Path(fileName));
+ if (sourcesFolder != null) {
+ file = ((IFolder) sourcesFolder).getFile(new Path(fileName));
+ }
+ if (!file.exists()) {
+ try {
+ file.create(source, IResource.NONE, null);
+ } catch (CoreException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+ resourceToOpen = file;
+ }
+ if (resourceToOpen != null) {
+ IWorkbenchPage page = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
+ try {
+ if (resourceToOpen.getType() == IResource.FILE) {
+ IDE.openEditor(page, (IFile) resourceToOpen);
+ }
+ } catch (PartInitException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileDownloadHyperlink.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileDownloadHyperlink.java
index bf7cd3a64a..605d75000b 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileDownloadHyperlink.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileDownloadHyperlink.java
@@ -27,99 +27,99 @@ import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
public class SourcesFileDownloadHyperlink implements IHyperlink {
- private String fileName;
- private IFile original;
- private IRegion region;
+ private String fileName;
+ private IFile original;
+ private IRegion region;
- /**
- * Creates hyperlink for the following file name, region and file whether
- * the file name is found.
- *
- * @param original
- * The file where the reference to this file name is.
- * @param fileName
- * The name of the file to open.
- * @param region
- * The hyperlink region.
- */
- public SourcesFileDownloadHyperlink(IFile original, String fileName,
- IRegion region) {
- this.fileName = fileName;
- this.original = original;
- this.region = region;
- }
+ /**
+ * Creates hyperlink for the following file name, region and file whether
+ * the file name is found.
+ *
+ * @param original
+ * The file where the reference to this file name is.
+ * @param fileName
+ * The name of the file to open.
+ * @param region
+ * The hyperlink region.
+ */
+ public SourcesFileDownloadHyperlink(IFile original, String fileName,
+ IRegion region) {
+ this.fileName = fileName;
+ this.original = original;
+ this.region = region;
+ }
- /**
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkRegion()
- */
- @Override
- public IRegion getHyperlinkRegion() {
- return region;
- }
+ /**
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkRegion()
+ */
+ @Override
+ public IRegion getHyperlinkRegion() {
+ return region;
+ }
- /**
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkText()
- */
- @Override
- public String getHyperlinkText() {
- return NLS.bind(Messages.SourcesFileHyperlink_1, fileName);
- }
+ /**
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkText()
+ */
+ @Override
+ public String getHyperlinkText() {
+ return NLS.bind(Messages.SourcesFileHyperlink_1, fileName);
+ }
- /**
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#getTypeLabel()
- */
- @Override
- public String getTypeLabel() {
- return null;
- }
+ /**
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#getTypeLabel()
+ */
+ @Override
+ public String getTypeLabel() {
+ return null;
+ }
- /**
- * Tries to open the given file name looking for it in the current directory
- * and in ../SOURCES.
- *
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#open()
- */
- @Override
- public void open() {
- IContainer container = original.getParent();
- IResource saveFolder = container.getParent().findMember(
- IRPMConstants.SOURCES_FOLDER);
- if (saveFolder == null) {
- saveFolder = container.findMember(original.getFullPath()
- .removeLastSegments(1));
- }
- if (saveFolder == null) {
- saveFolder = container.findMember("/"); //$NON-NLS-1$
- }
- try {
- URL url = new URL(fileName);
- URLConnection connection = url.openConnection();
- String savedFileName = fileName
- .substring(fileName.lastIndexOf('/') + 1);
- IFile savedFile = original.getProject().getFile(
- saveFolder.getProjectRelativePath().append(savedFileName));
- if (savedFile.exists()) {
- MessageBox mb = new MessageBox(Display.getCurrent()
- .getActiveShell(), SWT.ICON_QUESTION | SWT.OK
- | SWT.CANCEL);
- mb.setText(Messages.SourcesFileDownloadHyperlink_0);
- mb.setMessage(NLS.bind(Messages.SourcesFileDownloadHyperlink_1,
- savedFileName));
- int rc = mb.open();
- if (rc == SWT.OK) {
- new DownloadJob(savedFile, connection).schedule();
- }
+ /**
+ * Tries to open the given file name looking for it in the current directory
+ * and in ../SOURCES.
+ *
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#open()
+ */
+ @Override
+ public void open() {
+ IContainer container = original.getParent();
+ IResource saveFolder = container.getParent().findMember(
+ IRPMConstants.SOURCES_FOLDER);
+ if (saveFolder == null) {
+ saveFolder = container.findMember(original.getFullPath()
+ .removeLastSegments(1));
+ }
+ if (saveFolder == null) {
+ saveFolder = container.findMember("/"); //$NON-NLS-1$
+ }
+ try {
+ URL url = new URL(fileName);
+ URLConnection connection = url.openConnection();
+ String savedFileName = fileName
+ .substring(fileName.lastIndexOf('/') + 1);
+ IFile savedFile = original.getProject().getFile(
+ saveFolder.getProjectRelativePath().append(savedFileName));
+ if (savedFile.exists()) {
+ MessageBox mb = new MessageBox(Display.getCurrent()
+ .getActiveShell(), SWT.ICON_QUESTION | SWT.OK
+ | SWT.CANCEL);
+ mb.setText(Messages.SourcesFileDownloadHyperlink_0);
+ mb.setMessage(NLS.bind(Messages.SourcesFileDownloadHyperlink_1,
+ savedFileName));
+ int rc = mb.open();
+ if (rc == SWT.OK) {
+ new DownloadJob(savedFile, connection).schedule();
+ }
- } else {
- new DownloadJob(savedFile, connection).schedule();
- }
- } catch (IOException e) {
- MessageBox mb = new MessageBox(Display.getCurrent()
- .getActiveShell(), SWT.ICON_WARNING | SWT.OK);
- mb.setMessage(Messages.SourcesFileDownloadHyperlink_2);
- mb.setText(Messages.SourcesFileDownloadHyperlink_3);
- mb.open();
- }
- }
+ } else {
+ new DownloadJob(savedFile, connection).schedule();
+ }
+ } catch (IOException e) {
+ MessageBox mb = new MessageBox(Display.getCurrent()
+ .getActiveShell(), SWT.ICON_WARNING | SWT.OK);
+ mb.setMessage(Messages.SourcesFileDownloadHyperlink_2);
+ mb.setText(Messages.SourcesFileDownloadHyperlink_3);
+ mb.open();
+ }
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileHyperlink.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileHyperlink.java
index b627500678..88da81b7bd 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileHyperlink.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileHyperlink.java
@@ -32,71 +32,71 @@ import org.eclipse.ui.ide.IDE;
*/
public class SourcesFileHyperlink implements IHyperlink {
- private String fileName;
- private IFile original;
- private IRegion region;
+ private String fileName;
+ private IFile original;
+ private IRegion region;
- /**
- * Creates hyperlink for the following file name, region and file whether
- * the file name is found.
- *
- * @param original The file where the reference to this file name is.
- * @param fileName The name of the file to open.
- * @param region The hyperlink region.
- */
- public SourcesFileHyperlink(IFile original, String fileName, IRegion region) {
- this.fileName = fileName;
- this.original = original;
- this.region = region;
- }
+ /**
+ * Creates hyperlink for the following file name, region and file whether
+ * the file name is found.
+ *
+ * @param original The file where the reference to this file name is.
+ * @param fileName The name of the file to open.
+ * @param region The hyperlink region.
+ */
+ public SourcesFileHyperlink(IFile original, String fileName, IRegion region) {
+ this.fileName = fileName;
+ this.original = original;
+ this.region = region;
+ }
- /**
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkRegion()
- */
- @Override
- public IRegion getHyperlinkRegion() {
- return region;
- }
+ /**
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkRegion()
+ */
+ @Override
+ public IRegion getHyperlinkRegion() {
+ return region;
+ }
- /**
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkText()
- */
- @Override
- public String getHyperlinkText() {
- return NLS.bind(Messages.SourcesFileHyperlink_0, fileName);
- }
+ /**
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#getHyperlinkText()
+ */
+ @Override
+ public String getHyperlinkText() {
+ return NLS.bind(Messages.SourcesFileHyperlink_0, fileName);
+ }
- /**
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#getTypeLabel()
- */
- @Override
- public String getTypeLabel() {
- return null;
- }
+ /**
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#getTypeLabel()
+ */
+ @Override
+ public String getTypeLabel() {
+ return null;
+ }
- /**
- * Tries to open the given file name looking for it in the current directory
- * and in ../SOURCES.
- *
- * @see org.eclipse.jface.text.hyperlink.IHyperlink#open()
- */
- @Override
- public void open() {
- IContainer container = original.getParent();
- IResource resourceToOpen = container.findMember(fileName);
- if (resourceToOpen == null) {
- IResource sourcesFolder = container.getParent().findMember(
- "SOURCES"); //$NON-NLS-1$
- resourceToOpen = ((IFolder) sourcesFolder).getFile(fileName);
- }
- IWorkbenchPage page = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- try {
- if (resourceToOpen.getType() == IResource.FILE) {
- IDE.openEditor(page, (IFile) resourceToOpen);
- }
- } catch (PartInitException e) {
- SpecfileLog.logError(e);
- }
- }
+ /**
+ * Tries to open the given file name looking for it in the current directory
+ * and in ../SOURCES.
+ *
+ * @see org.eclipse.jface.text.hyperlink.IHyperlink#open()
+ */
+ @Override
+ public void open() {
+ IContainer container = original.getParent();
+ IResource resourceToOpen = container.findMember(fileName);
+ if (resourceToOpen == null) {
+ IResource sourcesFolder = container.getParent().findMember(
+ "SOURCES"); //$NON-NLS-1$
+ resourceToOpen = ((IFolder) sourcesFolder).getFile(fileName);
+ }
+ IWorkbenchPage page = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
+ try {
+ if (resourceToOpen.getType() == IResource.FILE) {
+ IDE.openEditor(page, (IFile) resourceToOpen);
+ }
+ } catch (PartInitException e) {
+ SpecfileLog.logError(e);
+ }
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileHyperlinkDetector.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileHyperlinkDetector.java
index 68e946c05b..32d77c25b8 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileHyperlinkDetector.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SourcesFileHyperlinkDetector.java
@@ -32,85 +32,85 @@ import org.eclipse.ui.part.FileEditorInput;
*/
public class SourcesFileHyperlinkDetector extends AbstractHyperlinkDetector {
- private SpecfileEditor editor;
- private static final String PATCH_IDENTIFIER = "Patch"; //$NON-NLS-1$
- private static final String SOURCE_IDENTIFIER = "Source"; //$NON-NLS-1$
- private static final String URL_IDENTIFIER = "URL"; //$NON-NLS-1$
+ private SpecfileEditor editor;
+ private static final String PATCH_IDENTIFIER = "Patch"; //$NON-NLS-1$
+ private static final String SOURCE_IDENTIFIER = "Source"; //$NON-NLS-1$
+ private static final String URL_IDENTIFIER = "URL"; //$NON-NLS-1$
- /**
- * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer,
- * org.eclipse.jface.text.IRegion, boolean)
- */
- @Override
- public IHyperlink[] detectHyperlinks(ITextViewer textViewer,
- IRegion region, boolean canShowMultipleHyperlinks) {
- if (region == null || textViewer == null) {
- return null;
- }
+ /**
+ * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer,
+ * org.eclipse.jface.text.IRegion, boolean)
+ */
+ @Override
+ public IHyperlink[] detectHyperlinks(ITextViewer textViewer,
+ IRegion region, boolean canShowMultipleHyperlinks) {
+ if (region == null || textViewer == null) {
+ return null;
+ }
- if (editor == null) {
- editor = ((SpecfileEditor) this.getAdapter(SpecfileEditor.class));
- if (editor == null) {
- return null;
- }
- }
+ if (editor == null) {
+ editor = ((SpecfileEditor) this.getAdapter(SpecfileEditor.class));
+ if (editor == null) {
+ return null;
+ }
+ }
- IDocument document = textViewer.getDocument();
+ IDocument document = textViewer.getDocument();
- int offset = region.getOffset();
+ int offset = region.getOffset();
- if (document == null) {
- return null;
- }
- IRegion lineInfo;
- String line;
- try {
- lineInfo = document.getLineInformationOfOffset(offset);
- line = document.get(lineInfo.getOffset(), lineInfo.getLength());
- } catch (BadLocationException ex) {
- return null;
- }
- List<IHyperlink> tempHList = new ArrayList<>();
- // !! it feels like there is duplicate code, fix that !!
- if (editor.getEditorInput() instanceof FileEditorInput) {
- IFile original = ((FileEditorInput) editor.getEditorInput())
- .getFile();
- if (line.startsWith(SOURCE_IDENTIFIER)
- || line.startsWith(PATCH_IDENTIFIER)
- || line.startsWith(URL_IDENTIFIER)) {
- int delimiterIndex = line.indexOf(':') + 1;
- String identifierValue = line.substring(delimiterIndex).trim();
- boolean validURL = RPMUtils.isValidUrl(identifierValue);
- // if valid URL, get its file name; else make file name the original identifier value
- String fileName = validURL ? RPMUtils.getURLFilename(identifierValue) : identifierValue;
- String resolvedFileName = UiUtils.resolveDefines(editor.getSpecfile(), fileName);
- boolean fileExists = RPMUtils.fileExistsInSources(original, resolvedFileName);
- if (region.getOffset() > lineInfo.getOffset()
- + line.indexOf(identifierValue)) {
- IRegion fileNameRegion = new Region(lineInfo.getOffset()
- + line.indexOf(identifierValue), identifierValue.length());
- if (fileExists) {
- // add "Open" file option
- tempHList.add(new SourcesFileHyperlink(original, resolvedFileName, fileNameRegion));
- } else {
- if (line.startsWith(PATCH_IDENTIFIER) && !identifierValue.endsWith("/")) { //$NON-NLS-1$
- // add "Create" patch option using filename
- tempHList.add(new SourcesFileCreateHyperlink(original, resolvedFileName, fileNameRegion));
- }
- }
- // if valid URL and has a valid file
- if (validURL && !identifierValue.endsWith("/")) { //$NON-NLS-1$
- // add "Download" option
- tempHList.add(new SourcesFileDownloadHyperlink(original, UiUtils.resolveDefines(editor.getSpecfile(), identifierValue), fileNameRegion));
- }
- }
- }
- }
+ if (document == null) {
+ return null;
+ }
+ IRegion lineInfo;
+ String line;
+ try {
+ lineInfo = document.getLineInformationOfOffset(offset);
+ line = document.get(lineInfo.getOffset(), lineInfo.getLength());
+ } catch (BadLocationException ex) {
+ return null;
+ }
+ List<IHyperlink> tempHList = new ArrayList<>();
+ // !! it feels like there is duplicate code, fix that !!
+ if (editor.getEditorInput() instanceof FileEditorInput) {
+ IFile original = ((FileEditorInput) editor.getEditorInput())
+ .getFile();
+ if (line.startsWith(SOURCE_IDENTIFIER)
+ || line.startsWith(PATCH_IDENTIFIER)
+ || line.startsWith(URL_IDENTIFIER)) {
+ int delimiterIndex = line.indexOf(':') + 1;
+ String identifierValue = line.substring(delimiterIndex).trim();
+ boolean validURL = RPMUtils.isValidUrl(identifierValue);
+ // if valid URL, get its file name; else make file name the original identifier value
+ String fileName = validURL ? RPMUtils.getURLFilename(identifierValue) : identifierValue;
+ String resolvedFileName = UiUtils.resolveDefines(editor.getSpecfile(), fileName);
+ boolean fileExists = RPMUtils.fileExistsInSources(original, resolvedFileName);
+ if (region.getOffset() > lineInfo.getOffset()
+ + line.indexOf(identifierValue)) {
+ IRegion fileNameRegion = new Region(lineInfo.getOffset()
+ + line.indexOf(identifierValue), identifierValue.length());
+ if (fileExists) {
+ // add "Open" file option
+ tempHList.add(new SourcesFileHyperlink(original, resolvedFileName, fileNameRegion));
+ } else {
+ if (line.startsWith(PATCH_IDENTIFIER) && !identifierValue.endsWith("/")) { //$NON-NLS-1$
+ // add "Create" patch option using filename
+ tempHList.add(new SourcesFileCreateHyperlink(original, resolvedFileName, fileNameRegion));
+ }
+ }
+ // if valid URL and has a valid file
+ if (validURL && !identifierValue.endsWith("/")) { //$NON-NLS-1$
+ // add "Download" option
+ tempHList.add(new SourcesFileDownloadHyperlink(original, UiUtils.resolveDefines(editor.getSpecfile(), identifierValue), fileNameRegion));
+ }
+ }
+ }
+ }
- return tempHList.isEmpty() ? null : tempHList.toArray(new IHyperlink[tempHList.size()]);
- }
+ return tempHList.isEmpty() ? null : tempHList.toArray(new IHyperlink[tempHList.size()]);
+ }
- public void setEditor(SpecfileEditor editor) {
- this.editor = editor;
- }
+ public void setEditor(SpecfileEditor editor) {
+ this.editor = editor;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SpecfileElementHyperlink.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SpecfileElementHyperlink.java
index 72eb0c8978..0e731dec96 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SpecfileElementHyperlink.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SpecfileElementHyperlink.java
@@ -30,59 +30,59 @@ import org.eclipse.ui.ide.IDE;
* and %define.
*/
public class SpecfileElementHyperlink implements IHyperlink {
- private IRegion region;
- private SpecfileElement source;
- private IFile file;
+ private IRegion region;
+ private SpecfileElement source;
+ private IFile file;
- public SpecfileElementHyperlink(IRegion region, SpecfileElement source,
- IFile file) {
- this.region = region;
- this.source = source;
- this.file = file;
- }
+ public SpecfileElementHyperlink(IRegion region, SpecfileElement source,
+ IFile file) {
+ this.region = region;
+ this.source = source;
+ this.file = file;
+ }
- @Override
- public IRegion getHyperlinkRegion() {
- return region;
- }
+ @Override
+ public IRegion getHyperlinkRegion() {
+ return region;
+ }
- @Override
- public String getHyperlinkText() {
- return NLS.bind(Messages.SourcesFileHyperlink_3, source.getName());
- }
+ @Override
+ public String getHyperlinkText() {
+ return NLS.bind(Messages.SourcesFileHyperlink_3, source.getName());
+ }
- @Override
- public String getTypeLabel() {
- return null;
- }
+ @Override
+ public String getTypeLabel() {
+ return null;
+ }
- @Override
- public void open() {
- IWorkbenchPage page = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry()
- .getDefaultEditor(file.getName());
- HashMap<String, Object> map = new HashMap<>();
- // TODO don't increment the line number once the SpecfileSource reports
- // correct line
- map.put(IMarker.LINE_NUMBER, Integer
- .valueOf(getSource().getLineNumber() + 1));
- map.put(IDE.EDITOR_ID_ATTR, desc.getId());
- try {
- IMarker marker = file.createMarker(IMarker.TEXT);
- marker.setAttributes(map);
- IDE.openEditor(page, marker);
- marker.delete();
- } catch (CoreException e) {
- SpecfileLog.logError(e);
- }
- }
+ @Override
+ public void open() {
+ IWorkbenchPage page = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
+ IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry()
+ .getDefaultEditor(file.getName());
+ HashMap<String, Object> map = new HashMap<>();
+ // TODO don't increment the line number once the SpecfileSource reports
+ // correct line
+ map.put(IMarker.LINE_NUMBER, Integer
+ .valueOf(getSource().getLineNumber() + 1));
+ map.put(IDE.EDITOR_ID_ATTR, desc.getId());
+ try {
+ IMarker marker = file.createMarker(IMarker.TEXT);
+ marker.setAttributes(map);
+ IDE.openEditor(page, marker);
+ marker.delete();
+ } catch (CoreException e) {
+ SpecfileLog.logError(e);
+ }
+ }
- /**
- * @return the source
- */
- public SpecfileElement getSource() {
- return source;
- }
+ /**
+ * @return the source
+ */
+ public SpecfileElement getSource() {
+ return source;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SpecfileElementHyperlinkDetector.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SpecfileElementHyperlinkDetector.java
index c5ebb1e269..7f7a70302f 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SpecfileElementHyperlinkDetector.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/SpecfileElementHyperlinkDetector.java
@@ -44,136 +44,136 @@ import com.ibm.icu.util.StringTokenizer;
*/
public class SpecfileElementHyperlinkDetector extends AbstractHyperlinkDetector {
- private static final String PATCH_IDENTIFIER = "%patch"; //$NON-NLS-1$
- private static final String SOURCE_IDENTIFIER = "%{SOURCE"; //$NON-NLS-1$
- private Specfile specfile;
-
- @Override
- public IHyperlink[] detectHyperlinks(ITextViewer textViewer,
- IRegion region, boolean canShowMultipleHyperlinks) {
-
- if (region == null || textViewer == null) {
- return null;
- }
-
- IDocument document = textViewer.getDocument();
- if (document == null) {
- return null;
- }
-
- // Keeps the errorHandler on the initial opening of the .spec file
- // otherwise, a new SpecfileParser does not initialize errorHandler
- // until a SpecfileEditor#editorSaved is called
- if (specfile == null) {
- SpecfileEditor a = ((SpecfileEditor) this.getAdapter(SpecfileEditor.class));
- if (a != null && a.getSpecfile() != null) {
- specfile = a.getSpecfile();
- } else {
- SpecfileParser parser = new SpecfileParser();
- specfile = parser.parse(document);
- }
- }
-
- int offset = region.getOffset();
-
- IRegion lineInfo;
- String line;
- try {
- lineInfo = document.getLineInformationOfOffset(offset);
- line = document.get(lineInfo.getOffset(), lineInfo.getLength());
- } catch (BadLocationException ex) {
- return null;
- }
-
- int offsetInLine = offset - lineInfo.getOffset();
-
- StringTokenizer tokens = new StringTokenizer(line);
- String word = ""; //$NON-NLS-1$
- int tempLineOffset = 0;
- int wordOffsetInLine = 0;
- while (tokens.hasMoreTokens()) {
- String tempWord = tokens.nextToken();
- Pattern defineRegexp = Pattern.compile("%\\{(.*?)\\}"); //$NON-NLS-1$
- Matcher fit = defineRegexp.matcher(tempWord);
- while (fit.find()){
- if ((fit.start()+tempLineOffset <= offsetInLine) && (offsetInLine <= fit.end()+tempLineOffset)){
- tempWord = fit.group();
- wordOffsetInLine = fit.start();
- tempLineOffset += fit.start();
- break;
- }
- }
- tempLineOffset += tempWord.length();
- word = tempWord;
- if (tempLineOffset > offsetInLine) {
- break;
- }
- }
- if (word.startsWith(SOURCE_IDENTIFIER)) {
- int sourceNumber = Integer.valueOf(
- word.substring(SOURCE_IDENTIFIER.length(),
- word.length() - 1)).intValue();
- SpecfileSource source = specfile.getSource(sourceNumber);
- if (source != null) {
- return prepareHyperlink(lineInfo, line, word, source);
- }
- } else if (word.startsWith(PATCH_IDENTIFIER)) {
-
- int sourceNumber = Integer.valueOf(
- word.substring(PATCH_IDENTIFIER.length(), word.length()))
- .intValue();
- SpecfileSource source = specfile.getPatch(sourceNumber);
- if (source != null) {
- return prepareHyperlink(lineInfo, line, word, source);
- }
- } else {
- String defineName = getDefineName(word);
- SpecfileDefine define = specfile.getDefine(defineName);
- if (define != null) {
- return prepareHyperlink(lineInfo, line, defineName, define,
- wordOffsetInLine);
- }
- }
- return null;
- }
-
- private String getDefineName(String word) {
- if (word.startsWith(ISpecfileSpecialSymbols.MACRO_START_LONG)) {
- return word.substring(2, word.length() - 1);
- }
- return ""; //$NON-NLS-1$
- }
-
- private IHyperlink[] prepareHyperlink(IRegion lineInfo, String line,
- String word, SpecfileElement source, int lineIndex) {
- IRegion urlRegion = new Region(lineInfo.getOffset()
- + line.indexOf(word, lineIndex), word.length());
-
- // will only work with 1 active page
- // does not work with CompareEditor
- IWorkbench wb = PlatformUI.getWorkbench();
- IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
- IWorkbenchPage page = win.getActivePage();
- IEditorPart editor = page.getActiveEditor();
- // A IFile cannot be retrieve from a IFileStoreEditorInput, so at this time
- // we can only provide this functionality for resources inside the workbench.
- if (editor.getEditorInput() instanceof FileEditorInput) {
- IFile original = ((FileEditorInput) editor.getEditorInput()).getFile();
- return new IHyperlink[] { new SpecfileElementHyperlink(urlRegion,
- source, original) };
- } else {
- return null;
- }
-
-
- }
-
- private IHyperlink[] prepareHyperlink(IRegion lineInfo, String line,
- String word, SpecfileElement source) {
- return prepareHyperlink(lineInfo, line, word, source, 0);
- }
-
- public void setSpecfile(Specfile specfile) {
- this.specfile = specfile;
- }
+ private static final String PATCH_IDENTIFIER = "%patch"; //$NON-NLS-1$
+ private static final String SOURCE_IDENTIFIER = "%{SOURCE"; //$NON-NLS-1$
+ private Specfile specfile;
+
+ @Override
+ public IHyperlink[] detectHyperlinks(ITextViewer textViewer,
+ IRegion region, boolean canShowMultipleHyperlinks) {
+
+ if (region == null || textViewer == null) {
+ return null;
+ }
+
+ IDocument document = textViewer.getDocument();
+ if (document == null) {
+ return null;
+ }
+
+ // Keeps the errorHandler on the initial opening of the .spec file
+ // otherwise, a new SpecfileParser does not initialize errorHandler
+ // until a SpecfileEditor#editorSaved is called
+ if (specfile == null) {
+ SpecfileEditor a = ((SpecfileEditor) this.getAdapter(SpecfileEditor.class));
+ if (a != null && a.getSpecfile() != null) {
+ specfile = a.getSpecfile();
+ } else {
+ SpecfileParser parser = new SpecfileParser();
+ specfile = parser.parse(document);
+ }
+ }
+
+ int offset = region.getOffset();
+
+ IRegion lineInfo;
+ String line;
+ try {
+ lineInfo = document.getLineInformationOfOffset(offset);
+ line = document.get(lineInfo.getOffset(), lineInfo.getLength());
+ } catch (BadLocationException ex) {
+ return null;
+ }
+
+ int offsetInLine = offset - lineInfo.getOffset();
+
+ StringTokenizer tokens = new StringTokenizer(line);
+ String word = ""; //$NON-NLS-1$
+ int tempLineOffset = 0;
+ int wordOffsetInLine = 0;
+ while (tokens.hasMoreTokens()) {
+ String tempWord = tokens.nextToken();
+ Pattern defineRegexp = Pattern.compile("%\\{(.*?)\\}"); //$NON-NLS-1$
+ Matcher fit = defineRegexp.matcher(tempWord);
+ while (fit.find()){
+ if ((fit.start()+tempLineOffset <= offsetInLine) && (offsetInLine <= fit.end()+tempLineOffset)){
+ tempWord = fit.group();
+ wordOffsetInLine = fit.start();
+ tempLineOffset += fit.start();
+ break;
+ }
+ }
+ tempLineOffset += tempWord.length();
+ word = tempWord;
+ if (tempLineOffset > offsetInLine) {
+ break;
+ }
+ }
+ if (word.startsWith(SOURCE_IDENTIFIER)) {
+ int sourceNumber = Integer.valueOf(
+ word.substring(SOURCE_IDENTIFIER.length(),
+ word.length() - 1)).intValue();
+ SpecfileSource source = specfile.getSource(sourceNumber);
+ if (source != null) {
+ return prepareHyperlink(lineInfo, line, word, source);
+ }
+ } else if (word.startsWith(PATCH_IDENTIFIER)) {
+
+ int sourceNumber = Integer.valueOf(
+ word.substring(PATCH_IDENTIFIER.length(), word.length()))
+ .intValue();
+ SpecfileSource source = specfile.getPatch(sourceNumber);
+ if (source != null) {
+ return prepareHyperlink(lineInfo, line, word, source);
+ }
+ } else {
+ String defineName = getDefineName(word);
+ SpecfileDefine define = specfile.getDefine(defineName);
+ if (define != null) {
+ return prepareHyperlink(lineInfo, line, defineName, define,
+ wordOffsetInLine);
+ }
+ }
+ return null;
+ }
+
+ private String getDefineName(String word) {
+ if (word.startsWith(ISpecfileSpecialSymbols.MACRO_START_LONG)) {
+ return word.substring(2, word.length() - 1);
+ }
+ return ""; //$NON-NLS-1$
+ }
+
+ private IHyperlink[] prepareHyperlink(IRegion lineInfo, String line,
+ String word, SpecfileElement source, int lineIndex) {
+ IRegion urlRegion = new Region(lineInfo.getOffset()
+ + line.indexOf(word, lineIndex), word.length());
+
+ // will only work with 1 active page
+ // does not work with CompareEditor
+ IWorkbench wb = PlatformUI.getWorkbench();
+ IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
+ IWorkbenchPage page = win.getActivePage();
+ IEditorPart editor = page.getActiveEditor();
+ // A IFile cannot be retrieve from a IFileStoreEditorInput, so at this time
+ // we can only provide this functionality for resources inside the workbench.
+ if (editor.getEditorInput() instanceof FileEditorInput) {
+ IFile original = ((FileEditorInput) editor.getEditorInput()).getFile();
+ return new IHyperlink[] { new SpecfileElementHyperlink(urlRegion,
+ source, original) };
+ } else {
+ return null;
+ }
+
+
+ }
+
+ private IHyperlink[] prepareHyperlink(IRegion lineInfo, String line,
+ String word, SpecfileElement source) {
+ return prepareHyperlink(lineInfo, line, word, source, 0);
+ }
+
+ public void setSpecfile(Specfile specfile) {
+ this.specfile = specfile;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/URLHyperlinkWithMacroDetector.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/URLHyperlinkWithMacroDetector.java
index 793287316f..cfeb4b71a5 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/URLHyperlinkWithMacroDetector.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/hyperlink/URLHyperlinkWithMacroDetector.java
@@ -29,35 +29,35 @@ import org.eclipse.linuxtools.rpm.ui.editor.parser.Specfile;
*/
public class URLHyperlinkWithMacroDetector extends URLHyperlinkDetector {
- private Specfile specfile;
-
- /*
- * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion, boolean)
- */
- @Override
- public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
- if (specfile == null) {
- SpecfileEditor a = ((SpecfileEditor) this.getAdapter(SpecfileEditor.class));
- if (a != null) {
- specfile = a.getSpecfile();
- } else {
- return null;
- }
- }
- IHyperlink[] returned = super.detectHyperlinks(textViewer, region, canShowMultipleHyperlinks);
- if (returned != null && returned.length > 0) {
- IHyperlink hyperlink = returned[0];
- if (hyperlink instanceof URLHyperlink) {
- URLHyperlink urlHyperlink = (URLHyperlink) hyperlink;
- String newURLString = UiUtils.resolveDefines(specfile, urlHyperlink.getURLString());
- return new IHyperlink[] {new URLHyperlink(urlHyperlink.getHyperlinkRegion(), newURLString)};
- }
- }
- return returned;
- }
-
- public void setSpecfile(Specfile specfile) {
- this.specfile = specfile;
- }
+ private Specfile specfile;
+
+ /*
+ * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion, boolean)
+ */
+ @Override
+ public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
+ if (specfile == null) {
+ SpecfileEditor a = ((SpecfileEditor) this.getAdapter(SpecfileEditor.class));
+ if (a != null) {
+ specfile = a.getSpecfile();
+ } else {
+ return null;
+ }
+ }
+ IHyperlink[] returned = super.detectHyperlinks(textViewer, region, canShowMultipleHyperlinks);
+ if (returned != null && returned.length > 0) {
+ IHyperlink hyperlink = returned[0];
+ if (hyperlink instanceof URLHyperlink) {
+ URLHyperlink urlHyperlink = (URLHyperlink) hyperlink;
+ String newURLString = UiUtils.resolveDefines(specfile, urlHyperlink.getURLString());
+ return new IHyperlink[] {new URLHyperlink(urlHyperlink.getHyperlinkRegion(), newURLString)};
+ }
+ }
+ return returned;
+ }
+
+ public void setSpecfile(Specfile specfile) {
+ this.specfile = specfile;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/ContainsFilter.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/ContainsFilter.java
index 23671803a8..f8dac12519 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/ContainsFilter.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/ContainsFilter.java
@@ -22,40 +22,40 @@ import org.eclipse.jface.viewers.ViewerFilter;
*/
public class ContainsFilter extends ViewerFilter {
- private String lookFor;
+ private String lookFor;
- public void setLookFor(String lookFor) {
- this.lookFor = lookFor;
- }
+ public void setLookFor(String lookFor) {
+ this.lookFor = lookFor;
+ }
- /**
- * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
- */
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (!(viewer instanceof TreeViewer)) {
- return true;
- }
- TreeViewer treeViewer = (TreeViewer) viewer;
- String currentLabel = ((ILabelProvider) treeViewer.getLabelProvider())
- .getText(element);
- if (lookFor == null) {
- return true;
- }
- if (currentLabel != null && currentLabel.contains(lookFor)) {
- return true;
- }
- return hasUnfilteredChild(treeViewer, element);
- }
+ /**
+ * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ if (!(viewer instanceof TreeViewer)) {
+ return true;
+ }
+ TreeViewer treeViewer = (TreeViewer) viewer;
+ String currentLabel = ((ILabelProvider) treeViewer.getLabelProvider())
+ .getText(element);
+ if (lookFor == null) {
+ return true;
+ }
+ if (currentLabel != null && currentLabel.contains(lookFor)) {
+ return true;
+ }
+ return hasUnfilteredChild(treeViewer, element);
+ }
- private boolean hasUnfilteredChild(TreeViewer viewer, Object element) {
- Object[] children = ((ITreeContentProvider) viewer.getContentProvider())
- .getChildren(element);
- for (Object child :children) {
- if (select(viewer, element, child)) {
- return true;
- }
- }
- return false;
- }
+ private boolean hasUnfilteredChild(TreeViewer viewer, Object element) {
+ Object[] children = ((ITreeContentProvider) viewer.getContentProvider())
+ .getChildren(element);
+ for (Object child :children) {
+ if (select(viewer, element, child)) {
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/Messages.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/Messages.java
index 58f797f990..88e962468d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/Messages.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -13,15 +13,15 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.outline;
import org.eclipse.osgi.util.NLS;
public final class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.outline.messages"; //$NON-NLS-1$
- public static String SpecfileLabelProvider_0;
- public static String SpecfileLabelProvider_1;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.outline.messages"; //$NON-NLS-1$
+ public static String SpecfileLabelProvider_0;
+ public static String SpecfileLabelProvider_1;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- super();
- }
+ private Messages() {
+ super();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileContentOutlinePage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileContentOutlinePage.java
index b78a14f1de..e4a50595fa 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileContentOutlinePage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileContentOutlinePage.java
@@ -25,85 +25,85 @@ import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
public class SpecfileContentOutlinePage extends ContentOutlinePage {
- private ITextEditor editor;
- private IEditorInput input;
-
- public SpecfileContentOutlinePage(SpecfileEditor editor) {
- super();
- this.editor = editor;
- }
-
- public void setInput(IEditorInput editorInput) {
- this.input = editorInput;
- update();
- }
-
- public void update() {
- //set the input so that the outlines parse can be called
- //update the tree viewer state
- final TreeViewer viewer = getTreeViewer();
-
- if (viewer != null)
- {
- final Control control = viewer.getControl();
- if (control != null && !control.isDisposed())
- {
- control.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- if (!control.isDisposed()) {
- control.setRedraw(false);
- if (input != null) {
- viewer.setInput(input);
- }
- viewer.expandAll();
- control.setRedraw(true);
- }
- }
- });
- }
- }
- }
-
- @Override
- public void createControl(Composite parent) {
-
- super.createControl(parent);
-
- TreeViewer viewer= getTreeViewer();
- viewer.setContentProvider(new SpecfileContentProvider(editor));
- SpecfileLabelProvider labelProvider = new SpecfileLabelProvider();
- viewer.setLabelProvider(labelProvider);
- viewer.addSelectionChangedListener(this);
-
- if (input != null) {
- viewer.setInput(input);
- }
- }
-
- /*
- * Change in selection
- */
- @Override
- public void selectionChanged(SelectionChangedEvent event)
- {
- super.selectionChanged(event);
-
- //find out which item in tree viewer we have selected, and set highlight range accordingly
- ISelection selection = event.getSelection();
- if (selection.isEmpty()) {
- editor.resetHighlightRange();
- } else {
- SpecfileElement element = (SpecfileElement) ((IStructuredSelection) selection)
- .getFirstElement();
-
- int start = element.getLineStartPosition();
- try {
- editor.setHighlightRange(start, 1, true);
- } catch (IllegalArgumentException e) {
- editor.resetHighlightRange();
- }
- }
- }
+ private ITextEditor editor;
+ private IEditorInput input;
+
+ public SpecfileContentOutlinePage(SpecfileEditor editor) {
+ super();
+ this.editor = editor;
+ }
+
+ public void setInput(IEditorInput editorInput) {
+ this.input = editorInput;
+ update();
+ }
+
+ public void update() {
+ //set the input so that the outlines parse can be called
+ //update the tree viewer state
+ final TreeViewer viewer = getTreeViewer();
+
+ if (viewer != null)
+ {
+ final Control control = viewer.getControl();
+ if (control != null && !control.isDisposed())
+ {
+ control.getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ if (!control.isDisposed()) {
+ control.setRedraw(false);
+ if (input != null) {
+ viewer.setInput(input);
+ }
+ viewer.expandAll();
+ control.setRedraw(true);
+ }
+ }
+ });
+ }
+ }
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+
+ super.createControl(parent);
+
+ TreeViewer viewer= getTreeViewer();
+ viewer.setContentProvider(new SpecfileContentProvider(editor));
+ SpecfileLabelProvider labelProvider = new SpecfileLabelProvider();
+ viewer.setLabelProvider(labelProvider);
+ viewer.addSelectionChangedListener(this);
+
+ if (input != null) {
+ viewer.setInput(input);
+ }
+ }
+
+ /*
+ * Change in selection
+ */
+ @Override
+ public void selectionChanged(SelectionChangedEvent event)
+ {
+ super.selectionChanged(event);
+
+ //find out which item in tree viewer we have selected, and set highlight range accordingly
+ ISelection selection = event.getSelection();
+ if (selection.isEmpty()) {
+ editor.resetHighlightRange();
+ } else {
+ SpecfileElement element = (SpecfileElement) ((IStructuredSelection) selection)
+ .getFirstElement();
+
+ int start = element.getLineStartPosition();
+ try {
+ editor.setHighlightRange(start, 1, true);
+ } catch (IllegalArgumentException e) {
+ editor.resetHighlightRange();
+ }
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileContentProvider.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileContentProvider.java
index be1d363581..a96f031337 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileContentProvider.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileContentProvider.java
@@ -26,90 +26,90 @@ import org.eclipse.ui.texteditor.ITextEditor;
public class SpecfileContentProvider implements ITreeContentProvider {
- private IDocumentProvider documentProvider;
- private Specfile specfile;
- private SpecfileEditor specEditor;
- protected static final String SECTION_POSITIONS = "section_positions"; //$NON-NLS-1$
- protected IPositionUpdater positionUpdater = new DefaultPositionUpdater(
- SECTION_POSITIONS);
+ private IDocumentProvider documentProvider;
+ private Specfile specfile;
+ private SpecfileEditor specEditor;
+ protected static final String SECTION_POSITIONS = "section_positions"; //$NON-NLS-1$
+ protected IPositionUpdater positionUpdater = new DefaultPositionUpdater(
+ SECTION_POSITIONS);
- public SpecfileContentProvider(ITextEditor editor) {
- if (editor instanceof SpecfileEditor) {
- specEditor = (SpecfileEditor) editor;
- specfile = specEditor.getSpecfile();
- }
- this.documentProvider = editor.getDocumentProvider();
- }
+ public SpecfileContentProvider(ITextEditor editor) {
+ if (editor instanceof SpecfileEditor) {
+ specEditor = (SpecfileEditor) editor;
+ specfile = specEditor.getSpecfile();
+ }
+ this.documentProvider = editor.getDocumentProvider();
+ }
- @Override
- public void dispose() {
- }
+ @Override
+ public void dispose() {
+ }
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- if (oldInput != null) {
- IDocument document = documentProvider.getDocument(oldInput);
- if (document != null) {
- try {
- document.removePositionCategory(SECTION_POSITIONS);
- } catch (BadPositionCategoryException x) {
- }
- document.removePositionUpdater(positionUpdater);
- }
- }
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ if (oldInput != null) {
+ IDocument document = documentProvider.getDocument(oldInput);
+ if (document != null) {
+ try {
+ document.removePositionCategory(SECTION_POSITIONS);
+ } catch (BadPositionCategoryException x) {
+ }
+ document.removePositionUpdater(positionUpdater);
+ }
+ }
- if (newInput != null) {
- IDocument document = documentProvider.getDocument(newInput);
- if (document != null) {
- document.addPositionCategory(SECTION_POSITIONS);
- document.addPositionUpdater(positionUpdater);
- if (specEditor != null) {
- specfile = specEditor.getSpecfile();
- }
- }
- }
- }
+ if (newInput != null) {
+ IDocument document = documentProvider.getDocument(newInput);
+ if (document != null) {
+ document.addPositionCategory(SECTION_POSITIONS);
+ document.addPositionUpdater(positionUpdater);
+ if (specEditor != null) {
+ specfile = specEditor.getSpecfile();
+ }
+ }
+ }
+ }
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement == specfile) {
- int elmsSize = 1 + 1 + specfile.getSections().size();
- Object[] elms = new Object[elmsSize];
- elms[0] = specfile.getPreamble();
- Object[] sections = specfile.getSections().toArray();
- for (int i = 0; i < sections.length; i++) {
- elms[i + 1] = sections[i];
- }
- elms[elmsSize - 1] = specfile.getPackages();
- return elms;
- } else if (parentElement instanceof SpecfilePackageContainer) {
- return ((SpecfilePackageContainer) parentElement).getPackages();
- } else if (parentElement instanceof SpecfilePackage) {
- return ((SpecfilePackage) parentElement).getSections();
- }
- return new Object[0];
- }
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ if (parentElement == specfile) {
+ int elmsSize = 1 + 1 + specfile.getSections().size();
+ Object[] elms = new Object[elmsSize];
+ elms[0] = specfile.getPreamble();
+ Object[] sections = specfile.getSections().toArray();
+ for (int i = 0; i < sections.length; i++) {
+ elms[i + 1] = sections[i];
+ }
+ elms[elmsSize - 1] = specfile.getPackages();
+ return elms;
+ } else if (parentElement instanceof SpecfilePackageContainer) {
+ return ((SpecfilePackageContainer) parentElement).getPackages();
+ } else if (parentElement instanceof SpecfilePackage) {
+ return ((SpecfilePackage) parentElement).getSections();
+ }
+ return new Object[0];
+ }
- @Override
- public Object getParent(Object element) {
- return null;
- }
+ @Override
+ public Object getParent(Object element) {
+ return null;
+ }
- @Override
- public boolean hasChildren(Object element) {
- if (element == specfile) {
- return true;
- } else if (element instanceof SpecfilePackageContainer) {
- return ((SpecfilePackageContainer) element).hasChildren();
- } else if (element instanceof SpecfilePackage) {
- return ((SpecfilePackage) element).hasChildren();
- }
- return false;
- }
+ @Override
+ public boolean hasChildren(Object element) {
+ if (element == specfile) {
+ return true;
+ } else if (element instanceof SpecfilePackageContainer) {
+ return ((SpecfilePackageContainer) element).hasChildren();
+ } else if (element instanceof SpecfilePackage) {
+ return ((SpecfilePackage) element).hasChildren();
+ }
+ return false;
+ }
- @Override
- public Object[] getElements(Object inputElement) {
- return this.getChildren(specfile);
- }
+ @Override
+ public Object[] getElements(Object inputElement) {
+ return this.getChildren(specfile);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileLabelProvider.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileLabelProvider.java
index 79929768e0..ef0a8544e5 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileLabelProvider.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileLabelProvider.java
@@ -26,69 +26,69 @@ import org.eclipse.swt.graphics.Image;
public class SpecfileLabelProvider extends LabelProvider {
- private static final String PREAMBLE_ICON="icons/preamble_obj.gif"; //$NON-NLS-1$
- private static final String SECTION_ICON="icons/section_obj.gif"; //$NON-NLS-1$
- private static final String PACKAGES_ICON="icons/packages_obj.gif"; //$NON-NLS-1$
- private static final String PACKAGE_ICON="icons/package_obj.gif"; //$NON-NLS-1$
+ private static final String PREAMBLE_ICON="icons/preamble_obj.gif"; //$NON-NLS-1$
+ private static final String SECTION_ICON="icons/section_obj.gif"; //$NON-NLS-1$
+ private static final String PACKAGES_ICON="icons/packages_obj.gif"; //$NON-NLS-1$
+ private static final String PACKAGE_ICON="icons/package_obj.gif"; //$NON-NLS-1$
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
- @Override
- public Image getImage(Object element) {
- if (element instanceof SpecfilePackage) {
- return Activator.getDefault().getImage(PACKAGE_ICON);
- } else if (element instanceof SpecfileSection) {
- return Activator.getDefault().getImage(SECTION_ICON);
- } else if (element instanceof SpecfilePackageContainer) {
- return Activator.getDefault().getImage(PACKAGES_ICON);
- }else if (element instanceof SpecfilePreamble) {
- return Activator.getDefault().getImage(PREAMBLE_ICON);
- }
- return null;
- }
+ @Override
+ public Image getImage(Object element) {
+ if (element instanceof SpecfilePackage) {
+ return Activator.getDefault().getImage(PACKAGE_ICON);
+ } else if (element instanceof SpecfileSection) {
+ return Activator.getDefault().getImage(SECTION_ICON);
+ } else if (element instanceof SpecfilePackageContainer) {
+ return Activator.getDefault().getImage(PACKAGES_ICON);
+ }else if (element instanceof SpecfilePreamble) {
+ return Activator.getDefault().getImage(PREAMBLE_ICON);
+ }
+ return null;
+ }
- @Override
- public String getText(Object element) {
- String str = ""; //$NON-NLS-1$
- if (element instanceof SpecfileSection) {
- SpecfileSection specfileSection = (SpecfileSection) element;
- str = specfileSection.toString();
- } else if (element instanceof Specfile) {
- str = ((Specfile) element).getName();
- } else if (element instanceof SpecfilePackageContainer) {
- str = Messages.SpecfileLabelProvider_0;
- } else if (element instanceof SpecfilePreamble){
- str = Messages.SpecfileLabelProvider_1;
- } else if (element instanceof SpecfileElement) {
- SpecfileElement specfileElement = (SpecfileElement) element;
- str = specfileElement.getName();
- } else if (element instanceof String) {
- str = (String) element;
- } else if (element instanceof SpecfilePackage) {
- str = ((SpecfilePackage) element).getName();
- }
- return filterMacros(str.trim());
- }
+ @Override
+ public String getText(Object element) {
+ String str = ""; //$NON-NLS-1$
+ if (element instanceof SpecfileSection) {
+ SpecfileSection specfileSection = (SpecfileSection) element;
+ str = specfileSection.toString();
+ } else if (element instanceof Specfile) {
+ str = ((Specfile) element).getName();
+ } else if (element instanceof SpecfilePackageContainer) {
+ str = Messages.SpecfileLabelProvider_0;
+ } else if (element instanceof SpecfilePreamble){
+ str = Messages.SpecfileLabelProvider_1;
+ } else if (element instanceof SpecfileElement) {
+ SpecfileElement specfileElement = (SpecfileElement) element;
+ str = specfileElement.getName();
+ } else if (element instanceof String) {
+ str = (String) element;
+ } else if (element instanceof SpecfilePackage) {
+ str = ((SpecfilePackage) element).getName();
+ }
+ return filterMacros(str.trim());
+ }
- /**
- * Remove any unresolved macros from the string. These are
- * macros that follow the format %{?...} (e.g. %{?scl_prefix}).
- *
- * @param text The text to filter macros out from.
- * @return A string without unresolved macros.
- *
- * @since 2.1
- */
- private String filterMacros(String text) {
- Pattern variablePattern = Pattern.compile("%\\{\\?\\w+\\}"); //$NON-NLS-1$
- Matcher variableMatcher = variablePattern.matcher(text);
- while (variableMatcher.find()) {
- text = text.replace(variableMatcher.group(0), ""); //$NON-NLS-1$
- }
- return text;
- }
+ /**
+ * Remove any unresolved macros from the string. These are
+ * macros that follow the format %{?...} (e.g. %{?scl_prefix}).
+ *
+ * @param text The text to filter macros out from.
+ * @return A string without unresolved macros.
+ *
+ * @since 2.1
+ */
+ private String filterMacros(String text) {
+ Pattern variablePattern = Pattern.compile("%\\{\\?\\w+\\}"); //$NON-NLS-1$
+ Matcher variableMatcher = variablePattern.matcher(text);
+ while (variableMatcher.find()) {
+ text = text.replace(variableMatcher.group(0), ""); //$NON-NLS-1$
+ }
+ return text;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileQuickOutlineDialog.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileQuickOutlineDialog.java
index 0e6f072080..488536aac7 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileQuickOutlineDialog.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/outline/SpecfileQuickOutlineDialog.java
@@ -36,137 +36,137 @@ import org.eclipse.swt.widgets.Tree;
public class SpecfileQuickOutlineDialog extends PopupDialog {
- TreeViewer treeViewer;
- private Text filterText;
- private SpecfileEditor editor;
- private ContainsFilter treeViewerFilter;
-
- public SpecfileQuickOutlineDialog(Shell parent, int shellStyle,
- SpecfileEditor editor) {
- super(parent, shellStyle, true, true, true, true, true, null, null);
- this.editor = editor;
- create();
- }
-
- public void setSize(int width, int height) {
- getShell().setSize(width, height);
- }
-
- public void setVisible(boolean visible) {
- if (visible) {
- open();
- filterText.setFocus();
- } else {
- saveDialogBounds(getShell());
- getShell().setVisible(false);
- }
- }
-
- public void dispose() {
- close();
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- createUIWidgetTreeViewer(parent);
- createUIListenersTreeViewer();
- return treeViewer.getControl();
- }
-
- @Override
- protected Control createTitleControl(Composite parent) {
- filterText = new Text(parent, SWT.NONE);
- GC gc = new GC(parent);
- gc.setFont(parent.getFont());
- FontMetrics fontMetrics = gc.getFontMetrics();
- gc.dispose();
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true,
- false).hint(SWT.DEFAULT,
- Dialog.convertHeightInCharsToPixels(fontMetrics, 1)).applyTo(
- filterText);
-
- filterText.addKeyListener(new KeyAdapter() {
- @Override
- public void keyPressed(KeyEvent e) {
- if (e.keyCode == 0x0D) { // Enter pressed
- gotoSelectedElement();
- } else if (e.keyCode == SWT.ARROW_DOWN) {
- treeViewer.getTree().setFocus();
- } else if (e.keyCode == SWT.ARROW_UP) {
- treeViewer.getTree().setFocus();
- } else if (e.character == 0x1B) { // Escape pressed
- dispose();
- }
- }
- });
- filterText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- String filterTextInput = ((Text) e.widget).getText()
- .toLowerCase();
- treeViewerFilter.setLookFor(filterTextInput);
- stringMatcherUpdated();
- }
- });
- return filterText;
- }
-
- private void stringMatcherUpdated() {
- treeViewer.getControl().setRedraw(false);
- treeViewer.refresh();
- treeViewer.expandAll();
- if(treeViewer.getTree().getTopItem() != null && treeViewer.getTree().getTopItem().getItemCount() > 0) {
- treeViewer.getTree().select(treeViewer.getTree().getTopItem().getItem(0));
- } else if(treeViewer.getTree().getItemCount()>0) {
- treeViewer.getTree().select(treeViewer.getTree().getItem(0));
- }
- treeViewer.getControl().setRedraw(true);
- }
-
- private void createUIWidgetTreeViewer(Composite parent) {
- final int style = SWT.H_SCROLL | SWT.V_SCROLL;
- final Tree widget = new Tree(parent, style);
- final GridData data = new GridData(GridData.FILL_BOTH);
- data.heightHint = widget.getItemHeight() * 12;
- widget.setLayoutData(data);
- treeViewer = new TreeViewer(widget);
- treeViewerFilter = new ContainsFilter();
- treeViewer.addFilter(treeViewerFilter);
- SpecfileContentProvider fOutlineContentProvider = new SpecfileContentProvider(
- editor);
- treeViewer.setContentProvider(fOutlineContentProvider);
- SpecfileLabelProvider fTreeLabelProvider = new SpecfileLabelProvider();
- treeViewer.setLabelProvider(fTreeLabelProvider);
- treeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
- treeViewer.setUseHashlookup(true);
- treeViewer.setInput(fOutlineContentProvider);
- }
-
- private void createUIListenersTreeViewer() {
- final Tree tree = treeViewer.getTree();
- tree.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- gotoSelectedElement();
- }
- });
- }
-
- private void gotoSelectedElement() {
- final SpecfileElement curElement = (SpecfileElement) getSelectedElement();
- if (curElement == null) {
- return;
- }
- dispose();
- editor.setHighlightRange(curElement.getLineStartPosition(), 1, true);
- }
-
-
- private Object getSelectedElement() {
- if (treeViewer == null) {
- return null;
- }
- return ((IStructuredSelection) treeViewer.getSelection())
- .getFirstElement();
- }
+ TreeViewer treeViewer;
+ private Text filterText;
+ private SpecfileEditor editor;
+ private ContainsFilter treeViewerFilter;
+
+ public SpecfileQuickOutlineDialog(Shell parent, int shellStyle,
+ SpecfileEditor editor) {
+ super(parent, shellStyle, true, true, true, true, true, null, null);
+ this.editor = editor;
+ create();
+ }
+
+ public void setSize(int width, int height) {
+ getShell().setSize(width, height);
+ }
+
+ public void setVisible(boolean visible) {
+ if (visible) {
+ open();
+ filterText.setFocus();
+ } else {
+ saveDialogBounds(getShell());
+ getShell().setVisible(false);
+ }
+ }
+
+ public void dispose() {
+ close();
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ createUIWidgetTreeViewer(parent);
+ createUIListenersTreeViewer();
+ return treeViewer.getControl();
+ }
+
+ @Override
+ protected Control createTitleControl(Composite parent) {
+ filterText = new Text(parent, SWT.NONE);
+ GC gc = new GC(parent);
+ gc.setFont(parent.getFont());
+ FontMetrics fontMetrics = gc.getFontMetrics();
+ gc.dispose();
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true,
+ false).hint(SWT.DEFAULT,
+ Dialog.convertHeightInCharsToPixels(fontMetrics, 1)).applyTo(
+ filterText);
+
+ filterText.addKeyListener(new KeyAdapter() {
+ @Override
+ public void keyPressed(KeyEvent e) {
+ if (e.keyCode == 0x0D) { // Enter pressed
+ gotoSelectedElement();
+ } else if (e.keyCode == SWT.ARROW_DOWN) {
+ treeViewer.getTree().setFocus();
+ } else if (e.keyCode == SWT.ARROW_UP) {
+ treeViewer.getTree().setFocus();
+ } else if (e.character == 0x1B) { // Escape pressed
+ dispose();
+ }
+ }
+ });
+ filterText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ String filterTextInput = ((Text) e.widget).getText()
+ .toLowerCase();
+ treeViewerFilter.setLookFor(filterTextInput);
+ stringMatcherUpdated();
+ }
+ });
+ return filterText;
+ }
+
+ private void stringMatcherUpdated() {
+ treeViewer.getControl().setRedraw(false);
+ treeViewer.refresh();
+ treeViewer.expandAll();
+ if(treeViewer.getTree().getTopItem() != null && treeViewer.getTree().getTopItem().getItemCount() > 0) {
+ treeViewer.getTree().select(treeViewer.getTree().getTopItem().getItem(0));
+ } else if(treeViewer.getTree().getItemCount()>0) {
+ treeViewer.getTree().select(treeViewer.getTree().getItem(0));
+ }
+ treeViewer.getControl().setRedraw(true);
+ }
+
+ private void createUIWidgetTreeViewer(Composite parent) {
+ final int style = SWT.H_SCROLL | SWT.V_SCROLL;
+ final Tree widget = new Tree(parent, style);
+ final GridData data = new GridData(GridData.FILL_BOTH);
+ data.heightHint = widget.getItemHeight() * 12;
+ widget.setLayoutData(data);
+ treeViewer = new TreeViewer(widget);
+ treeViewerFilter = new ContainsFilter();
+ treeViewer.addFilter(treeViewerFilter);
+ SpecfileContentProvider fOutlineContentProvider = new SpecfileContentProvider(
+ editor);
+ treeViewer.setContentProvider(fOutlineContentProvider);
+ SpecfileLabelProvider fTreeLabelProvider = new SpecfileLabelProvider();
+ treeViewer.setLabelProvider(fTreeLabelProvider);
+ treeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
+ treeViewer.setUseHashlookup(true);
+ treeViewer.setInput(fOutlineContentProvider);
+ }
+
+ private void createUIListenersTreeViewer() {
+ final Tree tree = treeViewer.getTree();
+ tree.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ gotoSelectedElement();
+ }
+ });
+ }
+
+ private void gotoSelectedElement() {
+ final SpecfileElement curElement = (SpecfileElement) getSelectedElement();
+ if (curElement == null) {
+ return;
+ }
+ dispose();
+ editor.setHighlightRange(curElement.getLineStartPosition(), 1, true);
+ }
+
+
+ private Object getSelectedElement() {
+ if (treeViewer == null) {
+ return null;
+ }
+ return ((IStructuredSelection) treeViewer.getSelection())
+ .getFirstElement();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/Messages.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/Messages.java
index c2018a062f..a511aff8b5 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/Messages.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -14,19 +14,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public final class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.rpm.ui.editor.parser.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.rpm.ui.editor.parser.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SourceComparator.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SourceComparator.java
index 1d1d39eac1..74ee578a17 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SourceComparator.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SourceComparator.java
@@ -15,23 +15,23 @@ import java.io.Serializable;
import java.util.Comparator;
public class SourceComparator implements Comparator<SpecfileSource>,
- Serializable {
- private static final long serialVersionUID = 1L;
+ Serializable {
+ private static final long serialVersionUID = 1L;
- @Override
- public int compare(SpecfileSource source0, SpecfileSource source1) {
- if (source0 == null) {
- return -1;
- }
- if (source1 == null) {
- return 1;
- }
- if (source0.getNumber() < source1.getNumber()) {
- return -1;
- } else if (source0.getNumber() == source1.getNumber()) {
- return 0;
- } else {
- return 1;
- }
- }
+ @Override
+ public int compare(SpecfileSource source0, SpecfileSource source1) {
+ if (source0 == null) {
+ return -1;
+ }
+ if (source1 == null) {
+ return 1;
+ }
+ if (source0.getNumber() < source1.getNumber()) {
+ return -1;
+ } else if (source0.getNumber() == source1.getNumber()) {
+ return 0;
+ } else {
+ return 1;
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileParseException.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileParseException.java
index 859d855525..393e09e393 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileParseException.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileParseException.java
@@ -13,62 +13,62 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.parser;
public class SpecfileParseException extends Exception {
- private static final long serialVersionUID = 1L;
- private String message;
- private int severity;
- private int lineNumber;
- private int startColumn;
- private int endColumn;
+ private static final long serialVersionUID = 1L;
+ private String message;
+ private int severity;
+ private int lineNumber;
+ private int startColumn;
+ private int endColumn;
- public int getEndColumn() {
- return endColumn;
- }
+ public int getEndColumn() {
+ return endColumn;
+ }
- public void setEndColumn(int endColumn) {
- this.endColumn = endColumn;
- }
+ public void setEndColumn(int endColumn) {
+ this.endColumn = endColumn;
+ }
- public int getLineNumber() {
- return lineNumber;
- }
+ public int getLineNumber() {
+ return lineNumber;
+ }
- public void setLineNumber(int lineNumber) {
- this.lineNumber = lineNumber;
- }
+ public void setLineNumber(int lineNumber) {
+ this.lineNumber = lineNumber;
+ }
- @Override
- public String getMessage() {
- return message;
- }
+ @Override
+ public String getMessage() {
+ return message;
+ }
- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }
- public int getStartColumn() {
- return startColumn;
- }
+ public int getStartColumn() {
+ return startColumn;
+ }
- public void setStartColumn(int startColumn) {
- this.startColumn = startColumn;
- }
+ public void setStartColumn(int startColumn) {
+ this.startColumn = startColumn;
+ }
- public SpecfileParseException(String message, int lineNumber,
- int startColumn, int endColumn, int severity) {
- super();
- this.message = message;
- this.lineNumber = lineNumber;
- this.startColumn = startColumn;
- this.endColumn = endColumn;
- this.severity = severity;
- }
+ public SpecfileParseException(String message, int lineNumber,
+ int startColumn, int endColumn, int severity) {
+ super();
+ this.message = message;
+ this.lineNumber = lineNumber;
+ this.startColumn = startColumn;
+ this.endColumn = endColumn;
+ this.severity = severity;
+ }
- public int getSeverity() {
- return severity;
- }
+ public int getSeverity() {
+ return severity;
+ }
- public void setSeverity(int severity) {
- this.severity = severity;
- }
+ public void setSeverity(int severity) {
+ this.severity = severity;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfilePatchMacro.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfilePatchMacro.java
index 7f14f225ac..af5ce5a5d5 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfilePatchMacro.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfilePatchMacro.java
@@ -14,23 +14,23 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.parser;
import java.text.MessageFormat;
public class SpecfilePatchMacro extends SpecfileMacro {
- private int patchNumber;
+ private int patchNumber;
- public SpecfilePatchMacro(int patchNumber) {
- super();
- this.patchNumber = patchNumber;
- }
+ public SpecfilePatchMacro(int patchNumber) {
+ super();
+ this.patchNumber = patchNumber;
+ }
- public int getPatchNumber() {
- return patchNumber;
- }
+ public int getPatchNumber() {
+ return patchNumber;
+ }
- public void setPatchNumber(int patchNumber) {
- this.patchNumber = patchNumber;
- }
+ public void setPatchNumber(int patchNumber) {
+ this.patchNumber = patchNumber;
+ }
- @Override
- public String toString() {
- return MessageFormat.format("patch #{0}", patchNumber); //$NON-NLS-1$
- }
+ @Override
+ public String toString() {
+ return MessageFormat.format("patch #{0}", patchNumber); //$NON-NLS-1$
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileSource.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileSource.java
index 34575dde57..7c9d2ace9e 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileSource.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileSource.java
@@ -23,134 +23,134 @@ import org.eclipse.linuxtools.rpm.ui.editor.parser.Specfile;
import org.eclipse.linuxtools.rpm.ui.editor.parser.SpecfileElement;
public class SpecfileSource extends SpecfileElement {
- private int number;
- private int lineNumber = -1;
- private String fileName;
-
- public enum SourceType {
- SOURCE, PATCH
- }
-
- private SourceType sourceType;
- private List<Integer> linesUsed;
-
- public SourceType getSourceType() {
- return sourceType;
- }
-
- public void setSourceType(SourceType sourceType) {
- this.sourceType = sourceType;
- }
-
- public SpecfileSource(int number, String fileName) {
- super("source"); //$NON-NLS-1$
- this.number = number;
- this.fileName = fileName;
- this.linesUsed = new ArrayList<>();
- }
-
- public String getFileName() {
- return resolve(fileName);
- }
-
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
-
- public int getNumber() {
- return number;
- }
-
- public void setNumber(int number) {
- this.number = number;
- }
-
- public void addLineUsed(int lineNumber) {
- linesUsed.add(Integer.valueOf(lineNumber));
- }
-
- public void removeLineUsed(int lineNumber) {
- linesUsed.remove(Integer.valueOf(lineNumber));
- }
-
- public List<Integer> getLinesUsed() {
- return linesUsed;
- }
-
- @Override
- public String toString() {
- if (sourceType == SourceType.SOURCE) {
- return MessageFormat.format(
- "Source #{0} (line #{1}, used on lines {2}) -> {3}", //$NON-NLS-1$
- number, lineNumber, getLinesUsed(), fileName);
- }
- return MessageFormat.format(
- "Patch #{0} (line #{1}, used on lines {2}) -> {3}", number, //$NON-NLS-1$
- lineNumber, getLinesUsed(), fileName);
- }
-
- // Note that changeReferences assumes that the number of the source/patch
- // has *already been set*. If this is not true, it will simply do nothing
- public void changeReferences(int oldPatchNumber) {
- Specfile specfile = this.getSpecfile();
- Pattern patchPattern;
- if (oldPatchNumber == 0) {
- patchPattern = Pattern
- .compile("%patch" + oldPatchNumber + "|%patch"); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- patchPattern = Pattern.compile("%patch" + oldPatchNumber); //$NON-NLS-1$
- }
- for (int lineNumber : getLinesUsed()) {
- String line;
- try {
- line = specfile.getLine(lineNumber);
- Matcher patchMatcher = patchPattern.matcher(line);
- if (!patchMatcher.find()) {
- System.out
- .println(Messages.getString("SpecfileSource.0") + patchPattern.pattern()); //$NON-NLS-1$
- // throw new BadLocationException("can't match " +
- // patchPattern);
- }
- specfile.changeLine(lineNumber, line.replaceAll(
- patchPattern.pattern(),
- Messages.getString("SpecfileSource.1") + number)); //$NON-NLS-1$
- } catch (BadLocationException e) {
- SpecfileLog.logError(e);
- }
- }
- }
-
- public void changeDeclaration(int oldPatchNumber) {
- Specfile specfile = this.getSpecfile();
- Pattern patchPattern;
- if (oldPatchNumber == 0) {
- patchPattern = Pattern.compile("Patch" + oldPatchNumber + "|Patch"); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- patchPattern = Pattern.compile("Patch" + oldPatchNumber); //$NON-NLS-1$
- }
- String line;
- try {
- line = specfile.getLine(lineNumber);
- Matcher patchMatcher = patchPattern.matcher(line);
- if (!patchMatcher.find()) {
- // TODO: Maybe we can throw a exception here.
- System.out
- .println(Messages.getString("SpecfileSource.2") + patchPattern.pattern()); //$NON-NLS-1$
- }
- specfile.changeLine(lineNumber,
- line.replaceAll(patchPattern.pattern(), "Patch" + number)); //$NON-NLS-1$
- } catch (BadLocationException e) {
- SpecfileLog.logError(e);
- }
- }
-
- @Override
- public int getLineNumber() {
- return lineNumber;
- }
-
- @Override
- public void setLineNumber(int lineNumber) {
- this.lineNumber = lineNumber;
- }
+ private int number;
+ private int lineNumber = -1;
+ private String fileName;
+
+ public enum SourceType {
+ SOURCE, PATCH
+ }
+
+ private SourceType sourceType;
+ private List<Integer> linesUsed;
+
+ public SourceType getSourceType() {
+ return sourceType;
+ }
+
+ public void setSourceType(SourceType sourceType) {
+ this.sourceType = sourceType;
+ }
+
+ public SpecfileSource(int number, String fileName) {
+ super("source"); //$NON-NLS-1$
+ this.number = number;
+ this.fileName = fileName;
+ this.linesUsed = new ArrayList<>();
+ }
+
+ public String getFileName() {
+ return resolve(fileName);
+ }
+
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ public int getNumber() {
+ return number;
+ }
+
+ public void setNumber(int number) {
+ this.number = number;
+ }
+
+ public void addLineUsed(int lineNumber) {
+ linesUsed.add(Integer.valueOf(lineNumber));
+ }
+
+ public void removeLineUsed(int lineNumber) {
+ linesUsed.remove(Integer.valueOf(lineNumber));
+ }
+
+ public List<Integer> getLinesUsed() {
+ return linesUsed;
+ }
+
+ @Override
+ public String toString() {
+ if (sourceType == SourceType.SOURCE) {
+ return MessageFormat.format(
+ "Source #{0} (line #{1}, used on lines {2}) -> {3}", //$NON-NLS-1$
+ number, lineNumber, getLinesUsed(), fileName);
+ }
+ return MessageFormat.format(
+ "Patch #{0} (line #{1}, used on lines {2}) -> {3}", number, //$NON-NLS-1$
+ lineNumber, getLinesUsed(), fileName);
+ }
+
+ // Note that changeReferences assumes that the number of the source/patch
+ // has *already been set*. If this is not true, it will simply do nothing
+ public void changeReferences(int oldPatchNumber) {
+ Specfile specfile = this.getSpecfile();
+ Pattern patchPattern;
+ if (oldPatchNumber == 0) {
+ patchPattern = Pattern
+ .compile("%patch" + oldPatchNumber + "|%patch"); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ patchPattern = Pattern.compile("%patch" + oldPatchNumber); //$NON-NLS-1$
+ }
+ for (int lineNumber : getLinesUsed()) {
+ String line;
+ try {
+ line = specfile.getLine(lineNumber);
+ Matcher patchMatcher = patchPattern.matcher(line);
+ if (!patchMatcher.find()) {
+ System.out
+ .println(Messages.getString("SpecfileSource.0") + patchPattern.pattern()); //$NON-NLS-1$
+ // throw new BadLocationException("can't match " +
+ // patchPattern);
+ }
+ specfile.changeLine(lineNumber, line.replaceAll(
+ patchPattern.pattern(),
+ Messages.getString("SpecfileSource.1") + number)); //$NON-NLS-1$
+ } catch (BadLocationException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+ }
+
+ public void changeDeclaration(int oldPatchNumber) {
+ Specfile specfile = this.getSpecfile();
+ Pattern patchPattern;
+ if (oldPatchNumber == 0) {
+ patchPattern = Pattern.compile("Patch" + oldPatchNumber + "|Patch"); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ patchPattern = Pattern.compile("Patch" + oldPatchNumber); //$NON-NLS-1$
+ }
+ String line;
+ try {
+ line = specfile.getLine(lineNumber);
+ Matcher patchMatcher = patchPattern.matcher(line);
+ if (!patchMatcher.find()) {
+ // TODO: Maybe we can throw a exception here.
+ System.out
+ .println(Messages.getString("SpecfileSource.2") + patchPattern.pattern()); //$NON-NLS-1$
+ }
+ specfile.changeLine(lineNumber,
+ line.replaceAll(patchPattern.pattern(), "Patch" + number)); //$NON-NLS-1$
+ } catch (BadLocationException e) {
+ SpecfileLog.logError(e);
+ }
+ }
+
+ @Override
+ public int getLineNumber() {
+ return lineNumber;
+ }
+
+ @Override
+ public void setLineNumber(int lineNumber) {
+ this.lineNumber = lineNumber;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileTag.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileTag.java
index 05a761ea92..9fa290df2a 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileTag.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/parser/SpecfileTag.java
@@ -17,81 +17,81 @@ import org.eclipse.linuxtools.rpm.ui.editor.parser.SpecfilePackage;
public class SpecfileTag extends SpecfileElement {
- public enum TagType {
- INT, STRING
- }
-
- private TagType tagType;
-
- private String stringValue;
- private int intValue;
- private SpecfilePackage parent;
-
- public SpecfileTag() {
- // Empty constructor
- }
-
- public SpecfileTag(String name, String value, Specfile specfile,
- SpecfilePackage parentPackage) {
- setName(name);
- this.stringValue = value;
- this.tagType = TagType.STRING;
- super.setSpecfile(specfile);
- this.parent = parentPackage;
- }
-
- public SpecfileTag(String name, int value, Specfile specfile,
- SpecfilePackage parentPackage) {
- setName(name);
- this.intValue = value;
- this.tagType = TagType.INT;
- super.setSpecfile(specfile);
- this.parent = parentPackage;
- }
-
- public String getStringValue() {
- if (tagType == TagType.INT) {
- return Integer.toString(intValue);
- }
- return resolve(stringValue);
- }
-
- public void setValue(String value) {
- this.tagType = TagType.STRING;
- this.stringValue = value;
- }
-
- public int getIntValue() {
- return intValue;
- }
-
- public void setValue(int value) {
- this.tagType = TagType.INT;
- this.intValue = value;
- }
-
- public SpecfilePackage getParent() {
- return parent;
- }
-
- public void setParent(SpecfilePackage parent) {
- this.parent = parent;
- }
-
- @Override
- public String toString() {
- if (tagType == TagType.INT) {
- return getName() + ": " + getIntValue(); //$NON-NLS-1$
- }
- String tagValue = getStringValue();
- if ((tagValue != null) && (tagValue.length() > 0)
- && (tagValue.indexOf('%') > 0)) {
- return getName() + ": " + super.resolve(tagValue); //$NON-NLS-1$
- }
- return getName() + ": " + getStringValue(); //$NON-NLS-1$
- }
-
- public TagType getTagType() {
- return tagType;
- }
+ public enum TagType {
+ INT, STRING
+ }
+
+ private TagType tagType;
+
+ private String stringValue;
+ private int intValue;
+ private SpecfilePackage parent;
+
+ public SpecfileTag() {
+ // Empty constructor
+ }
+
+ public SpecfileTag(String name, String value, Specfile specfile,
+ SpecfilePackage parentPackage) {
+ setName(name);
+ this.stringValue = value;
+ this.tagType = TagType.STRING;
+ super.setSpecfile(specfile);
+ this.parent = parentPackage;
+ }
+
+ public SpecfileTag(String name, int value, Specfile specfile,
+ SpecfilePackage parentPackage) {
+ setName(name);
+ this.intValue = value;
+ this.tagType = TagType.INT;
+ super.setSpecfile(specfile);
+ this.parent = parentPackage;
+ }
+
+ public String getStringValue() {
+ if (tagType == TagType.INT) {
+ return Integer.toString(intValue);
+ }
+ return resolve(stringValue);
+ }
+
+ public void setValue(String value) {
+ this.tagType = TagType.STRING;
+ this.stringValue = value;
+ }
+
+ public int getIntValue() {
+ return intValue;
+ }
+
+ public void setValue(int value) {
+ this.tagType = TagType.INT;
+ this.intValue = value;
+ }
+
+ public SpecfilePackage getParent() {
+ return parent;
+ }
+
+ public void setParent(SpecfilePackage parent) {
+ this.parent = parent;
+ }
+
+ @Override
+ public String toString() {
+ if (tagType == TagType.INT) {
+ return getName() + ": " + getIntValue(); //$NON-NLS-1$
+ }
+ String tagValue = getStringValue();
+ if ((tagValue != null) && (tagValue.length() > 0)
+ && (tagValue.indexOf('%') > 0)) {
+ return getName() + ": " + super.resolve(tagValue); //$NON-NLS-1$
+ }
+ return getName() + ": " + getStringValue(); //$NON-NLS-1$
+ }
+
+ public TagType getTagType() {
+ return tagType;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/MacroProposalsPreferencePage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/MacroProposalsPreferencePage.java
index aecb54005e..88d46116b3 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/MacroProposalsPreferencePage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/MacroProposalsPreferencePage.java
@@ -46,385 +46,385 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
*
*/
public class MacroProposalsPreferencePage extends FieldEditorPreferencePage
- implements IWorkbenchPreferencePage {
-
- public MacroProposalsPreferencePage() {
- super(FLAT);
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- }
-
- @Override
- public void init(IWorkbench workbench) {
- }
-
- @Override
- protected void createFieldEditors() {
- ListEditor macroListEditor = new MacroListEditor(
- PreferenceConstants.P_MACRO_PROPOSALS_FILESPATH,
- Messages.MacroProposalsPreferencePage_0, getFieldEditorParent());
- addField(macroListEditor);
- RadioGroupFieldEditor macroHoverListEditor = new RadioGroupFieldEditor(
- PreferenceConstants.P_MACRO_HOVER_CONTENT,
- Messages.MacroProposalsPreferencePage_1,
- 1,
- new String[][] {
- {
- Messages.MacroProposalsPreferencePage_2,
- PreferenceConstants.P_MACRO_HOVER_CONTENT_VIEWDESCRIPTION },
- {
- Messages.MacroProposalsPreferencePage_3,
- PreferenceConstants.P_MACRO_HOVER_CONTENT_VIEWCONTENT } },
- getFieldEditorParent(), true);
- addField(macroHoverListEditor);
- }
-
- static class MacroListEditor extends ListEditor {
-
- /**
- * The list widget; <code>null</code> if none (before creation or
- * after disposal).
- */
- private List list;
-
- /**
- * The button box containing the Add, Remove, Up, and Down buttons;
- * <code>null</code> if none (before creation or after disposal).
- */
- private Composite buttonBox;
-
- /**
- * The Add file button.
- */
- private Button addFileButton;
-
- /**
- * The Add button.
- */
- private Button addDirButton;
-
- /**
- * The Remove button.
- */
- private Button removeButton;
-
- /**
- * The Up button.
- */
- private Button upButton;
-
- /**
- * The Down button.
- */
- private Button downButton;
-
- /**
- * The selection listener.
- */
- private SelectionListener selectionListener;
-
- public MacroListEditor(String name, String labelText, Composite parent) {
- super();
- init(name, labelText);
- createControl(parent);
- list = getListControl(parent);
- }
-
- @Override
- protected String createList(String[] items) {
- StringBuilder path = new StringBuilder(""); //$NON-NLS-1$
- for (String item:items) {
- path.append(item);
- path.append(";"); //$NON-NLS-1$
- }
- return path.toString();
- }
-
- @Override
- protected String getNewInputObject() {
- FileDialog dialog = new FileDialog(getShell());
- return dialog.open();
- }
-
- protected String getNewDirInputObject() {
- DirectoryDialog dialog = new DirectoryDialog(getShell());
- return dialog.open();
- }
-
- @Override
- protected String[] parseString(String stringList) {
- StringTokenizer st = new StringTokenizer(stringList, ";\n\r"); //$NON-NLS-1$
- ArrayList<String> v = new ArrayList<>();
- while (st.hasMoreTokens()) {
- v.add(st.nextToken());
- }
- return v.toArray(new String[v.size()]);
- }
-
- /**
- * Notifies that the Add button has been pressed.
- */
- private void addFilePressed() {
- setPresentsDefaultValue(false);
- String input = getNewInputObject();
-
- if (input != null) {
- int index = list.getSelectionIndex();
- if (index >= 0) {
- list.add(input, index + 1);
- } else {
- list.add(input, 0);
- }
- selectionChanged();
- }
- }
-
- /**
- * Notifies that the Add button has been pressed.
- */
- private void addDirPressed() {
- setPresentsDefaultValue(false);
- String input = getNewDirInputObject();
-
- if (input != null) {
- int index = list.getSelectionIndex();
- if (index >= 0) {
- list.add(input, index + 1);
- } else {
- list.add(input, 0);
- }
- selectionChanged();
- }
- }
-
- /**
- * Creates the Add, Remove, Up, and Down button in the given button box.
- *
- * @param box
- * the box for the buttons
- */
- private void createButtons(Composite box) {
- addFileButton = createPushButton(box, Messages.MacroProposalsPreferencePage_4);
- addDirButton = createPushButton(box, Messages.MacroProposalsPreferencePage_5);
- removeButton = createPushButton(box, "ListEditor.remove");//$NON-NLS-1$
- upButton = createPushButton(box, "ListEditor.up");//$NON-NLS-1$
- downButton = createPushButton(box, "ListEditor.down");//$NON-NLS-1$
- }
-
- /**
- * Helper method to create a push button.
- *
- * @param parent
- * the parent control
- * @param key
- * the resource name used to supply the button's label text
- * @return Button
- */
- private Button createPushButton(Composite parent, String key) {
- Button button = new Button(parent, SWT.PUSH);
- button.setText(JFaceResources.getString(key));
- button.setFont(parent.getFont());
- GridData data = new GridData(GridData.FILL_HORIZONTAL);
- int widthHint = convertHorizontalDLUsToPixels(button,
- IDialogConstants.BUTTON_WIDTH);
- data.widthHint = Math.max(widthHint, button.computeSize(
- SWT.DEFAULT, SWT.DEFAULT, true).x);
- button.setLayoutData(data);
- button.addSelectionListener(getSelectionListener());
- return button;
- }
-
- /**
- * Creates a selection listener.
- */
- @Override
- public void createSelectionListener() {
- selectionListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- Widget widget = event.widget;
- if (widget == addFileButton) {
- addFilePressed();
- } else if (widget == addDirButton) {
- addDirPressed();
- }else if (widget == removeButton) {
- removePressed();
- } else if (widget == upButton) {
- upPressed();
- } else if (widget == downButton) {
- downPressed();
- } else if (widget == list) {
- selectionChanged();
- }
- }
- };
- }
-
- /**
- * Notifies that the Down button has been pressed.
- */
- private void downPressed() {
- swap(false);
- }
-
- /**
- * Returns this field editor's button box containing the Add, Remove,
- * Up, and Down button.
- *
- * @param parent The parent control
- * @return the button box
- */
- @Override
- public Composite getButtonBoxControl(Composite parent) {
- if (buttonBox == null) {
- buttonBox = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- layout.marginWidth = 0;
- buttonBox.setLayout(layout);
- createButtons(buttonBox);
- buttonBox.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent event) {
- addFileButton = null;
- addDirButton = null;
- removeButton = null;
- upButton = null;
- downButton = null;
- buttonBox = null;
- }
- });
-
- } else {
- checkParent(buttonBox, parent);
- }
-
- selectionChanged();
- return buttonBox;
- }
-
- /**
- * Returns this field editor's list control.
- *
- * @param parent The parent control
- * @return the list control
- */
- @Override
- public final List getListControl(Composite parent) {
- if (list == null) {
- list = new List(parent, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL
- | SWT.H_SCROLL);
- list.setFont(parent.getFont());
- list.addSelectionListener(getSelectionListener());
- list.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent event) {
- list = null;
- }
- });
- } else {
- checkParent(list, parent);
- }
- return list;
- }
-
- /**
- * Returns this field editor's selection listener. The listener is
- * created if nessessary.
- *
- * @return the selection listener
- */
- private SelectionListener getSelectionListener() {
- if (selectionListener == null) {
- createSelectionListener();
- }
- return selectionListener;
- }
-
- /**
- * Returns this field editor's shell.
- * <p>
- * This method is internal to the framework; subclassers should not call
- * this method.
- * </p>
- *
- * @return the shell
- */
- @Override
- protected Shell getShell() {
- if (addFileButton == null) {
- return null;
- }
- return addFileButton.getShell();
- }
-
- /**
- * Notifies that the Remove button has been pressed.
- */
- private void removePressed() {
- setPresentsDefaultValue(false);
- int index = list.getSelectionIndex();
- if (index >= 0) {
- list.remove(index);
- selectionChanged();
- }
- }
-
- /**
- * Notifies that the list selection has changed.
- */
- @Override
- protected void selectionChanged() {
-
- int index = list.getSelectionIndex();
- int size = list.getItemCount();
-
- removeButton.setEnabled(index >= 0);
- upButton.setEnabled(size > 1 && index > 0);
- downButton.setEnabled(size > 1 && index >= 0 && index < size - 1);
- }
-
- /**
- * Moves the currently selected item up or down.
- *
- * @param up
- * <code>true</code> if the item should move up, and
- * <code>false</code> if it should move down
- */
- private void swap(boolean up) {
- setPresentsDefaultValue(false);
- int index = list.getSelectionIndex();
- int target = up ? index - 1 : index + 1;
-
- if (index >= 0) {
- String[] selection = list.getSelection();
- Assert.isTrue(selection.length == 1);
- list.remove(index);
- list.add(selection[0], target);
- list.setSelection(target);
- }
- selectionChanged();
- }
-
- /**
- * Notifies that the Up button has been pressed.
- */
- private void upPressed() {
- swap(true);
- }
-
- /*
- * @see FieldEditor.setEnabled(boolean,Composite).
- */
- @Override
- public void setEnabled(boolean enabled, Composite parent) {
- super.setEnabled(enabled, parent);
- getListControl(parent).setEnabled(enabled);
- addFileButton.setEnabled(enabled);
- addDirButton.setEnabled(enabled);
- removeButton.setEnabled(enabled);
- upButton.setEnabled(enabled);
- downButton.setEnabled(enabled);
- }
-
- }
+ implements IWorkbenchPreferencePage {
+
+ public MacroProposalsPreferencePage() {
+ super(FLAT);
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ }
+
+ @Override
+ protected void createFieldEditors() {
+ ListEditor macroListEditor = new MacroListEditor(
+ PreferenceConstants.P_MACRO_PROPOSALS_FILESPATH,
+ Messages.MacroProposalsPreferencePage_0, getFieldEditorParent());
+ addField(macroListEditor);
+ RadioGroupFieldEditor macroHoverListEditor = new RadioGroupFieldEditor(
+ PreferenceConstants.P_MACRO_HOVER_CONTENT,
+ Messages.MacroProposalsPreferencePage_1,
+ 1,
+ new String[][] {
+ {
+ Messages.MacroProposalsPreferencePage_2,
+ PreferenceConstants.P_MACRO_HOVER_CONTENT_VIEWDESCRIPTION },
+ {
+ Messages.MacroProposalsPreferencePage_3,
+ PreferenceConstants.P_MACRO_HOVER_CONTENT_VIEWCONTENT } },
+ getFieldEditorParent(), true);
+ addField(macroHoverListEditor);
+ }
+
+ static class MacroListEditor extends ListEditor {
+
+ /**
+ * The list widget; <code>null</code> if none (before creation or
+ * after disposal).
+ */
+ private List list;
+
+ /**
+ * The button box containing the Add, Remove, Up, and Down buttons;
+ * <code>null</code> if none (before creation or after disposal).
+ */
+ private Composite buttonBox;
+
+ /**
+ * The Add file button.
+ */
+ private Button addFileButton;
+
+ /**
+ * The Add button.
+ */
+ private Button addDirButton;
+
+ /**
+ * The Remove button.
+ */
+ private Button removeButton;
+
+ /**
+ * The Up button.
+ */
+ private Button upButton;
+
+ /**
+ * The Down button.
+ */
+ private Button downButton;
+
+ /**
+ * The selection listener.
+ */
+ private SelectionListener selectionListener;
+
+ public MacroListEditor(String name, String labelText, Composite parent) {
+ super();
+ init(name, labelText);
+ createControl(parent);
+ list = getListControl(parent);
+ }
+
+ @Override
+ protected String createList(String[] items) {
+ StringBuilder path = new StringBuilder(""); //$NON-NLS-1$
+ for (String item:items) {
+ path.append(item);
+ path.append(";"); //$NON-NLS-1$
+ }
+ return path.toString();
+ }
+
+ @Override
+ protected String getNewInputObject() {
+ FileDialog dialog = new FileDialog(getShell());
+ return dialog.open();
+ }
+
+ protected String getNewDirInputObject() {
+ DirectoryDialog dialog = new DirectoryDialog(getShell());
+ return dialog.open();
+ }
+
+ @Override
+ protected String[] parseString(String stringList) {
+ StringTokenizer st = new StringTokenizer(stringList, ";\n\r"); //$NON-NLS-1$
+ ArrayList<String> v = new ArrayList<>();
+ while (st.hasMoreTokens()) {
+ v.add(st.nextToken());
+ }
+ return v.toArray(new String[v.size()]);
+ }
+
+ /**
+ * Notifies that the Add button has been pressed.
+ */
+ private void addFilePressed() {
+ setPresentsDefaultValue(false);
+ String input = getNewInputObject();
+
+ if (input != null) {
+ int index = list.getSelectionIndex();
+ if (index >= 0) {
+ list.add(input, index + 1);
+ } else {
+ list.add(input, 0);
+ }
+ selectionChanged();
+ }
+ }
+
+ /**
+ * Notifies that the Add button has been pressed.
+ */
+ private void addDirPressed() {
+ setPresentsDefaultValue(false);
+ String input = getNewDirInputObject();
+
+ if (input != null) {
+ int index = list.getSelectionIndex();
+ if (index >= 0) {
+ list.add(input, index + 1);
+ } else {
+ list.add(input, 0);
+ }
+ selectionChanged();
+ }
+ }
+
+ /**
+ * Creates the Add, Remove, Up, and Down button in the given button box.
+ *
+ * @param box
+ * the box for the buttons
+ */
+ private void createButtons(Composite box) {
+ addFileButton = createPushButton(box, Messages.MacroProposalsPreferencePage_4);
+ addDirButton = createPushButton(box, Messages.MacroProposalsPreferencePage_5);
+ removeButton = createPushButton(box, "ListEditor.remove");//$NON-NLS-1$
+ upButton = createPushButton(box, "ListEditor.up");//$NON-NLS-1$
+ downButton = createPushButton(box, "ListEditor.down");//$NON-NLS-1$
+ }
+
+ /**
+ * Helper method to create a push button.
+ *
+ * @param parent
+ * the parent control
+ * @param key
+ * the resource name used to supply the button's label text
+ * @return Button
+ */
+ private Button createPushButton(Composite parent, String key) {
+ Button button = new Button(parent, SWT.PUSH);
+ button.setText(JFaceResources.getString(key));
+ button.setFont(parent.getFont());
+ GridData data = new GridData(GridData.FILL_HORIZONTAL);
+ int widthHint = convertHorizontalDLUsToPixels(button,
+ IDialogConstants.BUTTON_WIDTH);
+ data.widthHint = Math.max(widthHint, button.computeSize(
+ SWT.DEFAULT, SWT.DEFAULT, true).x);
+ button.setLayoutData(data);
+ button.addSelectionListener(getSelectionListener());
+ return button;
+ }
+
+ /**
+ * Creates a selection listener.
+ */
+ @Override
+ public void createSelectionListener() {
+ selectionListener = new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent event) {
+ Widget widget = event.widget;
+ if (widget == addFileButton) {
+ addFilePressed();
+ } else if (widget == addDirButton) {
+ addDirPressed();
+ }else if (widget == removeButton) {
+ removePressed();
+ } else if (widget == upButton) {
+ upPressed();
+ } else if (widget == downButton) {
+ downPressed();
+ } else if (widget == list) {
+ selectionChanged();
+ }
+ }
+ };
+ }
+
+ /**
+ * Notifies that the Down button has been pressed.
+ */
+ private void downPressed() {
+ swap(false);
+ }
+
+ /**
+ * Returns this field editor's button box containing the Add, Remove,
+ * Up, and Down button.
+ *
+ * @param parent The parent control
+ * @return the button box
+ */
+ @Override
+ public Composite getButtonBoxControl(Composite parent) {
+ if (buttonBox == null) {
+ buttonBox = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ layout.marginWidth = 0;
+ buttonBox.setLayout(layout);
+ createButtons(buttonBox);
+ buttonBox.addDisposeListener(new DisposeListener() {
+ @Override
+ public void widgetDisposed(DisposeEvent event) {
+ addFileButton = null;
+ addDirButton = null;
+ removeButton = null;
+ upButton = null;
+ downButton = null;
+ buttonBox = null;
+ }
+ });
+
+ } else {
+ checkParent(buttonBox, parent);
+ }
+
+ selectionChanged();
+ return buttonBox;
+ }
+
+ /**
+ * Returns this field editor's list control.
+ *
+ * @param parent The parent control
+ * @return the list control
+ */
+ @Override
+ public final List getListControl(Composite parent) {
+ if (list == null) {
+ list = new List(parent, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL
+ | SWT.H_SCROLL);
+ list.setFont(parent.getFont());
+ list.addSelectionListener(getSelectionListener());
+ list.addDisposeListener(new DisposeListener() {
+ @Override
+ public void widgetDisposed(DisposeEvent event) {
+ list = null;
+ }
+ });
+ } else {
+ checkParent(list, parent);
+ }
+ return list;
+ }
+
+ /**
+ * Returns this field editor's selection listener. The listener is
+ * created if nessessary.
+ *
+ * @return the selection listener
+ */
+ private SelectionListener getSelectionListener() {
+ if (selectionListener == null) {
+ createSelectionListener();
+ }
+ return selectionListener;
+ }
+
+ /**
+ * Returns this field editor's shell.
+ * <p>
+ * This method is internal to the framework; subclassers should not call
+ * this method.
+ * </p>
+ *
+ * @return the shell
+ */
+ @Override
+ protected Shell getShell() {
+ if (addFileButton == null) {
+ return null;
+ }
+ return addFileButton.getShell();
+ }
+
+ /**
+ * Notifies that the Remove button has been pressed.
+ */
+ private void removePressed() {
+ setPresentsDefaultValue(false);
+ int index = list.getSelectionIndex();
+ if (index >= 0) {
+ list.remove(index);
+ selectionChanged();
+ }
+ }
+
+ /**
+ * Notifies that the list selection has changed.
+ */
+ @Override
+ protected void selectionChanged() {
+
+ int index = list.getSelectionIndex();
+ int size = list.getItemCount();
+
+ removeButton.setEnabled(index >= 0);
+ upButton.setEnabled(size > 1 && index > 0);
+ downButton.setEnabled(size > 1 && index >= 0 && index < size - 1);
+ }
+
+ /**
+ * Moves the currently selected item up or down.
+ *
+ * @param up
+ * <code>true</code> if the item should move up, and
+ * <code>false</code> if it should move down
+ */
+ private void swap(boolean up) {
+ setPresentsDefaultValue(false);
+ int index = list.getSelectionIndex();
+ int target = up ? index - 1 : index + 1;
+
+ if (index >= 0) {
+ String[] selection = list.getSelection();
+ Assert.isTrue(selection.length == 1);
+ list.remove(index);
+ list.add(selection[0], target);
+ list.setSelection(target);
+ }
+ selectionChanged();
+ }
+
+ /**
+ * Notifies that the Up button has been pressed.
+ */
+ private void upPressed() {
+ swap(true);
+ }
+
+ /*
+ * @see FieldEditor.setEnabled(boolean,Composite).
+ */
+ @Override
+ public void setEnabled(boolean enabled, Composite parent) {
+ super.setEnabled(enabled, parent);
+ getListControl(parent).setEnabled(enabled);
+ addFileButton.setEnabled(enabled);
+ addDirButton.setEnabled(enabled);
+ removeButton.setEnabled(enabled);
+ upButton.setEnabled(enabled);
+ downButton.setEnabled(enabled);
+ }
+
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/MainPreferencePage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/MainPreferencePage.java
index 6c358a7ef1..93139596fd 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/MainPreferencePage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/MainPreferencePage.java
@@ -37,109 +37,109 @@ import org.eclipse.ui.dialogs.PreferencesUtil;
*
*/
public class MainPreferencePage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
-
- private Combo combo;
-
- private int defaultItem;
-
- /**
- * default constructor
- */
- public MainPreferencePage() {
- super(GRID);
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- }
-
- private FieldEditor changelogEntryFormatFieldEditor(Composite parent) {
- RadioGroupFieldEditor changelogEntryFormatRadioGroupEditor = new RadioGroupFieldEditor(
- PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT,
- Messages.MainPreferencePage_2, 1, new String[][] {
- { Messages.MainPreferencePage_3, PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT_VERSIONED },
- { Messages.MainPreferencePage_4, PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT_VERSIONED_WITH_SEPARATOR},
- { Messages.MainPreferencePage_5, PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT_UNVERSIONED }}, parent, true);
- return changelogEntryFormatRadioGroupEditor;
- }
-
- private void createLocalesCombo(Composite parent) {
- combo = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY |SWT.BEGINNING);
- // populate the combo with all ISO countries
- int selectedItem = 0;
- String lastLocale = getPreferenceStore().getString(PreferenceConstants.P_CHANGELOG_LOCAL);
- String[] countries = Locale.getISOCountries();
- for (int i = 0; i < countries.length; i++) {
- Locale currentLocale = new Locale(countries[i]);
- combo.add(countries[i] + " - " + currentLocale.getDisplayLanguage()); //$NON-NLS-1$
- // get index of the Locale store in the preferences
- if (countries[i].equals(lastLocale)) {
- selectedItem = i;
- }
- // get the index of the default Locale
- if (countries[i].equals(PreferenceConstants.DP_CHANGELOG_LOCAL)) {
- defaultItem = i;
- }
- }
- combo.select(selectedItem);
- // update preferences
- combo.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- Combo combo = (Combo) e.getSource();
- getPreferenceStore().setValue(
- PreferenceConstants.P_CHANGELOG_LOCAL,
- combo.getText().split("-")[0].trim()); //$NON-NLS-1$
- }
- });
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors()
- */
- @Override
- public void createFieldEditors() {
- GridData data = new GridData();
- data.horizontalSpan = 2;
- final Composite parent = getFieldEditorParent();
- Link link= new Link(parent, SWT.NONE);
- link.setText(Messages.MainPreferencePage_0);
- link.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(parent.getShell() , e.text, null, null);
- }
- });
- addField(changelogEntryFormatFieldEditor(parent));
- Label labelLocal = new Label(parent, SWT.NONE);
- labelLocal.setText(Messages.MainPreferencePage_1);
-
- labelLocal.setLayoutData(data);
- createLocalesCombo(parent);
- addField(new BooleanFieldEditor(PreferenceConstants.P_SPACES_FOR_TABS,
- Messages.MainPreferencePage_6, parent));
- Composite numEditorComp = new Composite(parent, SWT.NONE);
- IntegerFieldEditor numEditor = new IntegerFieldEditor(
- PreferenceConstants.P_NBR_OF_SPACES_FOR_TAB,
- Messages.MainPreferencePage_7, numEditorComp, 1);
- addField(numEditor);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- @Override
- public void init(IWorkbench workbench) {
-
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.FieldEditorPreferencePage#performDefaults()
- */
- @Override
- protected void performDefaults() {
- super.performDefaults();
- combo.select(defaultItem);
- getPreferenceStore().setValue(PreferenceConstants.P_CHANGELOG_LOCAL, PreferenceConstants.DP_CHANGELOG_LOCAL);
- getPreferenceStore().setValue(PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT, PreferenceConstants.DP_CHANGELOG_ENTRY_FORMAT);
- }
+ IWorkbenchPreferencePage {
+
+ private Combo combo;
+
+ private int defaultItem;
+
+ /**
+ * default constructor
+ */
+ public MainPreferencePage() {
+ super(GRID);
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ }
+
+ private FieldEditor changelogEntryFormatFieldEditor(Composite parent) {
+ RadioGroupFieldEditor changelogEntryFormatRadioGroupEditor = new RadioGroupFieldEditor(
+ PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT,
+ Messages.MainPreferencePage_2, 1, new String[][] {
+ { Messages.MainPreferencePage_3, PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT_VERSIONED },
+ { Messages.MainPreferencePage_4, PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT_VERSIONED_WITH_SEPARATOR},
+ { Messages.MainPreferencePage_5, PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT_UNVERSIONED }}, parent, true);
+ return changelogEntryFormatRadioGroupEditor;
+ }
+
+ private void createLocalesCombo(Composite parent) {
+ combo = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY |SWT.BEGINNING);
+ // populate the combo with all ISO countries
+ int selectedItem = 0;
+ String lastLocale = getPreferenceStore().getString(PreferenceConstants.P_CHANGELOG_LOCAL);
+ String[] countries = Locale.getISOCountries();
+ for (int i = 0; i < countries.length; i++) {
+ Locale currentLocale = new Locale(countries[i]);
+ combo.add(countries[i] + " - " + currentLocale.getDisplayLanguage()); //$NON-NLS-1$
+ // get index of the Locale store in the preferences
+ if (countries[i].equals(lastLocale)) {
+ selectedItem = i;
+ }
+ // get the index of the default Locale
+ if (countries[i].equals(PreferenceConstants.DP_CHANGELOG_LOCAL)) {
+ defaultItem = i;
+ }
+ }
+ combo.select(selectedItem);
+ // update preferences
+ combo.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ Combo combo = (Combo) e.getSource();
+ getPreferenceStore().setValue(
+ PreferenceConstants.P_CHANGELOG_LOCAL,
+ combo.getText().split("-")[0].trim()); //$NON-NLS-1$
+ }
+ });
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors()
+ */
+ @Override
+ public void createFieldEditors() {
+ GridData data = new GridData();
+ data.horizontalSpan = 2;
+ final Composite parent = getFieldEditorParent();
+ Link link= new Link(parent, SWT.NONE);
+ link.setText(Messages.MainPreferencePage_0);
+ link.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ PreferencesUtil.createPreferenceDialogOn(parent.getShell() , e.text, null, null);
+ }
+ });
+ addField(changelogEntryFormatFieldEditor(parent));
+ Label labelLocal = new Label(parent, SWT.NONE);
+ labelLocal.setText(Messages.MainPreferencePage_1);
+
+ labelLocal.setLayoutData(data);
+ createLocalesCombo(parent);
+ addField(new BooleanFieldEditor(PreferenceConstants.P_SPACES_FOR_TABS,
+ Messages.MainPreferencePage_6, parent));
+ Composite numEditorComp = new Composite(parent, SWT.NONE);
+ IntegerFieldEditor numEditor = new IntegerFieldEditor(
+ PreferenceConstants.P_NBR_OF_SPACES_FOR_TAB,
+ Messages.MainPreferencePage_7, numEditorComp, 1);
+ addField(numEditor);
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
+ */
+ @Override
+ public void init(IWorkbench workbench) {
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.preference.FieldEditorPreferencePage#performDefaults()
+ */
+ @Override
+ protected void performDefaults() {
+ super.performDefaults();
+ combo.select(defaultItem);
+ getPreferenceStore().setValue(PreferenceConstants.P_CHANGELOG_LOCAL, PreferenceConstants.DP_CHANGELOG_LOCAL);
+ getPreferenceStore().setValue(PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT, PreferenceConstants.DP_CHANGELOG_ENTRY_FORMAT);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/Messages.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/Messages.java
index f2d8d3f774..6677564016 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/Messages.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -13,49 +13,49 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.preferences;
import org.eclipse.osgi.util.NLS;
public final class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.preferences.messages"; //$NON-NLS-1$
- public static String MacroProposalsPreferencePage_0;
- public static String MacroProposalsPreferencePage_1;
- public static String MacroProposalsPreferencePage_2;
- public static String MacroProposalsPreferencePage_3;
- public static String MacroProposalsPreferencePage_4;
- public static String MacroProposalsPreferencePage_5;
- public static String MainPreferencePage_0;
- public static String MainPreferencePage_1;
- public static String MainPreferencePage_2;
- public static String MainPreferencePage_3;
- public static String MainPreferencePage_4;
- public static String MainPreferencePage_5;
- public static String MainPreferencePage_6;
- public static String MainPreferencePage_7;
- public static String RpmInformationsPreferencePage_0;
- public static String RpmInformationsPreferencePage_1;
- public static String RpmInformationsPreferencePage_2;
- public static String RpmInformationsPreferencePage_3;
- public static String RpmInformationsPreferencePage_4;
- public static String RpmInformationsPreferencePage_5;
- public static String RpmInformationsPreferencePage_6;
- public static String RpmInformationsPreferencePage_7;
- public static String RpmProposalsPreferencePage_0;
- public static String RpmProposalsPreferencePage_1;
- public static String RpmProposalsPreferencePage_10;
- public static String RpmProposalsPreferencePage_12;
- public static String RpmProposalsPreferencePage_2;
- public static String RpmProposalsPreferencePage_3;
- public static String RpmProposalsPreferencePage_4;
- public static String RpmProposalsPreferencePage_5;
- public static String RpmProposalsPreferencePage_6;
- public static String RpmProposalsPreferencePage_7;
- public static String RpmProposalsPreferencePage_8;
- public static String TaskTagsPreferencePage_0;
- public static String TaskTagsPreferencePage_1;
- public static String TaskTagsPreferencePage_2;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.editor.preferences.messages"; //$NON-NLS-1$
+ public static String MacroProposalsPreferencePage_0;
+ public static String MacroProposalsPreferencePage_1;
+ public static String MacroProposalsPreferencePage_2;
+ public static String MacroProposalsPreferencePage_3;
+ public static String MacroProposalsPreferencePage_4;
+ public static String MacroProposalsPreferencePage_5;
+ public static String MainPreferencePage_0;
+ public static String MainPreferencePage_1;
+ public static String MainPreferencePage_2;
+ public static String MainPreferencePage_3;
+ public static String MainPreferencePage_4;
+ public static String MainPreferencePage_5;
+ public static String MainPreferencePage_6;
+ public static String MainPreferencePage_7;
+ public static String RpmInformationsPreferencePage_0;
+ public static String RpmInformationsPreferencePage_1;
+ public static String RpmInformationsPreferencePage_2;
+ public static String RpmInformationsPreferencePage_3;
+ public static String RpmInformationsPreferencePage_4;
+ public static String RpmInformationsPreferencePage_5;
+ public static String RpmInformationsPreferencePage_6;
+ public static String RpmInformationsPreferencePage_7;
+ public static String RpmProposalsPreferencePage_0;
+ public static String RpmProposalsPreferencePage_1;
+ public static String RpmProposalsPreferencePage_10;
+ public static String RpmProposalsPreferencePage_12;
+ public static String RpmProposalsPreferencePage_2;
+ public static String RpmProposalsPreferencePage_3;
+ public static String RpmProposalsPreferencePage_4;
+ public static String RpmProposalsPreferencePage_5;
+ public static String RpmProposalsPreferencePage_6;
+ public static String RpmProposalsPreferencePage_7;
+ public static String RpmProposalsPreferencePage_8;
+ public static String TaskTagsPreferencePage_0;
+ public static String TaskTagsPreferencePage_1;
+ public static String TaskTagsPreferencePage_2;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- super();
- }
+ private Messages() {
+ super();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/PreferenceConstants.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/PreferenceConstants.java
index b92ed9e65d..52f245882c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/PreferenceConstants.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/PreferenceConstants.java
@@ -16,101 +16,101 @@ package org.eclipse.linuxtools.internal.rpm.ui.editor.preferences;
*/
public final class PreferenceConstants {
- /*
- * Other Constant
- */
- public static final String RPMMACRO_FILE = System.getProperty("user.home") + "/.rpmmacros"; //$NON-NLS-1$//$NON-NLS-2$
+ /*
+ * Other Constant
+ */
+ public static final String RPMMACRO_FILE = System.getProperty("user.home") + "/.rpmmacros"; //$NON-NLS-1$//$NON-NLS-2$
- /*
- * Prefences keys
- */
+ /*
+ * Prefences keys
+ */
- // rpm list builder
- public static final String P_RPM_LIST_FILEPATH = "rpmListFilePath"; //$NON-NLS-1$
- public static final String P_RPM_LIST_MAX_PROPOSALS = "rpmListMaxProposalsInfo"; //$NON-NLS-1$
- public static final String P_CURRENT_RPMTOOLS = "currentRpmtools"; //$NON-NLS-1$
- public static final String P_RPM_LIST_BACKGROUND_BUILD = "rpmListBackgroundBuild"; //$NON-NLS-1$
- public static final String P_RPM_LIST_BUILD_PERIOD = "rpmListBuildPeriod"; //$NON-NLS-1$
- public static final String P_RPM_LIST_LAST_BUILD = "rpmLisMastBuild"; //$NON-NLS-1$
- // macro
- public static final String P_MACRO_PROPOSALS_FILESPATH = "macroProposalsFilespath"; //$NON-NLS-1$
- public static final String P_MACRO_HOVER_CONTENT_VIEWCONTENT = "macroHoverViewContent"; //$NON-NLS-1$
- public static final String P_MACRO_HOVER_CONTENT_VIEWDESCRIPTION = "macroHoverViewDescription"; //$NON-NLS-1$
- public static final String P_MACRO_HOVER_CONTENT = P_MACRO_HOVER_CONTENT_VIEWCONTENT;
- // changelog
- public static final String P_CHANGELOG_LOCAL = "changelogLocal"; //$NON-NLS-1$
+ // rpm list builder
+ public static final String P_RPM_LIST_FILEPATH = "rpmListFilePath"; //$NON-NLS-1$
+ public static final String P_RPM_LIST_MAX_PROPOSALS = "rpmListMaxProposalsInfo"; //$NON-NLS-1$
+ public static final String P_CURRENT_RPMTOOLS = "currentRpmtools"; //$NON-NLS-1$
+ public static final String P_RPM_LIST_BACKGROUND_BUILD = "rpmListBackgroundBuild"; //$NON-NLS-1$
+ public static final String P_RPM_LIST_BUILD_PERIOD = "rpmListBuildPeriod"; //$NON-NLS-1$
+ public static final String P_RPM_LIST_LAST_BUILD = "rpmLisMastBuild"; //$NON-NLS-1$
+ // macro
+ public static final String P_MACRO_PROPOSALS_FILESPATH = "macroProposalsFilespath"; //$NON-NLS-1$
+ public static final String P_MACRO_HOVER_CONTENT_VIEWCONTENT = "macroHoverViewContent"; //$NON-NLS-1$
+ public static final String P_MACRO_HOVER_CONTENT_VIEWDESCRIPTION = "macroHoverViewDescription"; //$NON-NLS-1$
+ public static final String P_MACRO_HOVER_CONTENT = P_MACRO_HOVER_CONTENT_VIEWCONTENT;
+ // changelog
+ public static final String P_CHANGELOG_LOCAL = "changelogLocal"; //$NON-NLS-1$
- public static final String P_CHANGELOG_ENTRY_FORMAT = "changelogEntryFormat"; //$NON-NLS-1$
- public static final String P_CHANGELOG_ENTRY_FORMAT_VERSIONED = "1"; //$NON-NLS-1$
- public static final String P_CHANGELOG_ENTRY_FORMAT_VERSIONED_WITH_SEPARATOR = "2"; //$NON-NLS-1$
- public static final String P_CHANGELOG_ENTRY_FORMAT_UNVERSIONED = "3"; //$NON-NLS-1$
+ public static final String P_CHANGELOG_ENTRY_FORMAT = "changelogEntryFormat"; //$NON-NLS-1$
+ public static final String P_CHANGELOG_ENTRY_FORMAT_VERSIONED = "1"; //$NON-NLS-1$
+ public static final String P_CHANGELOG_ENTRY_FORMAT_VERSIONED_WITH_SEPARATOR = "2"; //$NON-NLS-1$
+ public static final String P_CHANGELOG_ENTRY_FORMAT_UNVERSIONED = "3"; //$NON-NLS-1$
- // RPM informations
- public static final String P_RPMINFO_NAME = "RpmInfoName"; //$NON-NLS-1$
- public static final String P_RPMINFO_VERSION = "RpmInfoVersion"; //$NON-NLS-1$
- public static final String P_RPMINFO_RELEASE = "RpmInfoRelease"; //$NON-NLS-1$
- public static final String P_RPMINFO_SUMMARY = "RpmInfoSummary"; //$NON-NLS-1$
- public static final String P_RPMINFO_LICENSE = "RpmInfoLicense"; //$NON-NLS-1$
- public static final String P_RPMINFO_GROUP = "RpmInfoName"; //$NON-NLS-1$
- public static final String P_RPMINFO_URL = "RpmInfoUrl"; //$NON-NLS-1$
- public static final String P_RPMINFO_DESCRIPTION = "RpmInfoDescription"; //$NON-NLS-1$
- public static final String P_RPMINFO_INSTALLTIME = "RpmInfoInstallDate"; //$NON-NLS-1$
- public static final String P_RPMINFO_SIZE = "RpmInfoSize"; //$NON-NLS-1$
- public static final String P_RPMINFO_PACKAGER = "RpmInfoPackager"; //$NON-NLS-1$
- public static final String P_RPMINFO_VENDOR = "RpmInfoVendor"; //$NON-NLS-1$
- public static final String P_RPMINFO_BUILDTIME = "RpmInfoBuildDate"; //$NON-NLS-1$
- public static final String P_RPMINFO_SOURCERPM = "RpmInfoSourceRpm"; //$NON-NLS-1$
- public static final String P_TASK_TAGS = "RpmSpecTaskTags"; //$NON-NLS-1$
- // Convert tab by spaces
- public static final String P_SPACES_FOR_TABS = "SpacesForTabs"; //$NON-NLS-1$
- public static final String P_NBR_OF_SPACES_FOR_TAB = "NbrOfSpacesForTab"; //$NON-NLS-1$
+ // RPM informations
+ public static final String P_RPMINFO_NAME = "RpmInfoName"; //$NON-NLS-1$
+ public static final String P_RPMINFO_VERSION = "RpmInfoVersion"; //$NON-NLS-1$
+ public static final String P_RPMINFO_RELEASE = "RpmInfoRelease"; //$NON-NLS-1$
+ public static final String P_RPMINFO_SUMMARY = "RpmInfoSummary"; //$NON-NLS-1$
+ public static final String P_RPMINFO_LICENSE = "RpmInfoLicense"; //$NON-NLS-1$
+ public static final String P_RPMINFO_GROUP = "RpmInfoName"; //$NON-NLS-1$
+ public static final String P_RPMINFO_URL = "RpmInfoUrl"; //$NON-NLS-1$
+ public static final String P_RPMINFO_DESCRIPTION = "RpmInfoDescription"; //$NON-NLS-1$
+ public static final String P_RPMINFO_INSTALLTIME = "RpmInfoInstallDate"; //$NON-NLS-1$
+ public static final String P_RPMINFO_SIZE = "RpmInfoSize"; //$NON-NLS-1$
+ public static final String P_RPMINFO_PACKAGER = "RpmInfoPackager"; //$NON-NLS-1$
+ public static final String P_RPMINFO_VENDOR = "RpmInfoVendor"; //$NON-NLS-1$
+ public static final String P_RPMINFO_BUILDTIME = "RpmInfoBuildDate"; //$NON-NLS-1$
+ public static final String P_RPMINFO_SOURCERPM = "RpmInfoSourceRpm"; //$NON-NLS-1$
+ public static final String P_TASK_TAGS = "RpmSpecTaskTags"; //$NON-NLS-1$
+ // Convert tab by spaces
+ public static final String P_SPACES_FOR_TABS = "SpacesForTabs"; //$NON-NLS-1$
+ public static final String P_NBR_OF_SPACES_FOR_TAB = "NbrOfSpacesForTab"; //$NON-NLS-1$
- /*
- * Preferences default values
- */
+ /*
+ * Preferences default values
+ */
- public static final String DP_RPM_LIST_FILEPATH = System
- .getProperty("user.home") + System.getProperty("file.separator") + ".pkglist"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- public static final String DP_RPM_LIST_MAX_PROPOSALS = "10"; //$NON-NLS-1$
- public static final String DP_RPMTOOLS_RPM = "rpm -qa --qf '%{NAME}\\n'"; //$NON-NLS-1$
- public static final String DP_RPMTOOLS_YUM = "yum -C list all | grep - | cut -d \".\" -f 1"; //$NON-NLS-1$
- public static final String DP_RPMTOOLS_URPM = "urpmq --list"; //$NON-NLS-1$
- public static final boolean DP_RPM_LIST_BACKGROUND_BUILD = true;
- public static final int DP_RPM_LIST_BUILD_PERIOD = 1;
+ public static final String DP_RPM_LIST_FILEPATH = System
+ .getProperty("user.home") + System.getProperty("file.separator") + ".pkglist"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ public static final String DP_RPM_LIST_MAX_PROPOSALS = "10"; //$NON-NLS-1$
+ public static final String DP_RPMTOOLS_RPM = "rpm -qa --qf '%{NAME}\\n'"; //$NON-NLS-1$
+ public static final String DP_RPMTOOLS_YUM = "yum -C list all | grep - | cut -d \".\" -f 1"; //$NON-NLS-1$
+ public static final String DP_RPMTOOLS_URPM = "urpmq --list"; //$NON-NLS-1$
+ public static final boolean DP_RPM_LIST_BACKGROUND_BUILD = true;
+ public static final int DP_RPM_LIST_BUILD_PERIOD = 1;
- // macro
- public static final String DP_MACRO_PROPOSALS_FILESPATH = RPMMACRO_FILE
- + ";/usr/lib/rpm/macros;/etc/rpm"; //$NON-NLS-1$
- // changelog
- public static final String DP_CHANGELOG_LOCAL = "US"; //$NON-NLS-1$
- public static final String DP_CHANGELOG_ENTRY_FORMAT = P_CHANGELOG_ENTRY_FORMAT_VERSIONED;
- // task tags
- public static final String DP_TASK_TAGS = "TODO;FIXME"; //$NON-NLS-1$
+ // macro
+ public static final String DP_MACRO_PROPOSALS_FILESPATH = RPMMACRO_FILE
+ + ";/usr/lib/rpm/macros;/etc/rpm"; //$NON-NLS-1$
+ // changelog
+ public static final String DP_CHANGELOG_LOCAL = "US"; //$NON-NLS-1$
+ public static final String DP_CHANGELOG_ENTRY_FORMAT = P_CHANGELOG_ENTRY_FORMAT_VERSIONED;
+ // task tags
+ public static final String DP_TASK_TAGS = "TODO;FIXME"; //$NON-NLS-1$
- // Convert tab by spaces
- public static final boolean DP_SPACES_FOR_TABS = false;
- public static final String DP_NBR_OF_SPACES_FOR_TAB = "4"; //$NON-NLS-1$
+ // Convert tab by spaces
+ public static final boolean DP_SPACES_FOR_TABS = false;
+ public static final String DP_NBR_OF_SPACES_FOR_TAB = "4"; //$NON-NLS-1$
- // RPM informations
- public static final boolean DP_RPMINFO_NAME = true;
- public static final boolean DP_RPMINFO_VERSION = true;
- public static final boolean DP_RPMINFO_RELEASE = true;
- public static final boolean DP_RPMINFO_SUMMARY = true;
- public static final boolean DP_RPMINFO_LICENSE = true;
- public static final boolean DP_RPMINFO_GROUP = true;
- public static final boolean DP_RPMINFO_URL = true;
- public static final boolean DP_RPMINFO_DESCRIPTION = false;
- public static final boolean DP_RPMINFO_INSTALLTIME = true;
- public static final boolean DP_RPMINFO_SIZE = true;
- public static final boolean DP_RPMINFO_PACKAGER = false;
- public static final boolean DP_RPMINFO_VENDOR = true;
- public static final boolean DP_RPMINFO_BUILDTIME = true;
- public static final boolean DP_RPMINFO_SOURCERPM = true;
+ // RPM informations
+ public static final boolean DP_RPMINFO_NAME = true;
+ public static final boolean DP_RPMINFO_VERSION = true;
+ public static final boolean DP_RPMINFO_RELEASE = true;
+ public static final boolean DP_RPMINFO_SUMMARY = true;
+ public static final boolean DP_RPMINFO_LICENSE = true;
+ public static final boolean DP_RPMINFO_GROUP = true;
+ public static final boolean DP_RPMINFO_URL = true;
+ public static final boolean DP_RPMINFO_DESCRIPTION = false;
+ public static final boolean DP_RPMINFO_INSTALLTIME = true;
+ public static final boolean DP_RPMINFO_SIZE = true;
+ public static final boolean DP_RPMINFO_PACKAGER = false;
+ public static final boolean DP_RPMINFO_VENDOR = true;
+ public static final boolean DP_RPMINFO_BUILDTIME = true;
+ public static final boolean DP_RPMINFO_SOURCERPM = true;
- public static final long DP_RPM_LIST_LAST_BUILD = 0;
+ public static final long DP_RPM_LIST_LAST_BUILD = 0;
- private PreferenceConstants(){
- super();
- }
+ private PreferenceConstants(){
+ super();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/PreferenceInitializer.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/PreferenceInitializer.java
index c3b0c18d8c..b35079e5c9 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/PreferenceInitializer.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/PreferenceInitializer.java
@@ -20,69 +20,69 @@ import org.eclipse.linuxtools.internal.rpm.ui.editor.Activator;
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
- /*
- * (non-Javadoc)
- *
- * @seeorg.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#
- * initializeDefaultPreferences()
- */
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = Activator.getDefault().getPreferenceStore();
- store.setDefault(PreferenceConstants.P_CURRENT_RPMTOOLS,
- PreferenceConstants.DP_RPMTOOLS_RPM);
- store.setDefault(PreferenceConstants.P_RPM_LIST_FILEPATH,
- PreferenceConstants.DP_RPM_LIST_FILEPATH);
- store.setDefault(PreferenceConstants.P_RPM_LIST_MAX_PROPOSALS,
- PreferenceConstants.DP_RPM_LIST_MAX_PROPOSALS);
- store.setDefault(PreferenceConstants.P_RPM_LIST_BACKGROUND_BUILD,
- PreferenceConstants.DP_RPM_LIST_BACKGROUND_BUILD);
- store.setDefault(PreferenceConstants.P_RPM_LIST_BUILD_PERIOD,
- PreferenceConstants.DP_RPM_LIST_BUILD_PERIOD);
- store.setDefault(PreferenceConstants.P_MACRO_PROPOSALS_FILESPATH,
- PreferenceConstants.DP_MACRO_PROPOSALS_FILESPATH);
- store.setDefault(PreferenceConstants.P_CHANGELOG_LOCAL,
- PreferenceConstants.DP_CHANGELOG_LOCAL);
- store.setDefault(PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT,
- PreferenceConstants.DP_CHANGELOG_ENTRY_FORMAT);
- store.setDefault(PreferenceConstants.P_MACRO_HOVER_CONTENT,
- PreferenceConstants.P_MACRO_HOVER_CONTENT_VIEWDESCRIPTION);
- store.setDefault(PreferenceConstants.P_RPMINFO_NAME,
- PreferenceConstants.DP_RPMINFO_NAME);
- store.setDefault(PreferenceConstants.P_RPMINFO_VERSION,
- PreferenceConstants.DP_RPMINFO_VERSION);
- store.setDefault(PreferenceConstants.P_RPMINFO_RELEASE,
- PreferenceConstants.DP_RPMINFO_RELEASE);
- store.setDefault(PreferenceConstants.P_RPMINFO_SUMMARY,
- PreferenceConstants.DP_RPMINFO_SUMMARY);
- store.setDefault(PreferenceConstants.P_RPMINFO_LICENSE,
- PreferenceConstants.DP_RPMINFO_LICENSE);
- store.setDefault(PreferenceConstants.P_RPMINFO_GROUP,
- PreferenceConstants.DP_RPMINFO_GROUP);
- store.setDefault(PreferenceConstants.P_RPMINFO_URL,
- PreferenceConstants.DP_RPMINFO_URL);
- store.setDefault(PreferenceConstants.P_RPMINFO_DESCRIPTION,
- PreferenceConstants.DP_RPMINFO_DESCRIPTION);
- store.setDefault(PreferenceConstants.P_RPMINFO_INSTALLTIME,
- PreferenceConstants.DP_RPMINFO_INSTALLTIME);
- store.setDefault(PreferenceConstants.P_RPMINFO_SIZE,
- PreferenceConstants.DP_RPMINFO_SIZE);
- store.setDefault(PreferenceConstants.P_RPMINFO_PACKAGER,
- PreferenceConstants.DP_RPMINFO_PACKAGER);
- store.setDefault(PreferenceConstants.P_RPMINFO_VENDOR,
- PreferenceConstants.DP_RPMINFO_VENDOR);
- store.setDefault(PreferenceConstants.P_RPMINFO_BUILDTIME,
- PreferenceConstants.DP_RPMINFO_BUILDTIME);
- store.setDefault(PreferenceConstants.P_RPMINFO_SOURCERPM,
- PreferenceConstants.DP_RPMINFO_SOURCERPM);
- store.setDefault(PreferenceConstants.P_TASK_TAGS,
- PreferenceConstants.DP_TASK_TAGS);
- // Convert tab by spaces
- store.setDefault(PreferenceConstants.P_SPACES_FOR_TABS,
- PreferenceConstants.DP_SPACES_FOR_TABS);
- store.setDefault(PreferenceConstants.P_NBR_OF_SPACES_FOR_TAB,
- PreferenceConstants.DP_NBR_OF_SPACES_FOR_TAB);
+ /*
+ * (non-Javadoc)
+ *
+ * @seeorg.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#
+ * initializeDefaultPreferences()
+ */
+ @Override
+ public void initializeDefaultPreferences() {
+ IPreferenceStore store = Activator.getDefault().getPreferenceStore();
+ store.setDefault(PreferenceConstants.P_CURRENT_RPMTOOLS,
+ PreferenceConstants.DP_RPMTOOLS_RPM);
+ store.setDefault(PreferenceConstants.P_RPM_LIST_FILEPATH,
+ PreferenceConstants.DP_RPM_LIST_FILEPATH);
+ store.setDefault(PreferenceConstants.P_RPM_LIST_MAX_PROPOSALS,
+ PreferenceConstants.DP_RPM_LIST_MAX_PROPOSALS);
+ store.setDefault(PreferenceConstants.P_RPM_LIST_BACKGROUND_BUILD,
+ PreferenceConstants.DP_RPM_LIST_BACKGROUND_BUILD);
+ store.setDefault(PreferenceConstants.P_RPM_LIST_BUILD_PERIOD,
+ PreferenceConstants.DP_RPM_LIST_BUILD_PERIOD);
+ store.setDefault(PreferenceConstants.P_MACRO_PROPOSALS_FILESPATH,
+ PreferenceConstants.DP_MACRO_PROPOSALS_FILESPATH);
+ store.setDefault(PreferenceConstants.P_CHANGELOG_LOCAL,
+ PreferenceConstants.DP_CHANGELOG_LOCAL);
+ store.setDefault(PreferenceConstants.P_CHANGELOG_ENTRY_FORMAT,
+ PreferenceConstants.DP_CHANGELOG_ENTRY_FORMAT);
+ store.setDefault(PreferenceConstants.P_MACRO_HOVER_CONTENT,
+ PreferenceConstants.P_MACRO_HOVER_CONTENT_VIEWDESCRIPTION);
+ store.setDefault(PreferenceConstants.P_RPMINFO_NAME,
+ PreferenceConstants.DP_RPMINFO_NAME);
+ store.setDefault(PreferenceConstants.P_RPMINFO_VERSION,
+ PreferenceConstants.DP_RPMINFO_VERSION);
+ store.setDefault(PreferenceConstants.P_RPMINFO_RELEASE,
+ PreferenceConstants.DP_RPMINFO_RELEASE);
+ store.setDefault(PreferenceConstants.P_RPMINFO_SUMMARY,
+ PreferenceConstants.DP_RPMINFO_SUMMARY);
+ store.setDefault(PreferenceConstants.P_RPMINFO_LICENSE,
+ PreferenceConstants.DP_RPMINFO_LICENSE);
+ store.setDefault(PreferenceConstants.P_RPMINFO_GROUP,
+ PreferenceConstants.DP_RPMINFO_GROUP);
+ store.setDefault(PreferenceConstants.P_RPMINFO_URL,
+ PreferenceConstants.DP_RPMINFO_URL);
+ store.setDefault(PreferenceConstants.P_RPMINFO_DESCRIPTION,
+ PreferenceConstants.DP_RPMINFO_DESCRIPTION);
+ store.setDefault(PreferenceConstants.P_RPMINFO_INSTALLTIME,
+ PreferenceConstants.DP_RPMINFO_INSTALLTIME);
+ store.setDefault(PreferenceConstants.P_RPMINFO_SIZE,
+ PreferenceConstants.DP_RPMINFO_SIZE);
+ store.setDefault(PreferenceConstants.P_RPMINFO_PACKAGER,
+ PreferenceConstants.DP_RPMINFO_PACKAGER);
+ store.setDefault(PreferenceConstants.P_RPMINFO_VENDOR,
+ PreferenceConstants.DP_RPMINFO_VENDOR);
+ store.setDefault(PreferenceConstants.P_RPMINFO_BUILDTIME,
+ PreferenceConstants.DP_RPMINFO_BUILDTIME);
+ store.setDefault(PreferenceConstants.P_RPMINFO_SOURCERPM,
+ PreferenceConstants.DP_RPMINFO_SOURCERPM);
+ store.setDefault(PreferenceConstants.P_TASK_TAGS,
+ PreferenceConstants.DP_TASK_TAGS);
+ // Convert tab by spaces
+ store.setDefault(PreferenceConstants.P_SPACES_FOR_TABS,
+ PreferenceConstants.DP_SPACES_FOR_TABS);
+ store.setDefault(PreferenceConstants.P_NBR_OF_SPACES_FOR_TAB,
+ PreferenceConstants.DP_NBR_OF_SPACES_FOR_TAB);
- }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/RpmInformationsPreferencePage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/RpmInformationsPreferencePage.java
index 74c69c0a2c..453a8d8c43 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/RpmInformationsPreferencePage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/RpmInformationsPreferencePage.java
@@ -23,51 +23,51 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class RpmInformationsPreferencePage extends FieldEditorPreferencePage implements
IWorkbenchPreferencePage{
- /**
- * Default constructor
- */
- public RpmInformationsPreferencePage() {
- super(GRID);
- setDescription(Messages.RpmInformationsPreferencePage_0);
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- }
+ /**
+ * Default constructor
+ */
+ public RpmInformationsPreferencePage() {
+ super(GRID);
+ setDescription(Messages.RpmInformationsPreferencePage_0);
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ }
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors()
- */
- @Override
- public void createFieldEditors() {
- addField(maxProposalsIntegerFieldEditor());
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_NAME, RpmTags.NAME, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_VERSION, RpmTags.VERSION, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_RELEASE, RpmTags.RELEASE, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_SUMMARY, RpmTags.SUMMARY, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_LICENSE, RpmTags.LICENSE, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_GROUP, RpmTags.GROUP, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_URL, RpmTags.URL, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_INSTALLTIME, Messages.RpmInformationsPreferencePage_1, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_DESCRIPTION, Messages.RpmInformationsPreferencePage_2, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_PACKAGER, RpmTags.PACKAGER, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_VENDOR, RpmTags.VENDOR, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_SIZE, Messages.RpmInformationsPreferencePage_3, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_BUILDTIME, Messages.RpmInformationsPreferencePage_4, getFieldEditorParent()));
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_SOURCERPM, Messages.RpmInformationsPreferencePage_5, getFieldEditorParent()));
- }
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors()
+ */
+ @Override
+ public void createFieldEditors() {
+ addField(maxProposalsIntegerFieldEditor());
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_NAME, RpmTags.NAME, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_VERSION, RpmTags.VERSION, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_RELEASE, RpmTags.RELEASE, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_SUMMARY, RpmTags.SUMMARY, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_LICENSE, RpmTags.LICENSE, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_GROUP, RpmTags.GROUP, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_URL, RpmTags.URL, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_INSTALLTIME, Messages.RpmInformationsPreferencePage_1, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_DESCRIPTION, Messages.RpmInformationsPreferencePage_2, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_PACKAGER, RpmTags.PACKAGER, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_VENDOR, RpmTags.VENDOR, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_SIZE, Messages.RpmInformationsPreferencePage_3, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_BUILDTIME, Messages.RpmInformationsPreferencePage_4, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPMINFO_SOURCERPM, Messages.RpmInformationsPreferencePage_5, getFieldEditorParent()));
+ }
- private FieldEditor maxProposalsIntegerFieldEditor() {
- IntegerFieldEditor maxProposalsFieldEditor = new IntegerFieldEditor(
- PreferenceConstants.P_RPM_LIST_MAX_PROPOSALS,
- Messages.RpmInformationsPreferencePage_6, getFieldEditorParent());
- maxProposalsFieldEditor.setValidRange(1, 40);
- maxProposalsFieldEditor.setErrorMessage(Messages.RpmInformationsPreferencePage_7);
- return maxProposalsFieldEditor;
- }
+ private FieldEditor maxProposalsIntegerFieldEditor() {
+ IntegerFieldEditor maxProposalsFieldEditor = new IntegerFieldEditor(
+ PreferenceConstants.P_RPM_LIST_MAX_PROPOSALS,
+ Messages.RpmInformationsPreferencePage_6, getFieldEditorParent());
+ maxProposalsFieldEditor.setValidRange(1, 40);
+ maxProposalsFieldEditor.setErrorMessage(Messages.RpmInformationsPreferencePage_7);
+ return maxProposalsFieldEditor;
+ }
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- @Override
- public void init(IWorkbench workbench) {
- }
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
+ */
+ @Override
+ public void init(IWorkbench workbench) {
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/RpmProposalsPreferencePage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/RpmProposalsPreferencePage.java
index d23176af58..760b21f0e7 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/RpmProposalsPreferencePage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/RpmProposalsPreferencePage.java
@@ -37,126 +37,126 @@ import org.eclipse.ui.dialogs.PreferencesUtil;
*
*/
public class RpmProposalsPreferencePage extends FieldEditorPreferencePage
- implements IWorkbenchPreferencePage {
-
- private FieldEditor rpmtools;
-
- /*
- * default constructor
- */
- public RpmProposalsPreferencePage() {
- super(FLAT);
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors()
- */
- @Override
- public void createFieldEditors() {
- rpmtools = rpmtoolsRadioGroupFieldEditor();
- addField(rpmtools);
- // FIXME: there is validations problem when a FileFieldEditor is used, so
- // as a quick fix, StringFieldEditor is used.
- StringFieldEditor rpmListFieldEditor = new StringFieldEditor(PreferenceConstants.P_RPM_LIST_FILEPATH,
- Messages.RpmProposalsPreferencePage_0, getFieldEditorParent());
- addField(rpmListFieldEditor);
- addField(new BooleanFieldEditor(PreferenceConstants.P_RPM_LIST_BACKGROUND_BUILD,Messages.RpmProposalsPreferencePage_1, getFieldEditorParent()));
- addField(buildTimeListRateFieldEditor());
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createContents(org.eclipse.swt.widgets.Composite)
- */
- @Override
- protected Control createContents(final Composite parent) {
- Link link= new Link(parent, SWT.NONE);
- link.setText(Messages.RpmProposalsPreferencePage_2);
- link.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- PreferencesUtil.createPreferenceDialogOn(parent.getShell() , e.text, null, null);
- }
- });
- Composite fieldEditorComposite = (Composite) super
- .createContents(parent);
- return fieldEditorComposite;
- }
-
- private FieldEditor rpmtoolsRadioGroupFieldEditor() {
- ArrayList<String[]> list = new ArrayList<>();
- list.add(new String[] { Messages.RpmProposalsPreferencePage_3,
- PreferenceConstants.DP_RPMTOOLS_RPM });
- /*
- * Show only installed tools.
- * Don't forgot to add sanity check in UiUtils.pluginSanityCheck().
- */
- if (Utils.fileExist("/usr/bin/yum")) { //$NON-NLS-1$
- list.add(new String[] { Messages.RpmProposalsPreferencePage_4,
- PreferenceConstants.DP_RPMTOOLS_YUM });
- }
- if (Utils.fileExist("/usr/bin/urpmq")) { //$NON-NLS-1$
- list.add(new String[] { Messages.RpmProposalsPreferencePage_5,
- PreferenceConstants.DP_RPMTOOLS_URPM });
- }
-
- String[][] radioItems = new String[list.size()][2];
- int pos = 0;
- for (String[] item: list) {
- radioItems[pos][0] = item[0];
- radioItems[pos][1] = item[1];
- pos++;
-
- }
-
- RadioGroupFieldEditor rpmToolsRadioGroupEditor = new RadioGroupFieldEditor(
- PreferenceConstants.P_CURRENT_RPMTOOLS,
- Messages.RpmProposalsPreferencePage_6, 1, radioItems ,
- getFieldEditorParent(), true);
- return rpmToolsRadioGroupEditor;
- }
-
- private FieldEditor buildTimeListRateFieldEditor() {
- RadioGroupFieldEditor buildListTimeRateRadioGroupEditor = new RadioGroupFieldEditor(
- PreferenceConstants.P_RPM_LIST_BUILD_PERIOD,
- Messages.RpmProposalsPreferencePage_7, 1, new String[][] {
- { Messages.RpmProposalsPreferencePage_8, "1" }, //$NON-NLS-1$
- { Messages.RpmProposalsPreferencePage_10, "2" }, //$NON-NLS-1$
- { Messages.RpmProposalsPreferencePage_12, "3" }}, getFieldEditorParent(), true); //$NON-NLS-1$
- return buildListTimeRateRadioGroupEditor;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- @Override
- public void init(IWorkbench workbench) {
-
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.FieldEditorPreferencePage#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
- */
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- super.propertyChange(event);
- if (event.getSource().equals(rpmtools)) {
- if (!event.getOldValue().equals(event.getNewValue())) {
- String rpmpkgsFile = Activator.getDefault()
- .getPreferenceStore().getString(
- PreferenceConstants.P_RPM_LIST_FILEPATH);
- if (Utils.fileExist(rpmpkgsFile)) {
- new File(rpmpkgsFile).delete();
- }
- Activator.packagesList = null;
- }
- }
- }
+ implements IWorkbenchPreferencePage {
+
+ private FieldEditor rpmtools;
+
+ /*
+ * default constructor
+ */
+ public RpmProposalsPreferencePage() {
+ super(FLAT);
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createFieldEditors()
+ */
+ @Override
+ public void createFieldEditors() {
+ rpmtools = rpmtoolsRadioGroupFieldEditor();
+ addField(rpmtools);
+ // FIXME: there is validations problem when a FileFieldEditor is used, so
+ // as a quick fix, StringFieldEditor is used.
+ StringFieldEditor rpmListFieldEditor = new StringFieldEditor(PreferenceConstants.P_RPM_LIST_FILEPATH,
+ Messages.RpmProposalsPreferencePage_0, getFieldEditorParent());
+ addField(rpmListFieldEditor);
+ addField(new BooleanFieldEditor(PreferenceConstants.P_RPM_LIST_BACKGROUND_BUILD,Messages.RpmProposalsPreferencePage_1, getFieldEditorParent()));
+ addField(buildTimeListRateFieldEditor());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.preference.FieldEditorPreferencePage#createContents(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ protected Control createContents(final Composite parent) {
+ Link link= new Link(parent, SWT.NONE);
+ link.setText(Messages.RpmProposalsPreferencePage_2);
+ link.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ PreferencesUtil.createPreferenceDialogOn(parent.getShell() , e.text, null, null);
+ }
+ });
+ Composite fieldEditorComposite = (Composite) super
+ .createContents(parent);
+ return fieldEditorComposite;
+ }
+
+ private FieldEditor rpmtoolsRadioGroupFieldEditor() {
+ ArrayList<String[]> list = new ArrayList<>();
+ list.add(new String[] { Messages.RpmProposalsPreferencePage_3,
+ PreferenceConstants.DP_RPMTOOLS_RPM });
+ /*
+ * Show only installed tools.
+ * Don't forgot to add sanity check in UiUtils.pluginSanityCheck().
+ */
+ if (Utils.fileExist("/usr/bin/yum")) { //$NON-NLS-1$
+ list.add(new String[] { Messages.RpmProposalsPreferencePage_4,
+ PreferenceConstants.DP_RPMTOOLS_YUM });
+ }
+ if (Utils.fileExist("/usr/bin/urpmq")) { //$NON-NLS-1$
+ list.add(new String[] { Messages.RpmProposalsPreferencePage_5,
+ PreferenceConstants.DP_RPMTOOLS_URPM });
+ }
+
+ String[][] radioItems = new String[list.size()][2];
+ int pos = 0;
+ for (String[] item: list) {
+ radioItems[pos][0] = item[0];
+ radioItems[pos][1] = item[1];
+ pos++;
+
+ }
+
+ RadioGroupFieldEditor rpmToolsRadioGroupEditor = new RadioGroupFieldEditor(
+ PreferenceConstants.P_CURRENT_RPMTOOLS,
+ Messages.RpmProposalsPreferencePage_6, 1, radioItems ,
+ getFieldEditorParent(), true);
+ return rpmToolsRadioGroupEditor;
+ }
+
+ private FieldEditor buildTimeListRateFieldEditor() {
+ RadioGroupFieldEditor buildListTimeRateRadioGroupEditor = new RadioGroupFieldEditor(
+ PreferenceConstants.P_RPM_LIST_BUILD_PERIOD,
+ Messages.RpmProposalsPreferencePage_7, 1, new String[][] {
+ { Messages.RpmProposalsPreferencePage_8, "1" }, //$NON-NLS-1$
+ { Messages.RpmProposalsPreferencePage_10, "2" }, //$NON-NLS-1$
+ { Messages.RpmProposalsPreferencePage_12, "3" }}, getFieldEditorParent(), true); //$NON-NLS-1$
+ return buildListTimeRateRadioGroupEditor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
+ */
+ @Override
+ public void init(IWorkbench workbench) {
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.preference.FieldEditorPreferencePage#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
+ */
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ super.propertyChange(event);
+ if (event.getSource().equals(rpmtools)) {
+ if (!event.getOldValue().equals(event.getNewValue())) {
+ String rpmpkgsFile = Activator.getDefault()
+ .getPreferenceStore().getString(
+ PreferenceConstants.P_RPM_LIST_FILEPATH);
+ if (Utils.fileExist(rpmpkgsFile)) {
+ new File(rpmpkgsFile).delete();
+ }
+ Activator.packagesList = null;
+ }
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/SpecTemplatePreferencePage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/SpecTemplatePreferencePage.java
index dbba9ad7b4..5f360a5926 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/SpecTemplatePreferencePage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/SpecTemplatePreferencePage.java
@@ -21,40 +21,40 @@ import org.osgi.service.prefs.BackingStoreException;
*
*/
public class SpecTemplatePreferencePage extends TemplatePreferencePage {
-
- /**
- * Default constructor
- */
- public SpecTemplatePreferencePage() {
- super();
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- setTemplateStore(Activator.getDefault().getTemplateStore());
- setContextTypeRegistry(Activator.getDefault().getContextTypeRegistry());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#isShowFormatterSetting()
- */
- @Override
- protected boolean isShowFormatterSetting() {
- return true;
- }
-
-
- /**
- * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#performOk()
- */
- @Override
- public boolean performOk() {
- boolean ok= super.performOk();
- try {
- InstanceScope.INSTANCE.getNode(Activator.PLUGIN_ID).flush();
- } catch (BackingStoreException e) {
- //Error while saving.
- ok = false;
- }
- return ok;
- }
+
+ /**
+ * Default constructor
+ */
+ public SpecTemplatePreferencePage() {
+ super();
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ setTemplateStore(Activator.getDefault().getTemplateStore());
+ setContextTypeRegistry(Activator.getDefault().getContextTypeRegistry());
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#isShowFormatterSetting()
+ */
+ @Override
+ protected boolean isShowFormatterSetting() {
+ return true;
+ }
+
+
+ /**
+ * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#performOk()
+ */
+ @Override
+ public boolean performOk() {
+ boolean ok= super.performOk();
+ try {
+ InstanceScope.INSTANCE.getNode(Activator.PLUGIN_ID).flush();
+ } catch (BackingStoreException e) {
+ //Error while saving.
+ ok = false;
+ }
+ return ok;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/TaskTagsPreferencePage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/TaskTagsPreferencePage.java
index aac40b439a..3f44cb1aec 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/TaskTagsPreferencePage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/preferences/TaskTagsPreferencePage.java
@@ -20,60 +20,60 @@ import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
public class TaskTagsPreferencePage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
+ IWorkbenchPreferencePage {
- public TaskTagsPreferencePage() {
- super(GRID);
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- }
+ public TaskTagsPreferencePage() {
+ super(GRID);
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ }
- @Override
- public void init(IWorkbench workbench) {
- }
+ @Override
+ public void init(IWorkbench workbench) {
+ }
- @Override
- protected void createFieldEditors() {
- addField(new TasksListEditor(PreferenceConstants.P_TASK_TAGS,
- Messages.TaskTagsPreferencePage_0,
- getFieldEditorParent()));
- }
+ @Override
+ protected void createFieldEditors() {
+ addField(new TasksListEditor(PreferenceConstants.P_TASK_TAGS,
+ Messages.TaskTagsPreferencePage_0,
+ getFieldEditorParent()));
+ }
- static class TasksListEditor extends ListEditor {
+ static class TasksListEditor extends ListEditor {
- public TasksListEditor(String name, String labelText, Composite parent) {
- super(name, labelText, parent);
- }
+ public TasksListEditor(String name, String labelText, Composite parent) {
+ super(name, labelText, parent);
+ }
- @Override
- protected String createList(String[] items) {
- StringBuilder itemsString = new StringBuilder();
- for (String item : items) {
- itemsString.append(item + ';');
- }
- return itemsString.toString();
- }
+ @Override
+ protected String createList(String[] items) {
+ StringBuilder itemsString = new StringBuilder();
+ for (String item : items) {
+ itemsString.append(item + ';');
+ }
+ return itemsString.toString();
+ }
- @Override
- protected String getNewInputObject() {
- String result = null;
- // open an input dialog so that the user can enter a new task tag
- InputDialog inputDialog = new InputDialog(getShell(),
- Messages.TaskTagsPreferencePage_1, Messages.TaskTagsPreferencePage_2, "", null); //$NON-NLS-1$
- int returnCode = inputDialog.open();
+ @Override
+ protected String getNewInputObject() {
+ String result = null;
+ // open an input dialog so that the user can enter a new task tag
+ InputDialog inputDialog = new InputDialog(getShell(),
+ Messages.TaskTagsPreferencePage_1, Messages.TaskTagsPreferencePage_2, "", null); //$NON-NLS-1$
+ int returnCode = inputDialog.open();
- if (returnCode == Window.OK) {
- result = inputDialog.getValue();
- }
+ if (returnCode == Window.OK) {
+ result = inputDialog.getValue();
+ }
- return result;
+ return result;
- }
+ }
- @Override
- protected String[] parseString(String stringList) {
- return stringList.split(";"); //$NON-NLS-1$
- }
+ @Override
+ protected String[] parseString(String stringList) {
+ return stringList.split(";"); //$NON-NLS-1$
+ }
- }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/AuthorEmailRule.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/AuthorEmailRule.java
index 5e72d18d68..2b599a76cd 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/AuthorEmailRule.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/AuthorEmailRule.java
@@ -18,121 +18,121 @@ import org.eclipse.jface.text.rules.Token;
public class AuthorEmailRule implements IPredicateRule {
- /** Buffer used for pattern detection */
- private StringBuilder fBuffer = new StringBuilder();
-
- /** The success token */
- private IToken token;
-
- protected static final char START_CHAR = '<';
-
- protected static final char END_CHAR = '>';
-
- protected static final char[] INTER_CHARS = { '@', '.' };
-
- protected static final int STATE_START = 0;
-
- protected static final int STATE_OPENED = 1;
-
- protected static final int STATE_AT = 2;
-
- protected static final int STATE_PERIOD = 3;
-
- protected static final int STATE_DONE = 4;
-
- public AuthorEmailRule(IToken token) {
- this.token = token;
- }
-
- @Override
- public IToken getSuccessToken() {
- return token;
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner, boolean resume) {
- /*
- * whether we think we're reading the ending sequence, i.e. the next
- * section heading
- */
- int state = STATE_START;
- fBuffer.setLength(0);
- int c;
-
- do {
- c = scanner.read();
- fBuffer.append((char) c);
-
- // we have reached the end of file or line prematurely, this is not
- // considered success
- if (c == ICharacterScanner.EOF || (char) c == '\n') {
- unreadBuffer(scanner, fBuffer);
- return Token.UNDEFINED;
- }
-
- // we encountered the opening character at the beginning
- if (state == STATE_START && (char) c == START_CHAR) {
- state++;
- } else if (state == STATE_OPENED) {
- // we encountered the first neccessary intermediary char
- if ((char) c == INTER_CHARS[0]) {
- state++;
- }
-
- // check if we have a valid char
- if (! (Character.isLetterOrDigit((char) c) || c == '.' || c == '_' || c == '-' || c == '@')){
- unreadBuffer(scanner, fBuffer);
- return Token.UNDEFINED;
- }
-
- // we just keep reading
-
- } else if (state == STATE_AT) {
- // we encountered the second neccessary intermediary char
- if ((char) c == INTER_CHARS[1]) {
- state++;
- }
-
- // check if we have a valid char
- if (! (Character.isLetterOrDigit((char) c) || c == '.' || c == '_' || c == '-')){
- unreadBuffer(scanner, fBuffer);
- return Token.UNDEFINED;
- }
- // we just keep reading
- } else if (state == STATE_PERIOD) {
- // the last char before the ending char cannot be a '.'
- if ((char) c == END_CHAR && fBuffer.charAt(fBuffer.length() - 1) != '.') {
- state++;
- } else if ((char) c == END_CHAR){
- unreadBuffer(scanner, fBuffer);
- return Token.UNDEFINED;
- }
- } else {
- unreadBuffer(scanner, fBuffer);
- return Token.UNDEFINED;
- }
-
- } while (state != STATE_DONE);
-
- // we've gone through all states until we've reached STATE_DONE, success
- return token;
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner) {
- return evaluate(scanner, false);
- }
-
- /**
- * Returns the characters in the buffer to the scanner.
- *
- * @param scanner
- * the scanner to be used
- */
- protected void unreadBuffer(ICharacterScanner scanner, StringBuilder buffer) {
- for (int i = buffer.length() - 1; i >= 0; i--) {
- scanner.unread();
- }
- }
+ /** Buffer used for pattern detection */
+ private StringBuilder fBuffer = new StringBuilder();
+
+ /** The success token */
+ private IToken token;
+
+ protected static final char START_CHAR = '<';
+
+ protected static final char END_CHAR = '>';
+
+ protected static final char[] INTER_CHARS = { '@', '.' };
+
+ protected static final int STATE_START = 0;
+
+ protected static final int STATE_OPENED = 1;
+
+ protected static final int STATE_AT = 2;
+
+ protected static final int STATE_PERIOD = 3;
+
+ protected static final int STATE_DONE = 4;
+
+ public AuthorEmailRule(IToken token) {
+ this.token = token;
+ }
+
+ @Override
+ public IToken getSuccessToken() {
+ return token;
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner, boolean resume) {
+ /*
+ * whether we think we're reading the ending sequence, i.e. the next
+ * section heading
+ */
+ int state = STATE_START;
+ fBuffer.setLength(0);
+ int c;
+
+ do {
+ c = scanner.read();
+ fBuffer.append((char) c);
+
+ // we have reached the end of file or line prematurely, this is not
+ // considered success
+ if (c == ICharacterScanner.EOF || (char) c == '\n') {
+ unreadBuffer(scanner, fBuffer);
+ return Token.UNDEFINED;
+ }
+
+ // we encountered the opening character at the beginning
+ if (state == STATE_START && (char) c == START_CHAR) {
+ state++;
+ } else if (state == STATE_OPENED) {
+ // we encountered the first neccessary intermediary char
+ if ((char) c == INTER_CHARS[0]) {
+ state++;
+ }
+
+ // check if we have a valid char
+ if (! (Character.isLetterOrDigit((char) c) || c == '.' || c == '_' || c == '-' || c == '@')){
+ unreadBuffer(scanner, fBuffer);
+ return Token.UNDEFINED;
+ }
+
+ // we just keep reading
+
+ } else if (state == STATE_AT) {
+ // we encountered the second neccessary intermediary char
+ if ((char) c == INTER_CHARS[1]) {
+ state++;
+ }
+
+ // check if we have a valid char
+ if (! (Character.isLetterOrDigit((char) c) || c == '.' || c == '_' || c == '-')){
+ unreadBuffer(scanner, fBuffer);
+ return Token.UNDEFINED;
+ }
+ // we just keep reading
+ } else if (state == STATE_PERIOD) {
+ // the last char before the ending char cannot be a '.'
+ if ((char) c == END_CHAR && fBuffer.charAt(fBuffer.length() - 1) != '.') {
+ state++;
+ } else if ((char) c == END_CHAR){
+ unreadBuffer(scanner, fBuffer);
+ return Token.UNDEFINED;
+ }
+ } else {
+ unreadBuffer(scanner, fBuffer);
+ return Token.UNDEFINED;
+ }
+
+ } while (state != STATE_DONE);
+
+ // we've gone through all states until we've reached STATE_DONE, success
+ return token;
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner) {
+ return evaluate(scanner, false);
+ }
+
+ /**
+ * Returns the characters in the buffer to the scanner.
+ *
+ * @param scanner
+ * the scanner to be used
+ */
+ protected void unreadBuffer(ICharacterScanner scanner, StringBuilder buffer) {
+ for (int i = buffer.length() - 1; i >= 0; i--) {
+ scanner.unread();
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/CommentRule.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/CommentRule.java
index 2efdf137c3..21791c1e88 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/CommentRule.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/CommentRule.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -17,16 +17,16 @@ import org.eclipse.linuxtools.internal.rpm.ui.editor.ISpecfileSpecialSymbols;
/**
* A rule for matching comment line.
* Starts with # and ends at the end of line.
- *
+ *
*/
public class CommentRule extends EndOfLineRule{
- /**
- * Creates a EndofLineRule starting with the comment("#") symbol.
- *
- * @param token The token to look into.
- */
- public CommentRule(IToken token) {
- super(ISpecfileSpecialSymbols.COMMENT_START, token);
- }
+ /**
+ * Creates a EndofLineRule starting with the comment("#") symbol.
+ *
+ * @param token The token to look into.
+ */
+ public CommentRule(IToken token) {
+ super(ISpecfileSpecialSymbols.COMMENT_START, token);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/MacroRule.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/MacroRule.java
index e7dda2246c..63e33ba040 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/MacroRule.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/MacroRule.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -16,19 +16,19 @@ import org.eclipse.linuxtools.internal.rpm.ui.editor.ISpecfileSpecialSymbols;
/**
* A rule for matching %{...} sections in spec file.
- *
+ *
*/
public class MacroRule extends SingleLineRule {
- /**
- * Creates a SingleLineRule by using macros start and end identifiers for
- * start and end delimiters.
- *
- * @param token The token to look into.
- */
- public MacroRule(IToken token) {
- super(ISpecfileSpecialSymbols.MACRO_START_LONG,
- ISpecfileSpecialSymbols.MACRO_END_LONG, token);
- }
+ /**
+ * Creates a SingleLineRule by using macros start and end identifiers for
+ * start and end delimiters.
+ *
+ * @param token The token to look into.
+ */
+ public MacroRule(IToken token) {
+ super(ISpecfileSpecialSymbols.MACRO_START_LONG,
+ ISpecfileSpecialSymbols.MACRO_END_LONG, token);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/SectionRule.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/SectionRule.java
index 099527b300..e8e8acd081 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/SectionRule.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/SectionRule.java
@@ -18,124 +18,124 @@ import org.eclipse.jface.text.rules.Token;
public class SectionRule implements IPredicateRule {
- /** Buffer used for pattern detection */
- private StringBuilder fBuffer = new StringBuilder();
-
- /** Buffer used for pattern detection of next header */
- private StringBuilder nextHeaderBuffer = new StringBuilder();
-
- /** The success token */
- private IToken token;
-
- /** The beginning token, represents a section of the spec file */
- private String startingHeader;
-
- /** A list of possible ending section headers */
- private String[] endingHeaders;
-
- public SectionRule(String startingHeader, String[] endingHeaders,
- IToken token) {
- this.startingHeader = startingHeader;
- this.endingHeaders = endingHeaders;
- this.token = token;
- }
-
- @Override
- public IToken getSuccessToken() {
- return token;
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner, boolean resume) {
- /* whether we think we're reading the ending sequence, i.e. the next
- * section heading
- */
- boolean readingEndSequence = false;
- fBuffer.setLength(0);
- nextHeaderBuffer.setLength(0);
- int c = scanner.read();
-
- /* if we're starting at the beginning header we check that the partition
- * begins with the required header */
- if (!resume) {
- for (int i = 0; i < startingHeader.length(); i++) {
- fBuffer.append((char) c);
- if (startingHeader.charAt(i) != (char) c) {
- unreadBuffer(scanner, fBuffer);
- return Token.UNDEFINED;
- }
- c = scanner.read();
- }
- }
-
- fBuffer.append((char) c);
-
- do {
- // Sections can only begin with a % on a new line
- if (c == '\n') {
- // if we were readin a %blah, reset because it turned out to
- // not be a terminating section header
- readingEndSequence = false;
-
- // if we're reading a line beginning with % then it might be
- // at terminating sectino header
- c = scanner.read();
- if (c == '%') {
- // Start appending to the we reset the buffer for section
- // headers, and indicate that this line can be a terminating
- // section header
- nextHeaderBuffer.setLength(0);
- readingEndSequence = true;
- } else if (c == ICharacterScanner.EOF) {
- // we allow EOF as a valid ending to a section
- break;
- } else {
- fBuffer.append((char) c);
- continue;
- }
- }
- // we're in a line that's a possible terminating section header,
- // so we compare it with all terminating headers
- if (readingEndSequence) {
- nextHeaderBuffer.append((char) c);
- for (int i = 0; i < endingHeaders.length; i++) {
- String tempSectionheader = endingHeaders[i];
-
- // we've found our terminating header
- if (nextHeaderBuffer.toString().equals(tempSectionheader)) {
- // exclude the terminating header from the partition
- unreadBuffer(scanner, nextHeaderBuffer);
- return token;
- }
- }
- }
-
- // read the next char
- c = scanner.read();
- fBuffer.append((char) c);
- } while (c != ICharacterScanner.EOF);
-
- // we've reached EOF and since our section started with the correct
- // header, then this is just the current end of the partition, and
- // we return the success token
- return token;
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner) {
- return evaluate(scanner, false);
- }
-
- /**
- * Returns the characters in the buffer to the scanner.
- *
- * @param scanner
- * the scanner to be used
- */
- protected void unreadBuffer(ICharacterScanner scanner, StringBuilder buffer) {
- for (int i = buffer.length() - 1; i >= 0; i--) {
- scanner.unread();
- }
- }
+ /** Buffer used for pattern detection */
+ private StringBuilder fBuffer = new StringBuilder();
+
+ /** Buffer used for pattern detection of next header */
+ private StringBuilder nextHeaderBuffer = new StringBuilder();
+
+ /** The success token */
+ private IToken token;
+
+ /** The beginning token, represents a section of the spec file */
+ private String startingHeader;
+
+ /** A list of possible ending section headers */
+ private String[] endingHeaders;
+
+ public SectionRule(String startingHeader, String[] endingHeaders,
+ IToken token) {
+ this.startingHeader = startingHeader;
+ this.endingHeaders = endingHeaders;
+ this.token = token;
+ }
+
+ @Override
+ public IToken getSuccessToken() {
+ return token;
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner, boolean resume) {
+ /* whether we think we're reading the ending sequence, i.e. the next
+ * section heading
+ */
+ boolean readingEndSequence = false;
+ fBuffer.setLength(0);
+ nextHeaderBuffer.setLength(0);
+ int c = scanner.read();
+
+ /* if we're starting at the beginning header we check that the partition
+ * begins with the required header */
+ if (!resume) {
+ for (int i = 0; i < startingHeader.length(); i++) {
+ fBuffer.append((char) c);
+ if (startingHeader.charAt(i) != (char) c) {
+ unreadBuffer(scanner, fBuffer);
+ return Token.UNDEFINED;
+ }
+ c = scanner.read();
+ }
+ }
+
+ fBuffer.append((char) c);
+
+ do {
+ // Sections can only begin with a % on a new line
+ if (c == '\n') {
+ // if we were readin a %blah, reset because it turned out to
+ // not be a terminating section header
+ readingEndSequence = false;
+
+ // if we're reading a line beginning with % then it might be
+ // at terminating sectino header
+ c = scanner.read();
+ if (c == '%') {
+ // Start appending to the we reset the buffer for section
+ // headers, and indicate that this line can be a terminating
+ // section header
+ nextHeaderBuffer.setLength(0);
+ readingEndSequence = true;
+ } else if (c == ICharacterScanner.EOF) {
+ // we allow EOF as a valid ending to a section
+ break;
+ } else {
+ fBuffer.append((char) c);
+ continue;
+ }
+ }
+ // we're in a line that's a possible terminating section header,
+ // so we compare it with all terminating headers
+ if (readingEndSequence) {
+ nextHeaderBuffer.append((char) c);
+ for (int i = 0; i < endingHeaders.length; i++) {
+ String tempSectionheader = endingHeaders[i];
+
+ // we've found our terminating header
+ if (nextHeaderBuffer.toString().equals(tempSectionheader)) {
+ // exclude the terminating header from the partition
+ unreadBuffer(scanner, nextHeaderBuffer);
+ return token;
+ }
+ }
+ }
+
+ // read the next char
+ c = scanner.read();
+ fBuffer.append((char) c);
+ } while (c != ICharacterScanner.EOF);
+
+ // we've reached EOF and since our section started with the correct
+ // header, then this is just the current end of the partition, and
+ // we return the success token
+ return token;
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner) {
+ return evaluate(scanner, false);
+ }
+
+ /**
+ * Returns the characters in the buffer to the scanner.
+ *
+ * @param scanner
+ * the scanner to be used
+ */
+ protected void unreadBuffer(ICharacterScanner scanner, StringBuilder buffer) {
+ for (int i = buffer.length() - 1; i >= 0; i--) {
+ scanner.unread();
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/StringWithEndingRule.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/StringWithEndingRule.java
index 57bdcc96fa..2a17d6a644 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/StringWithEndingRule.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/StringWithEndingRule.java
@@ -19,85 +19,85 @@ import org.eclipse.linuxtools.internal.rpm.ui.editor.detectors.IStrictWordDetect
public class StringWithEndingRule implements IRule {
- private IToken token;
-
- private IStrictWordDetector fDetector;
-
- /** The column constraint */
- private int fColumn = UNDEFINED;
-
- /** Internal setting for the un-initialized column constraint */
- private static final int UNDEFINED = -1;
-
- /** Buffer used for pattern detection */
- private StringBuilder fBuffer = new StringBuilder();
-
- private String fStartingSequence;
-
- private boolean fMandatoryEndSequence;
-
- public StringWithEndingRule(String startingSequence,
- IStrictWordDetector trailingCharDetector, IToken inToken,
- boolean endSequenceRequired) {
- super();
- token = inToken;
- fDetector = trailingCharDetector;
- fStartingSequence = startingSequence;
- fMandatoryEndSequence = endSequenceRequired;
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner) {
- int c = scanner.read();
- fBuffer.setLength(0);
-
- for (int i = 0; i < fStartingSequence.length(); i++) {
- fBuffer.append((char) c);
- if (fStartingSequence.charAt(i) != c) {
- unreadBuffer(scanner);
- return Token.UNDEFINED;
- }
- c = scanner.read();
- }
-
- if (fDetector.isWordStart((char) c)) {
- if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) {
-
- do {
- fBuffer.append((char) c);
- c = scanner.read();
- } while (c != ICharacterScanner.EOF
- && fDetector.isWordPart((char) c));
-
- if (c != ICharacterScanner.EOF && !fDetector.isEndingCharacter((char) c)) {
- unreadBuffer(scanner);
- return Token.UNDEFINED;
- }
-
- return token;
- }
-
- }
-
- if (!fMandatoryEndSequence && fDetector.isEndingCharacter((char) c)) {
- return token;
- }
- scanner.unread();
-
- unreadBuffer(scanner);
- return Token.UNDEFINED;
- }
-
- /**
- * Returns the characters in the buffer to the scanner.
- *
- * @param scanner
- * the scanner to be used
- */
- protected void unreadBuffer(ICharacterScanner scanner) {
- for (int i = fBuffer.length() - 1; i >= 0; i--) {
- scanner.unread();
- }
- }
+ private IToken token;
+
+ private IStrictWordDetector fDetector;
+
+ /** The column constraint */
+ private int fColumn = UNDEFINED;
+
+ /** Internal setting for the un-initialized column constraint */
+ private static final int UNDEFINED = -1;
+
+ /** Buffer used for pattern detection */
+ private StringBuilder fBuffer = new StringBuilder();
+
+ private String fStartingSequence;
+
+ private boolean fMandatoryEndSequence;
+
+ public StringWithEndingRule(String startingSequence,
+ IStrictWordDetector trailingCharDetector, IToken inToken,
+ boolean endSequenceRequired) {
+ super();
+ token = inToken;
+ fDetector = trailingCharDetector;
+ fStartingSequence = startingSequence;
+ fMandatoryEndSequence = endSequenceRequired;
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner) {
+ int c = scanner.read();
+ fBuffer.setLength(0);
+
+ for (int i = 0; i < fStartingSequence.length(); i++) {
+ fBuffer.append((char) c);
+ if (fStartingSequence.charAt(i) != c) {
+ unreadBuffer(scanner);
+ return Token.UNDEFINED;
+ }
+ c = scanner.read();
+ }
+
+ if (fDetector.isWordStart((char) c)) {
+ if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) {
+
+ do {
+ fBuffer.append((char) c);
+ c = scanner.read();
+ } while (c != ICharacterScanner.EOF
+ && fDetector.isWordPart((char) c));
+
+ if (c != ICharacterScanner.EOF && !fDetector.isEndingCharacter((char) c)) {
+ unreadBuffer(scanner);
+ return Token.UNDEFINED;
+ }
+
+ return token;
+ }
+
+ }
+
+ if (!fMandatoryEndSequence && fDetector.isEndingCharacter((char) c)) {
+ return token;
+ }
+ scanner.unread();
+
+ unreadBuffer(scanner);
+ return Token.UNDEFINED;
+ }
+
+ /**
+ * Returns the characters in the buffer to the scanner.
+ *
+ * @param scanner
+ * the scanner to be used
+ */
+ protected void unreadBuffer(ICharacterScanner scanner) {
+ for (int i = fBuffer.length() - 1; i >= 0; i--) {
+ scanner.unread();
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/VersionReleaseRule.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/VersionReleaseRule.java
index 68e3e47181..2aec0ef713 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/VersionReleaseRule.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/rules/VersionReleaseRule.java
@@ -19,153 +19,153 @@ import org.eclipse.linuxtools.internal.rpm.ui.editor.scanners.SpecfileChangelogS
public class VersionReleaseRule implements IPredicateRule {
- /** Buffer used for pattern detection */
- private StringBuilder fBuffer = new StringBuilder();
-
- /** Buffer to keep track of trailing whitespace */
- private StringBuilder fWhiteSpaceBuffer = new StringBuilder();
-
- /** The success token */
- private IToken fToken;
-
- /** The token that has to preceed this token */
- private IToken fPreceedingToken;
-
- /** Where we can find out what the preceeding token was */
- private SpecfileChangelogScanner fChangelogScanner;
-
- protected static final char CHARS_SEPERATOR = '-';
-
- protected static final int STATE_START = 0;
-
- protected static final int STATE_VERSION = 1;
-
- protected static final int STATE_RELEASE = 2;
-
- protected static final int STATE_TRAIL = 3;
-
- protected static final int STATE_DONE = 4;
-
- public VersionReleaseRule(IToken token) {
- this.fToken = token;
- }
-
- public VersionReleaseRule(IToken successToken, IToken preceedingToken,
- SpecfileChangelogScanner scanner) {
- fToken = successToken;
- fPreceedingToken = preceedingToken;
- fChangelogScanner = scanner;
- }
-
- @Override
- public IToken getSuccessToken() {
- return fToken;
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner, boolean resume) {
- // if the last token successfully read was not the fPreceedingToke fail
- IToken lastToken = getLastToken();
-
- if (lastToken != fPreceedingToken) {
- return Token.UNDEFINED;
- }
-
- fBuffer.setLength(0);
- int state = STATE_START;
- int c;
- int numPreceedingBlanks = 0;
-
- do {
- c = scanner.read();
- fBuffer.append((char) c);
-
- // preceeding white space
- if (state == STATE_START) {
- if (Character.isWhitespace((char) c) || c == '-') {
- numPreceedingBlanks++;
- } else {
- state++;
- }
- }
- // version state (first part of version-release)
- if (state == STATE_VERSION) {
- // if we've read some semblance of a version and we've reached
- // the separator character
- if (fBuffer.length() > numPreceedingBlanks
- && c == CHARS_SEPERATOR) {
- state++;
- }
- // otherwise we allow only digits, letters, underscores, ':' or
- // '.' in the version
- else if (!(Character.isLetterOrDigit((char) c) || c == '.'
- || c == '_' || c == ':')) {
- unreadBuffer(scanner, fBuffer);
- return Token.UNDEFINED;
- }
- }
- // release state (second part of version-release)
- else if (state == STATE_RELEASE) {
- // an EOF or EOL indicates success
- if (c == ICharacterScanner.EOF || c == '\n') {
- state = STATE_DONE;
- }
-
- // if we encounter a space, we enter the optional trailing
- // space section which we consider valid (but not part of the
- // token) if and only if it is ended by and EOF or EOL
- else if (Character.isWhitespace((char) c)) {
- state++;
- fWhiteSpaceBuffer.setLength(0);
- fWhiteSpaceBuffer.append(c);
- } else if (!(Character.isLetterOrDigit((char) c) || c == '.' || c == '_')) {
- // allow digits, characters or '.' in the release
- unreadBuffer(scanner, fBuffer);
- return Token.UNDEFINED;
- }
-
- }
- // whitespace state, we finished redeaing the ver-rel and are
- // now looking for an EOF or EOL for success
- else if (state == STATE_TRAIL) {
- // success, unwind the whitespace
- if (c == ICharacterScanner.EOF || c == '\n') {
- unreadBuffer(scanner, fWhiteSpaceBuffer);
- state++;
- } // some other illegal token after ver-rel unwind the whole
- // deal
- else if (!Character.isWhitespace((char) c)) {
- unreadBuffer(scanner, fBuffer);
- return Token.UNDEFINED;
- } else { // white space, keep reading
- fWhiteSpaceBuffer.append((char) c);
- }
-
- }
- } while (state != STATE_DONE);
-
- // we've gone through all states until we've reached STATE_DONE, success
- return fToken;
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner) {
- return evaluate(scanner, false);
- }
-
- /**
- * Returns the characters in the buffer to the scanner.
- *
- * @param scanner
- * the scanner to be used
- */
- protected void unreadBuffer(ICharacterScanner scanner, StringBuilder buffer) {
- for (int i = buffer.length() - 1; i >= 0; i--) {
- scanner.unread();
- }
- }
-
- protected IToken getLastToken() {
- return fChangelogScanner.getLastToken();
- }
+ /** Buffer used for pattern detection */
+ private StringBuilder fBuffer = new StringBuilder();
+
+ /** Buffer to keep track of trailing whitespace */
+ private StringBuilder fWhiteSpaceBuffer = new StringBuilder();
+
+ /** The success token */
+ private IToken fToken;
+
+ /** The token that has to preceed this token */
+ private IToken fPreceedingToken;
+
+ /** Where we can find out what the preceeding token was */
+ private SpecfileChangelogScanner fChangelogScanner;
+
+ protected static final char CHARS_SEPERATOR = '-';
+
+ protected static final int STATE_START = 0;
+
+ protected static final int STATE_VERSION = 1;
+
+ protected static final int STATE_RELEASE = 2;
+
+ protected static final int STATE_TRAIL = 3;
+
+ protected static final int STATE_DONE = 4;
+
+ public VersionReleaseRule(IToken token) {
+ this.fToken = token;
+ }
+
+ public VersionReleaseRule(IToken successToken, IToken preceedingToken,
+ SpecfileChangelogScanner scanner) {
+ fToken = successToken;
+ fPreceedingToken = preceedingToken;
+ fChangelogScanner = scanner;
+ }
+
+ @Override
+ public IToken getSuccessToken() {
+ return fToken;
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner, boolean resume) {
+ // if the last token successfully read was not the fPreceedingToke fail
+ IToken lastToken = getLastToken();
+
+ if (lastToken != fPreceedingToken) {
+ return Token.UNDEFINED;
+ }
+
+ fBuffer.setLength(0);
+ int state = STATE_START;
+ int c;
+ int numPreceedingBlanks = 0;
+
+ do {
+ c = scanner.read();
+ fBuffer.append((char) c);
+
+ // preceeding white space
+ if (state == STATE_START) {
+ if (Character.isWhitespace((char) c) || c == '-') {
+ numPreceedingBlanks++;
+ } else {
+ state++;
+ }
+ }
+ // version state (first part of version-release)
+ if (state == STATE_VERSION) {
+ // if we've read some semblance of a version and we've reached
+ // the separator character
+ if (fBuffer.length() > numPreceedingBlanks
+ && c == CHARS_SEPERATOR) {
+ state++;
+ }
+ // otherwise we allow only digits, letters, underscores, ':' or
+ // '.' in the version
+ else if (!(Character.isLetterOrDigit((char) c) || c == '.'
+ || c == '_' || c == ':')) {
+ unreadBuffer(scanner, fBuffer);
+ return Token.UNDEFINED;
+ }
+ }
+ // release state (second part of version-release)
+ else if (state == STATE_RELEASE) {
+ // an EOF or EOL indicates success
+ if (c == ICharacterScanner.EOF || c == '\n') {
+ state = STATE_DONE;
+ }
+
+ // if we encounter a space, we enter the optional trailing
+ // space section which we consider valid (but not part of the
+ // token) if and only if it is ended by and EOF or EOL
+ else if (Character.isWhitespace((char) c)) {
+ state++;
+ fWhiteSpaceBuffer.setLength(0);
+ fWhiteSpaceBuffer.append(c);
+ } else if (!(Character.isLetterOrDigit((char) c) || c == '.' || c == '_')) {
+ // allow digits, characters or '.' in the release
+ unreadBuffer(scanner, fBuffer);
+ return Token.UNDEFINED;
+ }
+
+ }
+ // whitespace state, we finished redeaing the ver-rel and are
+ // now looking for an EOF or EOL for success
+ else if (state == STATE_TRAIL) {
+ // success, unwind the whitespace
+ if (c == ICharacterScanner.EOF || c == '\n') {
+ unreadBuffer(scanner, fWhiteSpaceBuffer);
+ state++;
+ } // some other illegal token after ver-rel unwind the whole
+ // deal
+ else if (!Character.isWhitespace((char) c)) {
+ unreadBuffer(scanner, fBuffer);
+ return Token.UNDEFINED;
+ } else { // white space, keep reading
+ fWhiteSpaceBuffer.append((char) c);
+ }
+
+ }
+ } while (state != STATE_DONE);
+
+ // we've gone through all states until we've reached STATE_DONE, success
+ return fToken;
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner) {
+ return evaluate(scanner, false);
+ }
+
+ /**
+ * Returns the characters in the buffer to the scanner.
+ *
+ * @param scanner
+ * the scanner to be used
+ */
+ protected void unreadBuffer(ICharacterScanner scanner, StringBuilder buffer) {
+ for (int i = buffer.length() - 1; i >= 0; i--) {
+ scanner.unread();
+ }
+ }
+
+ protected IToken getLastToken() {
+ return fChangelogScanner.getLastToken();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfileChangelogScanner.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfileChangelogScanner.java
index 00dee64b6b..917d563546 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfileChangelogScanner.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfileChangelogScanner.java
@@ -35,44 +35,44 @@ import org.eclipse.swt.SWT;
*/
public class SpecfileChangelogScanner extends RuleBasedScanner {
- private IToken fLastToken;
+ private IToken fLastToken;
- public SpecfileChangelogScanner(ColorManager manager) {
- super();
- IToken sectionToken = new Token(new TextAttribute(manager
- .getColor(ISpecfileColorConstants.SECTIONS), null, SWT.ITALIC));
+ public SpecfileChangelogScanner(ColorManager manager) {
+ super();
+ IToken sectionToken = new Token(new TextAttribute(manager
+ .getColor(ISpecfileColorConstants.SECTIONS), null, SWT.ITALIC));
- IToken authorEmail = new Token(new TextAttribute(manager
- .getColor(ISpecfileColorConstants.AUTHOR_MAIL), null, SWT.NONE));
+ IToken authorEmail = new Token(new TextAttribute(manager
+ .getColor(ISpecfileColorConstants.AUTHOR_MAIL), null, SWT.NONE));
- IToken versionRelease = new Token(new TextAttribute(manager
- .getColor(ISpecfileColorConstants.VER_REL), null, SWT.NONE));
+ IToken versionRelease = new Token(new TextAttribute(manager
+ .getColor(ISpecfileColorConstants.VER_REL), null, SWT.NONE));
- List<IRule> rules = new ArrayList<>();
+ List<IRule> rules = new ArrayList<>();
- // %prep, %build, ...
- WordRule wordRule = new WordRule(new KeywordWordDetector(), Token.UNDEFINED);
- wordRule.addWord(RpmSections.CHANGELOG_SECTION, sectionToken);
- rules.add(wordRule);
+ // %prep, %build, ...
+ WordRule wordRule = new WordRule(new KeywordWordDetector(), Token.UNDEFINED);
+ wordRule.addWord(RpmSections.CHANGELOG_SECTION, sectionToken);
+ rules.add(wordRule);
- AuthorEmailRule emailRule= new AuthorEmailRule(authorEmail);
- rules.add(emailRule);
+ AuthorEmailRule emailRule= new AuthorEmailRule(authorEmail);
+ rules.add(emailRule);
- VersionReleaseRule verRelRule = new VersionReleaseRule(versionRelease, authorEmail, this);
- rules.add(verRelRule);
+ VersionReleaseRule verRelRule = new VersionReleaseRule(versionRelease, authorEmail, this);
+ rules.add(verRelRule);
- IRule[] result = new IRule[rules.size()];
- rules.toArray(result);
- setRules(result);
- }
+ IRule[] result = new IRule[rules.size()];
+ rules.toArray(result);
+ setRules(result);
+ }
- public IToken getLastToken (){
- return fLastToken;
- }
+ public IToken getLastToken (){
+ return fLastToken;
+ }
- @Override
- public IToken nextToken() {
- fLastToken = super.nextToken();
- return fLastToken;
- }
+ @Override
+ public IToken nextToken() {
+ fLastToken = super.nextToken();
+ return fLastToken;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfilePackagesScanner.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfilePackagesScanner.java
index bae919b80f..74475aa010 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfilePackagesScanner.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfilePackagesScanner.java
@@ -35,49 +35,49 @@ import org.eclipse.swt.SWT;
*/
public class SpecfilePackagesScanner extends RuleBasedScanner {
- protected static final String[] PACKAGES_TAGS = {
- "BuildRequires", "BuildConflicts", //$NON-NLS-1$ //$NON-NLS-2$
- "BuildPreReq", "Requires", "Requires(post)", "Requires(postun)", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- "Requires(pre)", "Requires(preun)", "Requires(hint)", "Conflicts", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- "Obsoletes", "Prereq" }; //$NON-NLS-1$ //$NON-NLS-2$
+ protected static final String[] PACKAGES_TAGS = {
+ "BuildRequires", "BuildConflicts", //$NON-NLS-1$ //$NON-NLS-2$
+ "BuildPreReq", "Requires", "Requires(post)", "Requires(postun)", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ "Requires(pre)", "Requires(preun)", "Requires(hint)", "Conflicts", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ "Obsoletes", "Prereq" }; //$NON-NLS-1$ //$NON-NLS-2$
- public SpecfilePackagesScanner(ColorManager manager) {
- super();
- IToken packageToken = new Token(new TextAttribute(manager
- .getColor(ISpecfileColorConstants.PACKAGES), null, SWT.NONE));
+ public SpecfilePackagesScanner(ColorManager manager) {
+ super();
+ IToken packageToken = new Token(new TextAttribute(manager
+ .getColor(ISpecfileColorConstants.PACKAGES), null, SWT.NONE));
- IToken tagToken = new Token(new TextAttribute(manager
- .getColor(ISpecfileColorConstants.TAGS)));
+ IToken tagToken = new Token(new TextAttribute(manager
+ .getColor(ISpecfileColorConstants.TAGS)));
- IToken macroToken = new Token(new TextAttribute(manager
- .getColor(ISpecfileColorConstants.MACROS)));
+ IToken macroToken = new Token(new TextAttribute(manager
+ .getColor(ISpecfileColorConstants.MACROS)));
- List<IRule> rules = new ArrayList<>();
+ List<IRule> rules = new ArrayList<>();
- rules.add(new MacroRule(macroToken));
+ rules.add(new MacroRule(macroToken));
- // BuildRequires:, ...
- WordRule wordRule = new WordRule(new TagWordDetector(), Token.UNDEFINED);
- for (String packageTag : PACKAGES_TAGS) {
- wordRule.addWord(packageTag + ":", tagToken); //$NON-NLS-1$
- }
- rules.add(wordRule);
+ // BuildRequires:, ...
+ WordRule wordRule = new WordRule(new TagWordDetector(), Token.UNDEFINED);
+ for (String packageTag : PACKAGES_TAGS) {
+ wordRule.addWord(packageTag + ":", tagToken); //$NON-NLS-1$
+ }
+ rules.add(wordRule);
- // RPM packages
- wordRule = new WordRule(new PackageWordDetector(), Token.UNDEFINED);
- List<String[]> rpmPackages = Activator.getDefault().getRpmPackageList()
- .getProposals(""); //$NON-NLS-1$
- char[] startWith = {' ', '\t', ',', ':'};
- for (String[] item: rpmPackages){
- // FIXME Perhaps, that can slow down the scanning?
- for (char startChar : startWith) {
- wordRule.addWord(startChar + item[0], packageToken);
- }
- }
- rules.add(wordRule);
+ // RPM packages
+ wordRule = new WordRule(new PackageWordDetector(), Token.UNDEFINED);
+ List<String[]> rpmPackages = Activator.getDefault().getRpmPackageList()
+ .getProposals(""); //$NON-NLS-1$
+ char[] startWith = {' ', '\t', ',', ':'};
+ for (String[] item: rpmPackages){
+ // FIXME Perhaps, that can slow down the scanning?
+ for (char startChar : startWith) {
+ wordRule.addWord(startChar + item[0], packageToken);
+ }
+ }
+ rules.add(wordRule);
- IRule[] result = new IRule[rules.size()];
- rules.toArray(result);
- setRules(result);
- }
+ IRule[] result = new IRule[rules.size()];
+ rules.toArray(result);
+ setRules(result);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfilePartitionScanner.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfilePartitionScanner.java
index b1f4721dfc..1a5580749e 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfilePartitionScanner.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfilePartitionScanner.java
@@ -43,68 +43,68 @@ import org.eclipse.linuxtools.internal.rpm.ui.editor.rules.SectionRule;
public class SpecfilePartitionScanner extends RuleBasedPartitionScanner {
- public static final String SPEC_PREP = "__spec_prep"; //$NON-NLS-1$
- public static final String SPEC_SCRIPT = "__spec_script"; //$NON-NLS-1$
- public static final String SPEC_FILES = "__spec_files"; //$NON-NLS-1$
- public static final String SPEC_CHANGELOG = "__spec_changelog"; //$NON-NLS-1$
- public static final String SPEC_PACKAGES = "__spec_packages"; //$NON-NLS-1$
- public static final String SPEC_GROUP = "__spec_group"; //$NON-NLS-1$
- public static final String SPEC_FILE_PARTITIONING = "___spec_partitioning"; //$NON-NLS-1$
-
- public static final String[] SPEC_PARTITION_TYPES = { IDocument.DEFAULT_CONTENT_TYPE, SPEC_PREP, SPEC_SCRIPT,
- SPEC_FILES, SPEC_CHANGELOG, SPEC_PACKAGES, SPEC_GROUP};
-
- /** All possible headers for sections of the type SPEC_SCRIPT */
- private static final String[] SECTION_HEADERS = { BUILD_SECTION, INSTALL_SECTION,
- PRETRANS_SECTION, PRE_SECTION, PREUN_SECTION, POST_SECTION, POSTUN_SECTION,
- POSTTRANS_SECTION, CLEAN_SECTION};
-
- /** All possible headers for section that can come after sections of the type SPEC_SCRIPT */
- private static final String[] SECTION_ENDING_HEADERS = { BUILD_SECTION, INSTALL_SECTION,
- PRETRANS_SECTION, PRE_SECTION, PREUN_SECTION, POST_SECTION, POSTUN_SECTION, POSTTRANS_SECTION,
- CLEAN_SECTION, FILES_SECTION};
-
- public SpecfilePartitionScanner() {
- super();
-
- IToken specPrep = new Token(SPEC_PREP);
- IToken specScript = new Token(SPEC_SCRIPT);
- IToken specFiles = new Token(SPEC_FILES);
- IToken specChangelog = new Token(SPEC_CHANGELOG);
- IToken specPackages = new Token(SPEC_PACKAGES);
- IToken specGroup = new Token(SPEC_GROUP);
-
- List<IRule> rules = new ArrayList<>();
-
- // RPM packages
- for (String packageTag : SpecfilePackagesScanner.PACKAGES_TAGS) {
- rules.add(new SingleLineRule(packageTag, "", specPackages, (char)0 , true)); //$NON-NLS-1$
- }
-
- // %prep
- rules.add(new SectionRule(PREP_SECTION, new String[] { BUILD_SECTION }, specPrep));
-
- // %changelog
- rules.add(new MultiLineRule(RpmSections.CHANGELOG_SECTION, "", specChangelog, (char)0 , true)); //$NON-NLS-1$
-
- // "%build", "%install", "%pre", "%preun", "%post", "%postun"
- for (String sectionHeader : SECTION_HEADERS) {
- rules.add(new SectionRule(sectionHeader, SECTION_ENDING_HEADERS, specScript));
- }
-
- // comments
- rules.add(new CommentRule(specScript));
-
- // group tag
- rules.add(new EndOfLineRule("Group:", specGroup)); //$NON-NLS-1$
-
-
- // %files
- rules.add(new SectionRule(FILES_SECTION, new String[] { FILES_SECTION,
- CHANGELOG_SECTION }, specFiles));
-
- IPredicateRule[] result= new IPredicateRule[rules.size()];
- rules.toArray(result);
- setPredicateRules(result);
- }
+ public static final String SPEC_PREP = "__spec_prep"; //$NON-NLS-1$
+ public static final String SPEC_SCRIPT = "__spec_script"; //$NON-NLS-1$
+ public static final String SPEC_FILES = "__spec_files"; //$NON-NLS-1$
+ public static final String SPEC_CHANGELOG = "__spec_changelog"; //$NON-NLS-1$
+ public static final String SPEC_PACKAGES = "__spec_packages"; //$NON-NLS-1$
+ public static final String SPEC_GROUP = "__spec_group"; //$NON-NLS-1$
+ public static final String SPEC_FILE_PARTITIONING = "___spec_partitioning"; //$NON-NLS-1$
+
+ public static final String[] SPEC_PARTITION_TYPES = { IDocument.DEFAULT_CONTENT_TYPE, SPEC_PREP, SPEC_SCRIPT,
+ SPEC_FILES, SPEC_CHANGELOG, SPEC_PACKAGES, SPEC_GROUP};
+
+ /** All possible headers for sections of the type SPEC_SCRIPT */
+ private static final String[] SECTION_HEADERS = { BUILD_SECTION, INSTALL_SECTION,
+ PRETRANS_SECTION, PRE_SECTION, PREUN_SECTION, POST_SECTION, POSTUN_SECTION,
+ POSTTRANS_SECTION, CLEAN_SECTION};
+
+ /** All possible headers for section that can come after sections of the type SPEC_SCRIPT */
+ private static final String[] SECTION_ENDING_HEADERS = { BUILD_SECTION, INSTALL_SECTION,
+ PRETRANS_SECTION, PRE_SECTION, PREUN_SECTION, POST_SECTION, POSTUN_SECTION, POSTTRANS_SECTION,
+ CLEAN_SECTION, FILES_SECTION};
+
+ public SpecfilePartitionScanner() {
+ super();
+
+ IToken specPrep = new Token(SPEC_PREP);
+ IToken specScript = new Token(SPEC_SCRIPT);
+ IToken specFiles = new Token(SPEC_FILES);
+ IToken specChangelog = new Token(SPEC_CHANGELOG);
+ IToken specPackages = new Token(SPEC_PACKAGES);
+ IToken specGroup = new Token(SPEC_GROUP);
+
+ List<IRule> rules = new ArrayList<>();
+
+ // RPM packages
+ for (String packageTag : SpecfilePackagesScanner.PACKAGES_TAGS) {
+ rules.add(new SingleLineRule(packageTag, "", specPackages, (char)0 , true)); //$NON-NLS-1$
+ }
+
+ // %prep
+ rules.add(new SectionRule(PREP_SECTION, new String[] { BUILD_SECTION }, specPrep));
+
+ // %changelog
+ rules.add(new MultiLineRule(RpmSections.CHANGELOG_SECTION, "", specChangelog, (char)0 , true)); //$NON-NLS-1$
+
+ // "%build", "%install", "%pre", "%preun", "%post", "%postun"
+ for (String sectionHeader : SECTION_HEADERS) {
+ rules.add(new SectionRule(sectionHeader, SECTION_ENDING_HEADERS, specScript));
+ }
+
+ // comments
+ rules.add(new CommentRule(specScript));
+
+ // group tag
+ rules.add(new EndOfLineRule("Group:", specGroup)); //$NON-NLS-1$
+
+
+ // %files
+ rules.add(new SectionRule(FILES_SECTION, new String[] { FILES_SECTION,
+ CHANGELOG_SECTION }, specFiles));
+
+ IPredicateRule[] result= new IPredicateRule[rules.size()];
+ rules.toArray(result);
+ setPredicateRules(result);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfileScanner.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfileScanner.java
index 28877f644c..585bf6015d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfileScanner.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/scanners/SpecfileScanner.java
@@ -74,88 +74,88 @@ import org.eclipse.swt.SWT;
public class SpecfileScanner extends RuleBasedScanner {
- private static final String[] SECTIONS = { PREP_SECTION, BUILD_SECTION, INSTALL_SECTION,
- PRETRANS_SECTION, PRE_SECTION, PREUN_SECTION, POST_SECTION, FILES_SECTION, CHANGELOG_SECTION,
- PACKAGE_SECTION, DESCRIPTION_SECTION, POSTUN_SECTION, POSTTRANS_SECTION, CLEAN_SECTION,
- CHECK_SECTION };
-
- public static final String[] DEFINED_MACROS = {
- "%define", "%global", "%make", "%setup", "%autosetup", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- "%attrib", "%defattr", "%attr", "%dir", "%config", "%docdir", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "%doc", "%lang", "%verify", "%ghost" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-
- private static final String[] KEYWORDS = { "%if", "%ifarch", "%ifnarch", "%else", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- "%endif" }; //$NON-NLS-1$
-
- private static final String[] TAGS = { SUMMARY, NAME, VERSION, PACKAGER, ICON,
- URL, PREFIX, GROUP, LICENSE, RELEASE, BUILD_ROOT, DISTRIBUTION,
- VENDOR, PROVIDES, EXCLUSIVE_ARCH, EXCLUDE_ARCH, EXCLUDE_OS,
- BUILD_ARCH, BUILD_ARCHITECTURES, AUTO_REQUIRES, AUTO_REQ,
- AUTO_REQ_PROV, AUTO_PROV, EPOCH };
-
- public SpecfileScanner(ColorManager manager) {
- super();
- IToken sectionToken = new Token(new TextAttribute(manager
- .getColor(ISpecfileColorConstants.SECTIONS), null, SWT.ITALIC));
-
- IToken macroToken = new Token(new TextAttribute(manager
- .getColor(ISpecfileColorConstants.MACROS)));
-
- IToken keywordToken = new Token(new TextAttribute(manager
- .getColor(ISpecfileColorConstants.KEYWORDS), null, SWT.BOLD));
-
- IToken tagToken = new Token(new TextAttribute(manager
- .getColor(ISpecfileColorConstants.TAGS)));
-
- IToken commentToken = new Token(new TextAttribute(manager
- .getColor(ISpecfileColorConstants.COMMENT)));
-
- List<IRule> rules = new ArrayList<>();
-
- rules.add(new CommentRule(commentToken));
- rules.add(new MacroRule( macroToken));
-
- // %define, %make, ...
- WordRule wordRule = new WordRule(new MacroWordDetector(),
- Token.UNDEFINED);
- for (String definedMacro : DEFINED_MACROS) {
- wordRule.addWord(definedMacro, macroToken);
- }
- rules.add(wordRule);
-
- // %patch[0-9]+[\ \t]
- rules.add(new StringWithEndingRule("%patch", new PatchNumberDetector(), //$NON-NLS-1$
- macroToken, false ));
-
- // %if, %else ...
- wordRule = new WordRule(new KeywordWordDetector(), Token.UNDEFINED);
- for (String keyword : KEYWORDS) {
- wordRule.addWord(keyword, keywordToken);
- }
- rules.add(wordRule);
-
- // %prep, %build, ...
- wordRule = new WordRule(new KeywordWordDetector(), Token.UNDEFINED);
- for (String section : SECTIONS) {
- wordRule.addWord(section, sectionToken);
- }
- rules.add(wordRule);
-
- // Name:, Summary:, ...
- wordRule = new WordRule(new TagWordDetector(), Token.UNDEFINED);
- for (String tag : TAGS) {
- wordRule.addWord(tag + ":", tagToken); //$NON-NLS-1$
- }
- rules.add(wordRule);
-
- // Source[0-9]*:, Patch[0-9]*:
- rules.add(new StringWithEndingRule("Source", //$NON-NLS-1$
- new SuffixNumberDetector(), tagToken, false));
- rules.add(new StringWithEndingRule("Patch", new SuffixNumberDetector(), //$NON-NLS-1$
- tagToken, false));
-
- IRule[] result = new IRule[rules.size()];
- rules.toArray(result);
- setRules(result);
- }
+ private static final String[] SECTIONS = { PREP_SECTION, BUILD_SECTION, INSTALL_SECTION,
+ PRETRANS_SECTION, PRE_SECTION, PREUN_SECTION, POST_SECTION, FILES_SECTION, CHANGELOG_SECTION,
+ PACKAGE_SECTION, DESCRIPTION_SECTION, POSTUN_SECTION, POSTTRANS_SECTION, CLEAN_SECTION,
+ CHECK_SECTION };
+
+ public static final String[] DEFINED_MACROS = {
+ "%define", "%global", "%make", "%setup", "%autosetup", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ "%attrib", "%defattr", "%attr", "%dir", "%config", "%docdir", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "%doc", "%lang", "%verify", "%ghost" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+
+ private static final String[] KEYWORDS = { "%if", "%ifarch", "%ifnarch", "%else", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ "%endif" }; //$NON-NLS-1$
+
+ private static final String[] TAGS = { SUMMARY, NAME, VERSION, PACKAGER, ICON,
+ URL, PREFIX, GROUP, LICENSE, RELEASE, BUILD_ROOT, DISTRIBUTION,
+ VENDOR, PROVIDES, EXCLUSIVE_ARCH, EXCLUDE_ARCH, EXCLUDE_OS,
+ BUILD_ARCH, BUILD_ARCHITECTURES, AUTO_REQUIRES, AUTO_REQ,
+ AUTO_REQ_PROV, AUTO_PROV, EPOCH };
+
+ public SpecfileScanner(ColorManager manager) {
+ super();
+ IToken sectionToken = new Token(new TextAttribute(manager
+ .getColor(ISpecfileColorConstants.SECTIONS), null, SWT.ITALIC));
+
+ IToken macroToken = new Token(new TextAttribute(manager
+ .getColor(ISpecfileColorConstants.MACROS)));
+
+ IToken keywordToken = new Token(new TextAttribute(manager
+ .getColor(ISpecfileColorConstants.KEYWORDS), null, SWT.BOLD));
+
+ IToken tagToken = new Token(new TextAttribute(manager
+ .getColor(ISpecfileColorConstants.TAGS)));
+
+ IToken commentToken = new Token(new TextAttribute(manager
+ .getColor(ISpecfileColorConstants.COMMENT)));
+
+ List<IRule> rules = new ArrayList<>();
+
+ rules.add(new CommentRule(commentToken));
+ rules.add(new MacroRule( macroToken));
+
+ // %define, %make, ...
+ WordRule wordRule = new WordRule(new MacroWordDetector(),
+ Token.UNDEFINED);
+ for (String definedMacro : DEFINED_MACROS) {
+ wordRule.addWord(definedMacro, macroToken);
+ }
+ rules.add(wordRule);
+
+ // %patch[0-9]+[\ \t]
+ rules.add(new StringWithEndingRule("%patch", new PatchNumberDetector(), //$NON-NLS-1$
+ macroToken, false ));
+
+ // %if, %else ...
+ wordRule = new WordRule(new KeywordWordDetector(), Token.UNDEFINED);
+ for (String keyword : KEYWORDS) {
+ wordRule.addWord(keyword, keywordToken);
+ }
+ rules.add(wordRule);
+
+ // %prep, %build, ...
+ wordRule = new WordRule(new KeywordWordDetector(), Token.UNDEFINED);
+ for (String section : SECTIONS) {
+ wordRule.addWord(section, sectionToken);
+ }
+ rules.add(wordRule);
+
+ // Name:, Summary:, ...
+ wordRule = new WordRule(new TagWordDetector(), Token.UNDEFINED);
+ for (String tag : TAGS) {
+ wordRule.addWord(tag + ":", tagToken); //$NON-NLS-1$
+ }
+ rules.add(wordRule);
+
+ // Source[0-9]*:, Patch[0-9]*:
+ rules.add(new StringWithEndingRule("Source", //$NON-NLS-1$
+ new SuffixNumberDetector(), tagToken, false));
+ rules.add(new StringWithEndingRule("Patch", new SuffixNumberDetector(), //$NON-NLS-1$
+ tagToken, false));
+
+ IRule[] result = new IRule[rules.size()];
+ rules.toArray(result);
+ setRules(result);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/wizards/NoExecutableWizardPage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/wizards/NoExecutableWizardPage.java
index 6882cda0d5..1b050355fd 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/wizards/NoExecutableWizardPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/wizards/NoExecutableWizardPage.java
@@ -21,34 +21,34 @@ import org.eclipse.swt.widgets.Label;
public class NoExecutableWizardPage extends WizardPage {
- protected NoExecutableWizardPage() {
- super(Messages.NoExecutableWizardPage_0);
- this.setImageDescriptor(ImageDescriptor.createFromFile(getClass(),
- "/icons/rpm.gif")); //$NON-NLS-1$
- }
-
- @Override
- public void createControl(Composite parent) {
- final Composite container = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 3;
- layout.verticalSpacing = 9;
-
- // Project
- Label label = new Label(container, SWT.NULL);
- label
- .setText(Messages.NoExecutableWizardPage_1);
- // empty label for the last row.
- new Label(container, SWT.NULL);
- setControl(container);
- this.setTitle(Messages.NoExecutableWizardPage_2);
- }
-
- @Override
- public boolean isPageComplete() {
- return false;
- }
+ protected NoExecutableWizardPage() {
+ super(Messages.NoExecutableWizardPage_0);
+ this.setImageDescriptor(ImageDescriptor.createFromFile(getClass(),
+ "/icons/rpm.gif")); //$NON-NLS-1$
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ final Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 3;
+ layout.verticalSpacing = 9;
+
+ // Project
+ Label label = new Label(container, SWT.NULL);
+ label
+ .setText(Messages.NoExecutableWizardPage_1);
+ // empty label for the last row.
+ new Label(container, SWT.NULL);
+ setControl(container);
+ this.setTitle(Messages.NoExecutableWizardPage_2);
+ }
+
+ @Override
+ public boolean isPageComplete() {
+ return false;
+ }
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/wizards/SpecfileNewWizard.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/wizards/SpecfileNewWizard.java
index a468a16eef..fb9e94d2cb 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/wizards/SpecfileNewWizard.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/internal/rpm/ui/editor/wizards/SpecfileNewWizard.java
@@ -45,132 +45,132 @@ import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
public class SpecfileNewWizard extends Wizard implements INewWizard {
- private SpecfileNewWizardPage page;
- private ISelection selection;
+ private SpecfileNewWizardPage page;
+ private ISelection selection;
- /**
- * Constructor for SpecfileNewWizard.
- */
- public SpecfileNewWizard() {
- super();
- setNeedsProgressMonitor(true);
- }
+ /**
+ * Constructor for SpecfileNewWizard.
+ */
+ public SpecfileNewWizard() {
+ super();
+ setNeedsProgressMonitor(true);
+ }
- /**
- * Adding the page to the wizard.
- */
- @Override
- public void addPages() {
- if (!Utils.fileExist("/usr/bin/rpmdev-newspec")) { //$NON-NLS-1$
- addPage(new NoExecutableWizardPage());
- } else {
- page = new SpecfileNewWizardPage(selection);
- addPage(page);
- }
- }
+ /**
+ * Adding the page to the wizard.
+ */
+ @Override
+ public void addPages() {
+ if (!Utils.fileExist("/usr/bin/rpmdev-newspec")) { //$NON-NLS-1$
+ addPage(new NoExecutableWizardPage());
+ } else {
+ page = new SpecfileNewWizardPage(selection);
+ addPage(page);
+ }
+ }
- /**
- * This method is called when 'Finish' button is pressed in the wizard. We
- * will create an operation and run it using wizard as execution context.
- */
- @Override
- public boolean performFinish() {
- final String containerName = page.getProjectName();
- final String fileName = page.getFileName();
- final InputStream contentInputStream = openContentStream();
- IRunnableWithProgress op = new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor)
- throws InvocationTargetException {
- try {
- doFinish(containerName, fileName, contentInputStream,
- monitor);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
- };
- try {
- getContainer().run(true, false, op);
- } catch (InterruptedException e) {
- return false;
- } catch (InvocationTargetException e) {
- SpecfileLog.logError(e);
- Throwable realException = e.getTargetException();
- MessageDialog.openError(getShell(), Messages.SpecfileNewWizard_0,
- realException.getMessage());
- return false;
- }
- return true;
- }
+ /**
+ * This method is called when 'Finish' button is pressed in the wizard. We
+ * will create an operation and run it using wizard as execution context.
+ */
+ @Override
+ public boolean performFinish() {
+ final String containerName = page.getProjectName();
+ final String fileName = page.getFileName();
+ final InputStream contentInputStream = openContentStream();
+ IRunnableWithProgress op = new IRunnableWithProgress() {
+ @Override
+ public void run(IProgressMonitor monitor)
+ throws InvocationTargetException {
+ try {
+ doFinish(containerName, fileName, contentInputStream,
+ monitor);
+ } catch (CoreException e) {
+ throw new InvocationTargetException(e);
+ } finally {
+ monitor.done();
+ }
+ }
+ };
+ try {
+ getContainer().run(true, false, op);
+ } catch (InterruptedException e) {
+ return false;
+ } catch (InvocationTargetException e) {
+ SpecfileLog.logError(e);
+ Throwable realException = e.getTargetException();
+ MessageDialog.openError(getShell(), Messages.SpecfileNewWizard_0,
+ realException.getMessage());
+ return false;
+ }
+ return true;
+ }
- /**
- * The worker method. It will find the container, create the file if missing
- * or just replace its contents, and open the editor on the newly created
- * file.
- */
- private void doFinish(String projectName, String fileName,
- InputStream contentInputStream, IProgressMonitor monitor)
- throws CoreException {
- monitor.beginTask(Messages.SpecfileNewWizard_1 + fileName, 2);
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IResource resource = root.findMember(new Path(projectName));
- if (!resource.exists() || !(resource instanceof IContainer)) {
- throwCoreException(Messages.SpecfileNewWizard_2 + projectName
- + Messages.SpecfileNewWizard_3);
- }
- IContainer container = (IContainer) resource;
- final IFile file = container.getFile(new Path(fileName));
- try {
- InputStream stream = contentInputStream;
- if (file.exists()) {
- file.setContents(stream, true, true, monitor);
- } else {
- file.create(stream, true, monitor);
- }
- stream.close();
- } catch (IOException e) {
- }
- monitor.worked(1);
- monitor.setTaskName(Messages.SpecfileNewWizard_4);
- getShell().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- IWorkbenchPage page = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- try {
- IDE.openEditor(page, file, true);
- } catch (PartInitException e) {
- }
- }
- });
- monitor.worked(1);
- }
+ /**
+ * The worker method. It will find the container, create the file if missing
+ * or just replace its contents, and open the editor on the newly created
+ * file.
+ */
+ private void doFinish(String projectName, String fileName,
+ InputStream contentInputStream, IProgressMonitor monitor)
+ throws CoreException {
+ monitor.beginTask(Messages.SpecfileNewWizard_1 + fileName, 2);
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ IResource resource = root.findMember(new Path(projectName));
+ if (!resource.exists() || !(resource instanceof IContainer)) {
+ throwCoreException(Messages.SpecfileNewWizard_2 + projectName
+ + Messages.SpecfileNewWizard_3);
+ }
+ IContainer container = (IContainer) resource;
+ final IFile file = container.getFile(new Path(fileName));
+ try {
+ InputStream stream = contentInputStream;
+ if (file.exists()) {
+ file.setContents(stream, true, true, monitor);
+ } else {
+ file.create(stream, true, monitor);
+ }
+ stream.close();
+ } catch (IOException e) {
+ }
+ monitor.worked(1);
+ monitor.setTaskName(Messages.SpecfileNewWizard_4);
+ getShell().getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ IWorkbenchPage page = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
+ try {
+ IDE.openEditor(page, file, true);
+ } catch (PartInitException e) {
+ }
+ }
+ });
+ monitor.worked(1);
+ }
- /**
- * We will initialize file contents with the modified template text.
- */
- private InputStream openContentStream() {
- String contents = page.getContent();
- return new ByteArrayInputStream(contents.getBytes());
- }
+ /**
+ * We will initialize file contents with the modified template text.
+ */
+ private InputStream openContentStream() {
+ String contents = page.getContent();
+ return new ByteArrayInputStream(contents.getBytes());
+ }
- private void throwCoreException(String message) throws CoreException {
- IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID,
- IStatus.OK, message, null);
- throw new CoreException(status);
- }
+ private void throwCoreException(String message) throws CoreException {
+ IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID,
+ IStatus.OK, message, null);
+ throw new CoreException(status);
+ }
- /**
- * We will accept the selection in the workbench to see if we can initialize
- * from it.
- *
- * @see INewWizard#init(IWorkbench, IStructuredSelection)
- */
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- this.selection = selection;
- }
+ /**
+ * We will accept the selection in the workbench to see if we can initialize
+ * from it.
+ *
+ * @see INewWizard#init(IWorkbench, IStructuredSelection)
+ */
+ @Override
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ this.selection = selection;
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/SpecfileEditor.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/SpecfileEditor.java
index 54e9e065fc..442381edb0 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/SpecfileEditor.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/SpecfileEditor.java
@@ -42,207 +42,207 @@ import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
public class SpecfileEditor extends TextEditor {
- private ColorManager colorManager;
- private SpecfileContentOutlinePage outlinePage;
- private IEditorInput input;
- private Specfile specfile;
- private SpecfileParser parser;
- private RpmMacroOccurrencesUpdater fOccurrencesUpdater;
- private ProjectionSupport projectionSupport;
- private static SpecfileDocumentProvider fDocumentProvider;
-
- public SpecfileEditor() {
- super();
- colorManager = new ColorManager();
- parser = getParser();
- setSourceViewerConfiguration(new SpecfileConfiguration(colorManager,
- this));
- setKeyBindingScopes(new String[] { "org.eclipse.linuxtools.rpm.ui.specEditorScope" }); //$NON-NLS-1$
- }
-
- @Override
- public void dispose() {
- colorManager.dispose();
- // Set specfile field to null here is useful for test cases because
- // whether
- // the specfile in null SpecfileReconcilingStrategy#reconcile don't
- // update anything and thus it don't give false stacktraces.
- specfile = null;
- super.dispose();
- }
-
- @Override
- protected void doSetInput(IEditorInput newInput) throws CoreException {
- super.doSetInput(newInput);
- this.input = newInput;
-
- if (outlinePage != null) {
- outlinePage.setInput(input);
- }
-
- validateAndMark();
- }
-
- @Override
- protected void editorSaved() {
- super.editorSaved();
-
- // we validate and mark document here
- validateAndMark();
-
- if (outlinePage != null) {
- outlinePage.update();
- }
- }
-
- protected void validateAndMark() {
- try {
- IDocument document = getDocumentProvider().getDocument(input);
- SpecfileErrorHandler specfileErrorHandler = new SpecfileErrorHandler(
- getEditorInput(), document);
- specfileErrorHandler.removeExistingMarkers();
- SpecfileTaskHandler specfileTaskHandler = new SpecfileTaskHandler(
- getInputFile(), document);
- specfileTaskHandler.removeExistingMarkers();
- this.parser.setErrorHandler(specfileErrorHandler);
- this.parser.setTaskHandler(specfileTaskHandler);
- specfile = parser.parse(document);
- } catch (Exception e) {
- SpecfileLog.logError(e);
- }
- }
-
- /**
- * Get a {@link IFile}, this implementation return <code>null</code> if the
- * <code>IEditorInput</code> instance is not of type
- * {@link IFileEditorInput}.
- *
- * @return a <code>IFile</code> or <code>null</code>.
- */
- protected IFile getInputFile() {
- if (input instanceof IFileEditorInput) {
- IFileEditorInput ife = (IFileEditorInput) input;
- return ife.getFile();
- }
- return null;
- }
-
- @Override
- public Object getAdapter(Class required) {
- if (IContentOutlinePage.class.equals(required)) {
- return getOutlinePage();
- }
- if (IDocument.class.equals(required)) {
- return getDocumentProvider().getDocument(input);
- }
- if (projectionSupport != null) {
- Object adapter = projectionSupport.getAdapter(getSourceViewer(),
- required);
- if (adapter != null) {
- return adapter;
- }
- }
- return super.getAdapter(required);
- }
-
- /*
- * @see
- * org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createSourceViewer
- * (org.eclipse.swt.widgets.Composite,
- * org.eclipse.jface.text.source.IVerticalRuler, int)
- */
- @Override
- protected ISourceViewer createSourceViewer(Composite parent,
- IVerticalRuler ruler, int styles) {
- fAnnotationAccess = createAnnotationAccess();
- fOverviewRuler = createOverviewRuler(getSharedColors());
- ISourceViewer viewer = new ProjectionViewer(parent, ruler,
- fOverviewRuler, true, styles);
- getSourceViewerDecorationSupport(viewer);
- return viewer;
- }
-
- private ContentOutlinePage getOutlinePage() {
- if (outlinePage == null) {
- outlinePage = new SpecfileContentOutlinePage(this);
- if (getEditorInput() != null) {
- outlinePage.setInput(getEditorInput());
- }
- }
- return outlinePage;
- }
-
- public Specfile getSpecfile() {
- return specfile;
- }
-
- /*
- * If there is no explicit document provider set, the implicit one is
- * re-initialized based on the given editor input.
- *
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#setDocumentProvider(org.eclipse.ui.IEditorInput)
- */
- @Override
- protected void setDocumentProvider(IEditorInput input) {
- setDocumentProvider(getSpecfileDocumentProvider());
- }
-
- public static TextFileDocumentProvider getSpecfileDocumentProvider() {
- if (fDocumentProvider == null) {
- fDocumentProvider = new SpecfileDocumentProvider();
- }
- return fDocumentProvider;
- }
-
- /*
- * @see
- * org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createPartControl
- * (org.eclipse.swt.widgets.Composite)
- */
- @Override
- public void createPartControl(Composite parent) {
- super.createPartControl(parent);
- ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
- projectionSupport = new ProjectionSupport(projectionViewer,
- getAnnotationAccess(), getSharedColors());
- projectionSupport.install();
- projectionViewer.doOperation(ProjectionViewer.TOGGLE);
- fOccurrencesUpdater = new RpmMacroOccurrencesUpdater(this);
- }
-
- public void setSpecfile(Specfile specfile) {
- this.specfile = specfile;
- if (fOccurrencesUpdater != null) {
- Shell shell = getSite().getShell();
- if (!(shell == null || shell.isDisposed())) {
- shell.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- ISourceViewer viewer = getSourceViewer();
- if (viewer != null) {
- fOccurrencesUpdater.update(viewer);
- }
- }
- });
- }
- }
-
- }
-
- public final SpecfileParser getParser() {
- if (parser == null) {
- parser = new SpecfileParser();
- }
- return parser;
- }
-
- /**
- * Get the spefile source viewer, this method is useful for test cases.
- *
- * @return the specfile source viewer
- */
- public SourceViewer getSpecfileSourceViewer() {
- return (SourceViewer) getSourceViewer();
- }
+ private ColorManager colorManager;
+ private SpecfileContentOutlinePage outlinePage;
+ private IEditorInput input;
+ private Specfile specfile;
+ private SpecfileParser parser;
+ private RpmMacroOccurrencesUpdater fOccurrencesUpdater;
+ private ProjectionSupport projectionSupport;
+ private static SpecfileDocumentProvider fDocumentProvider;
+
+ public SpecfileEditor() {
+ super();
+ colorManager = new ColorManager();
+ parser = getParser();
+ setSourceViewerConfiguration(new SpecfileConfiguration(colorManager,
+ this));
+ setKeyBindingScopes(new String[] { "org.eclipse.linuxtools.rpm.ui.specEditorScope" }); //$NON-NLS-1$
+ }
+
+ @Override
+ public void dispose() {
+ colorManager.dispose();
+ // Set specfile field to null here is useful for test cases because
+ // whether
+ // the specfile in null SpecfileReconcilingStrategy#reconcile don't
+ // update anything and thus it don't give false stacktraces.
+ specfile = null;
+ super.dispose();
+ }
+
+ @Override
+ protected void doSetInput(IEditorInput newInput) throws CoreException {
+ super.doSetInput(newInput);
+ this.input = newInput;
+
+ if (outlinePage != null) {
+ outlinePage.setInput(input);
+ }
+
+ validateAndMark();
+ }
+
+ @Override
+ protected void editorSaved() {
+ super.editorSaved();
+
+ // we validate and mark document here
+ validateAndMark();
+
+ if (outlinePage != null) {
+ outlinePage.update();
+ }
+ }
+
+ protected void validateAndMark() {
+ try {
+ IDocument document = getDocumentProvider().getDocument(input);
+ SpecfileErrorHandler specfileErrorHandler = new SpecfileErrorHandler(
+ getEditorInput(), document);
+ specfileErrorHandler.removeExistingMarkers();
+ SpecfileTaskHandler specfileTaskHandler = new SpecfileTaskHandler(
+ getInputFile(), document);
+ specfileTaskHandler.removeExistingMarkers();
+ this.parser.setErrorHandler(specfileErrorHandler);
+ this.parser.setTaskHandler(specfileTaskHandler);
+ specfile = parser.parse(document);
+ } catch (Exception e) {
+ SpecfileLog.logError(e);
+ }
+ }
+
+ /**
+ * Get a {@link IFile}, this implementation return <code>null</code> if the
+ * <code>IEditorInput</code> instance is not of type
+ * {@link IFileEditorInput}.
+ *
+ * @return a <code>IFile</code> or <code>null</code>.
+ */
+ protected IFile getInputFile() {
+ if (input instanceof IFileEditorInput) {
+ IFileEditorInput ife = (IFileEditorInput) input;
+ return ife.getFile();
+ }
+ return null;
+ }
+
+ @Override
+ public Object getAdapter(Class required) {
+ if (IContentOutlinePage.class.equals(required)) {
+ return getOutlinePage();
+ }
+ if (IDocument.class.equals(required)) {
+ return getDocumentProvider().getDocument(input);
+ }
+ if (projectionSupport != null) {
+ Object adapter = projectionSupport.getAdapter(getSourceViewer(),
+ required);
+ if (adapter != null) {
+ return adapter;
+ }
+ }
+ return super.getAdapter(required);
+ }
+
+ /*
+ * @see
+ * org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createSourceViewer
+ * (org.eclipse.swt.widgets.Composite,
+ * org.eclipse.jface.text.source.IVerticalRuler, int)
+ */
+ @Override
+ protected ISourceViewer createSourceViewer(Composite parent,
+ IVerticalRuler ruler, int styles) {
+ fAnnotationAccess = createAnnotationAccess();
+ fOverviewRuler = createOverviewRuler(getSharedColors());
+ ISourceViewer viewer = new ProjectionViewer(parent, ruler,
+ fOverviewRuler, true, styles);
+ getSourceViewerDecorationSupport(viewer);
+ return viewer;
+ }
+
+ private ContentOutlinePage getOutlinePage() {
+ if (outlinePage == null) {
+ outlinePage = new SpecfileContentOutlinePage(this);
+ if (getEditorInput() != null) {
+ outlinePage.setInput(getEditorInput());
+ }
+ }
+ return outlinePage;
+ }
+
+ public Specfile getSpecfile() {
+ return specfile;
+ }
+
+ /*
+ * If there is no explicit document provider set, the implicit one is
+ * re-initialized based on the given editor input.
+ *
+ * @see org.eclipse.ui.texteditor.AbstractTextEditor#setDocumentProvider(org.eclipse.ui.IEditorInput)
+ */
+ @Override
+ protected void setDocumentProvider(IEditorInput input) {
+ setDocumentProvider(getSpecfileDocumentProvider());
+ }
+
+ public static TextFileDocumentProvider getSpecfileDocumentProvider() {
+ if (fDocumentProvider == null) {
+ fDocumentProvider = new SpecfileDocumentProvider();
+ }
+ return fDocumentProvider;
+ }
+
+ /*
+ * @see
+ * org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createPartControl
+ * (org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public void createPartControl(Composite parent) {
+ super.createPartControl(parent);
+ ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
+ projectionSupport = new ProjectionSupport(projectionViewer,
+ getAnnotationAccess(), getSharedColors());
+ projectionSupport.install();
+ projectionViewer.doOperation(ProjectionViewer.TOGGLE);
+ fOccurrencesUpdater = new RpmMacroOccurrencesUpdater(this);
+ }
+
+ public void setSpecfile(Specfile specfile) {
+ this.specfile = specfile;
+ if (fOccurrencesUpdater != null) {
+ Shell shell = getSite().getShell();
+ if (!(shell == null || shell.isDisposed())) {
+ shell.getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ ISourceViewer viewer = getSourceViewer();
+ if (viewer != null) {
+ fOccurrencesUpdater.update(viewer);
+ }
+ }
+ });
+ }
+ }
+
+ }
+
+ public final SpecfileParser getParser() {
+ if (parser == null) {
+ parser = new SpecfileParser();
+ }
+ return parser;
+ }
+
+ /**
+ * Get the spefile source viewer, this method is useful for test cases.
+ *
+ * @return the specfile source viewer
+ */
+ public SourceViewer getSpecfileSourceViewer() {
+ return (SourceViewer) getSourceViewer();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileErrorHandler.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileErrorHandler.java
index 036e8ab6a8..4a3fd85b2a 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileErrorHandler.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileErrorHandler.java
@@ -33,145 +33,145 @@ import org.eclipse.ui.part.FileEditorInput;
public class SpecfileErrorHandler extends SpecfileMarkerHandler {
- public static final String SPECFILE_ERROR_MARKER_ID = Activator.PLUGIN_ID
- + ".specfileerror"; //$NON-NLS-1$
-
- public static final String ANNOTATION_ERROR = "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$
- public static final String ANNOTATION_WARNING = "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$
- public static final String ANNOTATION_INFO = "org.eclipse.ui.workbench.texteditor.info"; //$NON-NLS-1$
-
- private Map<Position, Annotation> annotations = new HashMap<>();
- private AnnotationModel fAnnotationModel;
- private IEditorInput input;
-
- public SpecfileErrorHandler(IEditorInput input, IDocument document) {
- super(null, document);
- this.input = input;
- fAnnotationModel = getAnnotationModel();
- }
-
- private static class SpecfileAnnotation extends Annotation implements IQuickFixableAnnotation {
- public SpecfileAnnotation(String annotationType, boolean persist, String message) {
- super(annotationType, persist, message);
- }
-
- /**
- * Tells whether this annotation is quick fixable.
- */
- private boolean fIsQuickFixable;
- /**
- * Tells whether the quick fixable state (<code>fIsQuickFixable</code> has been computed.
- */
- private boolean fIsQuickFixableStateSet;
-
- /**
- * {@inheritDoc}
- *
- */
- @Override
- public void setQuickFixable(boolean state) {
- fIsQuickFixable= state;
- fIsQuickFixableStateSet= true;
- }
-
- /**
- * {@inheritDoc}
- *
- */
- @Override
- public boolean isQuickFixableStateSet() {
- return fIsQuickFixableStateSet;
- }
-
- /**
- * {@inheritDoc}
- *
- */
- @Override
- public boolean isQuickFixable() {
- Assert.isTrue(isQuickFixableStateSet());
- return fIsQuickFixable;
- }
-
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.linuxtools.cdt.autotools.ui.editors.IAutoconfErrorHandler#handleError(org.eclipse.linuxtools.cdt.autotools.core.ui.editors.parser.ParseException)
- */
- public void handleError(SpecfileParseException e) {
-
- int lineNumber = e.getLineNumber();
- int lineOffset = 0;
- try {
- lineOffset = document.getLineOffset(lineNumber);
- } catch (BadLocationException e2) {
- // do nothing
- }
-
- Integer charStart = Integer.valueOf(lineOffset + e.getStartColumn());
- Integer charEnd = Integer.valueOf(lineOffset + e.getEndColumn());
- String annotationType = ANNOTATION_INFO;
- if (e.getSeverity() == IMarker.SEVERITY_ERROR) {
- annotationType = ANNOTATION_ERROR;
- } else if (e.getSeverity() == IMarker.SEVERITY_WARNING) {
- annotationType = ANNOTATION_WARNING;
- }
- Annotation annotation = new SpecfileAnnotation(annotationType, true, e.getLocalizedMessage());
- Position p = new Position(charStart.intValue(),charEnd.intValue() - charStart.intValue());
- if (fAnnotationModel != null) {
- fAnnotationModel.addAnnotation(annotation, p);
- }
- annotations.put(p, annotation);
- return;
- }
-
- public void removeAllExistingMarkers()
- {
- fAnnotationModel.removeAllAnnotations();
- annotations.clear();
- }
-
- @Override
- public void removeExistingMarkers() {
- removeExistingMarkers(0, document.getLength());
- }
-
- private AnnotationModel getAnnotationModel() {
- return (AnnotationModel)SpecfileEditor.getSpecfileDocumentProvider().getAnnotationModel(input);
- }
-
- public void removeExistingMarkers(int offset, int length)
- {
- if (fAnnotationModel != null) {
- Iterator<Annotation> i = fAnnotationModel.getAnnotationIterator();
- while (i.hasNext()) {
- Annotation annotation = i.next();
- Position p = fAnnotationModel.getPosition(annotation);
- if (p != null) {
- int pStart = p.getOffset();
- if (pStart >= offset && pStart < (offset + length)) {
- // Remove directly from model instead of using
- // iterator so position will be removed from document.
- fAnnotationModel.removeAnnotation(annotation);
- }
- }
- }
- }
- }
-
- public SpecfileErrorHandler(IFile file, IDocument document)
- {
- this(new FileEditorInput(file), document);
- }
-
- @Override
- public void setFile(IFile file) {
- input = new FileEditorInput(file);
- }
-
- @Override
- String getMarkerID() {
- return SPECFILE_ERROR_MARKER_ID;
- }
+ public static final String SPECFILE_ERROR_MARKER_ID = Activator.PLUGIN_ID
+ + ".specfileerror"; //$NON-NLS-1$
+
+ public static final String ANNOTATION_ERROR = "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$
+ public static final String ANNOTATION_WARNING = "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$
+ public static final String ANNOTATION_INFO = "org.eclipse.ui.workbench.texteditor.info"; //$NON-NLS-1$
+
+ private Map<Position, Annotation> annotations = new HashMap<>();
+ private AnnotationModel fAnnotationModel;
+ private IEditorInput input;
+
+ public SpecfileErrorHandler(IEditorInput input, IDocument document) {
+ super(null, document);
+ this.input = input;
+ fAnnotationModel = getAnnotationModel();
+ }
+
+ private static class SpecfileAnnotation extends Annotation implements IQuickFixableAnnotation {
+ public SpecfileAnnotation(String annotationType, boolean persist, String message) {
+ super(annotationType, persist, message);
+ }
+
+ /**
+ * Tells whether this annotation is quick fixable.
+ */
+ private boolean fIsQuickFixable;
+ /**
+ * Tells whether the quick fixable state (<code>fIsQuickFixable</code> has been computed.
+ */
+ private boolean fIsQuickFixableStateSet;
+
+ /**
+ * {@inheritDoc}
+ *
+ */
+ @Override
+ public void setQuickFixable(boolean state) {
+ fIsQuickFixable= state;
+ fIsQuickFixableStateSet= true;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ */
+ @Override
+ public boolean isQuickFixableStateSet() {
+ return fIsQuickFixableStateSet;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ */
+ @Override
+ public boolean isQuickFixable() {
+ Assert.isTrue(isQuickFixableStateSet());
+ return fIsQuickFixable;
+ }
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.linuxtools.cdt.autotools.ui.editors.IAutoconfErrorHandler#handleError(org.eclipse.linuxtools.cdt.autotools.core.ui.editors.parser.ParseException)
+ */
+ public void handleError(SpecfileParseException e) {
+
+ int lineNumber = e.getLineNumber();
+ int lineOffset = 0;
+ try {
+ lineOffset = document.getLineOffset(lineNumber);
+ } catch (BadLocationException e2) {
+ // do nothing
+ }
+
+ Integer charStart = Integer.valueOf(lineOffset + e.getStartColumn());
+ Integer charEnd = Integer.valueOf(lineOffset + e.getEndColumn());
+ String annotationType = ANNOTATION_INFO;
+ if (e.getSeverity() == IMarker.SEVERITY_ERROR) {
+ annotationType = ANNOTATION_ERROR;
+ } else if (e.getSeverity() == IMarker.SEVERITY_WARNING) {
+ annotationType = ANNOTATION_WARNING;
+ }
+ Annotation annotation = new SpecfileAnnotation(annotationType, true, e.getLocalizedMessage());
+ Position p = new Position(charStart.intValue(),charEnd.intValue() - charStart.intValue());
+ if (fAnnotationModel != null) {
+ fAnnotationModel.addAnnotation(annotation, p);
+ }
+ annotations.put(p, annotation);
+ return;
+ }
+
+ public void removeAllExistingMarkers()
+ {
+ fAnnotationModel.removeAllAnnotations();
+ annotations.clear();
+ }
+
+ @Override
+ public void removeExistingMarkers() {
+ removeExistingMarkers(0, document.getLength());
+ }
+
+ private AnnotationModel getAnnotationModel() {
+ return (AnnotationModel)SpecfileEditor.getSpecfileDocumentProvider().getAnnotationModel(input);
+ }
+
+ public void removeExistingMarkers(int offset, int length)
+ {
+ if (fAnnotationModel != null) {
+ Iterator<Annotation> i = fAnnotationModel.getAnnotationIterator();
+ while (i.hasNext()) {
+ Annotation annotation = i.next();
+ Position p = fAnnotationModel.getPosition(annotation);
+ if (p != null) {
+ int pStart = p.getOffset();
+ if (pStart >= offset && pStart < (offset + length)) {
+ // Remove directly from model instead of using
+ // iterator so position will be removed from document.
+ fAnnotationModel.removeAnnotation(annotation);
+ }
+ }
+ }
+ }
+ }
+
+ public SpecfileErrorHandler(IFile file, IDocument document)
+ {
+ this(new FileEditorInput(file), document);
+ }
+
+ @Override
+ public void setFile(IFile file) {
+ input = new FileEditorInput(file);
+ }
+
+ @Override
+ String getMarkerID() {
+ return SPECFILE_ERROR_MARKER_ID;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileMarkerHandler.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileMarkerHandler.java
index 577c9e8100..cd951bc5b1 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileMarkerHandler.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileMarkerHandler.java
@@ -19,43 +19,43 @@ import org.eclipse.linuxtools.internal.rpm.ui.editor.SpecfileLog;
public abstract class SpecfileMarkerHandler {
- IDocument document;
- IFile file;
-
- public SpecfileMarkerHandler(IFile file, IDocument document) {
- this.file = file;
- this.document = document;
- }
-
- abstract String getMarkerID();
-
- protected Integer getCharOffset(int lineNumber, int columnNumber) {
- try {
- return document.getLineOffset(lineNumber)
- + columnNumber;
- } catch (BadLocationException e) {
- SpecfileLog.logError(e);
- return null;
- }
- }
-
- public void removeExistingMarkers() {
- if (file == null || !file.exists()) {
- return;
- }
-
- try {
- file.deleteMarkers(getMarkerID(), true, IResource.DEPTH_ZERO);
- } catch (CoreException e1) {
- SpecfileLog.logError(e1);
- }
- }
-
- public void setFile(IFile file) {
- this.file = file;
- }
-
- public void setDocument(IDocument document) {
- this.document = document;
- }
+ IDocument document;
+ IFile file;
+
+ public SpecfileMarkerHandler(IFile file, IDocument document) {
+ this.file = file;
+ this.document = document;
+ }
+
+ abstract String getMarkerID();
+
+ protected Integer getCharOffset(int lineNumber, int columnNumber) {
+ try {
+ return document.getLineOffset(lineNumber)
+ + columnNumber;
+ } catch (BadLocationException e) {
+ SpecfileLog.logError(e);
+ return null;
+ }
+ }
+
+ public void removeExistingMarkers() {
+ if (file == null || !file.exists()) {
+ return;
+ }
+
+ try {
+ file.deleteMarkers(getMarkerID(), true, IResource.DEPTH_ZERO);
+ } catch (CoreException e1) {
+ SpecfileLog.logError(e1);
+ }
+ }
+
+ public void setFile(IFile file) {
+ this.file = file;
+ }
+
+ public void setDocument(IDocument document) {
+ this.document = document;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileTaskHandler.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileTaskHandler.java
index 4e562ac05a..5efd7742e9 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileTaskHandler.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/markers/SpecfileTaskHandler.java
@@ -28,72 +28,72 @@ import org.eclipse.ui.texteditor.MarkerUtilities;
* @since 1.2
*/
public class SpecfileTaskHandler extends SpecfileMarkerHandler{
- public static final String SPECFILE_TASK_MARKER_ID = Activator.PLUGIN_ID
- + ".specfiletask"; //$NON-NLS-1$
+ public static final String SPECFILE_TASK_MARKER_ID = Activator.PLUGIN_ID
+ + ".specfiletask"; //$NON-NLS-1$
- /**
- * Construct a specfile task handler given a IFile.
- *
- * @param file The specfile file.
- * @param document The specfile document.
- */
- public SpecfileTaskHandler(IFile file, IDocument document) {
- super(file, document);
- }
+ /**
+ * Construct a specfile task handler given a IFile.
+ *
+ * @param file The specfile file.
+ * @param document The specfile document.
+ */
+ public SpecfileTaskHandler(IFile file, IDocument document) {
+ super(file, document);
+ }
- /**
- * Construct a specfile task handler given a FileEditorInput.
- *
- * @param file The FileEditorInput to get the file from.
- * @param document The specfile document.
- *
- * @since 2.0
- */
- public SpecfileTaskHandler(FileEditorInput file, IDocument document) {
- this(file.getFile(), document);
- }
+ /**
+ * Construct a specfile task handler given a FileEditorInput.
+ *
+ * @param file The FileEditorInput to get the file from.
+ * @param document The specfile document.
+ *
+ * @since 2.0
+ */
+ public SpecfileTaskHandler(FileEditorInput file, IDocument document) {
+ this(file.getFile(), document);
+ }
- /**
- * Handle the task of the specfile.
- *
- * @param lineNumber The line number of the task.
- * @param line The line contents.
- * @param taskType The task type.
- */
- public void handleTask(int lineNumber, String line, String taskType) {
- if (file == null) {
- return;
- }
+ /**
+ * Handle the task of the specfile.
+ *
+ * @param lineNumber The line number of the task.
+ * @param line The line contents.
+ * @param taskType The task type.
+ */
+ public void handleTask(int lineNumber, String line, String taskType) {
+ if (file == null) {
+ return;
+ }
- String message = line.substring(line.indexOf(taskType));
- Map<String, Object> map = new HashMap<>();
- MarkerUtilities.setLineNumber(map, lineNumber);
- MarkerUtilities.setMessage(map, message);
- map.put(IMarker.MESSAGE, message);
- map.put(IMarker.LOCATION, file.getFullPath().toString());
- map.put(IMarker.USER_EDITABLE, false);
- Integer charStart = getCharOffset(lineNumber, 0);
- if (charStart != null) {
- map.put(IMarker.CHAR_START, charStart);
- }
- Integer charEnd = getCharOffset(lineNumber, line.length());
- if (charEnd != null) {
- map.put(IMarker.CHAR_END, charEnd);
- }
+ String message = line.substring(line.indexOf(taskType));
+ Map<String, Object> map = new HashMap<>();
+ MarkerUtilities.setLineNumber(map, lineNumber);
+ MarkerUtilities.setMessage(map, message);
+ map.put(IMarker.MESSAGE, message);
+ map.put(IMarker.LOCATION, file.getFullPath().toString());
+ map.put(IMarker.USER_EDITABLE, false);
+ Integer charStart = getCharOffset(lineNumber, 0);
+ if (charStart != null) {
+ map.put(IMarker.CHAR_START, charStart);
+ }
+ Integer charEnd = getCharOffset(lineNumber, line.length());
+ if (charEnd != null) {
+ map.put(IMarker.CHAR_END, charEnd);
+ }
- try {
- MarkerUtilities.createMarker(file, map, SPECFILE_TASK_MARKER_ID);
- } catch (CoreException ee) {
- SpecfileLog.logError(ee);
- }
- }
+ try {
+ MarkerUtilities.createMarker(file, map, SPECFILE_TASK_MARKER_ID);
+ } catch (CoreException ee) {
+ SpecfileLog.logError(ee);
+ }
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.linuxtools.rpm.ui.editor.markers.SpecfileMarkerHandler#getMarkerID()
- */
- @Override
- String getMarkerID() {
- return SPECFILE_TASK_MARKER_ID;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.linuxtools.rpm.ui.editor.markers.SpecfileMarkerHandler#getMarkerID()
+ */
+ @Override
+ String getMarkerID() {
+ return SPECFILE_TASK_MARKER_ID;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/Specfile.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/Specfile.java
index b42133d451..a36fb35ce0 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/Specfile.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/Specfile.java
@@ -30,85 +30,85 @@ import org.eclipse.linuxtools.internal.rpm.ui.editor.parser.SpecfileTag;
public class Specfile {
- private SpecfilePreamble preamble;
+ private SpecfilePreamble preamble;
- private SpecfilePackageContainer packages;
+ private SpecfilePackageContainer packages;
- private List<SpecfileSection> sections;
- private List<SpecfileSection> complexSections;
+ private List<SpecfileSection> sections;
+ private List<SpecfileSection> complexSections;
- private Map<String, SpecfileDefine> defines;
+ private Map<String, SpecfileDefine> defines;
- private Map<Integer, SpecfileSource> sources;
+ private Map<Integer, SpecfileSource> sources;
- private Map<Integer, SpecfileSource> patches;
+ private Map<Integer, SpecfileSource> patches;
- private List<SpecfileTag> buildRequires;
+ private List<SpecfileTag> buildRequires;
- private List<SpecfileTag> requires;
+ private List<SpecfileTag> requires;
- private IDocument document;
+ private IDocument document;
- public Specfile() {
- packages = new SpecfilePackageContainer();
- preamble = new SpecfilePreamble();
- sections = new ArrayList<>();
- complexSections = new ArrayList<>();
- defines = new HashMap<>();
- sources = new HashMap<>();
- patches = new HashMap<>();
- buildRequires = new ArrayList<>();
- requires = new ArrayList<>();
- }
+ public Specfile() {
+ packages = new SpecfilePackageContainer();
+ preamble = new SpecfilePreamble();
+ sections = new ArrayList<>();
+ complexSections = new ArrayList<>();
+ defines = new HashMap<>();
+ sources = new HashMap<>();
+ patches = new HashMap<>();
+ buildRequires = new ArrayList<>();
+ requires = new ArrayList<>();
+ }
- public List<SpecfileSection> getSections() {
- return sections;
- }
+ public List<SpecfileSection> getSections() {
+ return sections;
+ }
- public SpecfileSection getSection(String sectionName){
- for (SpecfileSection section : sections) {
- if (sectionName.equals(section.getName())) {
- return section;
- }
- }
- return null;
- }
+ public SpecfileSection getSection(String sectionName){
+ for (SpecfileSection section : sections) {
+ if (sectionName.equals(section.getName())) {
+ return section;
+ }
+ }
+ return null;
+ }
- public List<SpecfileSection> getComplexSections() {
- return complexSections;
- }
+ public List<SpecfileSection> getComplexSections() {
+ return complexSections;
+ }
- public SpecfileSource getPatch(int number) {
- return patches.get(number);
- }
+ public SpecfileSource getPatch(int number) {
+ return patches.get(number);
+ }
- public SpecfileSource getSource(int number) {
- return sources.get(number);
- }
+ public SpecfileSource getSource(int number) {
+ return sources.get(number);
+ }
- public String getName() {
- SpecfileDefine define = getDefine(RpmTags.NAME.toLowerCase());
- if (define != null){
- return define.getStringValue();
- }
- return " "; //$NON-NLS-1$
- }
+ public String getName() {
+ SpecfileDefine define = getDefine(RpmTags.NAME.toLowerCase());
+ if (define != null){
+ return define.getStringValue();
+ }
+ return " "; //$NON-NLS-1$
+ }
- public void addSection(SpecfileSection section) {
- sections.add(section);
- }
+ public void addSection(SpecfileSection section) {
+ sections.add(section);
+ }
- public void addComplexSection(SpecfileSection section) {
- complexSections.add(section);
- }
+ public void addComplexSection(SpecfileSection section) {
+ complexSections.add(section);
+ }
- public void addSource(SpecfileSource source) {
- sources.put(Integer.valueOf(source.getNumber()), source);
- }
+ public void addSource(SpecfileSource source) {
+ sources.put(Integer.valueOf(source.getNumber()), source);
+ }
- public void addPatch(SpecfileSource patch) {
- patches.put(Integer.valueOf(patch.getNumber()), patch);
- }
+ public void addPatch(SpecfileSource patch) {
+ patches.put(Integer.valueOf(patch.getNumber()), patch);
+ }
/**
* Adds the given define to the map of defines for this specfile.
@@ -116,213 +116,213 @@ public class Specfile {
* @param define The define to add.
*/
public void addDefine(SpecfileDefine define) {
- SpecfilePackage rpmPackage = define.getParent();
- if (rpmPackage != null && !rpmPackage.isMainPackage()) {
- defines.put(UiUtils.getPackageDefineId(define, rpmPackage), define);
- return;
- }
- defines.put(define.getName(), define);
- }
+ SpecfilePackage rpmPackage = define.getParent();
+ if (rpmPackage != null && !rpmPackage.isMainPackage()) {
+ defines.put(UiUtils.getPackageDefineId(define, rpmPackage), define);
+ return;
+ }
+ defines.put(define.getName(), define);
+ }
public void addDefine(SpecfileTag tag) {
- addDefine(new SpecfileDefine(tag));
- }
+ addDefine(new SpecfileDefine(tag));
+ }
public SpecfileDefine getDefine(String defineName) {
- return defines.get(defineName.toLowerCase());
- }
-
- public SpecfileDefine getDefine(String defineName, SpecfilePackage rpmPackage) {
- return defines.get(UiUtils.getPackageDefineId(defineName, rpmPackage));
- }
-
- public int getEpoch() {
- SpecfileDefine define = getDefine(RpmTags.EPOCH.toLowerCase());
- if (define != null){
- return define.getIntValue();
- }
- return -1;
- }
-
- public String getRelease() {
- SpecfileDefine define = getDefine(RpmTags.RELEASE.toLowerCase());
- if (define != null){
- return define.getStringValue();
- }
- return "0"; //$NON-NLS-1$
- }
-
- public String getBuildArch() {
- SpecfileDefine define = getDefine(RpmTags.BUILD_ARCH.toLowerCase());
- if (define != null){
- return define.getStringValue();
- }
- return "0"; //$NON-NLS-1$
- }
-
- public String getVersion() {
- SpecfileDefine define = getDefine(RpmTags.VERSION.toLowerCase());
- if (define != null){
- return define.getStringValue();
- }
- return "0"; //$NON-NLS-1$
- }
-
- public List<SpecfileSource> getPatches() {
- List<SpecfileSource> patchesList = new ArrayList<>(patches.values());
- Collections.sort(patchesList, new SourceComparator());
- return patchesList;
- }
-
- public Collection<SpecfileSource> getSources() {
- List<SpecfileSource> sourcesList = new ArrayList<>(sources.values());
- Collections.sort(sourcesList, new SourceComparator());
- return sourcesList;
- }
-
- public List<SpecfileDefine> getDefines() {
- return new ArrayList<>(defines.values());
- }
-
- public void organizePatches() {
- List<SpecfileSource> patches = getPatches();
- int newPatchNumber = 0;
- int oldPatchNumber = -1;
- Map<Integer, SpecfileSource> newPatches = new HashMap<>();
- for (SpecfileSource thisPatch: patches) {
- if (thisPatch.getSpecfile() == null) {
- thisPatch.setSpecfile(this);
- }
- oldPatchNumber = thisPatch.getNumber();
- thisPatch.setNumber(newPatchNumber);
- thisPatch.changeDeclaration(oldPatchNumber);
- thisPatch.changeReferences(oldPatchNumber);
- newPatches.put(Integer.valueOf(newPatchNumber), thisPatch);
- newPatchNumber++;
- }
- setPatches(newPatches);
- }
-
- public void setDocument(IDocument specfileDocument) {
- document = specfileDocument;
- }
-
- public String getLine(int lineNumber) throws BadLocationException {
- int offset = document.getLineOffset(lineNumber);
- int length = getLineLength(lineNumber);
- return document.get(offset, length);
- }
-
- public IDocument getDocument() {
- return document;
- }
-
- public int getLineLength(int lineNumber) throws BadLocationException {
- int length = document.getLineLength(lineNumber);
- String lineDelimiter = document.getLineDelimiter(lineNumber);
- if (lineDelimiter != null) {
- length = length - lineDelimiter.length();
- }
- return length;
- }
-
- public void changeLine(int lineNumber, String string)
- throws BadLocationException {
- document.replace(document.getLineOffset(lineNumber),
- getLineLength(lineNumber), string);
- }
-
- public void setPatches(Map<Integer, SpecfileSource> patches) {
- this.patches = patches;
- }
-
- @Override
- public String toString() {
- return getName();
- }
-
- public String getLicense() {
- return defines.get(RpmTags.LICENSE.toLowerCase()).getStringValue();
- }
-
- public SpecfilePackageContainer getPackages() {
- return packages;
- }
-
- public SpecfileElement getPreamble() {
- return preamble;
- }
-
- public SpecfilePackage getPackage(String packageName) {
- return getPackages().getPackage(packageName);
- }
-
- public void addPackage(SpecfilePackage subPackage) {
- if (! packages.contains(subPackage)) {
- packages.addPackage(subPackage);
- }
- }
-
- public void modifyDefine(String defineName, SpecfilePackage rpmPackage,
- String newValue) {
- SpecfileDefine define = getDefine(UiUtils.getPackageDefineId(defineName, rpmPackage));
- if (define != null) {
- define.setValue(newValue);
- try {
- changeLine(define.getLineNumber(), defineName + ": " + newValue); //$NON-NLS-1$
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
- }
-
- }
-
- public void modifyDefine(String defineName, String newValue) {
- SpecfileDefine define = getDefine(defineName.toLowerCase());
- if (define != null) {
- define.setValue(newValue);
- try {
- changeLine(define.getLineNumber(), defineName + ": " + newValue); //$NON-NLS-1$
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
- }
- }
-
- public void modifyDefine(SpecfileTag define, String newValue) {
- if (define != null) {
- define.setValue(newValue);
- try {
- changeLine(define.getLineNumber(), define.getName() + ": " + newValue); //$NON-NLS-1$
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
- }
- }
-
- /**
- * @param buildRequire the buildRequire to add
- */
- public void addBuildRequire(SpecfileDefine buildRequire) {
- buildRequires.add(buildRequire);
- }
-
- /**
- * @param require the require to add
- */
- public void addRequire(SpecfileTag require) {
- requires.add(require);
- }
-
- /**
- * @return the buildRequires
- */
- public List<SpecfileTag> getBuildRequires() {
- return buildRequires;
- }
-
- public List<SpecfileTag> getRequires() {
- return requires;
- }
+ return defines.get(defineName.toLowerCase());
+ }
+
+ public SpecfileDefine getDefine(String defineName, SpecfilePackage rpmPackage) {
+ return defines.get(UiUtils.getPackageDefineId(defineName, rpmPackage));
+ }
+
+ public int getEpoch() {
+ SpecfileDefine define = getDefine(RpmTags.EPOCH.toLowerCase());
+ if (define != null){
+ return define.getIntValue();
+ }
+ return -1;
+ }
+
+ public String getRelease() {
+ SpecfileDefine define = getDefine(RpmTags.RELEASE.toLowerCase());
+ if (define != null){
+ return define.getStringValue();
+ }
+ return "0"; //$NON-NLS-1$
+ }
+
+ public String getBuildArch() {
+ SpecfileDefine define = getDefine(RpmTags.BUILD_ARCH.toLowerCase());
+ if (define != null){
+ return define.getStringValue();
+ }
+ return "0"; //$NON-NLS-1$
+ }
+
+ public String getVersion() {
+ SpecfileDefine define = getDefine(RpmTags.VERSION.toLowerCase());
+ if (define != null){
+ return define.getStringValue();
+ }
+ return "0"; //$NON-NLS-1$
+ }
+
+ public List<SpecfileSource> getPatches() {
+ List<SpecfileSource> patchesList = new ArrayList<>(patches.values());
+ Collections.sort(patchesList, new SourceComparator());
+ return patchesList;
+ }
+
+ public Collection<SpecfileSource> getSources() {
+ List<SpecfileSource> sourcesList = new ArrayList<>(sources.values());
+ Collections.sort(sourcesList, new SourceComparator());
+ return sourcesList;
+ }
+
+ public List<SpecfileDefine> getDefines() {
+ return new ArrayList<>(defines.values());
+ }
+
+ public void organizePatches() {
+ List<SpecfileSource> patches = getPatches();
+ int newPatchNumber = 0;
+ int oldPatchNumber = -1;
+ Map<Integer, SpecfileSource> newPatches = new HashMap<>();
+ for (SpecfileSource thisPatch: patches) {
+ if (thisPatch.getSpecfile() == null) {
+ thisPatch.setSpecfile(this);
+ }
+ oldPatchNumber = thisPatch.getNumber();
+ thisPatch.setNumber(newPatchNumber);
+ thisPatch.changeDeclaration(oldPatchNumber);
+ thisPatch.changeReferences(oldPatchNumber);
+ newPatches.put(Integer.valueOf(newPatchNumber), thisPatch);
+ newPatchNumber++;
+ }
+ setPatches(newPatches);
+ }
+
+ public void setDocument(IDocument specfileDocument) {
+ document = specfileDocument;
+ }
+
+ public String getLine(int lineNumber) throws BadLocationException {
+ int offset = document.getLineOffset(lineNumber);
+ int length = getLineLength(lineNumber);
+ return document.get(offset, length);
+ }
+
+ public IDocument getDocument() {
+ return document;
+ }
+
+ public int getLineLength(int lineNumber) throws BadLocationException {
+ int length = document.getLineLength(lineNumber);
+ String lineDelimiter = document.getLineDelimiter(lineNumber);
+ if (lineDelimiter != null) {
+ length = length - lineDelimiter.length();
+ }
+ return length;
+ }
+
+ public void changeLine(int lineNumber, String string)
+ throws BadLocationException {
+ document.replace(document.getLineOffset(lineNumber),
+ getLineLength(lineNumber), string);
+ }
+
+ public void setPatches(Map<Integer, SpecfileSource> patches) {
+ this.patches = patches;
+ }
+
+ @Override
+ public String toString() {
+ return getName();
+ }
+
+ public String getLicense() {
+ return defines.get(RpmTags.LICENSE.toLowerCase()).getStringValue();
+ }
+
+ public SpecfilePackageContainer getPackages() {
+ return packages;
+ }
+
+ public SpecfileElement getPreamble() {
+ return preamble;
+ }
+
+ public SpecfilePackage getPackage(String packageName) {
+ return getPackages().getPackage(packageName);
+ }
+
+ public void addPackage(SpecfilePackage subPackage) {
+ if (! packages.contains(subPackage)) {
+ packages.addPackage(subPackage);
+ }
+ }
+
+ public void modifyDefine(String defineName, SpecfilePackage rpmPackage,
+ String newValue) {
+ SpecfileDefine define = getDefine(UiUtils.getPackageDefineId(defineName, rpmPackage));
+ if (define != null) {
+ define.setValue(newValue);
+ try {
+ changeLine(define.getLineNumber(), defineName + ": " + newValue); //$NON-NLS-1$
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+
+ public void modifyDefine(String defineName, String newValue) {
+ SpecfileDefine define = getDefine(defineName.toLowerCase());
+ if (define != null) {
+ define.setValue(newValue);
+ try {
+ changeLine(define.getLineNumber(), defineName + ": " + newValue); //$NON-NLS-1$
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ public void modifyDefine(SpecfileTag define, String newValue) {
+ if (define != null) {
+ define.setValue(newValue);
+ try {
+ changeLine(define.getLineNumber(), define.getName() + ": " + newValue); //$NON-NLS-1$
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /**
+ * @param buildRequire the buildRequire to add
+ */
+ public void addBuildRequire(SpecfileDefine buildRequire) {
+ buildRequires.add(buildRequire);
+ }
+
+ /**
+ * @param require the require to add
+ */
+ public void addRequire(SpecfileTag require) {
+ requires.add(require);
+ }
+
+ /**
+ * @return the buildRequires
+ */
+ public List<SpecfileTag> getBuildRequires() {
+ return buildRequires;
+ }
+
+ public List<SpecfileTag> getRequires() {
+ return requires;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileDefine.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileDefine.java
index 578c9c7bd9..a90f097b21 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileDefine.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileDefine.java
@@ -15,26 +15,26 @@ import org.eclipse.linuxtools.internal.rpm.ui.editor.parser.SpecfileTag;
public class SpecfileDefine extends SpecfileTag {
- public SpecfileDefine(String name, int value, Specfile specfile, SpecfilePackage parent) {
- super(name, value, specfile, parent);
- }
+ public SpecfileDefine(String name, int value, Specfile specfile, SpecfilePackage parent) {
+ super(name, value, specfile, parent);
+ }
- public SpecfileDefine(String name, String value, Specfile specfile, SpecfilePackage parent) {
- super(name, value, specfile, parent);
- }
+ public SpecfileDefine(String name, String value, Specfile specfile, SpecfilePackage parent) {
+ super(name, value, specfile, parent);
+ }
- public SpecfileDefine(SpecfileTag tag) {
- super();
- setName(tag.getName().toLowerCase());
- setSpecfile(tag.getSpecfile());
- setLineNumber(tag.getLineNumber());
- setParent(tag.getParent());
- if (tag.getTagType().equals(TagType.STRING)) {
- setValue(tag.getStringValue());
- }
- if (tag.getTagType().equals(TagType.INT)) {
- setValue(tag.getIntValue());
- }
- }
+ public SpecfileDefine(SpecfileTag tag) {
+ super();
+ setName(tag.getName().toLowerCase());
+ setSpecfile(tag.getSpecfile());
+ setLineNumber(tag.getLineNumber());
+ setParent(tag.getParent());
+ if (tag.getTagType().equals(TagType.STRING)) {
+ setValue(tag.getStringValue());
+ }
+ if (tag.getTagType().equals(TagType.INT)) {
+ setValue(tag.getIntValue());
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileElement.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileElement.java
index 1b5ba82f43..0c8abf0a16 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileElement.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileElement.java
@@ -19,94 +19,94 @@ import org.eclipse.linuxtools.rpm.core.utils.RPMQuery;
import org.eclipse.osgi.util.NLS;
public class SpecfileElement {
- private Specfile specfile;
- private String name;
- private int lineNumber;
- private int lineStartPosition;
- private int lineEndPosition;
-
- public int getLineNumber() {
- return lineNumber;
- }
-
- public void setLineNumber(int lineNumber) {
- this.lineNumber = lineNumber;
- }
-
- public SpecfileElement() {
- // weird
- }
-
- public SpecfileElement(String name) {
- setName(name);
- }
-
- public String getName() {
- return resolve(name);
- }
-
- public final void setName(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return name;
- }
-
- public int getLineEndPosition() {
- return lineEndPosition;
- }
-
- public void setLineEndPosition(int lineEndPosition) {
- this.lineEndPosition = lineEndPosition;
- }
-
- public int getLineStartPosition() {
- return lineStartPosition;
- }
-
- public void setLineStartPosition(int lineStartPosition) {
- this.lineStartPosition = lineStartPosition;
- }
-
- public Specfile getSpecfile() {
- return specfile;
- }
-
- public void setSpecfile(Specfile specfile) {
- this.specfile = specfile;
- }
-
- public String resolve(String toResolve) {
- if (specfile == null || toResolve.equals("")) {//$NON-NLS-1$
- if (toResolve.length() > 2
- && toResolve.substring(2, toResolve.length() - 1).equals(
- name)) {
- return toResolve;
- }
- }
- return UiUtils.resolveDefines(specfile, toResolve);
- }
-
- /**
- * Resolve using RPM to evaluate string
- *
- * @param toResolve
- * The string to be evaluated
- * @return The evaluated string
- */
- public String resolveEval(String toResolve) {
- String str = ""; //$NON-NLS-1$
- try {
- if ((specfile == null || toResolve.equals("")) && toResolve.length() > 2 && toResolve.substring(2, toResolve.length() - 1).equals(name)) { //$NON-NLS-1$
- return toResolve;
- }
- str = RPMQuery.eval(UiUtils.resolveDefines(specfile, toResolve)).trim();
- } catch (CoreException e) {
- SpecfileLog.logError(NLS.bind(Messages.getString("SpecfileElement_unableToResolve"), toResolve), e); //$NON-NLS-1$
- }
- return str;
- }
+ private Specfile specfile;
+ private String name;
+ private int lineNumber;
+ private int lineStartPosition;
+ private int lineEndPosition;
+
+ public int getLineNumber() {
+ return lineNumber;
+ }
+
+ public void setLineNumber(int lineNumber) {
+ this.lineNumber = lineNumber;
+ }
+
+ public SpecfileElement() {
+ // weird
+ }
+
+ public SpecfileElement(String name) {
+ setName(name);
+ }
+
+ public String getName() {
+ return resolve(name);
+ }
+
+ public final void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+
+ public int getLineEndPosition() {
+ return lineEndPosition;
+ }
+
+ public void setLineEndPosition(int lineEndPosition) {
+ this.lineEndPosition = lineEndPosition;
+ }
+
+ public int getLineStartPosition() {
+ return lineStartPosition;
+ }
+
+ public void setLineStartPosition(int lineStartPosition) {
+ this.lineStartPosition = lineStartPosition;
+ }
+
+ public Specfile getSpecfile() {
+ return specfile;
+ }
+
+ public void setSpecfile(Specfile specfile) {
+ this.specfile = specfile;
+ }
+
+ public String resolve(String toResolve) {
+ if (specfile == null || toResolve.equals("")) {//$NON-NLS-1$
+ if (toResolve.length() > 2
+ && toResolve.substring(2, toResolve.length() - 1).equals(
+ name)) {
+ return toResolve;
+ }
+ }
+ return UiUtils.resolveDefines(specfile, toResolve);
+ }
+
+ /**
+ * Resolve using RPM to evaluate string
+ *
+ * @param toResolve
+ * The string to be evaluated
+ * @return The evaluated string
+ */
+ public String resolveEval(String toResolve) {
+ String str = ""; //$NON-NLS-1$
+ try {
+ if ((specfile == null || toResolve.equals("")) && toResolve.length() > 2 && toResolve.substring(2, toResolve.length() - 1).equals(name)) { //$NON-NLS-1$
+ return toResolve;
+ }
+ str = RPMQuery.eval(UiUtils.resolveDefines(specfile, toResolve)).trim();
+ } catch (CoreException e) {
+ SpecfileLog.logError(NLS.bind(Messages.getString("SpecfileElement_unableToResolve"), toResolve), e); //$NON-NLS-1$
+ }
+ return str;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfilePackage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfilePackage.java
index b223474b76..420a1fb2cc 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfilePackage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfilePackage.java
@@ -17,121 +17,121 @@ import java.util.List;
import org.eclipse.linuxtools.internal.rpm.ui.editor.parser.SpecfileTag;
public class SpecfilePackage extends SpecfileSection {
- private String description;
- private List<SpecfileSection> sections;
- private List<SpecfileTag> requires;
- private String packageName;
- private String summary;
- private String group;
-
- public SpecfilePackage(String packageName, Specfile specfile) {
- super("package", specfile); //$NON-NLS-1$
- super.setSpecfile(specfile);
- setPackageName(packageName);
+ private String description;
+ private List<SpecfileSection> sections;
+ private List<SpecfileTag> requires;
+ private String packageName;
+ private String summary;
+ private String group;
+
+ public SpecfilePackage(String packageName, Specfile specfile) {
+ super("package", specfile); //$NON-NLS-1$
+ super.setSpecfile(specfile);
+ setPackageName(packageName);
setPackage(this);
sections = new ArrayList<>();
requires = new ArrayList<>();
- }
+ }
- public String getDescription() {
- return description;
- }
+ public String getDescription() {
+ return description;
+ }
- public void setDescription(String description) {
- this.description = description;
- }
+ public void setDescription(String description) {
+ this.description = description;
+ }
- @Override
- public String toString() {
- return getPackageName();
- }
+ @Override
+ public String toString() {
+ return getPackageName();
+ }
+
+ public void addSection(SpecfileSection section) {
+ sections.add(section);
+ }
- public void addSection(SpecfileSection section) {
- sections.add(section);
- }
+ public SpecfileSection[] getSections() {
+ SpecfileSection[] toReturn = new SpecfileSection[sections.size()];
+ return sections.toArray(toReturn);
+ }
- public SpecfileSection[] getSections() {
- SpecfileSection[] toReturn = new SpecfileSection[sections.size()];
- return sections.toArray(toReturn);
- }
+ public boolean hasChildren() {
+ if (sections != null && sections.size() > 0) {
+ return true;
+ }
+ return false;
+ }
- public boolean hasChildren() {
- if (sections != null && sections.size() > 0) {
- return true;
- }
- return false;
- }
+ @Override
+ public SpecfilePackage getPackage() {
+ return this;
+ }
@Override
- public SpecfilePackage getPackage() {
- return this;
- }
-
- @Override
- public String getPackageName() {
- return resolve(this.packageName);
- }
-
- /**
- * Returns the full package name.
- *
- * @return The name of the package with the common part appended in front.
- */
- public String getFullPackageName() {
- if (getSpecfile().getName().equals(getPackageName())){
- return getPackageName();
- }
- return getSpecfile().getName()+"-" + getPackageName(); //$NON-NLS-1$
- }
-
- public final void setPackageName(String packageName) {
- this.packageName = packageName;
- }
-
- /**
- * @param summary the summary to set
- */
- public void setSummary(String summary) {
- this.summary = summary;
- }
-
- /**
- * @return the summary
- */
- public String getSummary() {
- return summary;
- }
-
- /**
- * @param group the group to set
- */
- public void setGroup(String group) {
- this.group = group;
- }
-
- /**
- * @return the group
- */
- public String getGroup() {
- return group;
- }
-
- public boolean isMainPackage() {
- if (getSpecfile().getName().equals(getPackageName())){
- return true;
- }
- return false;
- }
-
- /**
- * @param require the require to add
- */
- public void addRequire(SpecfileTag require) {
- requires.add(require);
- }
-
- public List<SpecfileTag> getRequires() {
- return requires;
- }
+ public String getPackageName() {
+ return resolve(this.packageName);
+ }
+
+ /**
+ * Returns the full package name.
+ *
+ * @return The name of the package with the common part appended in front.
+ */
+ public String getFullPackageName() {
+ if (getSpecfile().getName().equals(getPackageName())){
+ return getPackageName();
+ }
+ return getSpecfile().getName()+"-" + getPackageName(); //$NON-NLS-1$
+ }
+
+ public final void setPackageName(String packageName) {
+ this.packageName = packageName;
+ }
+
+ /**
+ * @param summary the summary to set
+ */
+ public void setSummary(String summary) {
+ this.summary = summary;
+ }
+
+ /**
+ * @return the summary
+ */
+ public String getSummary() {
+ return summary;
+ }
+
+ /**
+ * @param group the group to set
+ */
+ public void setGroup(String group) {
+ this.group = group;
+ }
+
+ /**
+ * @return the group
+ */
+ public String getGroup() {
+ return group;
+ }
+
+ public boolean isMainPackage() {
+ if (getSpecfile().getName().equals(getPackageName())){
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @param require the require to add
+ */
+ public void addRequire(SpecfileTag require) {
+ requires.add(require);
+ }
+
+ public List<SpecfileTag> getRequires() {
+ return requires;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfilePackageContainer.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfilePackageContainer.java
index 57f71a6dea..4030ba2911 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfilePackageContainer.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfilePackageContainer.java
@@ -17,88 +17,88 @@ import java.util.List;
import org.eclipse.linuxtools.internal.rpm.ui.editor.SpecfileLog;
public class SpecfilePackageContainer extends SpecfileElement {
- List<SpecfilePackage> packages;
-
- public SpecfilePackageContainer() {
- super();
- packages = new ArrayList<>();
- }
-
- public SpecfilePackage[] getPackages() {
- try {
- Object [] objs = packages.toArray();
- SpecfilePackage [] packs = new SpecfilePackage[objs.length];
- for (int i = 0; i < objs.length; i++) {
- SpecfilePackage pack = (SpecfilePackage) objs[i];
- packs[i] = pack;
- }
- return packs;
- }catch (Exception e){
- SpecfileLog.logError(e);
- }
- return new SpecfilePackage[0] ;
- }
-
- void addPackage(SpecfilePackage subPackage) {
- packages.add(subPackage);
- }
-
- @Override
- public int getLineStartPosition() {
- if ((packages == null) || (packages.size() == 0)) {
- return 0;
- }
-
- int lowestStartLine = Integer.MAX_VALUE;
-
- for (SpecfilePackage subPackage: packages){
- if (subPackage.getLineStartPosition() < lowestStartLine) {
- lowestStartLine = subPackage.getLineStartPosition();
- }
- }
-
- if (lowestStartLine == Integer.MAX_VALUE) {
- return 0;
- }
- return lowestStartLine;
- }
-
- @Override
- public int getLineEndPosition() {
- if ((packages == null) || packages.isEmpty()) {
- return 0;
- }
-
- int highestEndLine = 0;
-
- for (SpecfilePackage subPackage: packages){
- if (subPackage.getLineStartPosition() > highestEndLine)
- highestEndLine = subPackage.getLineEndPosition();
- }
-
- if (highestEndLine < 0) {
- return 0;
- }
- return highestEndLine;
- }
-
- public SpecfilePackage getPackage(String packageName) {
- for (SpecfilePackage thisPackage: packages) {
- if (thisPackage.getPackageName().equals(thisPackage.resolve(packageName))) {
- return thisPackage;
- }
- }
- return null;
- }
-
- public boolean contains(SpecfilePackage subPackage){
- return packages.contains(subPackage);
- }
-
- public boolean hasChildren() {
- if (packages != null && packages.size() > 0) {
- return true;
- }
- return false;
- }
+ List<SpecfilePackage> packages;
+
+ public SpecfilePackageContainer() {
+ super();
+ packages = new ArrayList<>();
+ }
+
+ public SpecfilePackage[] getPackages() {
+ try {
+ Object [] objs = packages.toArray();
+ SpecfilePackage [] packs = new SpecfilePackage[objs.length];
+ for (int i = 0; i < objs.length; i++) {
+ SpecfilePackage pack = (SpecfilePackage) objs[i];
+ packs[i] = pack;
+ }
+ return packs;
+ }catch (Exception e){
+ SpecfileLog.logError(e);
+ }
+ return new SpecfilePackage[0] ;
+ }
+
+ void addPackage(SpecfilePackage subPackage) {
+ packages.add(subPackage);
+ }
+
+ @Override
+ public int getLineStartPosition() {
+ if ((packages == null) || (packages.size() == 0)) {
+ return 0;
+ }
+
+ int lowestStartLine = Integer.MAX_VALUE;
+
+ for (SpecfilePackage subPackage: packages){
+ if (subPackage.getLineStartPosition() < lowestStartLine) {
+ lowestStartLine = subPackage.getLineStartPosition();
+ }
+ }
+
+ if (lowestStartLine == Integer.MAX_VALUE) {
+ return 0;
+ }
+ return lowestStartLine;
+ }
+
+ @Override
+ public int getLineEndPosition() {
+ if ((packages == null) || packages.isEmpty()) {
+ return 0;
+ }
+
+ int highestEndLine = 0;
+
+ for (SpecfilePackage subPackage: packages){
+ if (subPackage.getLineStartPosition() > highestEndLine)
+ highestEndLine = subPackage.getLineEndPosition();
+ }
+
+ if (highestEndLine < 0) {
+ return 0;
+ }
+ return highestEndLine;
+ }
+
+ public SpecfilePackage getPackage(String packageName) {
+ for (SpecfilePackage thisPackage: packages) {
+ if (thisPackage.getPackageName().equals(thisPackage.resolve(packageName))) {
+ return thisPackage;
+ }
+ }
+ return null;
+ }
+
+ public boolean contains(SpecfilePackage subPackage){
+ return packages.contains(subPackage);
+ }
+
+ public boolean hasChildren() {
+ if (packages != null && packages.size() > 0) {
+ return true;
+ }
+ return false;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileParser.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileParser.java
index c7853ba07b..b087198120 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileParser.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileParser.java
@@ -58,609 +58,609 @@ import org.eclipse.linuxtools.rpm.ui.editor.markers.SpecfileTaskHandler;
public class SpecfileParser {
- private static final String DEFINE_SEPARATOR = ":"; //$NON-NLS-1$
-
- private static final String SPACE_REGEX = "\\s+"; //$NON-NLS-1$
-
- /**
- * These are SRPM-wide sections, and they also cannot have any flags like -n
- * or -f. Hence they are called simple. This is probably a misleading name
- * and it should be renamed to reflect that they are SRPM-wide sections.
- */
- public static final String[] simpleSections = { PREP_SECTION, BUILD_SECTION,
- INSTALL_SECTION, CLEAN_SECTION, CHANGELOG_SECTION };
-
- /**
- * These are sections that apply to a particular sub-package (i.e. binary
- * RPM), including the main package. These can also have flags like -f or -n
- * appended to them, hence they are called complex. This should probably be
- * renamed to reflect that they are in fact per-RPM sections.
- */
- private static String[] complexSections = { PRETRANS_SECTION, PRE_SECTION,
- PREUN_SECTION, POST_SECTION, POSTUN_SECTION, POSTTRANS_SECTION,
- FILES_SECTION, PACKAGE_SECTION, DESCRIPTION_SECTION };
-
- private static String[] simpleDefinitions = { RpmTags.EPOCH, RpmTags.NAME,
- RpmTags.VERSION, RpmTags.RELEASE, RpmTags.URL, RpmTags.BUILD_ARCH };
-
- private static String[] directValuesDefinitions = { RpmTags.LICENSE,
- RpmTags.BUILD_ROOT };
- // Note that the ordering here should match that in
- // SpecfileSource#SOURCETYPE
- private static String[] complexDefinitions = { "Source", "Patch" }; //$NON-NLS-1$ //$NON-NLS-2$
-
- private static String[] packageLevelDefinitions = { RpmTags.SUMMARY,
- RpmTags.GROUP, RpmTags.OBSOLETES, RpmTags.PROVIDES,
- RpmTags.REQUIRES, RpmTags.REQUIRES_PRE, RpmTags.REQUIRES_POST,
- RpmTags.REQUIRES_POSTUN };
-
- private SpecfileErrorHandler errorHandler;
- private SpecfileTaskHandler taskHandler;
- private IPreferenceStore store;
- private SpecfileSection lastSection;
- private SpecfilePackage activePackage;
-
- public SpecfileParser() {
- store = Activator.getDefault().getPreferenceStore();
- }
-
- public Specfile parse(IDocument specfileDocument) {
-
- // remove all existing markers, if a SpecfileErrorHandler is
- // instantiated.
- if (errorHandler != null) {
- errorHandler.removeExistingMarkers();
- }
- if (taskHandler != null) {
- taskHandler.removeExistingMarkers();
- }
- LineNumberReader reader = new LineNumberReader(new StringReader(
- specfileDocument.get()));
- String line = ""; //$NON-NLS-1$
- int lineStartPosition = 0;
- Specfile specfile = new Specfile();
- specfile.setDocument(specfileDocument);
- try {
- while ((line = reader.readLine()) != null) {
- if (taskHandler != null) {
- generateTaskMarker(reader.getLineNumber() - 1, line);
- }
- // IDocument.getLine(#) is 0-indexed whereas
- // reader.getLineNumber appears to be 1-indexed
- SpecfileElement element = parseLine(line, specfile, reader
- .getLineNumber() - 1);
- if (element != null) {
- element.setLineNumber(reader.getLineNumber() - 1);
- element.setLineStartPosition(lineStartPosition);
- element.setLineEndPosition(lineStartPosition
- + line.length());
- if (element.getClass() == SpecfileTag.class) {
- SpecfileTag tag = (SpecfileTag) element;
- specfile.addDefine(tag);
- } else if ((element.getClass() == SpecfilePatchMacro.class)) {
- SpecfilePatchMacro thisPatchMacro = (SpecfilePatchMacro) element;
- if (thisPatchMacro != null) {
- thisPatchMacro.setSpecfile(specfile);
- }
- SpecfileSource thisPatch = specfile
- .getPatch(thisPatchMacro.getPatchNumber());
- if (thisPatch != null) {
- thisPatch.addLineUsed(reader.getLineNumber() - 1);
- thisPatch.setSpecfile(specfile);
- }
- } else if ((element.getClass() == SpecfileDefine.class)) {
- specfile.addDefine((SpecfileDefine) element);
- } else if ((element.getClass() == SpecfileSource.class)) {
- SpecfileSource source = (SpecfileSource) element;
-
- source.setLineNumber(reader.getLineNumber() - 1);
- if (source.getSourceType() == SpecfileSource.SourceType.SOURCE) {
- specfile.addSource(source);
- } else {
- specfile.addPatch(source);
- }
- }
- }
-
- // sets the last SpecfileSection's end line to that of the end of
- // the end of the specfileDocument.
- // SpecfileParser#parseMacro will handle correcting the end line
- // if the last SpecfileSection was not truly the last 1
- // This is for the purpose of making DocumentRangeNode work
- if (lastSection != null) {
- lastSection.setSectionEndLine(specfileDocument
- .getNumberOfLines() - 1);
- }
-
- // The +1 is for the line delimiter. FIXME: will we end up off
- // by one on the last line?
- lineStartPosition += line.length() + 1;
- }
- } catch (IOException e) {
- // FIXME
- SpecfileLog.logError(e);
- }
- return specfile;
- }
-
- /**
- * Parse a File into a specfile
- *
- * @param file The File to be parsed
- * @return A Specfile object
- */
- public Specfile parse(IFile file) {
- SpecfileParser parser = new SpecfileParser();
- StringBuilder sb = new StringBuilder();
- String line = null;
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- file.getContents()));
- while ((line = reader.readLine()) != null) {
- sb.append(line + "\n"); //$NON-NLS-1$
- }
- } catch (IOException e) {
- SpecfileLog.logError(Messages.getString("SpecfileParseFile.1"), e); //$NON-NLS-1$
- } catch (CoreException e) {
- SpecfileLog.logError(Messages.getString("SpecfileParseFile.2"), e); //$NON-NLS-1$
- }
- return parser.parse(sb.toString());
- }
-
- private void generateTaskMarker(int lineNumber, String line) {
- String[] taskTags = store.getString(PreferenceConstants.P_TASK_TAGS)
- .split(";"); //$NON-NLS-1$
- int commentCharIndex = line
- .indexOf(ISpecfileSpecialSymbols.COMMENT_START);
- if (commentCharIndex > -1) {
- for (String item : taskTags) {
- int taskIndex = line.indexOf(item);
- if (taskIndex > commentCharIndex) {
- taskHandler.handleTask(lineNumber, line, item);
- }
- }
- }
- }
-
- public Specfile parse(String specfileContent) {
- return parse(new Document(specfileContent));
- }
-
- public SpecfileElement parseLine(String lineText, Specfile specfile,
- int lineNumber) {
-
- if (lineText.startsWith("%")) {//$NON-NLS-1$
- return parseMacro(lineText, specfile, lineNumber);
- }
-
- for (String simpleDefinition : simpleDefinitions) {
- if (lineText.startsWith(simpleDefinition + DEFINE_SEPARATOR)) {
- return parseSimpleDefinition(lineText, specfile, lineNumber,
- false);
- }
- }
- for (String directValuesDefinition : directValuesDefinitions) {
- if (lineText.startsWith(directValuesDefinition + DEFINE_SEPARATOR)) {
- return parseDirectDefinition(lineText, specfile, lineNumber);
- }
- }
- for (String directValuesDefinition : packageLevelDefinitions) {
- if (lineText.startsWith(directValuesDefinition + DEFINE_SEPARATOR)) {
- SpecfileElement definition = parseDirectDefinition(lineText,
- specfile, lineNumber);
- if (directValuesDefinition.equals(RpmTags.REQUIRES)) {
- if (activePackage != null) {
- activePackage.addRequire((SpecfileTag) definition);
- } else {
- specfile.addRequire((SpecfileTag) definition);
- }
- }
- return definition;
- }
- }
-
- if (lineText.startsWith(complexDefinitions[0])
- && lineText.contains(DEFINE_SEPARATOR)) {
- return parseComplexDefinition(lineText, lineNumber,
- SourceType.SOURCE);
- } else if (lineText.startsWith(complexDefinitions[1])
- && lineText.contains(DEFINE_SEPARATOR)) {
- return parseComplexDefinition(lineText, lineNumber,
- SourceType.PATCH);
- } else if (lineText.startsWith("BuildRequires")) { //$NON-NLS-1$
- return parseBuildRequire(lineText, lineNumber, specfile);
- }
-
- return null;
- }
-
- private SpecfileElement parseBuildRequire(String lineText, int lineNumber,
- Specfile specfile) {
- String value = lineText.substring(lineText.indexOf(':') + 1,
- lineText.length()).trim();
- SpecfileDefine buildRequire = new SpecfileDefine(
- "BuildRequires", value, specfile, null); //$NON-NLS-1$
- buildRequire.setLineNumber(lineNumber);
- specfile.addBuildRequire(buildRequire);
- return buildRequire;
- }
-
- private SpecfileSection parseSection(String lineText, Specfile specfile,
- int lineNumber) {
- List<String> tokens = Arrays.asList(lineText.split(SPACE_REGEX));
- SpecfileSection toReturn = null;
- boolean isSimpleSection = false;
- for (Iterator<String> iter = tokens.iterator(); iter.hasNext();) {
- String token = iter.next();
-
- // Sections
- // Simple Section Headers
- for (String simpleSection : simpleSections) {
- if (token.equals(simpleSection)) {
- toReturn = new SpecfileSection(token.substring(1), specfile);
- specfile.addSection(toReturn);
- isSimpleSection = true;
- }
-
- }
-
- // Complex Section Headers
- for (String complexSection : complexSections) {
- if (token.equals(complexSection)) {
- String name = token.substring(1);
- if (!name.equals("package")) { //$NON-NLS-1$
- toReturn = new SpecfileSection(name, specfile);
- specfile.addComplexSection(toReturn);
- }
- while (iter.hasNext()) {
- String nextToken = iter.next();
- if (nextToken.equals("-n")) { //$NON-NLS-1$
- if (!iter.hasNext()) {
- errorHandler
- .handleError(new SpecfileParseException(
- Messages
- .getString("SpecfileParser.1") //$NON-NLS-1$
- + name
- + Messages
- .getString("SpecfileParser.2"), //$NON-NLS-1$
- lineNumber, 0, lineText
- .length(),
- IMarker.SEVERITY_ERROR));
- continue;
- }
-
- nextToken = iter.next();
- if (nextToken.startsWith("-")) { //$NON-NLS-1$
- errorHandler
- .handleError(new SpecfileParseException(
- Messages
- .getString("SpecfileParser.3") //$NON-NLS-1$
- + nextToken
- + Messages
- .getString("SpecfileParser.4"), //$NON-NLS-1$
- lineNumber, 0, lineText
- .length(),
- IMarker.SEVERITY_ERROR));
- }
-
- } else if (nextToken.equals("-p")) { //$NON-NLS-1$
- // FIXME: rest of line is the actual section
- break;
- } else if (nextToken.equals("-f")) { //$NON-NLS-1$
- break;
- }
-
- // this is a package
- if (toReturn == null) {
- SpecfilePackage tmpPackage = specfile
- .getPackage(nextToken);
-
- if (tmpPackage == null) {
- tmpPackage = new SpecfilePackage(nextToken,
- specfile);
- specfile.addPackage(tmpPackage);
- }
- activePackage = tmpPackage;
- return tmpPackage;
- }
-
- // this is another section
- SpecfilePackage enclosingPackage = specfile
- .getPackage(nextToken);
- if (enclosingPackage == null) {
- enclosingPackage = new SpecfilePackage(nextToken,
- specfile);
- specfile.addPackage(enclosingPackage);
- }
- toReturn.setPackage(enclosingPackage);
- enclosingPackage.addSection(toReturn);
- }
- }
- }
- }
-
- // if this package is part of the top level package, add it to
- // it
- if (toReturn != null && toReturn.getPackage() == null) {
- SpecfilePackage topPackage = specfile
- .getPackage(specfile.getName());
- if (topPackage == null) {
- topPackage = new SpecfilePackage(specfile.getName(), specfile);
- specfile.addPackage(topPackage);
- }
- if (!isSimpleSection) {
- topPackage.addSection(toReturn);
- }
- }
- if (lastSection != null) {
- lastSection.setSectionEndLine(lineNumber);
- }
- return toReturn;
- }
-
- private SpecfileElement parseMacro(String lineText, Specfile specfile,
- int lineNumber) {
- // FIXME: handle other macros
-
- if (lineText.startsWith("%define") || lineText.startsWith("%global")) { //$NON-NLS-1$ //$NON-NLS-2$
- return parseDefine(lineText, specfile, lineNumber);
- } else if (lineText.startsWith("%patch")) { //$NON-NLS-1$
- return parsePatch(lineText, lineNumber);
- }
-
- String[] sections = new String[simpleSections.length
- + complexSections.length];
- System.arraycopy(simpleSections, 0, sections, 0, simpleSections.length);
- System.arraycopy(complexSections, 0, sections, simpleSections.length,
- complexSections.length);
- for (String section : sections) {
- if (lineText.startsWith(section)) {
- lastSection = parseSection(lineText, specfile, lineNumber);
- if (lastSection != null) {
- lastSection.setSectionEndLine(lineNumber + 1);
- }
- return lastSection;
- }
- }
- // FIXME: add handling of lines containing %{SOURCENNN}
- return null;
- }
-
- private SpecfileElement parsePatch(String lineText, int lineNumber) {
-
- SpecfilePatchMacro toReturn = null;
-
- List<String> tokens = Arrays.asList(lineText.split(SPACE_REGEX));
-
- for (String token : tokens) {
- // %patchN+
- try {
- if (token.startsWith("%patch")) { //$NON-NLS-1$
- int patchNumber = 0;
- if (token.length() > 6) {
- patchNumber = Integer.parseInt(token.substring(6));
- }
- toReturn = new SpecfilePatchMacro(patchNumber);
- }
- } catch (NumberFormatException e) {
- errorHandler.handleError(new SpecfileParseException(
- Messages.getString("SpecfileParser.5"), //$NON-NLS-1$
- lineNumber, 0, lineText.length(),
- IMarker.SEVERITY_ERROR));
- return null;
- }
- }
-
- return toReturn;
- }
-
- private SpecfileDefine parseDefine(String lineText, Specfile specfile,
- int lineNumber) {
- List<String> tokens = Arrays.asList(lineText.split(SPACE_REGEX));
- SpecfileDefine toReturn = null;
- for (Iterator<String> iter = tokens.iterator(); iter.hasNext();) {
- // Eat the actual "%define" or "%global" token
- iter.next();
- while (iter.hasNext()) {
- String defineName = iter.next();
- // FIXME: is this true? investigate in rpmbuild source
- // Definitions must being with a letter
- if (!Character.isLetter(defineName.charAt(0))
- && (defineName.charAt(0) != '_')) {
- errorHandler.handleError(new SpecfileParseException(
- Messages.getString("SpecfileParser.6"), //$NON-NLS-1$
- lineNumber, 0, lineText.length(),
- IMarker.SEVERITY_ERROR));
- return null;
- } else {
- if (iter.hasNext()) {
- String defineStringValue = iter.next();
- // Defines that are more than one token
- if (iter.hasNext()) {
- defineStringValue = lineText.substring(lineText
- .indexOf(defineStringValue));
- // Eat up the rest of the tokens
- while (iter.hasNext()) {
- iter.next();
- }
- }
- int defineIntValue = -1;
- try {
- defineIntValue = Integer
- .parseInt(defineStringValue);
- } catch (NumberFormatException e) {
- toReturn = new SpecfileDefine(defineName,
- defineStringValue, specfile, null);
- }
- if (toReturn == null) {
- toReturn = new SpecfileDefine(defineName,
- defineIntValue, specfile, null);
- }
- } else {
- errorHandler.handleError(new SpecfileParseException(defineName+
- Messages.getString("SpecfileParser.14"), //$NON-NLS-1$
- lineNumber, 0, lineText.length(),
- IMarker.SEVERITY_ERROR));
- }
- }
- }
- }
- return toReturn;
- }
-
- private SpecfileElement parseComplexDefinition(String lineText,
- int lineNumber, SourceType sourceType) {
- SpecfileSource toReturn = null;
- List<String> tokens = Arrays.asList(lineText.split(SPACE_REGEX));
- int number = -1;
- boolean firstToken = true;
-
- for (Iterator<String> iter = tokens.iterator(); iter.hasNext();) {
- String token = iter.next();
- if (token != null && token.length() > 0) {
- if (firstToken) {
- if (token.endsWith(DEFINE_SEPARATOR)) {
- token = token.substring(0, token.length() - 1);
- } else {
- // FIXME: come up with a better error message here
- // FIXME: what about descriptions that begin a line with
- // the word "Source" or "Patch"?
- errorHandler.handleError(new SpecfileParseException(
- Messages.getString("SpecfileParser.8"), //$NON-NLS-1$
- lineNumber, 0, lineText.length(),
- IMarker.SEVERITY_WARNING));
- return null;
- }
- if (sourceType == SourceType.PATCH) {
- if (token.length() > 5) {
- number = Integer.parseInt(token.substring(5));
- if (!("patch" + number).equalsIgnoreCase(token)) { //$NON-NLS-1$
- errorHandler
- .handleError(new SpecfileParseException(
- Messages
- .getString("SpecfileParser.10"), //$NON-NLS-1$
- lineNumber, 0, lineText
- .length(),
- IMarker.SEVERITY_ERROR));
- return null;
- }
- } else {
- number = 0;
- }
- } else {
- if (token.length() > 6) {
- number = Integer.parseInt(token.substring(6));
- if (!("source" + number).equalsIgnoreCase(token)) { //$NON-NLS-1$
- errorHandler
- .handleError(new SpecfileParseException(
- Messages
- .getString("SpecfileParser.11"), //$NON-NLS-1$
- lineNumber, 0, lineText
- .length(),
- IMarker.SEVERITY_ERROR));
- return null;
- }
- } else {
- number = 0;
- }
- }
- toReturn = new SpecfileSource(number, ""); //$NON-NLS-1$
- toReturn.setSourceType(sourceType);
- firstToken = false;
- } else {
- // toReturn should never be null but check just in case
- if (toReturn != null) {
- toReturn.setFileName(token);
- }
- if (iter.hasNext()) {
- errorHandler.handleError(new SpecfileParseException(
- Messages.getString("SpecfileParser.12"), //$NON-NLS-1$
- lineNumber, 0, lineText.length(),
- IMarker.SEVERITY_ERROR));
- }
- }
- }
- }
-
- return toReturn;
- }
-
- private SpecfileElement parseSimpleDefinition(String lineText,
- Specfile specfile, int lineNumber, boolean warnMultipleValues) {
- List<String> tokens = Arrays.asList(lineText.split(SPACE_REGEX));
- SpecfileTag toReturn = null;
-
- for (Iterator<String> iter = tokens.iterator(); iter.hasNext();) {
- String token = iter.next();
-
- if (token.length() <= 0) {
- break;
- }
-
- if (iter.hasNext()) {
- String possValue = iter.next();
- if (possValue.startsWith("%") && iter.hasNext()) { //$NON-NLS-1$
- possValue += ' ' + iter.next();
- }
- toReturn = new SpecfileTag(token.substring(0,
- token.length() - 1).toLowerCase(), possValue, specfile,
- null);
- if (iter.hasNext() && !warnMultipleValues) {
- errorHandler.handleError(new SpecfileParseException(
- token.substring(0, token.length() - 1)
- + Messages.getString("SpecfileParser.13"), //$NON-NLS-1$
- lineNumber, 0, lineText.length(),
- IMarker.SEVERITY_ERROR));
- return null;
- }
- } else {
- errorHandler.handleError(new SpecfileParseException(token
- .substring(0, token.length() - 1)
- + Messages.getString("SpecfileParser.14"), lineNumber, //$NON-NLS-1$
- 0, lineText.length(), IMarker.SEVERITY_ERROR));
- toReturn = null;
- }
- }
- if ((toReturn != null) && (toReturn.getStringValue() != null)) {
- try {
- int intValue = Integer.parseInt(toReturn.getStringValue());
- toReturn.setValue(intValue);
- } catch (NumberFormatException e) {
- if (toReturn.getName().equalsIgnoreCase(RpmTags.EPOCH)) {
- errorHandler
- .handleError(new SpecfileParseException(
- Messages.getString("SpecfileParser.16"), lineNumber, //$NON-NLS-1$
- 0, lineText.length(),
- IMarker.SEVERITY_ERROR));
- toReturn = null;
- }
- }
- }
- return toReturn;
- }
-
- private SpecfileElement parseDirectDefinition(String lineText,
- Specfile specfile, int lineNumber) {
- String[] parts = lineText.split(DEFINE_SEPARATOR, 2);
- SpecfileTag directDefinition;
- if (parts.length == 2) {
- directDefinition = new SpecfileTag(parts[0], parts[1].trim(),
- specfile, activePackage);
- directDefinition.setLineNumber(lineNumber);
- } else {
- errorHandler.handleError(new SpecfileParseException(parts[0]
- + Messages.getString("SpecfileParser.14"), lineNumber, //$NON-NLS-1$
- 0, lineText.length(), IMarker.SEVERITY_ERROR));
- directDefinition = null;
- }
- return directDefinition;
- }
-
- public void setErrorHandler(SpecfileErrorHandler specfileErrorHandler) {
- errorHandler = specfileErrorHandler;
- }
-
- public void setTaskHandler(SpecfileTaskHandler specfileTaskHandler) {
- taskHandler = specfileTaskHandler;
- }
+ private static final String DEFINE_SEPARATOR = ":"; //$NON-NLS-1$
+
+ private static final String SPACE_REGEX = "\\s+"; //$NON-NLS-1$
+
+ /**
+ * These are SRPM-wide sections, and they also cannot have any flags like -n
+ * or -f. Hence they are called simple. This is probably a misleading name
+ * and it should be renamed to reflect that they are SRPM-wide sections.
+ */
+ public static final String[] simpleSections = { PREP_SECTION, BUILD_SECTION,
+ INSTALL_SECTION, CLEAN_SECTION, CHANGELOG_SECTION };
+
+ /**
+ * These are sections that apply to a particular sub-package (i.e. binary
+ * RPM), including the main package. These can also have flags like -f or -n
+ * appended to them, hence they are called complex. This should probably be
+ * renamed to reflect that they are in fact per-RPM sections.
+ */
+ private static String[] complexSections = { PRETRANS_SECTION, PRE_SECTION,
+ PREUN_SECTION, POST_SECTION, POSTUN_SECTION, POSTTRANS_SECTION,
+ FILES_SECTION, PACKAGE_SECTION, DESCRIPTION_SECTION };
+
+ private static String[] simpleDefinitions = { RpmTags.EPOCH, RpmTags.NAME,
+ RpmTags.VERSION, RpmTags.RELEASE, RpmTags.URL, RpmTags.BUILD_ARCH };
+
+ private static String[] directValuesDefinitions = { RpmTags.LICENSE,
+ RpmTags.BUILD_ROOT };
+ // Note that the ordering here should match that in
+ // SpecfileSource#SOURCETYPE
+ private static String[] complexDefinitions = { "Source", "Patch" }; //$NON-NLS-1$ //$NON-NLS-2$
+
+ private static String[] packageLevelDefinitions = { RpmTags.SUMMARY,
+ RpmTags.GROUP, RpmTags.OBSOLETES, RpmTags.PROVIDES,
+ RpmTags.REQUIRES, RpmTags.REQUIRES_PRE, RpmTags.REQUIRES_POST,
+ RpmTags.REQUIRES_POSTUN };
+
+ private SpecfileErrorHandler errorHandler;
+ private SpecfileTaskHandler taskHandler;
+ private IPreferenceStore store;
+ private SpecfileSection lastSection;
+ private SpecfilePackage activePackage;
+
+ public SpecfileParser() {
+ store = Activator.getDefault().getPreferenceStore();
+ }
+
+ public Specfile parse(IDocument specfileDocument) {
+
+ // remove all existing markers, if a SpecfileErrorHandler is
+ // instantiated.
+ if (errorHandler != null) {
+ errorHandler.removeExistingMarkers();
+ }
+ if (taskHandler != null) {
+ taskHandler.removeExistingMarkers();
+ }
+ LineNumberReader reader = new LineNumberReader(new StringReader(
+ specfileDocument.get()));
+ String line = ""; //$NON-NLS-1$
+ int lineStartPosition = 0;
+ Specfile specfile = new Specfile();
+ specfile.setDocument(specfileDocument);
+ try {
+ while ((line = reader.readLine()) != null) {
+ if (taskHandler != null) {
+ generateTaskMarker(reader.getLineNumber() - 1, line);
+ }
+ // IDocument.getLine(#) is 0-indexed whereas
+ // reader.getLineNumber appears to be 1-indexed
+ SpecfileElement element = parseLine(line, specfile, reader
+ .getLineNumber() - 1);
+ if (element != null) {
+ element.setLineNumber(reader.getLineNumber() - 1);
+ element.setLineStartPosition(lineStartPosition);
+ element.setLineEndPosition(lineStartPosition
+ + line.length());
+ if (element.getClass() == SpecfileTag.class) {
+ SpecfileTag tag = (SpecfileTag) element;
+ specfile.addDefine(tag);
+ } else if ((element.getClass() == SpecfilePatchMacro.class)) {
+ SpecfilePatchMacro thisPatchMacro = (SpecfilePatchMacro) element;
+ if (thisPatchMacro != null) {
+ thisPatchMacro.setSpecfile(specfile);
+ }
+ SpecfileSource thisPatch = specfile
+ .getPatch(thisPatchMacro.getPatchNumber());
+ if (thisPatch != null) {
+ thisPatch.addLineUsed(reader.getLineNumber() - 1);
+ thisPatch.setSpecfile(specfile);
+ }
+ } else if ((element.getClass() == SpecfileDefine.class)) {
+ specfile.addDefine((SpecfileDefine) element);
+ } else if ((element.getClass() == SpecfileSource.class)) {
+ SpecfileSource source = (SpecfileSource) element;
+
+ source.setLineNumber(reader.getLineNumber() - 1);
+ if (source.getSourceType() == SpecfileSource.SourceType.SOURCE) {
+ specfile.addSource(source);
+ } else {
+ specfile.addPatch(source);
+ }
+ }
+ }
+
+ // sets the last SpecfileSection's end line to that of the end of
+ // the end of the specfileDocument.
+ // SpecfileParser#parseMacro will handle correcting the end line
+ // if the last SpecfileSection was not truly the last 1
+ // This is for the purpose of making DocumentRangeNode work
+ if (lastSection != null) {
+ lastSection.setSectionEndLine(specfileDocument
+ .getNumberOfLines() - 1);
+ }
+
+ // The +1 is for the line delimiter. FIXME: will we end up off
+ // by one on the last line?
+ lineStartPosition += line.length() + 1;
+ }
+ } catch (IOException e) {
+ // FIXME
+ SpecfileLog.logError(e);
+ }
+ return specfile;
+ }
+
+ /**
+ * Parse a File into a specfile
+ *
+ * @param file The File to be parsed
+ * @return A Specfile object
+ */
+ public Specfile parse(IFile file) {
+ SpecfileParser parser = new SpecfileParser();
+ StringBuilder sb = new StringBuilder();
+ String line = null;
+ try {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(
+ file.getContents()));
+ while ((line = reader.readLine()) != null) {
+ sb.append(line + "\n"); //$NON-NLS-1$
+ }
+ } catch (IOException e) {
+ SpecfileLog.logError(Messages.getString("SpecfileParseFile.1"), e); //$NON-NLS-1$
+ } catch (CoreException e) {
+ SpecfileLog.logError(Messages.getString("SpecfileParseFile.2"), e); //$NON-NLS-1$
+ }
+ return parser.parse(sb.toString());
+ }
+
+ private void generateTaskMarker(int lineNumber, String line) {
+ String[] taskTags = store.getString(PreferenceConstants.P_TASK_TAGS)
+ .split(";"); //$NON-NLS-1$
+ int commentCharIndex = line
+ .indexOf(ISpecfileSpecialSymbols.COMMENT_START);
+ if (commentCharIndex > -1) {
+ for (String item : taskTags) {
+ int taskIndex = line.indexOf(item);
+ if (taskIndex > commentCharIndex) {
+ taskHandler.handleTask(lineNumber, line, item);
+ }
+ }
+ }
+ }
+
+ public Specfile parse(String specfileContent) {
+ return parse(new Document(specfileContent));
+ }
+
+ public SpecfileElement parseLine(String lineText, Specfile specfile,
+ int lineNumber) {
+
+ if (lineText.startsWith("%")) {//$NON-NLS-1$
+ return parseMacro(lineText, specfile, lineNumber);
+ }
+
+ for (String simpleDefinition : simpleDefinitions) {
+ if (lineText.startsWith(simpleDefinition + DEFINE_SEPARATOR)) {
+ return parseSimpleDefinition(lineText, specfile, lineNumber,
+ false);
+ }
+ }
+ for (String directValuesDefinition : directValuesDefinitions) {
+ if (lineText.startsWith(directValuesDefinition + DEFINE_SEPARATOR)) {
+ return parseDirectDefinition(lineText, specfile, lineNumber);
+ }
+ }
+ for (String directValuesDefinition : packageLevelDefinitions) {
+ if (lineText.startsWith(directValuesDefinition + DEFINE_SEPARATOR)) {
+ SpecfileElement definition = parseDirectDefinition(lineText,
+ specfile, lineNumber);
+ if (directValuesDefinition.equals(RpmTags.REQUIRES)) {
+ if (activePackage != null) {
+ activePackage.addRequire((SpecfileTag) definition);
+ } else {
+ specfile.addRequire((SpecfileTag) definition);
+ }
+ }
+ return definition;
+ }
+ }
+
+ if (lineText.startsWith(complexDefinitions[0])
+ && lineText.contains(DEFINE_SEPARATOR)) {
+ return parseComplexDefinition(lineText, lineNumber,
+ SourceType.SOURCE);
+ } else if (lineText.startsWith(complexDefinitions[1])
+ && lineText.contains(DEFINE_SEPARATOR)) {
+ return parseComplexDefinition(lineText, lineNumber,
+ SourceType.PATCH);
+ } else if (lineText.startsWith("BuildRequires")) { //$NON-NLS-1$
+ return parseBuildRequire(lineText, lineNumber, specfile);
+ }
+
+ return null;
+ }
+
+ private SpecfileElement parseBuildRequire(String lineText, int lineNumber,
+ Specfile specfile) {
+ String value = lineText.substring(lineText.indexOf(':') + 1,
+ lineText.length()).trim();
+ SpecfileDefine buildRequire = new SpecfileDefine(
+ "BuildRequires", value, specfile, null); //$NON-NLS-1$
+ buildRequire.setLineNumber(lineNumber);
+ specfile.addBuildRequire(buildRequire);
+ return buildRequire;
+ }
+
+ private SpecfileSection parseSection(String lineText, Specfile specfile,
+ int lineNumber) {
+ List<String> tokens = Arrays.asList(lineText.split(SPACE_REGEX));
+ SpecfileSection toReturn = null;
+ boolean isSimpleSection = false;
+ for (Iterator<String> iter = tokens.iterator(); iter.hasNext();) {
+ String token = iter.next();
+
+ // Sections
+ // Simple Section Headers
+ for (String simpleSection : simpleSections) {
+ if (token.equals(simpleSection)) {
+ toReturn = new SpecfileSection(token.substring(1), specfile);
+ specfile.addSection(toReturn);
+ isSimpleSection = true;
+ }
+
+ }
+
+ // Complex Section Headers
+ for (String complexSection : complexSections) {
+ if (token.equals(complexSection)) {
+ String name = token.substring(1);
+ if (!name.equals("package")) { //$NON-NLS-1$
+ toReturn = new SpecfileSection(name, specfile);
+ specfile.addComplexSection(toReturn);
+ }
+ while (iter.hasNext()) {
+ String nextToken = iter.next();
+ if (nextToken.equals("-n")) { //$NON-NLS-1$
+ if (!iter.hasNext()) {
+ errorHandler
+ .handleError(new SpecfileParseException(
+ Messages
+ .getString("SpecfileParser.1") //$NON-NLS-1$
+ + name
+ + Messages
+ .getString("SpecfileParser.2"), //$NON-NLS-1$
+ lineNumber, 0, lineText
+ .length(),
+ IMarker.SEVERITY_ERROR));
+ continue;
+ }
+
+ nextToken = iter.next();
+ if (nextToken.startsWith("-")) { //$NON-NLS-1$
+ errorHandler
+ .handleError(new SpecfileParseException(
+ Messages
+ .getString("SpecfileParser.3") //$NON-NLS-1$
+ + nextToken
+ + Messages
+ .getString("SpecfileParser.4"), //$NON-NLS-1$
+ lineNumber, 0, lineText
+ .length(),
+ IMarker.SEVERITY_ERROR));
+ }
+
+ } else if (nextToken.equals("-p")) { //$NON-NLS-1$
+ // FIXME: rest of line is the actual section
+ break;
+ } else if (nextToken.equals("-f")) { //$NON-NLS-1$
+ break;
+ }
+
+ // this is a package
+ if (toReturn == null) {
+ SpecfilePackage tmpPackage = specfile
+ .getPackage(nextToken);
+
+ if (tmpPackage == null) {
+ tmpPackage = new SpecfilePackage(nextToken,
+ specfile);
+ specfile.addPackage(tmpPackage);
+ }
+ activePackage = tmpPackage;
+ return tmpPackage;
+ }
+
+ // this is another section
+ SpecfilePackage enclosingPackage = specfile
+ .getPackage(nextToken);
+ if (enclosingPackage == null) {
+ enclosingPackage = new SpecfilePackage(nextToken,
+ specfile);
+ specfile.addPackage(enclosingPackage);
+ }
+ toReturn.setPackage(enclosingPackage);
+ enclosingPackage.addSection(toReturn);
+ }
+ }
+ }
+ }
+
+ // if this package is part of the top level package, add it to
+ // it
+ if (toReturn != null && toReturn.getPackage() == null) {
+ SpecfilePackage topPackage = specfile
+ .getPackage(specfile.getName());
+ if (topPackage == null) {
+ topPackage = new SpecfilePackage(specfile.getName(), specfile);
+ specfile.addPackage(topPackage);
+ }
+ if (!isSimpleSection) {
+ topPackage.addSection(toReturn);
+ }
+ }
+ if (lastSection != null) {
+ lastSection.setSectionEndLine(lineNumber);
+ }
+ return toReturn;
+ }
+
+ private SpecfileElement parseMacro(String lineText, Specfile specfile,
+ int lineNumber) {
+ // FIXME: handle other macros
+
+ if (lineText.startsWith("%define") || lineText.startsWith("%global")) { //$NON-NLS-1$ //$NON-NLS-2$
+ return parseDefine(lineText, specfile, lineNumber);
+ } else if (lineText.startsWith("%patch")) { //$NON-NLS-1$
+ return parsePatch(lineText, lineNumber);
+ }
+
+ String[] sections = new String[simpleSections.length
+ + complexSections.length];
+ System.arraycopy(simpleSections, 0, sections, 0, simpleSections.length);
+ System.arraycopy(complexSections, 0, sections, simpleSections.length,
+ complexSections.length);
+ for (String section : sections) {
+ if (lineText.startsWith(section)) {
+ lastSection = parseSection(lineText, specfile, lineNumber);
+ if (lastSection != null) {
+ lastSection.setSectionEndLine(lineNumber + 1);
+ }
+ return lastSection;
+ }
+ }
+ // FIXME: add handling of lines containing %{SOURCENNN}
+ return null;
+ }
+
+ private SpecfileElement parsePatch(String lineText, int lineNumber) {
+
+ SpecfilePatchMacro toReturn = null;
+
+ List<String> tokens = Arrays.asList(lineText.split(SPACE_REGEX));
+
+ for (String token : tokens) {
+ // %patchN+
+ try {
+ if (token.startsWith("%patch")) { //$NON-NLS-1$
+ int patchNumber = 0;
+ if (token.length() > 6) {
+ patchNumber = Integer.parseInt(token.substring(6));
+ }
+ toReturn = new SpecfilePatchMacro(patchNumber);
+ }
+ } catch (NumberFormatException e) {
+ errorHandler.handleError(new SpecfileParseException(
+ Messages.getString("SpecfileParser.5"), //$NON-NLS-1$
+ lineNumber, 0, lineText.length(),
+ IMarker.SEVERITY_ERROR));
+ return null;
+ }
+ }
+
+ return toReturn;
+ }
+
+ private SpecfileDefine parseDefine(String lineText, Specfile specfile,
+ int lineNumber) {
+ List<String> tokens = Arrays.asList(lineText.split(SPACE_REGEX));
+ SpecfileDefine toReturn = null;
+ for (Iterator<String> iter = tokens.iterator(); iter.hasNext();) {
+ // Eat the actual "%define" or "%global" token
+ iter.next();
+ while (iter.hasNext()) {
+ String defineName = iter.next();
+ // FIXME: is this true? investigate in rpmbuild source
+ // Definitions must being with a letter
+ if (!Character.isLetter(defineName.charAt(0))
+ && (defineName.charAt(0) != '_')) {
+ errorHandler.handleError(new SpecfileParseException(
+ Messages.getString("SpecfileParser.6"), //$NON-NLS-1$
+ lineNumber, 0, lineText.length(),
+ IMarker.SEVERITY_ERROR));
+ return null;
+ } else {
+ if (iter.hasNext()) {
+ String defineStringValue = iter.next();
+ // Defines that are more than one token
+ if (iter.hasNext()) {
+ defineStringValue = lineText.substring(lineText
+ .indexOf(defineStringValue));
+ // Eat up the rest of the tokens
+ while (iter.hasNext()) {
+ iter.next();
+ }
+ }
+ int defineIntValue = -1;
+ try {
+ defineIntValue = Integer
+ .parseInt(defineStringValue);
+ } catch (NumberFormatException e) {
+ toReturn = new SpecfileDefine(defineName,
+ defineStringValue, specfile, null);
+ }
+ if (toReturn == null) {
+ toReturn = new SpecfileDefine(defineName,
+ defineIntValue, specfile, null);
+ }
+ } else {
+ errorHandler.handleError(new SpecfileParseException(defineName+
+ Messages.getString("SpecfileParser.14"), //$NON-NLS-1$
+ lineNumber, 0, lineText.length(),
+ IMarker.SEVERITY_ERROR));
+ }
+ }
+ }
+ }
+ return toReturn;
+ }
+
+ private SpecfileElement parseComplexDefinition(String lineText,
+ int lineNumber, SourceType sourceType) {
+ SpecfileSource toReturn = null;
+ List<String> tokens = Arrays.asList(lineText.split(SPACE_REGEX));
+ int number = -1;
+ boolean firstToken = true;
+
+ for (Iterator<String> iter = tokens.iterator(); iter.hasNext();) {
+ String token = iter.next();
+ if (token != null && token.length() > 0) {
+ if (firstToken) {
+ if (token.endsWith(DEFINE_SEPARATOR)) {
+ token = token.substring(0, token.length() - 1);
+ } else {
+ // FIXME: come up with a better error message here
+ // FIXME: what about descriptions that begin a line with
+ // the word "Source" or "Patch"?
+ errorHandler.handleError(new SpecfileParseException(
+ Messages.getString("SpecfileParser.8"), //$NON-NLS-1$
+ lineNumber, 0, lineText.length(),
+ IMarker.SEVERITY_WARNING));
+ return null;
+ }
+ if (sourceType == SourceType.PATCH) {
+ if (token.length() > 5) {
+ number = Integer.parseInt(token.substring(5));
+ if (!("patch" + number).equalsIgnoreCase(token)) { //$NON-NLS-1$
+ errorHandler
+ .handleError(new SpecfileParseException(
+ Messages
+ .getString("SpecfileParser.10"), //$NON-NLS-1$
+ lineNumber, 0, lineText
+ .length(),
+ IMarker.SEVERITY_ERROR));
+ return null;
+ }
+ } else {
+ number = 0;
+ }
+ } else {
+ if (token.length() > 6) {
+ number = Integer.parseInt(token.substring(6));
+ if (!("source" + number).equalsIgnoreCase(token)) { //$NON-NLS-1$
+ errorHandler
+ .handleError(new SpecfileParseException(
+ Messages
+ .getString("SpecfileParser.11"), //$NON-NLS-1$
+ lineNumber, 0, lineText
+ .length(),
+ IMarker.SEVERITY_ERROR));
+ return null;
+ }
+ } else {
+ number = 0;
+ }
+ }
+ toReturn = new SpecfileSource(number, ""); //$NON-NLS-1$
+ toReturn.setSourceType(sourceType);
+ firstToken = false;
+ } else {
+ // toReturn should never be null but check just in case
+ if (toReturn != null) {
+ toReturn.setFileName(token);
+ }
+ if (iter.hasNext()) {
+ errorHandler.handleError(new SpecfileParseException(
+ Messages.getString("SpecfileParser.12"), //$NON-NLS-1$
+ lineNumber, 0, lineText.length(),
+ IMarker.SEVERITY_ERROR));
+ }
+ }
+ }
+ }
+
+ return toReturn;
+ }
+
+ private SpecfileElement parseSimpleDefinition(String lineText,
+ Specfile specfile, int lineNumber, boolean warnMultipleValues) {
+ List<String> tokens = Arrays.asList(lineText.split(SPACE_REGEX));
+ SpecfileTag toReturn = null;
+
+ for (Iterator<String> iter = tokens.iterator(); iter.hasNext();) {
+ String token = iter.next();
+
+ if (token.length() <= 0) {
+ break;
+ }
+
+ if (iter.hasNext()) {
+ String possValue = iter.next();
+ if (possValue.startsWith("%") && iter.hasNext()) { //$NON-NLS-1$
+ possValue += ' ' + iter.next();
+ }
+ toReturn = new SpecfileTag(token.substring(0,
+ token.length() - 1).toLowerCase(), possValue, specfile,
+ null);
+ if (iter.hasNext() && !warnMultipleValues) {
+ errorHandler.handleError(new SpecfileParseException(
+ token.substring(0, token.length() - 1)
+ + Messages.getString("SpecfileParser.13"), //$NON-NLS-1$
+ lineNumber, 0, lineText.length(),
+ IMarker.SEVERITY_ERROR));
+ return null;
+ }
+ } else {
+ errorHandler.handleError(new SpecfileParseException(token
+ .substring(0, token.length() - 1)
+ + Messages.getString("SpecfileParser.14"), lineNumber, //$NON-NLS-1$
+ 0, lineText.length(), IMarker.SEVERITY_ERROR));
+ toReturn = null;
+ }
+ }
+ if ((toReturn != null) && (toReturn.getStringValue() != null)) {
+ try {
+ int intValue = Integer.parseInt(toReturn.getStringValue());
+ toReturn.setValue(intValue);
+ } catch (NumberFormatException e) {
+ if (toReturn.getName().equalsIgnoreCase(RpmTags.EPOCH)) {
+ errorHandler
+ .handleError(new SpecfileParseException(
+ Messages.getString("SpecfileParser.16"), lineNumber, //$NON-NLS-1$
+ 0, lineText.length(),
+ IMarker.SEVERITY_ERROR));
+ toReturn = null;
+ }
+ }
+ }
+ return toReturn;
+ }
+
+ private SpecfileElement parseDirectDefinition(String lineText,
+ Specfile specfile, int lineNumber) {
+ String[] parts = lineText.split(DEFINE_SEPARATOR, 2);
+ SpecfileTag directDefinition;
+ if (parts.length == 2) {
+ directDefinition = new SpecfileTag(parts[0], parts[1].trim(),
+ specfile, activePackage);
+ directDefinition.setLineNumber(lineNumber);
+ } else {
+ errorHandler.handleError(new SpecfileParseException(parts[0]
+ + Messages.getString("SpecfileParser.14"), lineNumber, //$NON-NLS-1$
+ 0, lineText.length(), IMarker.SEVERITY_ERROR));
+ directDefinition = null;
+ }
+ return directDefinition;
+ }
+
+ public void setErrorHandler(SpecfileErrorHandler specfileErrorHandler) {
+ errorHandler = specfileErrorHandler;
+ }
+
+ public void setTaskHandler(SpecfileTaskHandler specfileTaskHandler) {
+ taskHandler = specfileTaskHandler;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileSection.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileSection.java
index 25edcd7664..d06422a589 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileSection.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/parser/SpecfileSection.java
@@ -18,62 +18,62 @@ import org.eclipse.jface.text.IDocument;
public class SpecfileSection extends SpecfileElement {
- private SpecfilePackage parentPackage;
- private int sectionEndLine;
+ private SpecfilePackage parentPackage;
+ private int sectionEndLine;
- public SpecfileSection(String name, Specfile specfile) {
- super(name);
- parentPackage = null;
- super.setSpecfile(specfile);
- }
+ public SpecfileSection(String name, Specfile specfile) {
+ super(name);
+ parentPackage = null;
+ super.setSpecfile(specfile);
+ }
- public SpecfilePackage getPackage() {
- return parentPackage;
- }
+ public SpecfilePackage getPackage() {
+ return parentPackage;
+ }
- public void setPackage(SpecfilePackage thePackage) {
- this.parentPackage = thePackage;
- }
+ public void setPackage(SpecfilePackage thePackage) {
+ this.parentPackage = thePackage;
+ }
- @Override
- public String toString() {
- if (parentPackage == null) {
- return getName();
- } else {
- return MessageFormat.format("{0} {1}", getName(), parentPackage); //$NON-NLS-1$
- }
- }
+ @Override
+ public String toString() {
+ if (parentPackage == null) {
+ return getName();
+ } else {
+ return MessageFormat.format("{0} {1}", getName(), parentPackage); //$NON-NLS-1$
+ }
+ }
- public String getPackageName() {
- return parentPackage.getPackageName();
- }
+ public String getPackageName() {
+ return parentPackage.getPackageName();
+ }
- /**
- * @param sectionEnd
- * the sectionEnd to set
- */
- public void setSectionEndLine(int sectionEnd) {
- this.sectionEndLine = sectionEnd;
- }
+ /**
+ * @param sectionEnd
+ * the sectionEnd to set
+ */
+ public void setSectionEndLine(int sectionEnd) {
+ this.sectionEndLine = sectionEnd;
+ }
- /**
- * @return the sectionEnd
- */
- public int getSectionEndLine() {
- return sectionEndLine;
- }
+ /**
+ * @return the sectionEnd
+ */
+ public int getSectionEndLine() {
+ return sectionEndLine;
+ }
- public String getContents() {
- IDocument document = getSpecfile().getDocument();
- int beginning = getLineStartPosition();
- try {
- int end = document.getLineOffset(getSectionEndLine());
- return document.get(beginning, end-beginning);
- } catch (BadLocationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return ""; //$NON-NLS-1$
- }
+ public String getContents() {
+ IDocument document = getSpecfile().getDocument();
+ int beginning = getLineStartPosition();
+ try {
+ int end = document.getLineOffset(getSectionEndLine());
+ return document.get(beginning, end-beginning);
+ } catch (BadLocationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return ""; //$NON-NLS-1$
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/utils/RPMUtils.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/utils/RPMUtils.java
index e0b7c3efa9..9258454a2f 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/utils/RPMUtils.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/utils/RPMUtils.java
@@ -29,94 +29,94 @@ import org.eclipse.ui.PlatformUI;
*/
public class RPMUtils {
- /**
- * Utility classes should not have a public or default constructor.
- */
- private RPMUtils() {}
+ /**
+ * Utility classes should not have a public or default constructor.
+ */
+ private RPMUtils() {}
- /**
- * Show an error dialog.
- *
- * @param shell A valid shell
- * @param title The error dialog title
- * @param message The message to be displayed.
- */
- public static void showErrorDialog(final Shell shell,
- final String title, final String message) {
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- MessageDialog.openError(shell, title, message);
- }
- });
- }
+ /**
+ * Show an error dialog.
+ *
+ * @param shell A valid shell
+ * @param title The error dialog title
+ * @param message The message to be displayed.
+ */
+ public static void showErrorDialog(final Shell shell,
+ final String title, final String message) {
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ MessageDialog.openError(shell, title, message);
+ }
+ });
+ }
- /**
- * Check if the line passed in is a valid URL.
- *
- * @param line The line to check if is a valid URL.
- * @return True if valid URL, false otherwise.
- */
- public static boolean isValidUrl(String line) {
- try {
- new URL(line);
- return true;
- } catch (MalformedURLException e) {
- return false;
- }
- }
+ /**
+ * Check if the line passed in is a valid URL.
+ *
+ * @param line The line to check if is a valid URL.
+ * @return True if valid URL, false otherwise.
+ */
+ public static boolean isValidUrl(String line) {
+ try {
+ new URL(line);
+ return true;
+ } catch (MalformedURLException e) {
+ return false;
+ }
+ }
- /**
- * Get the file from the URL if any.
- *
- * @param url The URL to get the file from.
- * @return Return the filename.
- */
- public static String getURLFilename(String url) {
- String rc = ""; //$NON-NLS-1$
+ /**
+ * Get the file from the URL if any.
+ *
+ * @param url The URL to get the file from.
+ * @return Return the filename.
+ */
+ public static String getURLFilename(String url) {
+ String rc = ""; //$NON-NLS-1$
- try {
- // URL#getPath will ignore any queries after the filename
- String fileName = new URL(url).getPath();
- int lastSegment = fileName.lastIndexOf("/") + 1; //$NON-NLS-1$
- rc = fileName.substring(lastSegment).trim();
- } catch (IndexOutOfBoundsException e) {
- SpecfileLog.logError(e);
- } catch (MalformedURLException e) {
- SpecfileLog.logError(e);
- }
+ try {
+ // URL#getPath will ignore any queries after the filename
+ String fileName = new URL(url).getPath();
+ int lastSegment = fileName.lastIndexOf("/") + 1; //$NON-NLS-1$
+ rc = fileName.substring(lastSegment).trim();
+ } catch (IndexOutOfBoundsException e) {
+ SpecfileLog.logError(e);
+ } catch (MalformedURLException e) {
+ SpecfileLog.logError(e);
+ }
- return rc;
- }
+ return rc;
+ }
- /**
- * Check if the file exists within the current project.
- * It will first check the root of the project and then the sources. If the
- * file cannot be found in either, return false.
- * An empty file name would immediately return false.
- *
- * @return True if the file exists.
- */
- public static boolean fileExistsInSources(IFile original, String fileName) {
- if (fileName.trim().isEmpty()) {
- return false;
- }
- IContainer container = original.getParent();
- IResource resourceToOpen = container.findMember(fileName);
- IFile file = null;
+ /**
+ * Check if the file exists within the current project.
+ * It will first check the root of the project and then the sources. If the
+ * file cannot be found in either, return false.
+ * An empty file name would immediately return false.
+ *
+ * @return True if the file exists.
+ */
+ public static boolean fileExistsInSources(IFile original, String fileName) {
+ if (fileName.trim().isEmpty()) {
+ return false;
+ }
+ IContainer container = original.getParent();
+ IResource resourceToOpen = container.findMember(fileName);
+ IFile file = null;
- if (resourceToOpen == null) {
- IResource sourcesFolder = container.getProject().findMember(
- "SOURCES"); //$NON-NLS-1$
- file = container.getFile(new Path(fileName));
- if (sourcesFolder != null) {
- file = ((IFolder) sourcesFolder).getFile(new Path(fileName));
- }
- if (!file.exists()) {
- return false;
- }
- }
+ if (resourceToOpen == null) {
+ IResource sourcesFolder = container.getProject().findMember(
+ "SOURCES"); //$NON-NLS-1$
+ file = container.getFile(new Path(fileName));
+ if (sourcesFolder != null) {
+ file = ((IFolder) sourcesFolder).getFile(new Path(fileName));
+ }
+ if (!file.exists()) {
+ return false;
+ }
+ }
- return true;
- }
+ return true;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/wizards/Messages.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/wizards/Messages.java
index 3ed977223d..5c4ef9a5cb 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/wizards/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/wizards/Messages.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -13,42 +13,42 @@ package org.eclipse.linuxtools.rpm.ui.editor.wizards;
import org.eclipse.osgi.util.NLS;
public final class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.rpm.ui.editor.wizards.messages"; //$NON-NLS-1$
- public static String NoExecutableWizardPage_0;
- public static String NoExecutableWizardPage_1;
- public static String NoExecutableWizardPage_2;
- public static String SpecfileNewWizard_0;
- public static String SpecfileNewWizard_1;
- public static String SpecfileNewWizard_2;
- public static String SpecfileNewWizard_3;
- public static String SpecfileNewWizard_4;
- public static String SpecfileNewWizardPage_10;
- public static String SpecfileNewWizardPage_11;
- public static String SpecfileNewWizardPage_12;
- public static String SpecfileNewWizardPage_13;
- public static String SpecfileNewWizardPage_14;
- public static String SpecfileNewWizardPage_15;
- public static String SpecfileNewWizardPage_16;
- public static String SpecfileNewWizardPage_17;
- public static String SpecfileNewWizardPage_18;
- public static String SpecfileNewWizardPage_19;
- public static String SpecfileNewWizardPage_20;
- public static String SpecfileNewWizardPage_21;
- public static String SpecfileNewWizardPage_22;
- public static String SpecfileNewWizardPage_23;
- public static String SpecfileNewWizardPage_24;
- public static String SpecfileNewWizardPage_25;
- public static String SpecfileNewWizardPage_26;
- public static String SpecfileNewWizardPage_27;
- public static String SpecfileNewWizardPage_28;
- public static String SpecfileNewWizardPage_29;
- public static String SpecfileNewWizardPage_9;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.rpm.ui.editor.wizards.messages"; //$NON-NLS-1$
+ public static String NoExecutableWizardPage_0;
+ public static String NoExecutableWizardPage_1;
+ public static String NoExecutableWizardPage_2;
+ public static String SpecfileNewWizard_0;
+ public static String SpecfileNewWizard_1;
+ public static String SpecfileNewWizard_2;
+ public static String SpecfileNewWizard_3;
+ public static String SpecfileNewWizard_4;
+ public static String SpecfileNewWizardPage_10;
+ public static String SpecfileNewWizardPage_11;
+ public static String SpecfileNewWizardPage_12;
+ public static String SpecfileNewWizardPage_13;
+ public static String SpecfileNewWizardPage_14;
+ public static String SpecfileNewWizardPage_15;
+ public static String SpecfileNewWizardPage_16;
+ public static String SpecfileNewWizardPage_17;
+ public static String SpecfileNewWizardPage_18;
+ public static String SpecfileNewWizardPage_19;
+ public static String SpecfileNewWizardPage_20;
+ public static String SpecfileNewWizardPage_21;
+ public static String SpecfileNewWizardPage_22;
+ public static String SpecfileNewWizardPage_23;
+ public static String SpecfileNewWizardPage_24;
+ public static String SpecfileNewWizardPage_25;
+ public static String SpecfileNewWizardPage_26;
+ public static String SpecfileNewWizardPage_27;
+ public static String SpecfileNewWizardPage_28;
+ public static String SpecfileNewWizardPage_29;
+ public static String SpecfileNewWizardPage_9;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- super();
- }
+ private Messages() {
+ super();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/wizards/SpecfileNewWizardPage.java b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/wizards/SpecfileNewWizardPage.java
index a57214297f..ac6ce5b3cd 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/wizards/SpecfileNewWizardPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/src/org/eclipse/linuxtools/rpm/ui/editor/wizards/SpecfileNewWizardPage.java
@@ -49,428 +49,428 @@ import org.eclipse.ui.dialogs.ContainerSelectionDialog;
public class SpecfileNewWizardPage extends WizardPage {
- private static final String NAME = "package_name"; //$NON-NLS-1$
-
- private static final String VERSION = "1.0"; //$NON-NLS-1$
-
- private static final String SUMMARY = "Summary of the package"; //$NON-NLS-1$
-
- private static final String GROUP = "Amusements/Games"; //$NON-NLS-1$
-
- private static final String LICENSE = "GPL"; //$NON-NLS-1$
-
- private static final String URL = "http://"; //$NON-NLS-1$
-
- private static final String SOURCE0 = "archive_name-%{version}"; //$NON-NLS-1$
-
- private Text projectText;
-
- private Text nameText;
-
- private Text versionText;
-
- private Text summaryText;
-
- private Combo groupCombo;
-
- private Text licenseText;
-
- private Text urlText;
-
- private Text source0Text;
-
- private GridData gd;
-
- private ISelection selection;
-
- private String selectedTemplate = "minimal"; //$NON-NLS-1$
-
- private String content;
-
- /**
- * Constructor for SpecfileNewWizardPage.
- *
- * @param selection
- * The selection to put the new spec file in.
- */
- public SpecfileNewWizardPage(ISelection selection) {
- super("wizardPage"); //$NON-NLS-1$
- setTitle(Messages.SpecfileNewWizardPage_9);
- setDescription(Messages.SpecfileNewWizardPage_10);
- this.selection = selection;
- }
-
- /**
- * @see WizardPage#createControl(Composite)
- */
- @Override
- public void createControl(Composite parent) {
- final Composite container = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 3;
- layout.verticalSpacing = 9;
-
- // Project
- Label label = new Label(container, SWT.NULL);
- label.setText(Messages.SpecfileNewWizardPage_11);
- projectText = new Text(container, SWT.BORDER | SWT.SINGLE);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- projectText.setLayoutData(gd);
- projectText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- dialogChanged();
- }
- });
- Button button = new Button(container, SWT.PUSH);
- button.setText(Messages.SpecfileNewWizardPage_12);
- button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleBrowse();
- }
- });
-
- // Template to use
- label = new Label(container, SWT.NULL);
- label.setText(Messages.SpecfileNewWizardPage_13);
- Combo templateCombo = new Combo(container, SWT.NULL);
- try {
- populateTemplateCombo(templateCombo);
- } catch (CoreException e2) {
- SpecfileLog.logError(e2);
- }
- // empty label for the last row.
- label = new Label(container, SWT.NULL);
- templateCombo.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedTemplate = ((Combo) e.getSource()).getText();
- InputStream inputStream = runRpmdevNewSpec(selectedTemplate);
- LineNumberReader reader = new LineNumberReader(
- new InputStreamReader(inputStream));
- String line;
- try {
- content = ""; //$NON-NLS-1$
- setDefaultValues();
- while ((line = reader.readLine()) != null) {
- if (line.startsWith("Name:")) { //$NON-NLS-1$
- setTemplateTagValue(nameText, line);
- }
- if (line.startsWith("Version:")) { //$NON-NLS-1$
- setTemplateTagValue(versionText, line);
- }
- if (line.startsWith("Summary:")) { //$NON-NLS-1$
- setTemplateTagValue(summaryText, line);
- }
- if (line.startsWith("Group:")) { //$NON-NLS-1$
- String[] items = line.split(":", 2); //$NON-NLS-1$
- String value = items[1].trim();
- if (!value.equals("")) {//$NON-NLS-1$
- groupCombo.setText(value);
- }
- }
- if (line.startsWith("License:")) { //$NON-NLS-1$
- setTemplateTagValue(licenseText, line);
- }
- if (line.startsWith("URL:")) { //$NON-NLS-1$
- setTemplateTagValue(urlText, line);
- }
- if (line.startsWith("Source0:")) { //$NON-NLS-1$
- setTemplateTagValue(source0Text, line);
- }
- content += line + '\n';
- }
- } catch (IOException e1) {
- SpecfileLog.logError(e1);
- }
- }
- });
-
- // Package Name
- nameText = setTextItem(container, Messages.SpecfileNewWizardPage_14);
-
- // Package Version
- versionText = setTextItem(container, Messages.SpecfileNewWizardPage_15);
-
- // Package Summary
- summaryText = setTextItem(container, Messages.SpecfileNewWizardPage_16);
-
- // Package Group
- label = new Label(container, SWT.NULL);
- label.setText(Messages.SpecfileNewWizardPage_17);
- groupCombo = new Combo(container, SWT.NULL);
- populateGroupCombo(groupCombo);
- // empty label for the last row.
- new Label(container, SWT.NULL);
-
- // Package License
- licenseText = setTextItem(container, Messages.SpecfileNewWizardPage_18);
-
- // Package URL
- urlText = setTextItem(container, Messages.SpecfileNewWizardPage_19);
-
- // Package Source0
- source0Text = setTextItem(container, Messages.SpecfileNewWizardPage_20);
-
- initialize();
- dialogChanged();
- setControl(container);
- }
-
- private Text setTextItem(Composite container, String textLabel) {
- Label label = new Label(container, SWT.NULL);
- label.setText(textLabel);
- Text text = new Text(container, SWT.BORDER | SWT.SINGLE);
- text.setLayoutData(gd);
- text.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- dialogChanged();
- }
- });
- // empty label for the last row.
- new Label(container, SWT.NULL);
- return text;
- }
-
- private void setTemplateTagValue(Text text, String line) {
- String[] items = line.split(":", 2); //$NON-NLS-1$
- String value = items[1].trim();
- if (!value.equals("")) { //$NON-NLS-1$
- text.setText(value);
- }
- }
-
- public String getProjectName() {
- return projectText.getText();
- }
-
- public String getFileName() {
- return nameText.getText() + ".spec"; //$NON-NLS-1$
- }
-
- public String getSelectedTemplate() {
- return selectedTemplate;
- }
-
- public String getContent() {
- InputStream inputStream = runRpmdevNewSpec(selectedTemplate);
- LineNumberReader reader = new LineNumberReader(new InputStreamReader(
- inputStream));
- String line;
- try {
- content = ""; //$NON-NLS-1$
- while ((line = reader.readLine()) != null) {
- if (line.startsWith("Name:")) { //$NON-NLS-1$
- line = "Name:" + " " + nameText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (line.startsWith("Version:")) { //$NON-NLS-1$
- line = "Version:" + " " + versionText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (line.startsWith("Summary:")) { //$NON-NLS-1$
- line = "Summary:" + " " + summaryText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (line.startsWith("Group:")) { //$NON-NLS-1$
- line = "Group:" + " " + groupCombo.getText(); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (line.startsWith("License:")) { //$NON-NLS-1$
- line = "License:" + " " + licenseText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (line.startsWith("URL:")) { //$NON-NLS-1$
- line = "URL:" + " " + urlText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (line.startsWith("Source0:")) { //$NON-NLS-1$
- line = "Source0:" + " " + source0Text.getText(); //$NON-NLS-1$ //$NON-NLS-2$
- }
- content += line + '\n';
- }
- } catch (IOException e1) {
- SpecfileLog.logError(e1);
- }
- return content;
- }
-
- /**
- * Tests if the current workbench selection is a suitable container to use.
- */
- private void initialize() {
- if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
- IStructuredSelection ssel = (IStructuredSelection) selection;
- if (ssel.size() > 1) {
- return;
- }
- Object obj = ssel.getFirstElement();
- if (obj instanceof IResource) {
- IContainer container;
- if (obj instanceof IContainer) {
- container = (IContainer) obj;
- } else {
- container = ((IResource) obj).getParent();
- }
- projectText.setText(container.getFullPath().toString());
- }
- }
- setDefaultValues();
- }
-
- /**
- * Uses the standard container selection dialog to choose the new value for
- * the container field.
- */
- private void handleBrowse() {
- ContainerSelectionDialog dialog = new ContainerSelectionDialog(
- getShell(), ResourcesPlugin.getWorkspace().getRoot(), false,
- Messages.SpecfileNewWizardPage_21);
- if (dialog.open() == Window.OK) {
- Object[] result = dialog.getResult();
- if (result.length == 1) {
- projectText.setText(((Path) result[0]).toString());
- }
- }
- }
-
- /**
- * Ensures that both text fields are set.
- */
- private void dialogChanged() {
- IResource container = ResourcesPlugin.getWorkspace().getRoot()
- .findMember(new Path(getProjectName()));
- String fileName = getFileName();
- if (getProjectName().length() == 0) {
- updateStatus(Messages.SpecfileNewWizardPage_22);
- return;
- }
- if (container == null
- || (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) {
- updateStatus(Messages.SpecfileNewWizardPage_23);
- return;
- }
- if (!container.isAccessible()) {
- updateStatus(Messages.SpecfileNewWizardPage_24);
- return;
- }
- if (fileName.length() == 0) {
- updateStatus(Messages.SpecfileNewWizardPage_25);
- return;
- }
-
- /*
- * Current RPM doc content (4.4.2): Names must not include whitespace
- * and may include a hyphen '-' (unlike version and releasetags). Names
- * should not include any numeric operators ('<', '>','=') as future
- * versions of rpm may need to reserve characters other than '-'.
- */
- String packageName = nameText.getText();
- if (packageName.indexOf(' ') != -1 || packageName.indexOf('<') != -1
- || packageName.indexOf('>') != -1 || packageName.indexOf('=') != -1) {
- updateStatus(Messages.SpecfileNewWizardPage_26
- + Messages.SpecfileNewWizardPage_27);
- return;
- }
-
- if (versionText.getText().indexOf("-") > -1) { //$NON-NLS-1$
- updateStatus(Messages.SpecfileNewWizardPage_28);
- return;
- }
-
- updateStatus(null);
- }
-
- protected void updateStatus(String message) {
- setErrorMessage(message);
- setPageComplete(message == null);
- }
-
- private void setDefaultValues() {
- nameText.setText(NAME);
- versionText.setText(VERSION);
- summaryText.setText(SUMMARY);
- groupCombo.setText(GROUP);
- licenseText.setText(LICENSE);
- urlText.setText(URL);
- source0Text.setText(SOURCE0);
- }
-
- private void populateTemplateCombo(Combo templateCombo)
- throws CoreException {
- // get a list of all files in a directory
- File dir = new File("/etc/rpmdevtools"); //$NON-NLS-1$
- String[] files = dir.list();
- if (dir.exists()) {
- String templateCSV = ""; //$NON-NLS-1$
- for (String file : files) {
- if (file.startsWith("spectemplate-")) { //$NON-NLS-1$
- templateCSV += file.split("-", 2)[1].replaceAll("\\.spec", //$NON-NLS-1$ //$NON-NLS-2$
- "") //$NON-NLS-1$
- + ","; //$NON-NLS-1$
- }
- }
- String[] templates = templateCSV.split(","); //$NON-NLS-1$
- for (String template : templates) {
- templateCombo.add(template);
- }
- templateCombo.setText(selectedTemplate);
- } else {
- throwCoreException(Messages.SpecfileNewWizardPage_29);
- }
- }
-
- private void populateGroupCombo(Combo groupsCombo) {
- List<String> rpmGroups = Activator.getDefault().getRpmGroups();
- for (String rpmGroup : rpmGroups) {
- groupsCombo.add(rpmGroup);
- }
- }
-
- private BufferedInputStream runRpmdevNewSpec(String template) {
- BufferedInputStream in = null;
- // Here we assuming that the rpmdevtools package is installed.
- try {
- in = org.eclipse.linuxtools.rpm.core.utils.Utils
- .runCommandToInputStream(
- "rpmdev-newspec", "-o", "-", "-t", template); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- } catch (IOException e) {
- // FIXME: rpmdev-newspec is not in the system $PATH, what should we
- // do here?.
- SpecfileLog.logError(e);
- }
- return in;
- }
-
- private void throwCoreException(String message) throws CoreException {
- IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID,
- IStatus.OK, message, null);
- throw new CoreException(status);
- }
-
- public Text getNameText() {
- return nameText;
- }
-
- public Text getProjectText() {
- return projectText;
- }
-
- public Text getVersionText() {
- return versionText;
- }
-
- public Text getUrlText() {
- return urlText;
- }
-
- public Text getLicenseText() {
- return licenseText;
- }
-
- public Text getSourceText() {
- return source0Text;
- }
-
- public Text getSummaryText() {
- return summaryText;
- }
+ private static final String NAME = "package_name"; //$NON-NLS-1$
+
+ private static final String VERSION = "1.0"; //$NON-NLS-1$
+
+ private static final String SUMMARY = "Summary of the package"; //$NON-NLS-1$
+
+ private static final String GROUP = "Amusements/Games"; //$NON-NLS-1$
+
+ private static final String LICENSE = "GPL"; //$NON-NLS-1$
+
+ private static final String URL = "http://"; //$NON-NLS-1$
+
+ private static final String SOURCE0 = "archive_name-%{version}"; //$NON-NLS-1$
+
+ private Text projectText;
+
+ private Text nameText;
+
+ private Text versionText;
+
+ private Text summaryText;
+
+ private Combo groupCombo;
+
+ private Text licenseText;
+
+ private Text urlText;
+
+ private Text source0Text;
+
+ private GridData gd;
+
+ private ISelection selection;
+
+ private String selectedTemplate = "minimal"; //$NON-NLS-1$
+
+ private String content;
+
+ /**
+ * Constructor for SpecfileNewWizardPage.
+ *
+ * @param selection
+ * The selection to put the new spec file in.
+ */
+ public SpecfileNewWizardPage(ISelection selection) {
+ super("wizardPage"); //$NON-NLS-1$
+ setTitle(Messages.SpecfileNewWizardPage_9);
+ setDescription(Messages.SpecfileNewWizardPage_10);
+ this.selection = selection;
+ }
+
+ /**
+ * @see WizardPage#createControl(Composite)
+ */
+ @Override
+ public void createControl(Composite parent) {
+ final Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 3;
+ layout.verticalSpacing = 9;
+
+ // Project
+ Label label = new Label(container, SWT.NULL);
+ label.setText(Messages.SpecfileNewWizardPage_11);
+ projectText = new Text(container, SWT.BORDER | SWT.SINGLE);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ projectText.setLayoutData(gd);
+ projectText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ dialogChanged();
+ }
+ });
+ Button button = new Button(container, SWT.PUSH);
+ button.setText(Messages.SpecfileNewWizardPage_12);
+ button.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ handleBrowse();
+ }
+ });
+
+ // Template to use
+ label = new Label(container, SWT.NULL);
+ label.setText(Messages.SpecfileNewWizardPage_13);
+ Combo templateCombo = new Combo(container, SWT.NULL);
+ try {
+ populateTemplateCombo(templateCombo);
+ } catch (CoreException e2) {
+ SpecfileLog.logError(e2);
+ }
+ // empty label for the last row.
+ label = new Label(container, SWT.NULL);
+ templateCombo.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedTemplate = ((Combo) e.getSource()).getText();
+ InputStream inputStream = runRpmdevNewSpec(selectedTemplate);
+ LineNumberReader reader = new LineNumberReader(
+ new InputStreamReader(inputStream));
+ String line;
+ try {
+ content = ""; //$NON-NLS-1$
+ setDefaultValues();
+ while ((line = reader.readLine()) != null) {
+ if (line.startsWith("Name:")) { //$NON-NLS-1$
+ setTemplateTagValue(nameText, line);
+ }
+ if (line.startsWith("Version:")) { //$NON-NLS-1$
+ setTemplateTagValue(versionText, line);
+ }
+ if (line.startsWith("Summary:")) { //$NON-NLS-1$
+ setTemplateTagValue(summaryText, line);
+ }
+ if (line.startsWith("Group:")) { //$NON-NLS-1$
+ String[] items = line.split(":", 2); //$NON-NLS-1$
+ String value = items[1].trim();
+ if (!value.equals("")) {//$NON-NLS-1$
+ groupCombo.setText(value);
+ }
+ }
+ if (line.startsWith("License:")) { //$NON-NLS-1$
+ setTemplateTagValue(licenseText, line);
+ }
+ if (line.startsWith("URL:")) { //$NON-NLS-1$
+ setTemplateTagValue(urlText, line);
+ }
+ if (line.startsWith("Source0:")) { //$NON-NLS-1$
+ setTemplateTagValue(source0Text, line);
+ }
+ content += line + '\n';
+ }
+ } catch (IOException e1) {
+ SpecfileLog.logError(e1);
+ }
+ }
+ });
+
+ // Package Name
+ nameText = setTextItem(container, Messages.SpecfileNewWizardPage_14);
+
+ // Package Version
+ versionText = setTextItem(container, Messages.SpecfileNewWizardPage_15);
+
+ // Package Summary
+ summaryText = setTextItem(container, Messages.SpecfileNewWizardPage_16);
+
+ // Package Group
+ label = new Label(container, SWT.NULL);
+ label.setText(Messages.SpecfileNewWizardPage_17);
+ groupCombo = new Combo(container, SWT.NULL);
+ populateGroupCombo(groupCombo);
+ // empty label for the last row.
+ new Label(container, SWT.NULL);
+
+ // Package License
+ licenseText = setTextItem(container, Messages.SpecfileNewWizardPage_18);
+
+ // Package URL
+ urlText = setTextItem(container, Messages.SpecfileNewWizardPage_19);
+
+ // Package Source0
+ source0Text = setTextItem(container, Messages.SpecfileNewWizardPage_20);
+
+ initialize();
+ dialogChanged();
+ setControl(container);
+ }
+
+ private Text setTextItem(Composite container, String textLabel) {
+ Label label = new Label(container, SWT.NULL);
+ label.setText(textLabel);
+ Text text = new Text(container, SWT.BORDER | SWT.SINGLE);
+ text.setLayoutData(gd);
+ text.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ dialogChanged();
+ }
+ });
+ // empty label for the last row.
+ new Label(container, SWT.NULL);
+ return text;
+ }
+
+ private void setTemplateTagValue(Text text, String line) {
+ String[] items = line.split(":", 2); //$NON-NLS-1$
+ String value = items[1].trim();
+ if (!value.equals("")) { //$NON-NLS-1$
+ text.setText(value);
+ }
+ }
+
+ public String getProjectName() {
+ return projectText.getText();
+ }
+
+ public String getFileName() {
+ return nameText.getText() + ".spec"; //$NON-NLS-1$
+ }
+
+ public String getSelectedTemplate() {
+ return selectedTemplate;
+ }
+
+ public String getContent() {
+ InputStream inputStream = runRpmdevNewSpec(selectedTemplate);
+ LineNumberReader reader = new LineNumberReader(new InputStreamReader(
+ inputStream));
+ String line;
+ try {
+ content = ""; //$NON-NLS-1$
+ while ((line = reader.readLine()) != null) {
+ if (line.startsWith("Name:")) { //$NON-NLS-1$
+ line = "Name:" + " " + nameText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (line.startsWith("Version:")) { //$NON-NLS-1$
+ line = "Version:" + " " + versionText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (line.startsWith("Summary:")) { //$NON-NLS-1$
+ line = "Summary:" + " " + summaryText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (line.startsWith("Group:")) { //$NON-NLS-1$
+ line = "Group:" + " " + groupCombo.getText(); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (line.startsWith("License:")) { //$NON-NLS-1$
+ line = "License:" + " " + licenseText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (line.startsWith("URL:")) { //$NON-NLS-1$
+ line = "URL:" + " " + urlText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (line.startsWith("Source0:")) { //$NON-NLS-1$
+ line = "Source0:" + " " + source0Text.getText(); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ content += line + '\n';
+ }
+ } catch (IOException e1) {
+ SpecfileLog.logError(e1);
+ }
+ return content;
+ }
+
+ /**
+ * Tests if the current workbench selection is a suitable container to use.
+ */
+ private void initialize() {
+ if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
+ IStructuredSelection ssel = (IStructuredSelection) selection;
+ if (ssel.size() > 1) {
+ return;
+ }
+ Object obj = ssel.getFirstElement();
+ if (obj instanceof IResource) {
+ IContainer container;
+ if (obj instanceof IContainer) {
+ container = (IContainer) obj;
+ } else {
+ container = ((IResource) obj).getParent();
+ }
+ projectText.setText(container.getFullPath().toString());
+ }
+ }
+ setDefaultValues();
+ }
+
+ /**
+ * Uses the standard container selection dialog to choose the new value for
+ * the container field.
+ */
+ private void handleBrowse() {
+ ContainerSelectionDialog dialog = new ContainerSelectionDialog(
+ getShell(), ResourcesPlugin.getWorkspace().getRoot(), false,
+ Messages.SpecfileNewWizardPage_21);
+ if (dialog.open() == Window.OK) {
+ Object[] result = dialog.getResult();
+ if (result.length == 1) {
+ projectText.setText(((Path) result[0]).toString());
+ }
+ }
+ }
+
+ /**
+ * Ensures that both text fields are set.
+ */
+ private void dialogChanged() {
+ IResource container = ResourcesPlugin.getWorkspace().getRoot()
+ .findMember(new Path(getProjectName()));
+ String fileName = getFileName();
+ if (getProjectName().length() == 0) {
+ updateStatus(Messages.SpecfileNewWizardPage_22);
+ return;
+ }
+ if (container == null
+ || (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) {
+ updateStatus(Messages.SpecfileNewWizardPage_23);
+ return;
+ }
+ if (!container.isAccessible()) {
+ updateStatus(Messages.SpecfileNewWizardPage_24);
+ return;
+ }
+ if (fileName.length() == 0) {
+ updateStatus(Messages.SpecfileNewWizardPage_25);
+ return;
+ }
+
+ /*
+ * Current RPM doc content (4.4.2): Names must not include whitespace
+ * and may include a hyphen '-' (unlike version and releasetags). Names
+ * should not include any numeric operators ('<', '>','=') as future
+ * versions of rpm may need to reserve characters other than '-'.
+ */
+ String packageName = nameText.getText();
+ if (packageName.indexOf(' ') != -1 || packageName.indexOf('<') != -1
+ || packageName.indexOf('>') != -1 || packageName.indexOf('=') != -1) {
+ updateStatus(Messages.SpecfileNewWizardPage_26
+ + Messages.SpecfileNewWizardPage_27);
+ return;
+ }
+
+ if (versionText.getText().indexOf("-") > -1) { //$NON-NLS-1$
+ updateStatus(Messages.SpecfileNewWizardPage_28);
+ return;
+ }
+
+ updateStatus(null);
+ }
+
+ protected void updateStatus(String message) {
+ setErrorMessage(message);
+ setPageComplete(message == null);
+ }
+
+ private void setDefaultValues() {
+ nameText.setText(NAME);
+ versionText.setText(VERSION);
+ summaryText.setText(SUMMARY);
+ groupCombo.setText(GROUP);
+ licenseText.setText(LICENSE);
+ urlText.setText(URL);
+ source0Text.setText(SOURCE0);
+ }
+
+ private void populateTemplateCombo(Combo templateCombo)
+ throws CoreException {
+ // get a list of all files in a directory
+ File dir = new File("/etc/rpmdevtools"); //$NON-NLS-1$
+ String[] files = dir.list();
+ if (dir.exists()) {
+ String templateCSV = ""; //$NON-NLS-1$
+ for (String file : files) {
+ if (file.startsWith("spectemplate-")) { //$NON-NLS-1$
+ templateCSV += file.split("-", 2)[1].replaceAll("\\.spec", //$NON-NLS-1$ //$NON-NLS-2$
+ "") //$NON-NLS-1$
+ + ","; //$NON-NLS-1$
+ }
+ }
+ String[] templates = templateCSV.split(","); //$NON-NLS-1$
+ for (String template : templates) {
+ templateCombo.add(template);
+ }
+ templateCombo.setText(selectedTemplate);
+ } else {
+ throwCoreException(Messages.SpecfileNewWizardPage_29);
+ }
+ }
+
+ private void populateGroupCombo(Combo groupsCombo) {
+ List<String> rpmGroups = Activator.getDefault().getRpmGroups();
+ for (String rpmGroup : rpmGroups) {
+ groupsCombo.add(rpmGroup);
+ }
+ }
+
+ private BufferedInputStream runRpmdevNewSpec(String template) {
+ BufferedInputStream in = null;
+ // Here we assuming that the rpmdevtools package is installed.
+ try {
+ in = org.eclipse.linuxtools.rpm.core.utils.Utils
+ .runCommandToInputStream(
+ "rpmdev-newspec", "-o", "-", "-t", template); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ } catch (IOException e) {
+ // FIXME: rpmdev-newspec is not in the system $PATH, what should we
+ // do here?.
+ SpecfileLog.logError(e);
+ }
+ return in;
+ }
+
+ private void throwCoreException(String message) throws CoreException {
+ IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID,
+ IStatus.OK, message, null);
+ throw new CoreException(status);
+ }
+
+ public Text getNameText() {
+ return nameText;
+ }
+
+ public Text getProjectText() {
+ return projectText;
+ }
+
+ public Text getVersionText() {
+ return versionText;
+ }
+
+ public Text getUrlText() {
+ return urlText;
+ }
+
+ public Text getLicenseText() {
+ return licenseText;
+ }
+
+ public Text getSourceText() {
+ return source0Text;
+ }
+
+ public Text getSummaryText() {
+ return summaryText;
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui.editor/templates/templates.xml b/rpm/org.eclipse.linuxtools.rpm.ui.editor/templates/templates.xml
index 84b329752b..2ae3dd973a 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui.editor/templates/templates.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.ui.editor/templates/templates.xml
@@ -4,7 +4,7 @@
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-
+
Contributors:
Red Hat - initial API and implementation
-->
@@ -84,9 +84,9 @@ rm -rf %{buildroot}
<template id="rmBuildRoot" name="rm" description="rm -rf ${buildroot} template" context="org.eclipse.linuxtools.rpm.ui.editor.installSection" enabled="true">rm -rf %{buildroot}</template>
<template id="makeInstall" name="make DESTDIR=" description="make DESTDIR" context="org.eclipse.linuxtools.rpm.ui.editor.installSection" enabled="true">make DESTDIR=%{buildroot} install || exit 1</template>
<template id="desktopFileInstall" name="desktop-file-install" description="desktop-file-install template" context="org.eclipse.linuxtools.rpm.ui.editor.installSection" enabled="true">desktop-file-install --vendor ${vendor} \
- --dir %{buildroot}%{_datadir}/applications \
- --add-category ${app_category} \
- %{buildroot}%{_datadir}/applications/${desktopfile_name}.desktop
+ --dir %{buildroot}%{_datadir}/applications \
+ --add-category ${app_category} \
+ %{buildroot}%{_datadir}/applications/${desktopfile_name}.desktop
</template>
<template id="updateDesktopDB" name="update-desktop-database" description="desktop-file-install template" context="org.eclipse.linuxtools.rpm.ui.editor.installSection" enabled="true">update-desktop-database -q %{_datadir}/applications</template>
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/plugin.xml b/rpm/org.eclipse.linuxtools.rpm.ui/plugin.xml
index e455705c7c..adf12a54a8 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/plugin.xml
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/plugin.xml
@@ -5,7 +5,7 @@
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-
+
Contributors:
Red Hat - initial API and implementation
-->
@@ -20,7 +20,7 @@
<wizard
name="%wizard.name.1"
icon="icons/rpm.gif"
- class="org.eclipse.linuxtools.internal.rpm.ui.SRPMImportWizard"
+ class="org.eclipse.linuxtools.internal.rpm.ui.SRPMImportWizard"
category="org.eclipse.linuxtools.rpm.ui"
id="org.eclipse.linuxtools.rpm.ui.SRPMImportWizard">
<description>
@@ -31,7 +31,7 @@
</selection>
</wizard>
</extension>
- <extension
+ <extension
point="org.eclipse.ui.propertyPages">
<page
class="org.eclipse.linuxtools.internal.rpm.ui.propertypage.SpecFileHeaderPage"
@@ -67,7 +67,7 @@
<extension
point="org.eclipse.ui.newWizards">
<wizard
- project="true"
+ project="true"
category="org.eclipse.linuxtools.rpm.ui.editor"
class="org.eclipse.linuxtools.internal.rpm.ui.RPMNewProject"
icon="icons/rpm.gif"
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/Activator.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/Activator.java
index c5c896f862..ad108adc8d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/Activator.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/Activator.java
@@ -20,50 +20,50 @@ import org.osgi.framework.BundleContext;
*/
public class Activator extends AbstractUIPlugin {
- /** The symbolic ID of the plugin */
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.rpm.ui"; //$NON-NLS-1$
+ /** The symbolic ID of the plugin */
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.rpm.ui"; //$NON-NLS-1$
- // The shared instance
- private static Activator plugin;
+ // The shared instance
+ private static Activator plugin;
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
- /**
- * Log an error.
- *
- * @param message A human-readable message.
- * @param exception The exception to log.
- */
- public static void logError(String message, Throwable exception) {
- IStatus status = new Status(IStatus.ERROR, PLUGIN_ID, message,
- exception);
- getDefault().getLog().log(status);
- }
+ /**
+ * Log an error.
+ *
+ * @param message A human-readable message.
+ * @param exception The exception to log.
+ */
+ public static void logError(String message, Throwable exception) {
+ IStatus status = new Status(IStatus.ERROR, PLUGIN_ID, message,
+ exception);
+ getDefault().getLog().log(status);
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/BuildType.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/BuildType.java
index 634d468e24..bc699ff0e3 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/BuildType.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/BuildType.java
@@ -16,20 +16,20 @@ package org.eclipse.linuxtools.internal.rpm.ui;
*/
public enum BuildType {
- /**
- * Default.
- */
- NONE,
- /**
- * Everything - rpmbuild -ba.
- */
- ALL,
- /**
- * Binary - rpmbuild -bb.
- */
- BINARY,
- /**
- * Source RPM - rpmbuild -bs.
- */
- SOURCE
+ /**
+ * Default.
+ */
+ NONE,
+ /**
+ * Everything - rpmbuild -ba.
+ */
+ ALL,
+ /**
+ * Binary - rpmbuild -bb.
+ */
+ BINARY,
+ /**
+ * Source RPM - rpmbuild -bs.
+ */
+ SOURCE
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/ErrorLineMatcher.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/ErrorLineMatcher.java
index 64c8de8366..b126826d84 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/ErrorLineMatcher.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/ErrorLineMatcher.java
@@ -20,40 +20,40 @@ import org.eclipse.ui.console.TextConsole;
/**
* Matcher adding hyperlink to navigate to line in the spec file whenever
* rpmbuild reports the line in error.
- *
+ *
*/
public class ErrorLineMatcher implements IPatternMatchListenerDelegate {
- private static final String LINE = "line"; //$NON-NLS-1$
- private RpmConsole console;
-
- @Override
- public void connect(TextConsole console) {
- this.console = (RpmConsole) console;
- }
-
- @Override
- public void disconnect() {
- this.console = null;
- }
-
- @Override
- public void matchFound(PatternMatchEvent event) {
- String line = null;
- try {
- line = console.getDocument().get(event.getOffset(),
- event.getLength());
- int lineNumber = Integer.parseInt(line.substring(12,
- line.indexOf(':', line.indexOf(LINE))).trim());
- FileLink fileLink = new FileLink(
- (IFile) console.getSpecfile().getAdapter(IFile.class),
- "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor", -1, -1, lineNumber); //$NON-NLS-1$
- console.addHyperlink(fileLink, 7,
- line.indexOf(':', line.indexOf(LINE)) - 7);
- } catch (BadLocationException e1) {
- return;
- }
-
- }
+ private static final String LINE = "line"; //$NON-NLS-1$
+ private RpmConsole console;
+
+ @Override
+ public void connect(TextConsole console) {
+ this.console = (RpmConsole) console;
+ }
+
+ @Override
+ public void disconnect() {
+ this.console = null;
+ }
+
+ @Override
+ public void matchFound(PatternMatchEvent event) {
+ String line = null;
+ try {
+ line = console.getDocument().get(event.getOffset(),
+ event.getLength());
+ int lineNumber = Integer.parseInt(line.substring(12,
+ line.indexOf(':', line.indexOf(LINE))).trim());
+ FileLink fileLink = new FileLink(
+ (IFile) console.getSpecfile().getAdapter(IFile.class),
+ "org.eclipse.linuxtools.rpm.ui.editor.SpecfileEditor", -1, -1, lineNumber); //$NON-NLS-1$
+ console.addHyperlink(fileLink, 7,
+ line.indexOf(':', line.indexOf(LINE)) - 7);
+ } catch (BadLocationException e1) {
+ return;
+ }
+
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/Messages.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/Messages.java
index be0ae7ff93..0f6fb8a49a 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/Messages.java
@@ -20,23 +20,23 @@ import java.util.ResourceBundle;
*/
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.rpm_strings"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.rpm_strings"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- /**
- * Returns the string for the given key.
- * @param key The key we are looking for.
- * @return The found value.
- */
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ /**
+ * Returns the string for the given key.
+ * @param key The key we are looking for.
+ * @return The found value.
+ */
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/NewProjectCreationPage.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/NewProjectCreationPage.java
index fbd687c3c2..89df10d18d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/NewProjectCreationPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/NewProjectCreationPage.java
@@ -36,165 +36,165 @@ import org.eclipse.ui.dialogs.WorkingSetConfigurationBlock;
*/
public class NewProjectCreationPage extends WizardNewProjectCreationPage {
- private ComboViewer typeCombo;
- private final WorkingSetGroup wsGroup;
-
- private static final IWorkingSet[] EMPTY_WORKING_SET_ARRAY = new IWorkingSet[0];
-
- /**
- * Instantiate the page.
- * @param pageName The name of the page.
- */
- public NewProjectCreationPage(String pageName) {
- super(pageName);
- wsGroup = new WorkingSetGroup();
- setWorkingSets(EMPTY_WORKING_SET_ARRAY);
- }
-
- /**
- * The wizard owning this page can call this method to initialise fields using the
- * current selection.
- *
- * @param selection the current object selection
- */
- public void init(IStructuredSelection selection) {
- setWorkingSets(getSelectedWorkingSet(selection));
- }
-
- @Override
- public void createControl(Composite parent) {
- super.createControl(parent);
- Composite control = (Composite) getControl();
- Composite projectTypeGroup = new Composite(control, SWT.NONE);
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- projectTypeGroup.setLayout(layout);
- projectTypeGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- Label typeLabel = new Label(projectTypeGroup, SWT.NONE);
- typeLabel.setText(Messages.getString("SRPMImportPage.4")); //$NON-NLS-1$
- GridData data = new GridData(GridData.FILL_HORIZONTAL);
- data.grabExcessHorizontalSpace = true;
- typeCombo = new ComboViewer(projectTypeGroup, SWT.READ_ONLY);
- typeCombo.getControl().setLayoutData(data);
- typeCombo.setContentProvider(ArrayContentProvider.getInstance());
- typeCombo.setInput(RPMProjectLayout.values());
- typeCombo.getCombo().select(0);
- // Working set controls
- Control workingSetControl = wsGroup.createControl(control);
- workingSetControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- }
-
- /**
- * Returns the selected layout if any or the default one - RPMBUILD.
- *
- * @return The selected project layout.
- */
- public RPMProjectLayout getSelectedLayout() {
- return RPMProjectLayout.valueOf(typeCombo.getCombo().getItem(
- typeCombo.getCombo().getSelectionIndex()));
-
- }
-
- /**
- * Returns the working sets to which the new project should be added.
- *
- * @return the selected working sets to which the new project should be added
- */
- public IWorkingSet[] getWorkingSets() {
- return wsGroup.getSelectedWorkingSets();
- }
-
- /**
- * Sets the working sets to which the new project should be added.
- *
- * @param workingSets the initial selected working sets
- */
- public void setWorkingSets(IWorkingSet[] workingSets) {
- if (workingSets == null) {
- wsGroup.setWorkingSets(EMPTY_WORKING_SET_ARRAY);
- }
- wsGroup.setWorkingSets(workingSets);
- }
-
- /**
- * Try our best to set the working sets field to something sensible based on the
- * current selection.
- */
- private IWorkingSet[] getSelectedWorkingSet(IStructuredSelection selection) {
- if (!(selection instanceof ITreeSelection)) {
- return EMPTY_WORKING_SET_ARRAY;
- }
-
- ITreeSelection treeSelection = (ITreeSelection) selection;
- if (treeSelection.isEmpty()) {
- return EMPTY_WORKING_SET_ARRAY;
- }
-
- List<?> elements= treeSelection.toList();
- if (elements.size() == 1) {
- Object element = elements.get(0);
- TreePath[] paths = treeSelection.getPathsFor(element);
- if (paths.length != 1 || paths[0].getSegmentCount() == 0) {
- return EMPTY_WORKING_SET_ARRAY;
- }
-
- Object candidate = paths[0].getSegment(0);
- if (!(candidate instanceof IWorkingSet)) {
- return EMPTY_WORKING_SET_ARRAY;
- }
-
- IWorkingSet workingSetCandidate = (IWorkingSet) candidate;
- if (!workingSetCandidate.isAggregateWorkingSet()) {
- return new IWorkingSet[] { workingSetCandidate };
- }
-
- return EMPTY_WORKING_SET_ARRAY;
- }
-
- ArrayList<IWorkingSet> result = new ArrayList<>();
- for (Object element : elements) {
- if (element instanceof IWorkingSet && !((IWorkingSet) element).isAggregateWorkingSet()) {
- result.add((IWorkingSet)element);
- }
- }
-
- if (!result.isEmpty()) {
- return result.toArray(new IWorkingSet[result.size()]);
- } else {
- return EMPTY_WORKING_SET_ARRAY;
- }
- }
-
- /**
- * Little class to encapsulate the working set group of controls.
- */
- private static final class WorkingSetGroup {
-
- private WorkingSetConfigurationBlock workingSetBlock;
-
- public WorkingSetGroup() {
- String[] workingSetIds = new String[] { "org.eclipse.ui.resourceWorkingSetPage" }; //$NON-NLS-1$
- workingSetBlock = new WorkingSetConfigurationBlock(workingSetIds,
- Activator.getDefault().getDialogSettings());
- }
-
- public Control createControl(Composite composite) {
- Group workingSetGroup = new Group(composite, SWT.NONE);
- workingSetGroup.setFont(composite.getFont());
- workingSetGroup.setText(Messages.getString("NewProjectCreationPage.0")); //$NON-NLS-1$
- workingSetGroup.setLayout(new GridLayout(1, false));
-
- workingSetBlock.createContent(workingSetGroup);
-
- return workingSetGroup;
- }
-
- public void setWorkingSets(IWorkingSet[] workingSets) {
- workingSetBlock.setWorkingSets(workingSets);
- }
-
- public IWorkingSet[] getSelectedWorkingSets() {
- return workingSetBlock.getSelectedWorkingSets();
- }
- }
+ private ComboViewer typeCombo;
+ private final WorkingSetGroup wsGroup;
+
+ private static final IWorkingSet[] EMPTY_WORKING_SET_ARRAY = new IWorkingSet[0];
+
+ /**
+ * Instantiate the page.
+ * @param pageName The name of the page.
+ */
+ public NewProjectCreationPage(String pageName) {
+ super(pageName);
+ wsGroup = new WorkingSetGroup();
+ setWorkingSets(EMPTY_WORKING_SET_ARRAY);
+ }
+
+ /**
+ * The wizard owning this page can call this method to initialise fields using the
+ * current selection.
+ *
+ * @param selection the current object selection
+ */
+ public void init(IStructuredSelection selection) {
+ setWorkingSets(getSelectedWorkingSet(selection));
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ super.createControl(parent);
+ Composite control = (Composite) getControl();
+ Composite projectTypeGroup = new Composite(control, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ projectTypeGroup.setLayout(layout);
+ projectTypeGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ Label typeLabel = new Label(projectTypeGroup, SWT.NONE);
+ typeLabel.setText(Messages.getString("SRPMImportPage.4")); //$NON-NLS-1$
+ GridData data = new GridData(GridData.FILL_HORIZONTAL);
+ data.grabExcessHorizontalSpace = true;
+ typeCombo = new ComboViewer(projectTypeGroup, SWT.READ_ONLY);
+ typeCombo.getControl().setLayoutData(data);
+ typeCombo.setContentProvider(ArrayContentProvider.getInstance());
+ typeCombo.setInput(RPMProjectLayout.values());
+ typeCombo.getCombo().select(0);
+ // Working set controls
+ Control workingSetControl = wsGroup.createControl(control);
+ workingSetControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ }
+
+ /**
+ * Returns the selected layout if any or the default one - RPMBUILD.
+ *
+ * @return The selected project layout.
+ */
+ public RPMProjectLayout getSelectedLayout() {
+ return RPMProjectLayout.valueOf(typeCombo.getCombo().getItem(
+ typeCombo.getCombo().getSelectionIndex()));
+
+ }
+
+ /**
+ * Returns the working sets to which the new project should be added.
+ *
+ * @return the selected working sets to which the new project should be added
+ */
+ public IWorkingSet[] getWorkingSets() {
+ return wsGroup.getSelectedWorkingSets();
+ }
+
+ /**
+ * Sets the working sets to which the new project should be added.
+ *
+ * @param workingSets the initial selected working sets
+ */
+ public void setWorkingSets(IWorkingSet[] workingSets) {
+ if (workingSets == null) {
+ wsGroup.setWorkingSets(EMPTY_WORKING_SET_ARRAY);
+ }
+ wsGroup.setWorkingSets(workingSets);
+ }
+
+ /**
+ * Try our best to set the working sets field to something sensible based on the
+ * current selection.
+ */
+ private IWorkingSet[] getSelectedWorkingSet(IStructuredSelection selection) {
+ if (!(selection instanceof ITreeSelection)) {
+ return EMPTY_WORKING_SET_ARRAY;
+ }
+
+ ITreeSelection treeSelection = (ITreeSelection) selection;
+ if (treeSelection.isEmpty()) {
+ return EMPTY_WORKING_SET_ARRAY;
+ }
+
+ List<?> elements= treeSelection.toList();
+ if (elements.size() == 1) {
+ Object element = elements.get(0);
+ TreePath[] paths = treeSelection.getPathsFor(element);
+ if (paths.length != 1 || paths[0].getSegmentCount() == 0) {
+ return EMPTY_WORKING_SET_ARRAY;
+ }
+
+ Object candidate = paths[0].getSegment(0);
+ if (!(candidate instanceof IWorkingSet)) {
+ return EMPTY_WORKING_SET_ARRAY;
+ }
+
+ IWorkingSet workingSetCandidate = (IWorkingSet) candidate;
+ if (!workingSetCandidate.isAggregateWorkingSet()) {
+ return new IWorkingSet[] { workingSetCandidate };
+ }
+
+ return EMPTY_WORKING_SET_ARRAY;
+ }
+
+ ArrayList<IWorkingSet> result = new ArrayList<>();
+ for (Object element : elements) {
+ if (element instanceof IWorkingSet && !((IWorkingSet) element).isAggregateWorkingSet()) {
+ result.add((IWorkingSet)element);
+ }
+ }
+
+ if (!result.isEmpty()) {
+ return result.toArray(new IWorkingSet[result.size()]);
+ } else {
+ return EMPTY_WORKING_SET_ARRAY;
+ }
+ }
+
+ /**
+ * Little class to encapsulate the working set group of controls.
+ */
+ private static final class WorkingSetGroup {
+
+ private WorkingSetConfigurationBlock workingSetBlock;
+
+ public WorkingSetGroup() {
+ String[] workingSetIds = new String[] { "org.eclipse.ui.resourceWorkingSetPage" }; //$NON-NLS-1$
+ workingSetBlock = new WorkingSetConfigurationBlock(workingSetIds,
+ Activator.getDefault().getDialogSettings());
+ }
+
+ public Control createControl(Composite composite) {
+ Group workingSetGroup = new Group(composite, SWT.NONE);
+ workingSetGroup.setFont(composite.getFont());
+ workingSetGroup.setText(Messages.getString("NewProjectCreationPage.0")); //$NON-NLS-1$
+ workingSetGroup.setLayout(new GridLayout(1, false));
+
+ workingSetBlock.createContent(workingSetGroup);
+
+ return workingSetGroup;
+ }
+
+ public void setWorkingSets(IWorkingSet[] workingSets) {
+ workingSetBlock.setWorkingSets(workingSets);
+ }
+
+ public IWorkingSet[] getSelectedWorkingSets() {
+ return workingSetBlock.getSelectedWorkingSets();
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RPMDetailsPanel.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RPMDetailsPanel.java
index 54dd26c883..7738f770de 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RPMDetailsPanel.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RPMDetailsPanel.java
@@ -32,115 +32,115 @@ import org.eclipse.swt.widgets.Text;
/**
* Custom panel to be reused by different RPM project creation and import
* wizards. Contains the path and project type.
- *
+ *
*/
public class RPMDetailsPanel {
- private Text locationPath;
- private ComboViewer typeCombo;
- private Button defaultSettings;
- private Composite parent;
-
- /**
- * Initializes the panel with all the needed components and listeners.
- *
- * @param parent
- * The composite that will handle the childrens
- */
- public RPMDetailsPanel(Composite parent) {
- this.parent = parent;
- initialize();
- }
-
- private void initialize() {
- defaultSettings = new Button(parent, SWT.CHECK);
- defaultSettings.setText(Messages.getString("SRPMImportPage.0")); //$NON-NLS-1$
- defaultSettings.setSelection(true);
-
- final Group specGrid = new Group(parent, SWT.NONE);
- defaultSettings.addSelectionListener(new SelectionAdapter() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (defaultSettings.getSelection()) {
- for (Control control : specGrid.getChildren()) {
- specGrid.setEnabled(false);
- control.setEnabled(false);
- }
- } else {
- for (Control control : specGrid.getChildren()) {
- specGrid.setEnabled(true);
- control.setEnabled(true);
- }
- }
- }
-
- });
- GridLayout layout = new GridLayout();
- layout.numColumns = 3;
- specGrid.setLayout(layout);
- specGrid.setText(Messages.getString("SRPMImportPage.1")); //$NON-NLS-1$
- specGrid.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
- | GridData.HORIZONTAL_ALIGN_FILL));
- specGrid.setEnabled(false);
- Label locationLabel = new Label(specGrid, SWT.NULL);
- locationLabel.setText(Messages.getString("SRPMImportPage.2")); //$NON-NLS-1$
- locationLabel.setEnabled(false);
- locationPath = new Text(specGrid, SWT.SINGLE | SWT.BORDER);
- locationPath.setEnabled(false);
- locationPath.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL
- | GridData.GRAB_HORIZONTAL));
- Button containerBrowseButton = new Button(specGrid, SWT.PUSH);
- containerBrowseButton.setText(Messages.getString("SRPMImportPage.3")); //$NON-NLS-1$
- containerBrowseButton.setLayoutData(new GridData(
- GridData.HORIZONTAL_ALIGN_FILL));
- containerBrowseButton.setEnabled(false);
-
- final Composite projectTypeGroup = new Composite(parent, SWT.NONE);
- layout = new GridLayout();
- layout.numColumns = 2;
- projectTypeGroup.setLayout(layout);
- projectTypeGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- Label typeLabel = new Label(projectTypeGroup, SWT.NULL);
- typeLabel.setText(Messages.getString("SRPMImportPage.4")); //$NON-NLS-1$
- GridData gridData = new GridData();
- gridData.horizontalAlignment = GridData.FILL;
- gridData.grabExcessHorizontalSpace = true;
- typeCombo = new ComboViewer(projectTypeGroup, SWT.READ_ONLY);
- typeCombo.getCombo().setLayoutData(gridData);
- typeCombo.setContentProvider(ArrayContentProvider.getInstance());
- typeCombo.setInput(RPMProjectLayout.values());
- typeCombo.setSelection(new StructuredSelection(RPMProjectLayout.RPMBUILD));
-
- }
-
- /**
- * Returns the selected layout if any or the default one - RPMBUILD.
- *
- * @return The selected project layout.
- */
- public RPMProjectLayout getSelectedLayout() {
- return RPMProjectLayout.valueOf(typeCombo.getCombo().getItem(
- typeCombo.getCombo().getSelectionIndex()));
- }
-
- /**
- * Sets the location path to given absolute path.
- *
- * @param absolutePath The path to be shown.
- */
- public void setLocationPath(String absolutePath) {
- locationPath.setText(absolutePath);
-
- }
-
- /**
- * Returns the default path or whatever is entered.
- *
- * @return The location path to use for the project.
- */
- public IPath getLocationPath() {
- return Path.fromOSString(locationPath.getText());
- }
+ private Text locationPath;
+ private ComboViewer typeCombo;
+ private Button defaultSettings;
+ private Composite parent;
+
+ /**
+ * Initializes the panel with all the needed components and listeners.
+ *
+ * @param parent
+ * The composite that will handle the childrens
+ */
+ public RPMDetailsPanel(Composite parent) {
+ this.parent = parent;
+ initialize();
+ }
+
+ private void initialize() {
+ defaultSettings = new Button(parent, SWT.CHECK);
+ defaultSettings.setText(Messages.getString("SRPMImportPage.0")); //$NON-NLS-1$
+ defaultSettings.setSelection(true);
+
+ final Group specGrid = new Group(parent, SWT.NONE);
+ defaultSettings.addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ if (defaultSettings.getSelection()) {
+ for (Control control : specGrid.getChildren()) {
+ specGrid.setEnabled(false);
+ control.setEnabled(false);
+ }
+ } else {
+ for (Control control : specGrid.getChildren()) {
+ specGrid.setEnabled(true);
+ control.setEnabled(true);
+ }
+ }
+ }
+
+ });
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 3;
+ specGrid.setLayout(layout);
+ specGrid.setText(Messages.getString("SRPMImportPage.1")); //$NON-NLS-1$
+ specGrid.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
+ | GridData.HORIZONTAL_ALIGN_FILL));
+ specGrid.setEnabled(false);
+ Label locationLabel = new Label(specGrid, SWT.NULL);
+ locationLabel.setText(Messages.getString("SRPMImportPage.2")); //$NON-NLS-1$
+ locationLabel.setEnabled(false);
+ locationPath = new Text(specGrid, SWT.SINGLE | SWT.BORDER);
+ locationPath.setEnabled(false);
+ locationPath.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL
+ | GridData.GRAB_HORIZONTAL));
+ Button containerBrowseButton = new Button(specGrid, SWT.PUSH);
+ containerBrowseButton.setText(Messages.getString("SRPMImportPage.3")); //$NON-NLS-1$
+ containerBrowseButton.setLayoutData(new GridData(
+ GridData.HORIZONTAL_ALIGN_FILL));
+ containerBrowseButton.setEnabled(false);
+
+ final Composite projectTypeGroup = new Composite(parent, SWT.NONE);
+ layout = new GridLayout();
+ layout.numColumns = 2;
+ projectTypeGroup.setLayout(layout);
+ projectTypeGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ Label typeLabel = new Label(projectTypeGroup, SWT.NULL);
+ typeLabel.setText(Messages.getString("SRPMImportPage.4")); //$NON-NLS-1$
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ typeCombo = new ComboViewer(projectTypeGroup, SWT.READ_ONLY);
+ typeCombo.getCombo().setLayoutData(gridData);
+ typeCombo.setContentProvider(ArrayContentProvider.getInstance());
+ typeCombo.setInput(RPMProjectLayout.values());
+ typeCombo.setSelection(new StructuredSelection(RPMProjectLayout.RPMBUILD));
+
+ }
+
+ /**
+ * Returns the selected layout if any or the default one - RPMBUILD.
+ *
+ * @return The selected project layout.
+ */
+ public RPMProjectLayout getSelectedLayout() {
+ return RPMProjectLayout.valueOf(typeCombo.getCombo().getItem(
+ typeCombo.getCombo().getSelectionIndex()));
+ }
+
+ /**
+ * Sets the location path to given absolute path.
+ *
+ * @param absolutePath The path to be shown.
+ */
+ public void setLocationPath(String absolutePath) {
+ locationPath.setText(absolutePath);
+
+ }
+
+ /**
+ * Returns the default path or whatever is entered.
+ *
+ * @return The location path to use for the project.
+ */
+ public IPath getLocationPath() {
+ return Path.fromOSString(locationPath.getText());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RPMNewProject.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RPMNewProject.java
index 3bd279e756..91cfa25f82 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RPMNewProject.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RPMNewProject.java
@@ -31,47 +31,47 @@ import org.eclipse.ui.actions.WorkspaceModifyOperation;
*
*/
public class RPMNewProject extends Wizard implements INewWizard {
- private NewProjectCreationPage namePage;
+ private NewProjectCreationPage namePage;
- @Override
- public boolean performFinish() {
- try {
- WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
- @Override
- protected void execute(IProgressMonitor monitor) throws CoreException {
- createProject(monitor != null ? monitor
- : new NullProgressMonitor());
- }
- };
- getContainer().run(false, true, op);
- } catch (InvocationTargetException x) {
- return false;
- } catch (InterruptedException x) {
- return false;
- }
- return true;
- }
+ @Override
+ public boolean performFinish() {
+ try {
+ WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
+ @Override
+ protected void execute(IProgressMonitor monitor) throws CoreException {
+ createProject(monitor != null ? monitor
+ : new NullProgressMonitor());
+ }
+ };
+ getContainer().run(false, true, op);
+ } catch (InvocationTargetException x) {
+ return false;
+ } catch (InterruptedException x) {
+ return false;
+ }
+ return true;
+ }
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- super.addPages();
- namePage = new NewProjectCreationPage(Messages.getString("RPMNewProject.0")); //$NON-NLS-1$
- namePage.setTitle(Messages.getString("RPMNewProject.1")); //$NON-NLS-1$
- namePage
- .setDescription(Messages.getString("RPMNewProject.2")); //$NON-NLS-1$
- namePage.setImageDescriptor(ImageDescriptor.createFromFile(getClass(),
- "/icons/rpm.gif")); //$NON-NLS-1$
- addPage(namePage);
- namePage.init(selection);
- }
+ @Override
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ super.addPages();
+ namePage = new NewProjectCreationPage(Messages.getString("RPMNewProject.0")); //$NON-NLS-1$
+ namePage.setTitle(Messages.getString("RPMNewProject.1")); //$NON-NLS-1$
+ namePage
+ .setDescription(Messages.getString("RPMNewProject.2")); //$NON-NLS-1$
+ namePage.setImageDescriptor(ImageDescriptor.createFromFile(getClass(),
+ "/icons/rpm.gif")); //$NON-NLS-1$
+ addPage(namePage);
+ namePage.init(selection);
+ }
- protected void createProject(IProgressMonitor monitor) throws CoreException {
- RPMProjectCreator rpmProjectCreator = new RPMProjectCreator(namePage.getSelectedLayout());
- IProject project = rpmProjectCreator.create(namePage.getProjectName(), namePage.getLocationPath(), monitor);
- // Add new project to working sets, if requested
- IWorkingSet[] workingSets = namePage.getWorkingSets();
- if (workingSets.length > 0) {
- PlatformUI.getWorkbench().getWorkingSetManager().addToWorkingSets(project, workingSets);
- }
- }
+ protected void createProject(IProgressMonitor monitor) throws CoreException {
+ RPMProjectCreator rpmProjectCreator = new RPMProjectCreator(namePage.getSelectedLayout());
+ IProject project = rpmProjectCreator.create(namePage.getProjectName(), namePage.getLocationPath(), monitor);
+ // Add new project to working sets, if requested
+ IWorkingSet[] workingSets = namePage.getWorkingSets();
+ if (workingSets.length > 0) {
+ PlatformUI.getWorkbench().getWorkingSetManager().addToWorkingSets(project, workingSets);
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RpmConsole.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RpmConsole.java
index ed244edc2b..a832f2f42d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RpmConsole.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/RpmConsole.java
@@ -19,58 +19,58 @@ import org.eclipse.ui.console.IOConsole;
import org.eclipse.ui.console.MessageConsole;
/**
* RpmConsole is used to output rpm/rpmbuild output.
- *
+ *
*/
public class RpmConsole extends IOConsole {
- /** Id of this console. */
- public static final String ID = "rpmbuild"; //$NON-NLS-1$
- private RPMProject rpmProject;
+ /** Id of this console. */
+ public static final String ID = "rpmbuild"; //$NON-NLS-1$
+ private RPMProject rpmProject;
- /**
- * Creates the console.
- *
- * @param rpmProject
- * The RPM project to use.
- */
- public RpmConsole(RPMProject rpmProject) {
- super(ID+'('+rpmProject.getSpecFile().getProject().getName()+')', ID, null, true);
- this.rpmProject = rpmProject;
- }
+ /**
+ * Creates the console.
+ *
+ * @param rpmProject
+ * The RPM project to use.
+ */
+ public RpmConsole(RPMProject rpmProject) {
+ super(ID+'('+rpmProject.getSpecFile().getProject().getName()+')', ID, null, true);
+ this.rpmProject = rpmProject;
+ }
- /**
- * Returns the spec file for this rpm project.
- *
- * @return The spec file.
- */
- public IResource getSpecfile() {
- return rpmProject.getSpecFile();
- }
+ /**
+ * Returns the spec file for this rpm project.
+ *
+ * @return The spec file.
+ */
+ public IResource getSpecfile() {
+ return rpmProject.getSpecFile();
+ }
- /**
- * Get the console.
- *
- * @param packageName The name of the package(RPM) this console will be for.
- * @return A console instance.
- */
- public static IOConsole findConsole(String packageName) {
- ConsolePlugin plugin = ConsolePlugin.getDefault();
- IConsoleManager conMan = plugin.getConsoleManager();
- String projectConsoleName = ID+'('+packageName+')';
- IOConsole ret = null;
- for (IConsole cons : ConsolePlugin.getDefault().getConsoleManager()
- .getConsoles()) {
- if (cons.getName().equals(projectConsoleName)) {
- ret = (MessageConsole) cons;
- }
- }
- // no existing console, create new one
- if (ret == null) {
- ret = new MessageConsole(ID+'('+packageName+')', null, null, true);
- }
- conMan.addConsoles(new IConsole[] { ret });
- ret.clearConsole();
- ret.activate();
- return ret;
- }
+ /**
+ * Get the console.
+ *
+ * @param packageName The name of the package(RPM) this console will be for.
+ * @return A console instance.
+ */
+ public static IOConsole findConsole(String packageName) {
+ ConsolePlugin plugin = ConsolePlugin.getDefault();
+ IConsoleManager conMan = plugin.getConsoleManager();
+ String projectConsoleName = ID+'('+packageName+')';
+ IOConsole ret = null;
+ for (IConsole cons : ConsolePlugin.getDefault().getConsoleManager()
+ .getConsoles()) {
+ if (cons.getName().equals(projectConsoleName)) {
+ ret = (MessageConsole) cons;
+ }
+ }
+ // no existing console, create new one
+ if (ret == null) {
+ ret = new MessageConsole(ID+'('+packageName+')', null, null, true);
+ }
+ conMan.addConsoles(new IConsole[] { ret });
+ ret.clearConsole();
+ ret.activate();
+ return ret;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/SRPMImportPage.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/SRPMImportPage.java
index b8f4e2e888..8e0e89b794 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/SRPMImportPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/SRPMImportPage.java
@@ -46,223 +46,223 @@ import org.eclipse.swt.widgets.Text;
* validation (need to add to this) SRPMImportPage. Called by SRPMImportwizard.
* Class can not be subclassed extends WizardPage and implements Listener (for
* events)
- *
+ *
*/
public class SRPMImportPage extends WizardPage {
- // GUI Control variables
- private Text sourceSRPM;
- private RPMDetailsPanel detailsPanel;
+ // GUI Control variables
+ private Text sourceSRPM;
+ private RPMDetailsPanel detailsPanel;
- /**
- * Constructor for SRPMImportPage class
- */
- public SRPMImportPage() {
- super(
- Messages.getString("SRPMImportPage.Import_SRPM"), //$NON-NLS-1$
- Messages.getString("SRPMImportPage.Select_project_to_import"), null); //$NON-NLS-1$
+ /**
+ * Constructor for SRPMImportPage class
+ */
+ public SRPMImportPage() {
+ super(
+ Messages.getString("SRPMImportPage.Import_SRPM"), //$NON-NLS-1$
+ Messages.getString("SRPMImportPage.Select_project_to_import"), null); //$NON-NLS-1$
- setPageComplete(false);
- setDescription(Messages
- .getString("SRPMImportPage.Select_project_to_import")); //$NON-NLS-1$
- }
+ setPageComplete(false);
+ setDescription(Messages
+ .getString("SRPMImportPage.Select_project_to_import")); //$NON-NLS-1$
+ }
- @Override
- public void createControl(Composite parent) {
- // Set Page complete to false. Don't allow the user to execute wizard
- // until we have all the required data
- setPageComplete(false);
+ @Override
+ public void createControl(Composite parent) {
+ // Set Page complete to false. Don't allow the user to execute wizard
+ // until we have all the required data
+ setPageComplete(false);
- // Create a generic composite to hold ui variable
- Composite composite = new Composite(parent, SWT.NULL);
+ // Create a generic composite to hold ui variable
+ Composite composite = new Composite(parent, SWT.NULL);
- // Create a layout for the wizard page
- composite.setLayout(new GridLayout());
- composite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
- setControl(composite);
+ // Create a layout for the wizard page
+ composite.setLayout(new GridLayout());
+ composite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
+ setControl(composite);
- // Create contols on the page
- createSourceRPMCombo(composite);
- detailsPanel = new RPMDetailsPanel(composite);
- }
+ // Create contols on the page
+ createSourceRPMCombo(composite);
+ detailsPanel = new RPMDetailsPanel(composite);
+ }
- private void createSourceRPMCombo(Composite parent) {
- Group specGrid = new Group(parent, SWT.NONE);
- specGrid.setLayout(new GridLayout());
- specGrid.setText(Messages.getString("SRPMImportPage.SRPM_Name")); //$NON-NLS-1$
- specGrid.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
- | GridData.HORIZONTAL_ALIGN_FILL));
+ private void createSourceRPMCombo(Composite parent) {
+ Group specGrid = new Group(parent, SWT.NONE);
+ specGrid.setLayout(new GridLayout());
+ specGrid.setText(Messages.getString("SRPMImportPage.SRPM_Name")); //$NON-NLS-1$
+ specGrid.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
+ | GridData.HORIZONTAL_ALIGN_FILL));
- Composite sourceSpecComposite = new Composite(specGrid, SWT.NONE);
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- sourceSpecComposite.setLayout(layout);
- sourceSpecComposite.setLayoutData(new GridData(
- GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
+ Composite sourceSpecComposite = new Composite(specGrid, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ sourceSpecComposite.setLayout(layout);
+ sourceSpecComposite.setLayoutData(new GridData(
+ GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
- sourceSRPM = new Text(sourceSpecComposite, SWT.BORDER);
- sourceSRPM.setToolTipText(Messages
- .getString("SRPMImportPage.toolTip_SRPM_Name")); //$NON-NLS-1$
+ sourceSRPM = new Text(sourceSpecComposite, SWT.BORDER);
+ sourceSRPM.setToolTipText(Messages
+ .getString("SRPMImportPage.toolTip_SRPM_Name")); //$NON-NLS-1$
- GridData gridData = new GridData();
- gridData.horizontalAlignment = GridData.FILL;
- gridData.grabExcessHorizontalSpace = true;
- sourceSRPM.setLayoutData(gridData);
- sourceSRPM.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- boolean validSRPM = canFinish();
- if (validSRPM) {
- setPageComplete(validSRPM);
- changeProjectSettings();
- }
- }
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = GridData.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ sourceSRPM.setLayoutData(gridData);
+ sourceSRPM.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ boolean validSRPM = canFinish();
+ if (validSRPM) {
+ setPageComplete(validSRPM);
+ changeProjectSettings();
+ }
+ }
- });
+ });
- Button srpmBrowse = new Button(sourceSpecComposite, SWT.PUSH);
- srpmBrowse.setToolTipText(Messages
- .getString("SRPMImportPage.toolTip_Open_file_navigator")); //$NON-NLS-1$
- srpmBrowse.setText(Messages.getString("RPMPage.Browse")); //$NON-NLS-1$
- srpmBrowse.addListener(SWT.Selection, new Listener() {
- @Override
- public void handleEvent(Event event) {
- FileDialog srpmBrowseDialog = new FileDialog(getContainer()
- .getShell(), SWT.OPEN);
- String selectedSRPMName = srpmBrowseDialog.open();
- if (selectedSRPMName != null) {
- File testSRPMfilename = new File(selectedSRPMName);
- if (testSRPMfilename.isFile()) {
- sourceSRPM.setText(selectedSRPMName);
- }
- }
- }
- });
- }
+ Button srpmBrowse = new Button(sourceSpecComposite, SWT.PUSH);
+ srpmBrowse.setToolTipText(Messages
+ .getString("SRPMImportPage.toolTip_Open_file_navigator")); //$NON-NLS-1$
+ srpmBrowse.setText(Messages.getString("RPMPage.Browse")); //$NON-NLS-1$
+ srpmBrowse.addListener(SWT.Selection, new Listener() {
+ @Override
+ public void handleEvent(Event event) {
+ FileDialog srpmBrowseDialog = new FileDialog(getContainer()
+ .getShell(), SWT.OPEN);
+ String selectedSRPMName = srpmBrowseDialog.open();
+ if (selectedSRPMName != null) {
+ File testSRPMfilename = new File(selectedSRPMName);
+ if (testSRPMfilename.isFile()) {
+ sourceSRPM.setText(selectedSRPMName);
+ }
+ }
+ }
+ });
+ }
- private void changeProjectSettings() {
- String srpmName = sourceSRPM.getText();
+ private void changeProjectSettings() {
+ String srpmName = sourceSRPM.getText();
- detailsPanel.setLocationPath(ResourcesPlugin.getWorkspace().getRoot()
- .getLocation().append(getProjectName(srpmName)).toFile()
- .getAbsolutePath());
- }
+ detailsPanel.setLocationPath(ResourcesPlugin.getWorkspace().getRoot()
+ .getLocation().append(getProjectName(srpmName)).toFile()
+ .getAbsolutePath());
+ }
- private String getProjectName(String srpmName) {
- String projectName = srpmName.substring(srpmName.lastIndexOf('/') + 1);
- return projectName.replaceAll("-[\\d|\\.]+-[\\d|\\.].+", ""); //$NON-NLS-1$ //$NON-NLS-2$
- }
+ private String getProjectName(String srpmName) {
+ String projectName = srpmName.substring(srpmName.lastIndexOf('/') + 1);
+ return projectName.replaceAll("-[\\d|\\.]+-[\\d|\\.].+", ""); //$NON-NLS-1$ //$NON-NLS-2$
+ }
- /**
- * canFinish()
- *
- * Hot validation. Called to determine whether Finish button can be set to
- * true
- *
- * @return boolean. true if finish can be activated
- */
- public boolean canFinish() {
- // Make sure an srpm name has been provided
- String sourceSRPMName = sourceSRPM.getText();
- if (!sourceSRPMName.isEmpty()
- && sourceSRPM.getText().lastIndexOf(".src.rpm") == -1) {//$NON-NLS-1$
- setErrorMessage(Messages.getString("SRPMImportPage.No_src_rpm_ext")); //$NON-NLS-1$
- return false;
- }
- if (sourceSRPMName.startsWith("http://")) { //$NON-NLS-1$
- try {
- URL url = new URL(sourceSRPMName);
- if (HttpURLConnection.HTTP_NOT_FOUND == ((HttpURLConnection) url
- .openConnection()).getResponseCode()) {
- setErrorMessage(Messages
- .getString("SRPMImportPage.Source_not_Valid")); //$NON-NLS-1$
- return false;
- }
- } catch (MalformedURLException e) {
- setErrorMessage(Messages
- .getString("SRPMImportPage.Source_not_Valid")); //$NON-NLS-1$
- return false;
- } catch (IOException e) {
- setErrorMessage(Messages
- .getString("SRPMImportPage.Source_not_Valid")); //$NON-NLS-1$
- return false;
- }
- } else {
- if (sourceSRPMName.equals("")) { //$NON-NLS-1$
- return false;
- }
- File srpm = new File(sourceSRPMName);
- if (!srpm.isFile()) {
- setErrorMessage(Messages
- .getString("SRPMImportPage.Source_not_Valid")); //$NON-NLS-1$
- return false;
- }
- }
- setErrorMessage(null);
- return true;
- }
+ /**
+ * canFinish()
+ *
+ * Hot validation. Called to determine whether Finish button can be set to
+ * true
+ *
+ * @return boolean. true if finish can be activated
+ */
+ public boolean canFinish() {
+ // Make sure an srpm name has been provided
+ String sourceSRPMName = sourceSRPM.getText();
+ if (!sourceSRPMName.isEmpty()
+ && sourceSRPM.getText().lastIndexOf(".src.rpm") == -1) {//$NON-NLS-1$
+ setErrorMessage(Messages.getString("SRPMImportPage.No_src_rpm_ext")); //$NON-NLS-1$
+ return false;
+ }
+ if (sourceSRPMName.startsWith("http://")) { //$NON-NLS-1$
+ try {
+ URL url = new URL(sourceSRPMName);
+ if (HttpURLConnection.HTTP_NOT_FOUND == ((HttpURLConnection) url
+ .openConnection()).getResponseCode()) {
+ setErrorMessage(Messages
+ .getString("SRPMImportPage.Source_not_Valid")); //$NON-NLS-1$
+ return false;
+ }
+ } catch (MalformedURLException e) {
+ setErrorMessage(Messages
+ .getString("SRPMImportPage.Source_not_Valid")); //$NON-NLS-1$
+ return false;
+ } catch (IOException e) {
+ setErrorMessage(Messages
+ .getString("SRPMImportPage.Source_not_Valid")); //$NON-NLS-1$
+ return false;
+ }
+ } else {
+ if (sourceSRPMName.equals("")) { //$NON-NLS-1$
+ return false;
+ }
+ File srpm = new File(sourceSRPMName);
+ if (!srpm.isFile()) {
+ setErrorMessage(Messages
+ .getString("SRPMImportPage.Source_not_Valid")); //$NON-NLS-1$
+ return false;
+ }
+ }
+ setErrorMessage(null);
+ return true;
+ }
- /**
- * finish()
- *
- * Perform finish after finish button is pressed
- *
- * @return boolean
- */
- public boolean finish() {
- SRPMImportOperation srpmImportOp = null;
- try {
- IProject detailedProject = getNewProject();
- String srpmName = sourceSRPM.getText();
- if (srpmName.startsWith("http://")) { //$NON-NLS-1$
- URL sourceRPMURL = new URL(srpmName);
- srpmImportOp = new SRPMImportOperation(detailedProject,
- sourceRPMURL, detailsPanel.getSelectedLayout());
- } else {
- File sourceRPMFile = new File(srpmName);
- srpmImportOp = new SRPMImportOperation(detailedProject,
- sourceRPMFile, detailsPanel.getSelectedLayout());
- }
- getContainer().run(true, true, srpmImportOp);
- } catch (InterruptedException e) {
- setErrorMessage(e.toString());
- return false;
- } catch (InvocationTargetException e) {
- setErrorMessage(e.toString());
- return false;
- } catch (MalformedURLException e) {
- setErrorMessage(e.toString());
- return false;
- } catch (CoreException e) {
- setErrorMessage(e.toString());
- return false;
- }
+ /**
+ * finish()
+ *
+ * Perform finish after finish button is pressed
+ *
+ * @return boolean
+ */
+ public boolean finish() {
+ SRPMImportOperation srpmImportOp = null;
+ try {
+ IProject detailedProject = getNewProject();
+ String srpmName = sourceSRPM.getText();
+ if (srpmName.startsWith("http://")) { //$NON-NLS-1$
+ URL sourceRPMURL = new URL(srpmName);
+ srpmImportOp = new SRPMImportOperation(detailedProject,
+ sourceRPMURL, detailsPanel.getSelectedLayout());
+ } else {
+ File sourceRPMFile = new File(srpmName);
+ srpmImportOp = new SRPMImportOperation(detailedProject,
+ sourceRPMFile, detailsPanel.getSelectedLayout());
+ }
+ getContainer().run(true, true, srpmImportOp);
+ } catch (InterruptedException e) {
+ setErrorMessage(e.toString());
+ return false;
+ } catch (InvocationTargetException e) {
+ setErrorMessage(e.toString());
+ return false;
+ } catch (MalformedURLException e) {
+ setErrorMessage(e.toString());
+ return false;
+ } catch (CoreException e) {
+ setErrorMessage(e.toString());
+ return false;
+ }
- // Get the status of the operation
- IStatus srpmImportStatus = srpmImportOp.getStatus();
+ // Get the status of the operation
+ IStatus srpmImportStatus = srpmImportOp.getStatus();
- // If the status does not come back clean, open error dialog
- if (!srpmImportStatus.isOK()) {
- ErrorDialog.openError(getContainer().getShell(),
- Messages.getString("SRPMImportPage.Errors_importing_SRPM"), //$NON-NLS-1$
- null, // no special message
- srpmImportStatus);
+ // If the status does not come back clean, open error dialog
+ if (!srpmImportStatus.isOK()) {
+ ErrorDialog.openError(getContainer().getShell(),
+ Messages.getString("SRPMImportPage.Errors_importing_SRPM"), //$NON-NLS-1$
+ null, // no special message
+ srpmImportStatus);
- return false;
- }
+ return false;
+ }
- return true;
- }
+ return true;
+ }
- /**
- * Creates a new project.
- * @throws CoreException If project creation failed.
- */
- private IProject getNewProject() throws CoreException {
- IPath path = detailsPanel.getLocationPath();
- RPMProjectCreator projectCreator = new RPMProjectCreator(
- detailsPanel.getSelectedLayout());
- return projectCreator.create(getProjectName(path.lastSegment()),
- path.removeLastSegments(1), new NullProgressMonitor());
- }
+ /**
+ * Creates a new project.
+ * @throws CoreException If project creation failed.
+ */
+ private IProject getNewProject() throws CoreException {
+ IPath path = detailsPanel.getLocationPath();
+ RPMProjectCreator projectCreator = new RPMProjectCreator(
+ detailsPanel.getSelectedLayout());
+ return projectCreator.create(getProjectName(path.lastSegment()),
+ path.removeLastSegments(1), new NullProgressMonitor());
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/SRPMImportWizard.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/SRPMImportWizard.java
index d675760bf5..7a7a1e251b 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/SRPMImportWizard.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/SRPMImportWizard.java
@@ -23,47 +23,47 @@ import org.eclipse.ui.IWorkbench;
* for the import rpm plug-in.
*/
public class SRPMImportWizard extends Wizard implements IImportWizard {
- private SRPMImportPage mainPage;
+ private SRPMImportPage mainPage;
- /**
- * @see org.eclipse.ui.IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
- */
- @Override
- public void init(IWorkbench workbench, IStructuredSelection currentSelection) {
- setWindowTitle(Messages.getString("SRPMImportwizard.Import_an_SRPM")); //$NON-NLS-1$
- setNeedsProgressMonitor(true);
- }
+ /**
+ * @see org.eclipse.ui.IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
+ */
+ @Override
+ public void init(IWorkbench workbench, IStructuredSelection currentSelection) {
+ setWindowTitle(Messages.getString("SRPMImportwizard.Import_an_SRPM")); //$NON-NLS-1$
+ setNeedsProgressMonitor(true);
+ }
- /**
- * @see org.eclipse.jface.wizard.IWizard#performFinish()
- */
+ /**
+ * @see org.eclipse.jface.wizard.IWizard#performFinish()
+ */
- // We have elected to do the Finish button clickin in the SRPMImportPage. So override
- //the default and point to SRPMImport finish()
- @Override
- public boolean performFinish() {
- return mainPage.finish();
- }
+ // We have elected to do the Finish button clickin in the SRPMImportPage. So override
+ //the default and point to SRPMImport finish()
+ @Override
+ public boolean performFinish() {
+ return mainPage.finish();
+ }
- /**
- * @see org.eclipse.jface.wizard.IWizard#canFinish()
- *
- * Select to finish validation in the SRPMImportPage
- */
- @Override
- public boolean canFinish() {
- return mainPage.canFinish();
- }
+ /**
+ * @see org.eclipse.jface.wizard.IWizard#canFinish()
+ *
+ * Select to finish validation in the SRPMImportPage
+ */
+ @Override
+ public boolean canFinish() {
+ return mainPage.canFinish();
+ }
- /**
- * @see org.eclipse.jface.wizard.IWizard#addPages()
- */
+ /**
+ * @see org.eclipse.jface.wizard.IWizard#addPages()
+ */
- // Add the SRPMImportPage as the only page in this wizard.
- @Override
- public void addPages() {
- mainPage = new SRPMImportPage();
- addPage(mainPage);
- super.addPages();
- }
+ // Add the SRPMImportPage as the only page in this wizard.
+ @Override
+ public void addPages() {
+ mainPage = new SRPMImportPage();
+ addPage(mainPage);
+ super.addPages();
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/handlers/SpecfileEditorRPMBuildHandler.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/handlers/SpecfileEditorRPMBuildHandler.java
index 2782fa1146..0a09076d51 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/handlers/SpecfileEditorRPMBuildHandler.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/handlers/SpecfileEditorRPMBuildHandler.java
@@ -42,83 +42,83 @@ import org.eclipse.ui.part.EditorPart;
*/
public class SpecfileEditorRPMBuildHandler extends AbstractHandler {
- protected RPMProject rpj;
+ protected RPMProject rpj;
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- final IResource resource = getResource(event);
- final String eventBuildType = event.getParameter("buildType"); //$NON-NLS-1$
- rpj = getRPMProject(resource);
- Job job = new RPMExportOperation(rpj, eventBuildType);
- job.setUser(true);
- job.schedule();
- return null;
- }
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ final IResource resource = getResource(event);
+ final String eventBuildType = event.getParameter("buildType"); //$NON-NLS-1$
+ rpj = getRPMProject(resource);
+ Job job = new RPMExportOperation(rpj, eventBuildType);
+ job.setUser(true);
+ job.schedule();
+ return null;
+ }
- /**
- * Extract the IResource that was selected when the event was fired.
- * @param event The fired execution event.
- * @return The resource that was selected.
- */
- private static IResource getResource(ExecutionEvent event) {
- IWorkbenchPart part = HandlerUtil.getActivePart(event);
- if (part == null) {
- return null;
- }
- if (part instanceof EditorPart) {
- IEditorInput input = ((EditorPart) part).getEditorInput();
- if (input instanceof IFileEditorInput) {
- return ((IFileEditorInput) input).getFile();
- }
- return null;
- }
- IWorkbenchSite site = part.getSite();
- if (site == null) {
- return null;
- }
- ISelectionProvider provider = site.getSelectionProvider();
- if (provider == null) {
- return null;
- }
- ISelection selection = provider.getSelection();
- if (selection instanceof IStructuredSelection) {
- Object element = ((IStructuredSelection) selection)
- .getFirstElement();
- if (element instanceof IResource) {
- return (IResource) element;
- } else if (element instanceof IAdaptable) {
- IAdaptable adaptable = (IAdaptable) element;
- return (IResource) adaptable.getAdapter(IResource.class);
- } else {
- return null;
- }
- }
- return null;
- }
+ /**
+ * Extract the IResource that was selected when the event was fired.
+ * @param event The fired execution event.
+ * @return The resource that was selected.
+ */
+ private static IResource getResource(ExecutionEvent event) {
+ IWorkbenchPart part = HandlerUtil.getActivePart(event);
+ if (part == null) {
+ return null;
+ }
+ if (part instanceof EditorPart) {
+ IEditorInput input = ((EditorPart) part).getEditorInput();
+ if (input instanceof IFileEditorInput) {
+ return ((IFileEditorInput) input).getFile();
+ }
+ return null;
+ }
+ IWorkbenchSite site = part.getSite();
+ if (site == null) {
+ return null;
+ }
+ ISelectionProvider provider = site.getSelectionProvider();
+ if (provider == null) {
+ return null;
+ }
+ ISelection selection = provider.getSelection();
+ if (selection instanceof IStructuredSelection) {
+ Object element = ((IStructuredSelection) selection)
+ .getFirstElement();
+ if (element instanceof IResource) {
+ return (IResource) element;
+ } else if (element instanceof IAdaptable) {
+ IAdaptable adaptable = (IAdaptable) element;
+ return (IResource) adaptable.getAdapter(IResource.class);
+ } else {
+ return null;
+ }
+ }
+ return null;
+ }
- /**
- * Get an RPMProject for the resource creating a new instance to an RPMProject.
- * @param resource The resource to check its parent project.
- * @return The RPMProject of the resource passed in.
- */
- private static RPMProject getRPMProject(IResource resource) {
- RPMProject rc = null;
- try {
- IProject parentProject = resource.getProject();
+ /**
+ * Get an RPMProject for the resource creating a new instance to an RPMProject.
+ * @param resource The resource to check its parent project.
+ * @return The RPMProject of the resource passed in.
+ */
+ private static RPMProject getRPMProject(IResource resource) {
+ RPMProject rc = null;
+ try {
+ IProject parentProject = resource.getProject();
- // determine if project selected is an RPMProject
- if (parentProject.hasNature(IRPMConstants.RPM_NATURE_ID)) {
- if (parentProject.getPersistentProperty(new QualifiedName(IRPMConstants.RPM_CORE_ID, IRPMConstants.SPECS_FOLDER)) != null){
- rc = new RPMProject(parentProject, RPMProjectLayout.RPMBUILD);
- } else {
- rc = new RPMProject(parentProject, RPMProjectLayout.FLAT);
- }
- } else {
- rc = new RPMProject(parentProject, RPMProjectLayout.FLAT);
- }
- } catch (CoreException e) {
- Activator.logError(Messages.getString("SpecfileEditorRPMBuildHandler.logRPMProjectError"), e); //$NON-NLS-1$
- }
- return rc;
- }
+ // determine if project selected is an RPMProject
+ if (parentProject.hasNature(IRPMConstants.RPM_NATURE_ID)) {
+ if (parentProject.getPersistentProperty(new QualifiedName(IRPMConstants.RPM_CORE_ID, IRPMConstants.SPECS_FOLDER)) != null){
+ rc = new RPMProject(parentProject, RPMProjectLayout.RPMBUILD);
+ } else {
+ rc = new RPMProject(parentProject, RPMProjectLayout.FLAT);
+ }
+ } else {
+ rc = new RPMProject(parentProject, RPMProjectLayout.FLAT);
+ }
+ } catch (CoreException e) {
+ Activator.logError(Messages.getString("SpecfileEditorRPMBuildHandler.logRPMProjectError"), e); //$NON-NLS-1$
+ }
+ return rc;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/AbstractRPMPropertyPage.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/AbstractRPMPropertyPage.java
index 7f9141171e..33b9e1b72d 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/AbstractRPMPropertyPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/AbstractRPMPropertyPage.java
@@ -23,26 +23,26 @@ import org.eclipse.ui.dialogs.PropertyPage;
*/
public abstract class AbstractRPMPropertyPage extends PropertyPage {
- protected abstract void addFields(Composite parent);
-
- /**
- * @see PropertyPage#createContents(Composite)
- */
- @Override
- protected Control createContents(Composite parent) {
- Composite composite = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- composite.setLayout(layout);
+ protected abstract void addFields(Composite parent);
- GridData data = new GridData();
- data.grabExcessHorizontalSpace = true;
- data.verticalAlignment = GridData.FILL;
- data.horizontalAlignment = GridData.FILL;
- composite.setLayoutData(data);
+ /**
+ * @see PropertyPage#createContents(Composite)
+ */
+ @Override
+ protected Control createContents(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ composite.setLayout(layout);
+
+ GridData data = new GridData();
+ data.grabExcessHorizontalSpace = true;
+ data.verticalAlignment = GridData.FILL;
+ data.horizontalAlignment = GridData.FILL;
+ composite.setLayoutData(data);
+
+ addFields(composite);
+ return composite;
+ }
- addFields(composite);
- return composite;
- }
-
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/ChangelogPage.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/ChangelogPage.java
index 6b2498d14f..8ab5365972 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/ChangelogPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/ChangelogPage.java
@@ -24,27 +24,27 @@ import org.eclipse.swt.widgets.Text;
*/
public class ChangelogPage extends AbstractRPMPropertyPage {
- private static final int CL_ENTRIES_FIELD_WIDTH = 80;
+ private static final int CL_ENTRIES_FIELD_WIDTH = 80;
- private static final int CL_ENTRIES_FIELD_HEIGHT = 50;
+ private static final int CL_ENTRIES_FIELD_HEIGHT = 50;
- @Override
- protected void addFields(Composite composite) {
+ @Override
+ protected void addFields(Composite composite) {
- // RPM labels and text fields setup
+ // RPM labels and text fields setup
- Label rpmChangelogEntriesLabel = new Label(composite, SWT.NONE);
- rpmChangelogEntriesLabel.setText(Messages
- .getString("ChangelogPage.entries")); //$NON-NLS-1$
- Text rpmChangelogEntriesText = new Text(composite, SWT.MULTI
- | SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
- GridData gdEntries = new GridData();
- gdEntries.widthHint = convertWidthInCharsToPixels(CL_ENTRIES_FIELD_WIDTH);
- gdEntries.heightHint = convertWidthInCharsToPixels(CL_ENTRIES_FIELD_HEIGHT);
- rpmChangelogEntriesText.setLayoutData(gdEntries);
+ Label rpmChangelogEntriesLabel = new Label(composite, SWT.NONE);
+ rpmChangelogEntriesLabel.setText(Messages
+ .getString("ChangelogPage.entries")); //$NON-NLS-1$
+ Text rpmChangelogEntriesText = new Text(composite, SWT.MULTI
+ | SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
+ GridData gdEntries = new GridData();
+ gdEntries.widthHint = convertWidthInCharsToPixels(CL_ENTRIES_FIELD_WIDTH);
+ gdEntries.heightHint = convertWidthInCharsToPixels(CL_ENTRIES_FIELD_HEIGHT);
+ rpmChangelogEntriesText.setLayoutData(gdEntries);
- String rpm_ChangelogEntries = RPMQuery
- .getChangelog((IFile) getElement());
- rpmChangelogEntriesText.setText(rpm_ChangelogEntries);
- }
+ String rpm_ChangelogEntries = RPMQuery
+ .getChangelog((IFile) getElement());
+ rpmChangelogEntriesText.setText(rpm_ChangelogEntries);
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/InstallScriptsPage.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/InstallScriptsPage.java
index 5fec282b8d..772f630590 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/InstallScriptsPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/InstallScriptsPage.java
@@ -20,58 +20,58 @@ import org.eclipse.swt.widgets.Text;
/**
* Property page displaying install scripts as fetched by RPM headers.
- *
+ *
*/
public class InstallScriptsPage extends AbstractRPMPropertyPage {
- @Override
- protected void addFields(Composite composite) {
+ @Override
+ protected void addFields(Composite composite) {
- // RPM labels and text fields setup
- GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+ // RPM labels and text fields setup
+ GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
- Label rpmPreInstallLabel = new Label(composite, SWT.NONE);
- rpmPreInstallLabel.setText(Messages
- .getString("InstallScriptsPage.PreinstallScript")); //$NON-NLS-1$
- Text rpmPreInstallText = new Text(composite, SWT.MULTI | SWT.BORDER
- | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
- rpmPreInstallText.setLayoutData(gd);
+ Label rpmPreInstallLabel = new Label(composite, SWT.NONE);
+ rpmPreInstallLabel.setText(Messages
+ .getString("InstallScriptsPage.PreinstallScript")); //$NON-NLS-1$
+ Text rpmPreInstallText = new Text(composite, SWT.MULTI | SWT.BORDER
+ | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
+ rpmPreInstallText.setLayoutData(gd);
- Label rpmPostInstallLabel = new Label(composite, SWT.NONE);
- rpmPostInstallLabel.setText(Messages
- .getString("InstallScriptsPage.PostinstallScript")); //$NON-NLS-1$
- Text rpmPostInstallText = new Text(composite, SWT.MULTI | SWT.BORDER
- | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
- rpmPostInstallText.setLayoutData(gd);
+ Label rpmPostInstallLabel = new Label(composite, SWT.NONE);
+ rpmPostInstallLabel.setText(Messages
+ .getString("InstallScriptsPage.PostinstallScript")); //$NON-NLS-1$
+ Text rpmPostInstallText = new Text(composite, SWT.MULTI | SWT.BORDER
+ | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
+ rpmPostInstallText.setLayoutData(gd);
- Label rpmPreUnInstallLabel = new Label(composite, SWT.NONE);
- rpmPreUnInstallLabel.setText(Messages
- .getString("InstallScriptsPage.PreuninstallScript")); //$NON-NLS-1$
- Text rpmPreUnInstallText = new Text(composite, SWT.MULTI | SWT.BORDER
- | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
- rpmPreUnInstallText.setLayoutData(gd);
+ Label rpmPreUnInstallLabel = new Label(composite, SWT.NONE);
+ rpmPreUnInstallLabel.setText(Messages
+ .getString("InstallScriptsPage.PreuninstallScript")); //$NON-NLS-1$
+ Text rpmPreUnInstallText = new Text(composite, SWT.MULTI | SWT.BORDER
+ | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
+ rpmPreUnInstallText.setLayoutData(gd);
- Label rpmPostUnInstallLabel = new Label(composite, SWT.NONE);
- rpmPostUnInstallLabel.setText(Messages
- .getString("InstallScriptsPage.PostuninstallScript")); //$NON-NLS-1$
- Text rpmPostUnInstallText = new Text(composite, SWT.MULTI | SWT.BORDER
- | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
- rpmPostUnInstallText.setLayoutData(gd);
+ Label rpmPostUnInstallLabel = new Label(composite, SWT.NONE);
+ rpmPostUnInstallLabel.setText(Messages
+ .getString("InstallScriptsPage.PostuninstallScript")); //$NON-NLS-1$
+ Text rpmPostUnInstallText = new Text(composite, SWT.MULTI | SWT.BORDER
+ | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
+ rpmPostUnInstallText.setLayoutData(gd);
- // Populate RPM text fields
- IFile rpmFile = (IFile) getElement();
- String rpm_PreInstall = RPMQuery.getPreInstallScript(rpmFile);
- rpmPreInstallText.setText(rpm_PreInstall);
+ // Populate RPM text fields
+ IFile rpmFile = (IFile) getElement();
+ String rpm_PreInstall = RPMQuery.getPreInstallScript(rpmFile);
+ rpmPreInstallText.setText(rpm_PreInstall);
- String rpm_PostInstall = RPMQuery.getPostInstallScript(rpmFile);
- rpmPostInstallText.setText(rpm_PostInstall);
+ String rpm_PostInstall = RPMQuery.getPostInstallScript(rpmFile);
+ rpmPostInstallText.setText(rpm_PostInstall);
- String rpm_PreUnInstall = RPMQuery.getPreUninstallScript(rpmFile);
- rpmPreUnInstallText.setText(rpm_PreUnInstall);
+ String rpm_PreUnInstall = RPMQuery.getPreUninstallScript(rpmFile);
+ rpmPreUnInstallText.setText(rpm_PreUnInstall);
- String rpm_PostUnInstall = RPMQuery.getPostUninstallScript(rpmFile);
- rpmPostUnInstallText.setText(rpm_PostUnInstall);
+ String rpm_PostUnInstall = RPMQuery.getPostUninstallScript(rpmFile);
+ rpmPostUnInstallText.setText(rpm_PostUnInstall);
- }
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/Messages.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/Messages.java
index c38d93655a..6ba625f948 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/Messages.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/Messages.java
@@ -15,19 +15,19 @@ import java.util.ResourceBundle;
@SuppressWarnings("javadoc")
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.propertypage.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.rpm.ui.propertypage.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/ProvidesPage.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/ProvidesPage.java
index d0927025bc..873acd710c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/ProvidesPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/ProvidesPage.java
@@ -24,27 +24,27 @@ import org.eclipse.swt.widgets.Text;
*/
public class ProvidesPage extends AbstractRPMPropertyPage {
- private static final int QL_FIELD_WIDTH = 80;
-
- private static final int QL_FIELD_HEIGHT = 40;
-
- @Override
- protected void addFields(Composite composite) {
- // RPM labels and text fields setup
-
- Label rpmDescriptionLabel = new Label(composite, SWT.NONE);
- rpmDescriptionLabel
- .setText(Messages.getString("ProvidesPage.Provides")); //$NON-NLS-1$
- Text rpmQlText = new Text(composite, SWT.MULTI | SWT.BORDER
- | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
- GridData gdQL = new GridData();
- gdQL.widthHint = convertWidthInCharsToPixels(QL_FIELD_WIDTH);
- gdQL.heightHint = convertWidthInCharsToPixels(QL_FIELD_HEIGHT);
- rpmQlText.setLayoutData(gdQL);
-
- // Populate RPM text fields
- String rpm_ql = RPMQuery.getProvides((IFile) getElement());
- rpmQlText.setText(rpm_ql);
- }
+ private static final int QL_FIELD_WIDTH = 80;
+
+ private static final int QL_FIELD_HEIGHT = 40;
+
+ @Override
+ protected void addFields(Composite composite) {
+ // RPM labels and text fields setup
+
+ Label rpmDescriptionLabel = new Label(composite, SWT.NONE);
+ rpmDescriptionLabel
+ .setText(Messages.getString("ProvidesPage.Provides")); //$NON-NLS-1$
+ Text rpmQlText = new Text(composite, SWT.MULTI | SWT.BORDER
+ | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
+ GridData gdQL = new GridData();
+ gdQL.widthHint = convertWidthInCharsToPixels(QL_FIELD_WIDTH);
+ gdQL.heightHint = convertWidthInCharsToPixels(QL_FIELD_HEIGHT);
+ rpmQlText.setLayoutData(gdQL);
+
+ // Populate RPM text fields
+ String rpm_ql = RPMQuery.getProvides((IFile) getElement());
+ rpmQlText.setText(rpm_ql);
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/SpecFileHeaderPage.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/SpecFileHeaderPage.java
index f1d6ff1d83..8349dc5e70 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/SpecFileHeaderPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/SpecFileHeaderPage.java
@@ -24,28 +24,28 @@ import org.eclipse.swt.widgets.Text;
*/
public class SpecFileHeaderPage extends AbstractRPMPropertyPage {
- private static final int QI_FIELD_WIDTH = 80;
+ private static final int QI_FIELD_WIDTH = 80;
- private static final int QI_FIELD_HEIGHT = 40;
+ private static final int QI_FIELD_HEIGHT = 40;
- @Override
- protected void addFields(Composite composite) {
+ @Override
+ protected void addFields(Composite composite) {
- // RPM labels and text fields setup
+ // RPM labels and text fields setup
- Label rpmDescriptionLabel = new Label(composite, SWT.NONE);
- rpmDescriptionLabel.setText(Messages
- .getString("SpecFileHeaderPage.info")); //$NON-NLS-1$
- Text rpmQiText = new Text(composite, SWT.MULTI | SWT.BORDER
- | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
- GridData gdQI = new GridData();
- gdQI.widthHint = convertWidthInCharsToPixels(QI_FIELD_WIDTH);
- gdQI.heightHint = convertWidthInCharsToPixels(QI_FIELD_HEIGHT);
- rpmQiText.setLayoutData(gdQI);
+ Label rpmDescriptionLabel = new Label(composite, SWT.NONE);
+ rpmDescriptionLabel.setText(Messages
+ .getString("SpecFileHeaderPage.info")); //$NON-NLS-1$
+ Text rpmQiText = new Text(composite, SWT.MULTI | SWT.BORDER
+ | SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP);
+ GridData gdQI = new GridData();
+ gdQI.widthHint = convertWidthInCharsToPixels(QI_FIELD_WIDTH);
+ gdQI.heightHint = convertWidthInCharsToPixels(QI_FIELD_HEIGHT);
+ rpmQiText.setLayoutData(gdQI);
- // Populate RPM text field
- String rpm_qi = RPMQuery.getHeaderInfo((IFile) getElement());
- rpmQiText.setText(rpm_qi);
- }
+ // Populate RPM text field
+ String rpm_qi = RPMQuery.getHeaderInfo((IFile) getElement());
+ rpmQiText.setText(rpm_qi);
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/TargetPage.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/TargetPage.java
index 5882619648..e1601a3a9c 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/TargetPage.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/internal/rpm/ui/propertypage/TargetPage.java
@@ -20,52 +20,52 @@ import org.eclipse.swt.widgets.Label;
/**
* Property page displaying the target (aka build arch and friends) as fetched
* from the RPM headers.
- *
+ *
*/
public class TargetPage extends AbstractRPMPropertyPage {
- @Override
- protected void addFields(Composite composite) {
- // RPM labels and text fields setup
- GridData gd = new GridData(SWT.FILL, SWT.NONE, true, false);
+ @Override
+ protected void addFields(Composite composite) {
+ // RPM labels and text fields setup
+ GridData gd = new GridData(SWT.FILL, SWT.NONE, true, false);
- Label rpmArchLabel = new Label(composite, SWT.NONE);
- rpmArchLabel.setText(Messages.getString("TargetPage.Architecture")); //$NON-NLS-1$
- Label rpmArchText = new Label(composite, SWT.NONE);
- rpmArchText.setLayoutData(gd);
+ Label rpmArchLabel = new Label(composite, SWT.NONE);
+ rpmArchLabel.setText(Messages.getString("TargetPage.Architecture")); //$NON-NLS-1$
+ Label rpmArchText = new Label(composite, SWT.NONE);
+ rpmArchText.setLayoutData(gd);
- Label rpmPlatformLabel = new Label(composite, SWT.NONE);
- rpmPlatformLabel.setText(Messages.getString("TargetPage.Platform")); //$NON-NLS-1$
- Label rpmPlatformText = new Label(composite, SWT.NONE);
- rpmPlatformText.setLayoutData(gd);
+ Label rpmPlatformLabel = new Label(composite, SWT.NONE);
+ rpmPlatformLabel.setText(Messages.getString("TargetPage.Platform")); //$NON-NLS-1$
+ Label rpmPlatformText = new Label(composite, SWT.NONE);
+ rpmPlatformText.setLayoutData(gd);
- Label rpmOSLabel = new Label(composite, SWT.NONE);
- rpmOSLabel.setText(Messages.getString("TargetPage.OS")); //$NON-NLS-1$
- Label rpmOsText = new Label(composite, SWT.NONE);
- rpmOsText.setLayoutData(gd);
+ Label rpmOSLabel = new Label(composite, SWT.NONE);
+ rpmOSLabel.setText(Messages.getString("TargetPage.OS")); //$NON-NLS-1$
+ Label rpmOsText = new Label(composite, SWT.NONE);
+ rpmOsText.setLayoutData(gd);
- Label rpmHostLabel = new Label(composite, SWT.NONE);
- rpmHostLabel.setText(Messages.getString("TargetPage.BuildHost")); //$NON-NLS-1$
- Label rpmHostText = new Label(composite, SWT.NONE);
- rpmHostText.setLayoutData(gd);
+ Label rpmHostLabel = new Label(composite, SWT.NONE);
+ rpmHostLabel.setText(Messages.getString("TargetPage.BuildHost")); //$NON-NLS-1$
+ Label rpmHostText = new Label(composite, SWT.NONE);
+ rpmHostText.setLayoutData(gd);
- Label rpmTimeLabel = new Label(composite, SWT.NONE);
- rpmTimeLabel.setText(Messages.getString("TargetPage.BuildTime")); //$NON-NLS-1$
- Label rpmTimeText = new Label(composite, SWT.NONE);
- rpmTimeText.setLayoutData(gd);
+ Label rpmTimeLabel = new Label(composite, SWT.NONE);
+ rpmTimeLabel.setText(Messages.getString("TargetPage.BuildTime")); //$NON-NLS-1$
+ Label rpmTimeText = new Label(composite, SWT.NONE);
+ rpmTimeText.setLayoutData(gd);
- // Populate RPM text fields
- IFile rpmFile = (IFile) getElement();
- String rpmArch = RPMQuery.getArch(rpmFile);
- rpmArchText.setText(rpmArch);
- String rpmPlatform = RPMQuery.getPlatform(rpmFile);
- rpmPlatformText.setText(rpmPlatform);
- String rpmOs = RPMQuery.getOS(rpmFile);
- rpmOsText.setText(rpmOs);
- String rpmHost = RPMQuery.getBuildHost(rpmFile);
- rpmHostText.setText(rpmHost);
- String rpmTime = RPMQuery.getBuildTime(rpmFile);
- rpmTimeText.setText(rpmTime);
- }
+ // Populate RPM text fields
+ IFile rpmFile = (IFile) getElement();
+ String rpmArch = RPMQuery.getArch(rpmFile);
+ rpmArchText.setText(rpmArch);
+ String rpmPlatform = RPMQuery.getPlatform(rpmFile);
+ rpmPlatformText.setText(rpmPlatform);
+ String rpmOs = RPMQuery.getOS(rpmFile);
+ rpmOsText.setText(rpmOs);
+ String rpmHost = RPMQuery.getBuildHost(rpmFile);
+ rpmHostText.setText(rpmHost);
+ String rpmTime = RPMQuery.getBuildTime(rpmFile);
+ rpmTimeText.setText(rpmTime);
+ }
} \ No newline at end of file
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/rpm/ui/RPMExportOperation.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/rpm/ui/RPMExportOperation.java
index f436ea2400..68bab96a6a 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/rpm/ui/RPMExportOperation.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/rpm/ui/RPMExportOperation.java
@@ -28,66 +28,66 @@ import org.osgi.framework.FrameworkUtil;
* @since 1.1
*/
public class RPMExportOperation extends Job {
- private RPMProject rpmProject;
- private BuildType exportType;
+ private RPMProject rpmProject;
+ private BuildType exportType;
- /**
- * Creates the job for exporting rpms.
- *
- * @param rpmProject The project to use as base for the export operation.
- * @param exportType The export type. [SOURCE, BINARY, ALL]
- */
- public RPMExportOperation(RPMProject rpmProject, String exportType) {
- super(Messages.getString("RPMExportWizard.0")); //$NON-NLS-1$
- this.rpmProject = rpmProject;
- this.exportType = BuildType.valueOf(exportType);
- }
+ /**
+ * Creates the job for exporting rpms.
+ *
+ * @param rpmProject The project to use as base for the export operation.
+ * @param exportType The export type. [SOURCE, BINARY, ALL]
+ */
+ public RPMExportOperation(RPMProject rpmProject, String exportType) {
+ super(Messages.getString("RPMExportWizard.0")); //$NON-NLS-1$
+ this.rpmProject = rpmProject;
+ this.exportType = BuildType.valueOf(exportType);
+ }
- /**
- * @see org.eclipse.jface.operation.IRunnableWithProgress#run(IProgressMonitor)
- *
- */
- @Override
- public IStatus run(IProgressMonitor monitor) {
- IStatus result = null;
- IOConsole myConsole = RpmConsole.findConsole(rpmProject.getSpecFile().getProject().getName());
- IOConsoleOutputStream out = myConsole.newOutputStream();
- myConsole.clearConsole();
- myConsole.activate();
- switch (exportType) {
- case ALL:
- try {
- monitor.beginTask(Messages
- .getString("RPMExportOperation.Executing_All_Export"), IProgressMonitor.UNKNOWN); //$NON-NLS-1$
- result = rpmProject.buildAll(out);
- } catch (CoreException e) {
- result = new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(),
- e.getMessage(), e);
- }
- break;
+ /**
+ * @see org.eclipse.jface.operation.IRunnableWithProgress#run(IProgressMonitor)
+ *
+ */
+ @Override
+ public IStatus run(IProgressMonitor monitor) {
+ IStatus result = null;
+ IOConsole myConsole = RpmConsole.findConsole(rpmProject.getSpecFile().getProject().getName());
+ IOConsoleOutputStream out = myConsole.newOutputStream();
+ myConsole.clearConsole();
+ myConsole.activate();
+ switch (exportType) {
+ case ALL:
+ try {
+ monitor.beginTask(Messages
+ .getString("RPMExportOperation.Executing_All_Export"), IProgressMonitor.UNKNOWN); //$NON-NLS-1$
+ result = rpmProject.buildAll(out);
+ } catch (CoreException e) {
+ result = new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(),
+ e.getMessage(), e);
+ }
+ break;
- case BINARY:
- monitor.beginTask(Messages
- .getString("RPMExportOperation.Executing_RPM_Export"), IProgressMonitor.UNKNOWN); //$NON-NLS-1$
- try {
- result = rpmProject.buildBinaryRPM(out);
- } catch (CoreException e) {
- result = new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(),
- e.getMessage(), e);
- }
- break;
+ case BINARY:
+ monitor.beginTask(Messages
+ .getString("RPMExportOperation.Executing_RPM_Export"), IProgressMonitor.UNKNOWN); //$NON-NLS-1$
+ try {
+ result = rpmProject.buildBinaryRPM(out);
+ } catch (CoreException e) {
+ result = new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(),
+ e.getMessage(), e);
+ }
+ break;
- case SOURCE:
- monitor.beginTask(Messages
- .getString("RPMExportOperation.Executing_SRPM_Export"), IProgressMonitor.UNKNOWN); //$NON-NLS-1$
- try {
- result = rpmProject.buildSourceRPM(out);
- } catch (CoreException e) {
- result = new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(),
- e.getMessage(), e);
- }
- break;
- }
- return result;
- }
+ case SOURCE:
+ monitor.beginTask(Messages
+ .getString("RPMExportOperation.Executing_SRPM_Export"), IProgressMonitor.UNKNOWN); //$NON-NLS-1$
+ try {
+ result = rpmProject.buildSourceRPM(out);
+ } catch (CoreException e) {
+ result = new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(),
+ e.getMessage(), e);
+ }
+ break;
+ }
+ return result;
+ }
}
diff --git a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/rpm/ui/SRPMImportOperation.java b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/rpm/ui/SRPMImportOperation.java
index de7b0790a7..d85ba56868 100644
--- a/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/rpm/ui/SRPMImportOperation.java
+++ b/rpm/org.eclipse.linuxtools.rpm.ui/src/org/eclipse/linuxtools/rpm/ui/SRPMImportOperation.java
@@ -34,85 +34,85 @@ import org.eclipse.ui.PlatformUI;
*/
public class SRPMImportOperation implements IRunnableWithProgress {
- private IProject project;
- private File sourceRPM;
- private URL remoteSRPM;
- private RPMProjectLayout projectLayout;
-
- private List<CoreException> rpmErrorTable;
-
- /**
- * Method SRPMImportOperation.
- * @param project The project to import into.
- * @param sourceRPM The source rpm to import.
- * @param rpmProjectLayout The required layout of the project.
- */
- public SRPMImportOperation(IProject project, File sourceRPM, RPMProjectLayout rpmProjectLayout) {
- this.project = project;
- this.sourceRPM = sourceRPM;
- this.projectLayout = rpmProjectLayout;
- }
-
- /**
- * @param project The project to import to.
- * @param sourceRPM The remote SRPM file.
- * @param rpmProjectLayout The desired project layout of the project.
- */
- public SRPMImportOperation(IProject project, URL sourceRPM, RPMProjectLayout rpmProjectLayout) {
- this.remoteSRPM = sourceRPM;
- this.project = project;
- this.projectLayout = rpmProjectLayout;
- }
-
-
- /**
- * @see org.eclipse.jface.operation.IRunnableWithProgress#run(IProgressMonitor)
- *
- * Perform the import of SRPM import. Call the build class incrementally
- */
- @Override
- public void run(IProgressMonitor progressMonitor) {
- // Total number of work steps needed
- int totalWork = 3;
-
- rpmErrorTable = new ArrayList<>();
-
- progressMonitor.beginTask(Messages.getString("SRPMImportOperation.Starting"), //$NON-NLS-1$
- totalWork);
-
- // Try to create an instance of the build class.
- try {
- RPMProject rpmProject = new RPMProject(project, projectLayout);
- progressMonitor.worked(1);
- progressMonitor.setTaskName(Messages.getString("SRPMImportOperation.Importing_SRPM")); //$NON-NLS-1$
- if (sourceRPM != null) {
- rpmProject.importSourceRPM(sourceRPM);
- progressMonitor.worked(2);
- } else if (remoteSRPM != null) {
- SubProgressMonitor submonitor = new SubProgressMonitor(progressMonitor, 1);
- rpmProject.importSourceRPM(remoteSRPM, submonitor);
- progressMonitor.worked(2);
- }
- } catch (CoreException e) {
- rpmErrorTable.add(e);
- }
- progressMonitor.worked(2);
- }
-
-
- /**
- * @return The result of the operation.
- */
- public MultiStatus getStatus() {
- IStatus[] errors = new IStatus[rpmErrorTable.size()];
- int iCount = 0;
- for (CoreException ex : rpmErrorTable) {
- errors[iCount] = ex.getStatus();
- iCount++;
- }
-
- return new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, errors, Messages.getString("SRPMImportOperation.3"), //$NON-NLS-1$
- null);
+ private IProject project;
+ private File sourceRPM;
+ private URL remoteSRPM;
+ private RPMProjectLayout projectLayout;
+
+ private List<CoreException> rpmErrorTable;
+
+ /**
+ * Method SRPMImportOperation.
+ * @param project The project to import into.
+ * @param sourceRPM The source rpm to import.
+ * @param rpmProjectLayout The required layout of the project.
+ */
+ public SRPMImportOperation(IProject project, File sourceRPM, RPMProjectLayout rpmProjectLayout) {
+ this.project = project;
+ this.sourceRPM = sourceRPM;
+ this.projectLayout = rpmProjectLayout;
+ }
+
+ /**
+ * @param project The project to import to.
+ * @param sourceRPM The remote SRPM file.
+ * @param rpmProjectLayout The desired project layout of the project.
+ */
+ public SRPMImportOperation(IProject project, URL sourceRPM, RPMProjectLayout rpmProjectLayout) {
+ this.remoteSRPM = sourceRPM;
+ this.project = project;
+ this.projectLayout = rpmProjectLayout;
+ }
+
+
+ /**
+ * @see org.eclipse.jface.operation.IRunnableWithProgress#run(IProgressMonitor)
+ *
+ * Perform the import of SRPM import. Call the build class incrementally
+ */
+ @Override
+ public void run(IProgressMonitor progressMonitor) {
+ // Total number of work steps needed
+ int totalWork = 3;
+
+ rpmErrorTable = new ArrayList<>();
+
+ progressMonitor.beginTask(Messages.getString("SRPMImportOperation.Starting"), //$NON-NLS-1$
+ totalWork);
+
+ // Try to create an instance of the build class.
+ try {
+ RPMProject rpmProject = new RPMProject(project, projectLayout);
+ progressMonitor.worked(1);
+ progressMonitor.setTaskName(Messages.getString("SRPMImportOperation.Importing_SRPM")); //$NON-NLS-1$
+ if (sourceRPM != null) {
+ rpmProject.importSourceRPM(sourceRPM);
+ progressMonitor.worked(2);
+ } else if (remoteSRPM != null) {
+ SubProgressMonitor submonitor = new SubProgressMonitor(progressMonitor, 1);
+ rpmProject.importSourceRPM(remoteSRPM, submonitor);
+ progressMonitor.worked(2);
+ }
+ } catch (CoreException e) {
+ rpmErrorTable.add(e);
+ }
+ progressMonitor.worked(2);
+ }
+
+
+ /**
+ * @return The result of the operation.
+ */
+ public MultiStatus getStatus() {
+ IStatus[] errors = new IStatus[rpmErrorTable.size()];
+ int iCount = 0;
+ for (CoreException ex : rpmErrorTable) {
+ errors[iCount] = ex.getStatus();
+ iCount++;
+ }
+
+ return new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, errors, Messages.getString("SRPMImportOperation.3"), //$NON-NLS-1$
+ null);
}
-
+
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph-feature/pom.xml b/systemtap/org.eclipse.linuxtools.callgraph-feature/pom.xml
index 4e35e1fb9c..5dcb230734 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph-feature/pom.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph-feature/pom.xml
@@ -21,7 +21,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools C/C++ Call Graph Visualization Feature</name>
-
+
<build>
<plugins>
<plugin>
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/plugin.xml b/systemtap/org.eclipse.linuxtools.callgraph.core/plugin.xml
index 0e85c132ad..9e577556fc 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/plugin.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/plugin.xml
@@ -2,7 +2,7 @@
<?eclipse version="3.4"?>
<plugin>
<extension-point id="org.eclipse.linuxtools.callgraph.core.parser" name="%systemtapparserextensionpoint" schema="schema/org.eclipse.linuxtools.callgraph.core.parser.exsd"/>
-
+
<extension
id="org.eclipse.linuxtools.callgraph.core.systemtaptextview"
name="%systemtaptextviewname"
@@ -13,7 +13,7 @@
id="org.eclipse.linuxtools.callgraph.core.staptextview"
name="%view.name"
restorable="true"
- icon="icons/12446.monitorOn.gif"
+ icon="icons/12446.monitorOn.gif"
allowMultiple="true">
</view>
</extension>
@@ -27,6 +27,6 @@
realtime="true">
</parser>
</extension>
-
+
</plugin>
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/CallgraphCorePlugin.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/CallgraphCorePlugin.java
index 2b780ec041..23aa440a6a 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/CallgraphCorePlugin.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/CallgraphCorePlugin.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -25,82 +25,82 @@ import org.osgi.framework.BundleContext;
/**
- * Activator class behaves like standard Wizard-created activator,
+ * Activator class behaves like standard Wizard-created activator,
* except for the checkRun() function.
*
*/
public class CallgraphCorePlugin extends AbstractUIPlugin {
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.callgraph.core"; //$NON-NLS-1$
- // The shared instance
- private static CallgraphCorePlugin plugin;
-
- /**
- * The constructor
- */
- public CallgraphCorePlugin() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
-
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static CallgraphCorePlugin getDefault() {
- return plugin;
- }
-
-
- /**
- * Returns the location of the plugin by checking the path of the bundle's
- * locationURL.
- *
- * @return
- */
- public static String getPluginLocation() {
- Bundle bundle = Platform.getBundle(PLUGIN_ID);
-
- URL locationUrl = FileLocator.find(bundle,new Path("/"), null); //$NON-NLS-1$
- URL fileUrl = null;
- try {
- fileUrl = FileLocator.toFileURL(locationUrl);
- return fileUrl.getFile();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return new String();
- }
-
- /**
- * Log specified exception.
- * @param e Exception to log.
- */
- public static void logException(Exception e) {
- Status status = new Status(IStatus.ERROR, CallgraphCorePlugin.PLUGIN_ID,
- e.getMessage());
- CallgraphCorePlugin.getDefault().getLog().log(status);
- }
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.callgraph.core"; //$NON-NLS-1$
+ // The shared instance
+ private static CallgraphCorePlugin plugin;
+
+ /**
+ * The constructor
+ */
+ public CallgraphCorePlugin() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static CallgraphCorePlugin getDefault() {
+ return plugin;
+ }
+
+
+ /**
+ * Returns the location of the plugin by checking the path of the bundle's
+ * locationURL.
+ *
+ * @return
+ */
+ public static String getPluginLocation() {
+ Bundle bundle = Platform.getBundle(PLUGIN_ID);
+
+ URL locationUrl = FileLocator.find(bundle,new Path("/"), null); //$NON-NLS-1$
+ URL fileUrl = null;
+ try {
+ fileUrl = FileLocator.toFileURL(locationUrl);
+ return fileUrl.getFile();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return new String();
+ }
+
+ /**
+ * Log specified exception.
+ * @param e Exception to log.
+ */
+ public static void logException(Exception e) {
+ Status status = new Status(IStatus.ERROR, CallgraphCorePlugin.PLUGIN_ID,
+ e.getMessage());
+ CallgraphCorePlugin.getDefault().getLog().log(status);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/DocWriter.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/DocWriter.java
index 1081a6c4a8..d9a453806f 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/DocWriter.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/DocWriter.java
@@ -19,55 +19,55 @@ import org.eclipse.ui.console.TextConsole;
import org.eclipse.ui.progress.UIJob;
public class DocWriter extends UIJob {
- private TextConsole console;
- private String message;
- private int length;
- private int start;
+ private TextConsole console;
+ private String message;
+ private int length;
+ private int start;
- /**
- * Initiate DocWriter class. DocWriter will append the given message
- * to the given console in a separate UI job. By default, DocWriter will
- * append to the end of the console and replace 0 characters. To change this,
- * see DocWriter's set methods.
- *
- *
- * @param name
- * @param console
- * @param message
- */
- public DocWriter(String name, TextConsole console, String message) {
+ /**
+ * Initiate DocWriter class. DocWriter will append the given message
+ * to the given console in a separate UI job. By default, DocWriter will
+ * append to the end of the console and replace 0 characters. To change this,
+ * see DocWriter's set methods.
+ *
+ *
+ * @param name
+ * @param console
+ * @param message
+ */
+ public DocWriter(String name, TextConsole console, String message) {
- super(name);
- this.console = console;
- this.message = message;
- this.start=-1;
- this.length=-1;
- }
+ super(name);
+ this.console = console;
+ this.message = message;
+ this.start=-1;
+ this.length=-1;
+ }
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- if (console == null) {
- return Status.CANCEL_STATUS;
- }
- if (message == null) {
- return Status.OK_STATUS;
- }
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ if (console == null) {
+ return Status.CANCEL_STATUS;
+ }
+ if (message == null) {
+ return Status.OK_STATUS;
+ }
- IDocument doc = console.getDocument();
+ IDocument doc = console.getDocument();
- if (length < 0) {
- length = 0;
- }
- if (start < 0) {
- start = doc.getLength();
- }
- try {
- doc.replace(start, length, message);
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
+ if (length < 0) {
+ length = 0;
+ }
+ if (start < 0) {
+ start = doc.getLength();
+ }
+ try {
+ doc.replace(start, length, message);
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
- return Status.OK_STATUS;
- }
+ return Status.OK_STATUS;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/FileFinderOpener.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/FileFinderOpener.java
index dc8c402163..c7dcd97f76 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/FileFinderOpener.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/FileFinderOpener.java
@@ -28,61 +28,61 @@ import org.eclipse.ui.dialogs.ElementListSelectionDialog;
*/
public class FileFinderOpener {
- private static Map<String, int []> map = new HashMap<>();
+ private static Map<String, int []> map = new HashMap<>();
- /**
- * Seeks all functions in the given proejct that contains the given function name.
- * Farms off the work of generating the list to the findFunctionsInProject function.
- * Opens a selection dialog if more than one file is found.
- *
- * @param project
- * @param functionName
- * @return
- */
- public static void findAndOpen(ICProject project, String functionName) {
- //Safety valve: Do not enforce use of project names
- if (project == null) {
- return;
- }
+ /**
+ * Seeks all functions in the given proejct that contains the given function name.
+ * Farms off the work of generating the list to the findFunctionsInProject function.
+ * Opens a selection dialog if more than one file is found.
+ *
+ * @param project
+ * @param functionName
+ * @return
+ */
+ public static void findAndOpen(ICProject project, String functionName) {
+ //Safety valve: Do not enforce use of project names
+ if (project == null) {
+ return;
+ }
- map = ProfileUIUtils.findFunctionsInProject(project, functionName, -1, null);
- ArrayList<String> files = new ArrayList<>(map.keySet());
+ map = ProfileUIUtils.findFunctionsInProject(project, functionName, -1, null);
+ ArrayList<String> files = new ArrayList<>(map.keySet());
- if (files == null || files.size() < 1) {
- return;
- }
+ if (files == null || files.size() < 1) {
+ return;
+ }
- if (files.size() == 1) {
- open(files.get(0), map.get(files.get(0))[0], map.get(files.get(0))[1]);
- } else {
- ElementListSelectionDialog d = new ElementListSelectionDialog(new Shell(), new LabelProvider());
- d.setTitle(Messages.getString("FileFinderOpener.MultipleFilesDialog")); //$NON-NLS-1$
- d.setMessage(Messages.getString("FileFinderOpener.MultFilesDialogM1") + functionName + Messages.getString("FileFinderOpener.MultFilesDialogM2") + //$NON-NLS-1$ //$NON-NLS-2$
- Messages.getString("FileFinderOpener.MultFilesDialogM3")); //$NON-NLS-1$
- d.setElements(files.toArray());
- d.open();
+ if (files.size() == 1) {
+ open(files.get(0), map.get(files.get(0))[0], map.get(files.get(0))[1]);
+ } else {
+ ElementListSelectionDialog d = new ElementListSelectionDialog(new Shell(), new LabelProvider());
+ d.setTitle(Messages.getString("FileFinderOpener.MultipleFilesDialog")); //$NON-NLS-1$
+ d.setMessage(Messages.getString("FileFinderOpener.MultFilesDialogM1") + functionName + Messages.getString("FileFinderOpener.MultFilesDialogM2") + //$NON-NLS-1$ //$NON-NLS-2$
+ Messages.getString("FileFinderOpener.MultFilesDialogM3")); //$NON-NLS-1$
+ d.setElements(files.toArray());
+ d.open();
- if (d.getResult() == null) {
- return;
- }
+ if (d.getResult() == null) {
+ return;
+ }
- for (Object o : d.getResult()) {
- if (o instanceof String) {
- String s = (String) o;
- open(s, map.get(s)[0], map.get(s)[1]);
- }
- }
- }
- }
+ for (Object o : d.getResult()) {
+ if (o instanceof String) {
+ String s = (String) o;
+ open(s, map.get(s)[0], map.get(s)[1]);
+ }
+ }
+ }
+ }
- private static void open(String path, int offset, int length) {
- if (path == null) {
- return;
- }
- try {
- ProfileUIUtils.openEditorAndSelect(path, offset, length);
- } catch (PartInitException e) {
- e.printStackTrace();
- }
- }
+ private static void open(String path, int offset, int length) {
+ if (path == null) {
+ return;
+ }
+ try {
+ ProfileUIUtils.openEditorAndSelect(path, offset, length);
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/Helper.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/Helper.java
index f39087ee63..38bd15d912 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/Helper.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/Helper.java
@@ -23,62 +23,62 @@ import org.eclipse.ui.console.TextConsole;
public class Helper {
- /**
- * @param name : A String that can be found in the console (BE AS SPECIFIC AS POSSIBLE)
- * @return The TextConsole having 'name' somewhere within it's name
- */
- public static TextConsole getConsoleByName(String name) {
- for (int i = 0; i < ConsolePlugin.getDefault().getConsoleManager()
- .getConsoles().length; i++) {
- if (ConsolePlugin.getDefault().getConsoleManager().
- getConsoles()[i].getName().contains(name)) {
- return (TextConsole)ConsolePlugin.getDefault().getConsoleManager().getConsoles()[i];
- }
- }
- return null;
- }
+ /**
+ * @param name : A String that can be found in the console (BE AS SPECIFIC AS POSSIBLE)
+ * @return The TextConsole having 'name' somewhere within it's name
+ */
+ public static TextConsole getConsoleByName(String name) {
+ for (int i = 0; i < ConsolePlugin.getDefault().getConsoleManager()
+ .getConsoles().length; i++) {
+ if (ConsolePlugin.getDefault().getConsoleManager().
+ getConsoles()[i].getName().contains(name)) {
+ return (TextConsole)ConsolePlugin.getDefault().getConsoleManager().getConsoles()[i];
+ }
+ }
+ return null;
+ }
- /**
- * Read the contents of a file
- * @param absoluteFilePath : The absolute path of the file from which to read.
- * @return : The contents of the file as a String.
- */
- public static String readFile(String absoluteFilePath) {
+ /**
+ * Read the contents of a file
+ * @param absoluteFilePath : The absolute path of the file from which to read.
+ * @return : The contents of the file as a String.
+ */
+ public static String readFile(String absoluteFilePath) {
- try (BufferedReader bw = new BufferedReader(new FileReader(new File(absoluteFilePath)))) {
- String output = ""; //$NON-NLS-1$
- String tmp = ""; //$NON-NLS-1$
- while ((tmp = bw.readLine()) != null) {
- output+=tmp + "\n"; //$NON-NLS-1$
- }
- bw.close();
+ try (BufferedReader bw = new BufferedReader(new FileReader(new File(absoluteFilePath)))) {
+ String output = ""; //$NON-NLS-1$
+ String tmp = ""; //$NON-NLS-1$
+ while ((tmp = bw.readLine()) != null) {
+ output+=tmp + "\n"; //$NON-NLS-1$
+ }
+ bw.close();
- return output;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
+ return output;
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
- public static BufferedWriter setBufferedWriter(String absoluteFilePath) {
- try {
- File f = new File(absoluteFilePath);
- f.delete();
- f.createNewFile();
- FileWriter fstream;
- fstream = new FileWriter(absoluteFilePath, true);
- return new BufferedWriter(fstream);
- } catch (IOException e) {
- SystemTapUIErrorMessages err = new SystemTapUIErrorMessages
- (Messages.getString("SystemTapView.FileIOErr"), //$NON-NLS-1$
- Messages.getString("SystemTapView.FileIOErr"), //$NON-NLS-1$
- Messages.getString("SystemTapView.FileIOErrMsg")); //$NON-NLS-1$
- err.schedule();
- e.printStackTrace();
- return null;
- }
- }
+ public static BufferedWriter setBufferedWriter(String absoluteFilePath) {
+ try {
+ File f = new File(absoluteFilePath);
+ f.delete();
+ f.createNewFile();
+ FileWriter fstream;
+ fstream = new FileWriter(absoluteFilePath, true);
+ return new BufferedWriter(fstream);
+ } catch (IOException e) {
+ SystemTapUIErrorMessages err = new SystemTapUIErrorMessages
+ (Messages.getString("SystemTapView.FileIOErr"), //$NON-NLS-1$
+ Messages.getString("SystemTapView.FileIOErr"), //$NON-NLS-1$
+ Messages.getString("SystemTapView.FileIOErrMsg")); //$NON-NLS-1$
+ err.schedule();
+ e.printStackTrace();
+ return null;
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/LaunchConfigurationConstants.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/LaunchConfigurationConstants.java
index 17ffb5b9dd..447f864c22 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/LaunchConfigurationConstants.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/LaunchConfigurationConstants.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -12,85 +12,85 @@ package org.eclipse.linuxtools.internal.callgraph.core;
/**
- * Contains the name and default value of configuration variables, as well as
+ * Contains the name and default value of configuration variables, as well as
* a few other plugin-specific constants.
*
*/
public final class LaunchConfigurationConstants {
-
-
- //Configuration type variables
- private static final String INVALID = ""; //$NON-NLS-1$
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.callgraph.launch"; //$NON-NLS-1$
- public static final String COMMAND_VERBOSE = PLUGIN_ID + ".COMMAND_VERBOSE"; //$NON-NLS-1$
- public static final String COMMAND_PASS = PLUGIN_ID + ".PASS"; //$NON-NLS-1$
- public static final String COMMAND_KEEP_TEMPORARY = PLUGIN_ID + ".KEEP_TEMPORARY"; //$NON-NLS-1$
- public static final String COMMAND_GURU = PLUGIN_ID + ".GURU"; //$NON-NLS-1$
- public static final String COMMAND_PROLOGUE_SEARCH = PLUGIN_ID + ".PROLOGUE_SEARCH"; //$NON-NLS-1$
- public static final String COMMAND_NO_CODE_ELISION = PLUGIN_ID + ".NO_CODE_ELISION"; //$NON-NLS-1$
- public static final String COMMAND_DISABLE_WARNINGS = PLUGIN_ID + ".DISABLE_WARNINGS"; //$NON-NLS-1$
- public static final String COMMAND_BULK_MODE = PLUGIN_ID + ".BULK_MODE"; //$NON-NLS-1$
- public static final String COMMAND_TIMING_INFO = PLUGIN_ID + ".TIMING_INFO"; //$NON-NLS-1$
- public static final String COMMAND_SKIP_BADVARS = PLUGIN_ID + ".SKIP_BADVARS"; //$NON-NLS-1$
- public static final String COMMAND_IGNORE_DWARF = PLUGIN_ID + ".IGNORE_DWARF"; //$NON-NLS-1$
- public static final String COMMAND_TAPSET_COVERAGE = PLUGIN_ID + ".TAPSET_COVERAGE"; //$NON-NLS-1$
- public static final String BINARY_PATH = PLUGIN_ID + ".BINARY_PATH"; //$NON-NLS-1$
- public static final String SCRIPT_PATH = PLUGIN_ID + ".SCRIPT_PATH"; //$NON-NLS-1$
- public static final String COMMAND_LEAVE_RUNNING = PLUGIN_ID + ".LEAVE_RUNNING"; //$NON-NLS-1$
- public static final String COMMAND_C_DIRECTIVES = PLUGIN_ID + ".C_DIRECTIVES"; //$NON-NLS-1$
- public static final String COMMAND_BUFFER_BYTES = PLUGIN_ID + ".BUFFER_BYTES"; //$NON-NLS-1$
- public static final String COMMAND_TARGET_PID = PLUGIN_ID + ".TARGET_PID"; //$NON-NLS-1$
- public static final String ARGUMENTS = PLUGIN_ID + ".ARGUMENTS"; //$NON-NLS-1$
- public static final String NUMBER_OF_ARGUMENTS = PLUGIN_ID + ".NUMBER_OF_ARGUMENTS"; //$NON-NLS-1$
- public static final String OUTPUT_PATH = PLUGIN_ID + ".OUTPUT_PATH"; //$NON-NLS-1$
- public static final String OVERWRITE = PLUGIN_ID + ".OVERWRITE"; //$NON-NLS-1$
- public static final String BUILD_PROJECT = PLUGIN_ID + ".BUILD_PROJECT"; //$NON-NLS-1$
- public static final String COMMAND_LIST = PLUGIN_ID + ".COMMAND_LIST"; //$NON-NLS-1$
- public static final String BINARY_ARGUMENTS = PLUGIN_ID + ".BINARY_ARGUMENTS"; //$NON-NLS-1$
- public static final String PARSER_CLASS = PLUGIN_ID + ".PARSER_CLASS"; //$NON-NLS-1$
- public static final String VIEW_CLASS = PLUGIN_ID + ".VIEW_CLASS"; //$NON-NLS-1$
- public static final String SECONDARY_VIEW_ID = PLUGIN_ID + ".SECONDARY_VIEW_ID"; //$NON-NLS-1$
+ //Configuration type variables
+ private static final String INVALID = ""; //$NON-NLS-1$
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.callgraph.launch"; //$NON-NLS-1$
+
+ public static final String COMMAND_VERBOSE = PLUGIN_ID + ".COMMAND_VERBOSE"; //$NON-NLS-1$
+ public static final String COMMAND_PASS = PLUGIN_ID + ".PASS"; //$NON-NLS-1$
+ public static final String COMMAND_KEEP_TEMPORARY = PLUGIN_ID + ".KEEP_TEMPORARY"; //$NON-NLS-1$
+ public static final String COMMAND_GURU = PLUGIN_ID + ".GURU"; //$NON-NLS-1$
+ public static final String COMMAND_PROLOGUE_SEARCH = PLUGIN_ID + ".PROLOGUE_SEARCH"; //$NON-NLS-1$
+ public static final String COMMAND_NO_CODE_ELISION = PLUGIN_ID + ".NO_CODE_ELISION"; //$NON-NLS-1$
+ public static final String COMMAND_DISABLE_WARNINGS = PLUGIN_ID + ".DISABLE_WARNINGS"; //$NON-NLS-1$
+ public static final String COMMAND_BULK_MODE = PLUGIN_ID + ".BULK_MODE"; //$NON-NLS-1$
+ public static final String COMMAND_TIMING_INFO = PLUGIN_ID + ".TIMING_INFO"; //$NON-NLS-1$
+ public static final String COMMAND_SKIP_BADVARS = PLUGIN_ID + ".SKIP_BADVARS"; //$NON-NLS-1$
+ public static final String COMMAND_IGNORE_DWARF = PLUGIN_ID + ".IGNORE_DWARF"; //$NON-NLS-1$
+ public static final String COMMAND_TAPSET_COVERAGE = PLUGIN_ID + ".TAPSET_COVERAGE"; //$NON-NLS-1$
+ public static final String BINARY_PATH = PLUGIN_ID + ".BINARY_PATH"; //$NON-NLS-1$
+ public static final String SCRIPT_PATH = PLUGIN_ID + ".SCRIPT_PATH"; //$NON-NLS-1$
+ public static final String COMMAND_LEAVE_RUNNING = PLUGIN_ID + ".LEAVE_RUNNING"; //$NON-NLS-1$
+ public static final String COMMAND_C_DIRECTIVES = PLUGIN_ID + ".C_DIRECTIVES"; //$NON-NLS-1$
+ public static final String COMMAND_BUFFER_BYTES = PLUGIN_ID + ".BUFFER_BYTES"; //$NON-NLS-1$
+ public static final String COMMAND_TARGET_PID = PLUGIN_ID + ".TARGET_PID"; //$NON-NLS-1$
+ public static final String ARGUMENTS = PLUGIN_ID + ".ARGUMENTS"; //$NON-NLS-1$
+ public static final String NUMBER_OF_ARGUMENTS = PLUGIN_ID + ".NUMBER_OF_ARGUMENTS"; //$NON-NLS-1$
+ public static final String OUTPUT_PATH = PLUGIN_ID + ".OUTPUT_PATH"; //$NON-NLS-1$
+ public static final String OVERWRITE = PLUGIN_ID + ".OVERWRITE"; //$NON-NLS-1$
+ public static final String BUILD_PROJECT = PLUGIN_ID + ".BUILD_PROJECT"; //$NON-NLS-1$
+ public static final String COMMAND_LIST = PLUGIN_ID + ".COMMAND_LIST"; //$NON-NLS-1$
+ public static final String BINARY_ARGUMENTS = PLUGIN_ID + ".BINARY_ARGUMENTS"; //$NON-NLS-1$
+ public static final String PARSER_CLASS = PLUGIN_ID + ".PARSER_CLASS"; //$NON-NLS-1$
+ public static final String VIEW_CLASS = PLUGIN_ID + ".VIEW_CLASS"; //$NON-NLS-1$
+ public static final String SECONDARY_VIEW_ID = PLUGIN_ID + ".SECONDARY_VIEW_ID"; //$NON-NLS-1$
+
+
+ public static final String GENERATED_SCRIPT = PLUGIN_ID + ".GENERATED_SCRIPT"; //$NON-NLS-1$
+ public static final String NEED_TO_GENERATE = PLUGIN_ID + ".NEED_TO_GENERATE"; //$NON-NLS-1$
+ public static final String USE_COLOUR = PLUGIN_ID + ".USE_COLOUR"; //$NON-NLS-1$
+ public static final String COMMAND = ".COMMAND"; //$NON-NLS-1$
+
+ //Defaults
+ public static final int DEFAULT_COMMAND_VERBOSE = 0;
+ public static final int DEFAULT_COMMAND_PASS = 0;
+ public static final boolean DEFAULT_COMMAND_KEEP_TEMPORARY = false;
+ public static final boolean DEFAULT_COMMAND_GURU = false;
+ public static final boolean DEFAULT_COMMAND_PROLOGUE_SEARCH = false;
+ public static final boolean DEFAULT_COMMAND_NO_CODE_ELISION = false;
+ public static final boolean DEFAULT_COMMAND_DISABLE_WARNINGS = false;
+ public static final boolean DEFAULT_COMMAND_BULK_MODE = false;
+ public static final boolean DEFAULT_COMMAND_TIMING_INFO = false;
+ public static final boolean DEFAULT_COMMAND_SKIP_BADVARS = false;
+ public static final boolean DEFAULT_COMMAND_IGNORE_DWARF = false;
+ public static final boolean DEFAULT_COMMAND_TAPSET_COVERAGE = false;
+ public static final String DEFAULT_BINARY_PATH = INVALID;
+ public static final String DEFAULT_SCRIPT_PATH = INVALID;
+ public static final boolean DEFAULT_COMMAND_LEAVE_RUNNING = false;
+ public static final String DEFAULT_COMMAND_C_DIRECTIVES = INVALID;
+ public static final int DEFAULT_COMMAND_BUFFER_BYTES = 0;
+ public static final int DEFAULT_COMMAND_TARGET_PID = 0;
+ public static final String DEFAULT_ARGUMENTS = INVALID;
+ public static final String DEFAULT_OUTPUT_PATH = INVALID;
+ public static final boolean DEFAULT_OVERWRITE = false;
+ public static final int DEFAULT_NUMBER_OF_ARGUMENTS = 0;
+ public static final boolean DEFAULT_BUILD_PROJECT = true;
+ public static final String DEFAULT_COMMAND_LIST = INVALID;
+ public static final String DEFAULT_BINARY_ARGUMENTS = INVALID;
+
+ public static final String DEFAULT_GENERATED_SCRIPT = INVALID;
+ public static final boolean DEFAULT_NEED_TO_GENERATE = false;
+ public static final boolean DEFAULT_USE_COLOUR = false;
- public static final String GENERATED_SCRIPT = PLUGIN_ID + ".GENERATED_SCRIPT"; //$NON-NLS-1$
- public static final String NEED_TO_GENERATE = PLUGIN_ID + ".NEED_TO_GENERATE"; //$NON-NLS-1$
- public static final String USE_COLOUR = PLUGIN_ID + ".USE_COLOUR"; //$NON-NLS-1$
- public static final String COMMAND = ".COMMAND"; //$NON-NLS-1$
-
- //Defaults
- public static final int DEFAULT_COMMAND_VERBOSE = 0;
- public static final int DEFAULT_COMMAND_PASS = 0;
- public static final boolean DEFAULT_COMMAND_KEEP_TEMPORARY = false;
- public static final boolean DEFAULT_COMMAND_GURU = false;
- public static final boolean DEFAULT_COMMAND_PROLOGUE_SEARCH = false;
- public static final boolean DEFAULT_COMMAND_NO_CODE_ELISION = false;
- public static final boolean DEFAULT_COMMAND_DISABLE_WARNINGS = false;
- public static final boolean DEFAULT_COMMAND_BULK_MODE = false;
- public static final boolean DEFAULT_COMMAND_TIMING_INFO = false;
- public static final boolean DEFAULT_COMMAND_SKIP_BADVARS = false;
- public static final boolean DEFAULT_COMMAND_IGNORE_DWARF = false;
- public static final boolean DEFAULT_COMMAND_TAPSET_COVERAGE = false;
- public static final String DEFAULT_BINARY_PATH = INVALID;
- public static final String DEFAULT_SCRIPT_PATH = INVALID;
- public static final boolean DEFAULT_COMMAND_LEAVE_RUNNING = false;
- public static final String DEFAULT_COMMAND_C_DIRECTIVES = INVALID;
- public static final int DEFAULT_COMMAND_BUFFER_BYTES = 0;
- public static final int DEFAULT_COMMAND_TARGET_PID = 0;
- public static final String DEFAULT_ARGUMENTS = INVALID;
- public static final String DEFAULT_OUTPUT_PATH = INVALID;
- public static final boolean DEFAULT_OVERWRITE = false;
- public static final int DEFAULT_NUMBER_OF_ARGUMENTS = 0;
- public static final boolean DEFAULT_BUILD_PROJECT = true;
- public static final String DEFAULT_COMMAND_LIST = INVALID;
- public static final String DEFAULT_BINARY_ARGUMENTS = INVALID;
-
- public static final String DEFAULT_GENERATED_SCRIPT = INVALID;
- public static final boolean DEFAULT_NEED_TO_GENERATE = false;
- public static final boolean DEFAULT_USE_COLOUR = false;
-
- public static final String DEFAULT_PARSER_CLASS = INVALID;
- public static final String DEFAULT_VIEW_CLASS = INVALID;
- public static final String DEFAULT_SECONDARY_VIEW_ID = INVALID;
+ public static final String DEFAULT_PARSER_CLASS = INVALID;
+ public static final String DEFAULT_VIEW_CLASS = INVALID;
+ public static final String DEFAULT_SECONDARY_VIEW_ID = INVALID;
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/Messages.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/Messages.java
index c80d00c580..36ce1c8a5a 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/Messages.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -18,19 +18,19 @@ import java.util.ResourceBundle;
*
*/
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.callgraph.core.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.callgraph.core.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/PluginConstants.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/PluginConstants.java
index cb33ddad85..ccba0d3838 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/PluginConstants.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/PluginConstants.java
@@ -12,61 +12,61 @@ package org.eclipse.linuxtools.internal.callgraph.core;
public final class PluginConstants {
- private static String PLUGIN_LOCATION = ""; //$NON-NLS-1$
- public static final String CONFIGURATION_TYPE_ID = "org.eclipse.linuxtools.callgraph.launch.systemtapLaunch"; //$NON-NLS-1$
- public static final String PARSER_CLASS = "org.eclipse.linuxtools.callgraph.core.parser"; //$NON-NLS-1$
- public static final String PARSER_RESOURCE = "org.eclipse.linuxtools.callgraph.core"; //$NON-NLS-1$
- public static final String PARSER_NAME = "parser"; //$NON-NLS-1$
- public static final String VIEW_CLASS = "org.eclipse.linuxtools.callgraph.core.view"; //$NON-NLS-1$
- public static final String VIEW_RESOURCE = "org.eclipse.ui"; //$NON-NLS-1$
- public static final String VIEW_NAME = "views"; //$NON-NLS-1$
- public static final String ATTR_CLASS = "class"; //$NON-NLS-1$
- public static final String ATTR_REALTIME = "realtime"; //$NON-NLS-1$
- public static final String VAL_TRUE = "true"; //$NON-NLS-1$
+ private static String PLUGIN_LOCATION = ""; //$NON-NLS-1$
+ public static final String CONFIGURATION_TYPE_ID = "org.eclipse.linuxtools.callgraph.launch.systemtapLaunch"; //$NON-NLS-1$
+ public static final String PARSER_CLASS = "org.eclipse.linuxtools.callgraph.core.parser"; //$NON-NLS-1$
+ public static final String PARSER_RESOURCE = "org.eclipse.linuxtools.callgraph.core"; //$NON-NLS-1$
+ public static final String PARSER_NAME = "parser"; //$NON-NLS-1$
+ public static final String VIEW_CLASS = "org.eclipse.linuxtools.callgraph.core.view"; //$NON-NLS-1$
+ public static final String VIEW_RESOURCE = "org.eclipse.ui"; //$NON-NLS-1$
+ public static final String VIEW_NAME = "views"; //$NON-NLS-1$
+ public static final String ATTR_CLASS = "class"; //$NON-NLS-1$
+ public static final String ATTR_REALTIME = "realtime"; //$NON-NLS-1$
+ public static final String VAL_TRUE = "true"; //$NON-NLS-1$
- public static final String NEW_LINE = "\n"; //$NON-NLS-1$
- public static final int MAX_ERRORS = 500; //Maximum number of errors to tolerate
- public static int SYSTEMTAP_OPTIONS_TAB_HORIZONTAL_SPACING = 30;
- public static String STAP_PATH = "stap"; //$NON-NLS-1$
+ public static final String NEW_LINE = "\n"; //$NON-NLS-1$
+ public static final int MAX_ERRORS = 500; //Maximum number of errors to tolerate
+ public static int SYSTEMTAP_OPTIONS_TAB_HORIZONTAL_SPACING = 30;
+ public static String STAP_PATH = "stap"; //$NON-NLS-1$
- public static final String DEFAULT_VIEW_ID = "org.eclipse.linuxtools.callgraph.core.staptextview"; //$NON-NLS-1$
- public static final String DEFAULT_PARSER_ID = "org.eclipse.linuxtools.callgraph.core.systemtaptextparser"; //$NON-NLS-1$
- private static String DEFAULT_OUTPUT = ""; //$NON-NLS-1$
- private static String STAP_GRAPH_DEFAULT_IO_PATH = ""; //$NON-NLS-1$
+ public static final String DEFAULT_VIEW_ID = "org.eclipse.linuxtools.callgraph.core.staptextview"; //$NON-NLS-1$
+ public static final String DEFAULT_PARSER_ID = "org.eclipse.linuxtools.callgraph.core.systemtaptextparser"; //$NON-NLS-1$
+ private static String DEFAULT_OUTPUT = ""; //$NON-NLS-1$
+ private static String STAP_GRAPH_DEFAULT_IO_PATH = ""; //$NON-NLS-1$
- /**
- * Sets the absolute path of the Plugin folder and updates
- * the PLUGIN_LOCATION.
- *
- * @param loc
- */
- public static void setPluginLocation(String loc) {
- PLUGIN_LOCATION = loc;
- }
+ /**
+ * Sets the absolute path of the Plugin folder and updates
+ * the PLUGIN_LOCATION.
+ *
+ * @param loc
+ */
+ public static void setPluginLocation(String loc) {
+ PLUGIN_LOCATION = loc;
+ }
- public static String getPluginLocation() {
- if (PLUGIN_LOCATION.length() < 1) {
- PluginConstants.setPluginLocation(CallgraphCorePlugin.getPluginLocation());
- }
+ public static String getPluginLocation() {
+ if (PLUGIN_LOCATION.length() < 1) {
+ PluginConstants.setPluginLocation(CallgraphCorePlugin.getPluginLocation());
+ }
- return PLUGIN_LOCATION;
- }
+ return PLUGIN_LOCATION;
+ }
- public static String getDefaultOutput() {
- if (DEFAULT_OUTPUT.length() < 1){
- DEFAULT_OUTPUT = CallgraphCorePlugin.getDefault().getStateLocation().toString()+"/"; //$NON-NLS-1$
- }
+ public static String getDefaultOutput() {
+ if (DEFAULT_OUTPUT.length() < 1){
+ DEFAULT_OUTPUT = CallgraphCorePlugin.getDefault().getStateLocation().toString()+"/"; //$NON-NLS-1$
+ }
- return DEFAULT_OUTPUT;
- }
+ return DEFAULT_OUTPUT;
+ }
- public static String getDefaultIOPath() {
- if (STAP_GRAPH_DEFAULT_IO_PATH.length() < 1)
- {
- STAP_GRAPH_DEFAULT_IO_PATH = CallgraphCorePlugin.getDefault().getStateLocation().toString()+"/callgraph.out"; //$NON-NLS-1$
- }
- return STAP_GRAPH_DEFAULT_IO_PATH;
- }
+ public static String getDefaultIOPath() {
+ if (STAP_GRAPH_DEFAULT_IO_PATH.length() < 1)
+ {
+ STAP_GRAPH_DEFAULT_IO_PATH = CallgraphCorePlugin.getDefault().getStateLocation().toString()+"/callgraph.out"; //$NON-NLS-1$
+ }
+ return STAP_GRAPH_DEFAULT_IO_PATH;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/StapUIJob.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/StapUIJob.java
index 9d77870403..f6afd0ebf6 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/StapUIJob.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/StapUIJob.java
@@ -23,46 +23,46 @@ import org.eclipse.ui.progress.UIJob;
*
*/
public class StapUIJob extends UIJob {
- private SystemTapParser parser;
- private String viewID;
- private SystemTapView viewer;
+ private SystemTapParser parser;
+ private String viewID;
+ private SystemTapView viewer;
- public StapUIJob(String name, SystemTapParser parser, String viewID) {
- super(name);
- // CREATE THE SHELL
- this.parser = parser;
- this.viewID = viewID;
- }
+ public StapUIJob(String name, SystemTapParser parser, String viewID) {
+ super(name);
+ // CREATE THE SHELL
+ this.parser = parser;
+ this.viewID = viewID;
+ }
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- if (parser.getSecondaryID() != null && parser.getSecondaryID().length() > 0) {
- viewer = ViewFactory.createView(viewID, parser.getSecondaryID());
- } else {
- viewer = ViewFactory.createView(viewID);
- }
- if (!viewer.setParser(parser)) {
- return Status.CANCEL_STATUS;
- }
- if (viewer.initializeView(this.getDisplay(), monitor) == Status.CANCEL_STATUS) {
- return Status.CANCEL_STATUS;
- }
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ if (parser.getSecondaryID() != null && parser.getSecondaryID().length() > 0) {
+ viewer = ViewFactory.createView(viewID, parser.getSecondaryID());
+ } else {
+ viewer = ViewFactory.createView(viewID);
+ }
+ if (!viewer.setParser(parser)) {
+ return Status.CANCEL_STATUS;
+ }
+ if (viewer.initializeView(this.getDisplay(), monitor) == Status.CANCEL_STATUS) {
+ return Status.CANCEL_STATUS;
+ }
- if (!parser.realTime) {
- viewer.updateMethod();
- }
- viewer.setSourcePath(parser.getFile());
- viewer.setKillButtonEnabled(true);
+ if (!parser.realTime) {
+ viewer.updateMethod();
+ }
+ viewer.setSourcePath(parser.getFile());
+ viewer.setKillButtonEnabled(true);
- return Status.OK_STATUS;
- }
+ return Status.OK_STATUS;
+ }
- /**
- * Returns the viewer object. Viewer is initialized within the run method, and
- * is not guaranteed to be non-null until the job has terminated.
- * @return
- */
- public SystemTapView getViewer() {
- return viewer;
- }
+ /**
+ * Returns the viewer object. Viewer is initialized within the run method, and
+ * is not guaranteed to be non-null until the job has terminated.
+ * @return
+ */
+ public SystemTapView getViewer() {
+ return viewer;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapCommandGenerator.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapCommandGenerator.java
index 643cd18da5..a93fb35319 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapCommandGenerator.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapCommandGenerator.java
@@ -20,83 +20,83 @@ import java.util.ArrayList;
*/
public class SystemTapCommandGenerator {
- private static boolean needsToSendCommand;
- private static boolean needsArguments;
- private static String arguments;
- private static String scriptPath;
- private static String flags;
- private static String binaryPath = null;
- private static String binaryArguments;
- private static String command;
-
-
- public static String generateCommand(String scrPath, String binPath, String opts, boolean needBinary, boolean needsArgs, String arg, String binArguments,
- String cmdTarget) {
- needsToSendCommand = needBinary;
- needsArguments = needsArgs;
- binaryPath = binPath;
- scriptPath = scrPath;
- arguments = "--runtime=dyninst " + arg; //$NON-NLS-1$
- flags = opts;
- binaryArguments = binArguments;
- command = cmdTarget;
-
-
- String[] script = buildScript();
-
- String cmd = ""; //$NON-NLS-1$
- for (int i = 0; i < script.length-1; i++) {
- cmd = cmd + script[i] + " "; //$NON-NLS-1$
- }
- cmd = cmd + script[script.length-1];
-
- return cmd;
- }
-
-
- /**
- * Parses the data created from generateCommand
- * @return An array of strings to be joined and executed by the shell
- */
- private static String[] buildScript() {
- //TODO: Take care of this in the next release. For now only the guru mode is sent
- ArrayList<String> cmdList = new ArrayList<>();
- String[] script;
-
- if (flags.length() > 0){
- cmdList.add(flags);
- }
-
- //Execute a binary
- if (needsToSendCommand){
- if (binaryArguments.length() < 1){
- cmdList.add("-c '" + binaryPath + "'"); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- cmdList.add("-c \"" + binaryPath + " " + binaryArguments +"\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- }
-
-
- if (needsArguments) {
- script = new String[cmdList.size() + 3];
- script[script.length-2] = scriptPath;
- script[script.length-1] = arguments;
- } else {
- script = new String[cmdList.size() + 2];
- script[script.length-1] = scriptPath;
- }
-
- script[0] = command;
-
- for(int i=0; i< cmdList.size(); i++) {
- if (cmdList.get(i) != null) {
- script[i +1] = cmdList.get(i);
- } else {
- script[i + 1] = ""; //$NON-NLS-1$
- }
- }
- return script;
-
- }
+ private static boolean needsToSendCommand;
+ private static boolean needsArguments;
+ private static String arguments;
+ private static String scriptPath;
+ private static String flags;
+ private static String binaryPath = null;
+ private static String binaryArguments;
+ private static String command;
+
+
+ public static String generateCommand(String scrPath, String binPath, String opts, boolean needBinary, boolean needsArgs, String arg, String binArguments,
+ String cmdTarget) {
+ needsToSendCommand = needBinary;
+ needsArguments = needsArgs;
+ binaryPath = binPath;
+ scriptPath = scrPath;
+ arguments = "--runtime=dyninst " + arg; //$NON-NLS-1$
+ flags = opts;
+ binaryArguments = binArguments;
+ command = cmdTarget;
+
+
+ String[] script = buildScript();
+
+ String cmd = ""; //$NON-NLS-1$
+ for (int i = 0; i < script.length-1; i++) {
+ cmd = cmd + script[i] + " "; //$NON-NLS-1$
+ }
+ cmd = cmd + script[script.length-1];
+
+ return cmd;
+ }
+
+
+ /**
+ * Parses the data created from generateCommand
+ * @return An array of strings to be joined and executed by the shell
+ */
+ private static String[] buildScript() {
+ //TODO: Take care of this in the next release. For now only the guru mode is sent
+ ArrayList<String> cmdList = new ArrayList<>();
+ String[] script;
+
+ if (flags.length() > 0){
+ cmdList.add(flags);
+ }
+
+ //Execute a binary
+ if (needsToSendCommand){
+ if (binaryArguments.length() < 1){
+ cmdList.add("-c '" + binaryPath + "'"); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ cmdList.add("-c \"" + binaryPath + " " + binaryArguments +"\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ }
+
+
+ if (needsArguments) {
+ script = new String[cmdList.size() + 3];
+ script[script.length-2] = scriptPath;
+ script[script.length-1] = arguments;
+ } else {
+ script = new String[cmdList.size() + 2];
+ script[script.length-1] = scriptPath;
+ }
+
+ script[0] = command;
+
+ for(int i=0; i< cmdList.size(); i++) {
+ if (cmdList.get(i) != null) {
+ script[i +1] = cmdList.get(i);
+ } else {
+ script[i + 1] = ""; //$NON-NLS-1$
+ }
+ }
+ return script;
+
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapErrorHandler.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapErrorHandler.java
index be0cc1c0f1..d90b4ae2bf 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapErrorHandler.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapErrorHandler.java
@@ -56,35 +56,35 @@ public class SystemTapErrorHandler {
try (BufferedReader buff1 = new BufferedReader(new FileReader(file))) {
String line;
for (String message : errorsList) {
- try (BufferedReader innerBuff = new BufferedReader(
- new FileReader(file))) {
- while ((line = innerBuff.readLine()) != null) {
- if (m != null && m.isCanceled()) {
- return;
- }
- int index = line.indexOf('=');
- Pattern pat = Pattern.compile(line.substring(0, index),
- Pattern.DOTALL);
- Matcher matcher = pat.matcher(message);
-
- if (matcher.matches()) {
- if (!isErrorRecognized()) {
- // First error
- errorMessage
- .append(Messages
- .getString("SystemTapErrorHandler.ErrorMessage2")); //$NON-NLS-1$
- errorRecognized = true;
- }
- String errorFound = line.substring(index + 1);
-
- if (!errorMessage.toString().contains(errorFound)) {
- errorMessage.append(errorFound
- + PluginConstants.NEW_LINE);
- }
- break;
- }
- }
- }
+ try (BufferedReader innerBuff = new BufferedReader(
+ new FileReader(file))) {
+ while ((line = innerBuff.readLine()) != null) {
+ if (m != null && m.isCanceled()) {
+ return;
+ }
+ int index = line.indexOf('=');
+ Pattern pat = Pattern.compile(line.substring(0, index),
+ Pattern.DOTALL);
+ Matcher matcher = pat.matcher(message);
+
+ if (matcher.matches()) {
+ if (!isErrorRecognized()) {
+ // First error
+ errorMessage
+ .append(Messages
+ .getString("SystemTapErrorHandler.ErrorMessage2")); //$NON-NLS-1$
+ errorRecognized = true;
+ }
+ String errorFound = line.substring(index + 1);
+
+ if (!errorMessage.toString().contains(errorFound)) {
+ errorMessage.append(errorFound
+ + PluginConstants.NEW_LINE);
+ }
+ break;
+ }
+ }
+ }
}
logContents.append(errors);
@@ -148,8 +148,8 @@ public class SystemTapErrorHandler {
* time.
*/
private void writeToLog() {
- IStatus status = new Status(IStatus.ERROR,CallgraphCorePlugin.PLUGIN_ID,logContents.toString());
- CallgraphCorePlugin.getDefault().getLog().log(status);
+ IStatus status = new Status(IStatus.ERROR,CallgraphCorePlugin.PLUGIN_ID,logContents.toString());
+ CallgraphCorePlugin.getDefault().getLog().log(status);
logContents = new StringBuilder();
}
@@ -166,6 +166,6 @@ public class SystemTapErrorHandler {
* @return The error message string
*/
public String getErrorMessage(){
- return errorMessage.toString();
+ return errorMessage.toString();
}
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapParser.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapParser.java
index 7356689d6a..e558a220a0 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapParser.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapParser.java
@@ -22,309 +22,309 @@ import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
public abstract class SystemTapParser extends Job {
- protected IProgressMonitor monitor;
- protected String sourcePath;
- protected String viewID;
- protected SystemTapView view;
- protected boolean realTime = false;
- protected Object data;
- protected Object internalData;
- private String secondaryID = ""; //$NON-NLS-1$
-
- public boolean done;
-
- public SystemTapParser() {
- super("Parsing data"); //$NON-NLS-1$
- this.sourcePath = PluginConstants.getDefaultIOPath();
- this.viewID = null;
- initialize();
- done = false;
-
- //PURELY FOR TESTING
- if (monitor == null){
- monitor = new NullProgressMonitor();
- }
- }
-
-
- public SystemTapParser(String name, String filePath) {
- super(name);
- // BY DEFAULT READ/WRITE FROM HERE
- if (filePath != null) {
- this.sourcePath = filePath;
- } else {
- this.sourcePath = PluginConstants.getDefaultIOPath();
- }
- this.viewID = null;
- initialize();
- }
-
-
- /**
- * Initialize will be called in the constructors for this class. Use this
- * method to initialize variables.
- */
- protected abstract void initialize();
-
-
- /**
- * Implement this method to execute parsing. The return from
- * executeParsing() will be the return value of the run command.
- *
- * SystemTapParser will call executeParsing() within its run method. (i.e.
- * will execute in a separate, non-UI thread)
- *
- * @return
- */
- public abstract IStatus nonRealTimeParsing();
-
-
- /**
- * Implement this method if your parser is to execute in realtime. This method
- * will be called as part of a while loop in a separate Job. Use the setInternalData
- * method to initialize some data object for use in realTimeParsing. The default
- * setInternalMethod method will set internalData to a BufferedReader
- * <br> <br>
- * After the isDone flag is set to true, the realTimeParsing() method will
- * be run one more time to catch any stragglers.
- */
- public abstract IStatus realTimeParsing();
-
-
- /**
- * Cleans names of form 'name").return', returning just the name
- *
- * @param name
- */
- protected String cleanFunctionName(String name) {
- return name.split("\"")[0]; //$NON-NLS-1$
- }
-
- /**
- * Checks for quotations and brackets in the function name
- *
- * @param name
- */
- protected boolean isFunctionNameClean(String name) {
- if (name.contains("\"") || name.contains(")")) //$NON-NLS-1$ //$NON-NLS-2$
- return false;
- return true;
- }
-
- /**
- * Creates a popup error dialog in a separate UI thread. Dialog title is
- * 'Unexpected symbol,' name is 'ParseError' and body is the specified
- * message.
- *
- * @param message
- */
- protected void parsingError(String message) {
- SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
- Messages.getString("SystemTapParser.ParseErr"), //$NON-NLS-1$
- Messages.getString("SystemTapParser.ErrSymbol"), //$NON-NLS-1$
- message);
- mess.schedule();
- }
-
- /**
- * Load the specified viewID by creating a StapUIJob. Does not return until the StapUIJob has.
- * Returns true if the makeView was successful, false otherwise.
- */
- private boolean makeView() {
- // Create a UIJob to handle the rest
- if (viewID != null && viewID.length() > 0) {
- try {
- StapUIJob uijob = new StapUIJob(
- Messages.getString("StapGraphParser.JobName"), this, viewID); //$NON-NLS-1$
- uijob.schedule();
- uijob.join();
- view = uijob.getViewer();
- return true;
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- return false;
- }
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- // Generate real-time job
- IStatus returnStatus = Status.CANCEL_STATUS;
- this.monitor = monitor;
- if (this.monitor == null) {
- this.monitor = new NullProgressMonitor();
- }
-
- makeView();
- if (realTime) {
- try {
- setInternalData();
- while (!done){
- returnStatus = realTimeParsing();
- if (monitor.isCanceled() || returnStatus == Status.CANCEL_STATUS) {
- done = true;
- return Status.CANCEL_STATUS;
- }
-
- Thread.sleep(500);
- }
- if (!monitor.isCanceled()) returnStatus = realTimeParsing();
- done = true;
- return returnStatus;
- } catch (InterruptedException e) {
- SystemTapUIErrorMessages m = new SystemTapUIErrorMessages(
- Messages.getString("SystemTapParser.InternalData"), //$NON-NLS-1$
- Messages.getString("SystemTapParser.FailedToSetData"), //$NON-NLS-1$
- Messages.getString("SystemTapParser.FailedToSetDataMessage")); //$NON-NLS-1$
- m.schedule();
- return Status.CANCEL_STATUS;
- } catch (FileNotFoundException e) {
- SystemTapUIErrorMessages m = new SystemTapUIErrorMessages(
- Messages.getString("SystemTapParser.InternalData"), //$NON-NLS-1$
- Messages.getString("SystemTapParser.FailedToSetData"), //$NON-NLS-1$
- Messages.getString("SystemTapParser.FailedToSetDataMessage")); //$NON-NLS-1$
- m.schedule();
- return Status.CANCEL_STATUS;
- }
- } else {
- returnStatus = nonRealTimeParsing();
- if (!returnStatus.isOK()){
- return returnStatus;
- }
-
- setData(this);
- return returnStatus;
- }
-
- }
-
- /**
- * For easier JUnit testing only. Allows public access to run method without
- * scheduling an extra job.
- *
- * @param m
- * @return
- */
- public IStatus testRun(IProgressMonitor m, boolean realTime) {
- try {
- internalData = new BufferedReader(new FileReader(new File(
- sourcePath)));
- if (realTime) {
- return realTimeParsing();
- } else {
- return nonRealTimeParsing();
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- return Status.CANCEL_STATUS;
- }
-
-
- /**
- * @return the Data object
- */
- public Object getData() {
- return data;
- }
-
- /**
- * Generic method for setting the internalData object. This will be called
- * by a real-time-parser immediately before its main polling loop. By default,
- * this method will attempt to create a bufferedReader around File(filePath)
- * @throws FileNotFoundException
- */
- protected void setInternalData() throws FileNotFoundException {
- File file = new File(sourcePath);
- internalData = new BufferedReader(new FileReader(file));
- }
-
- /**
- * Gets the file to read from
- *
- * @return
- */
- public String getFile() {
- return sourcePath;
- }
-
- /**
- * Sets the file to read from
- *
- * @param source
- */
- public void setSourcePath(String source) {
- this.sourcePath = source;
- }
-
- /**
- * Will terminate the parser at the next opportunity (~once every 0.5s)s
- *
- * @param val
- */
- public void setDone(boolean val) {
- done = val;
- }
-
- public void setMonitor(IProgressMonitor m) {
- this.monitor = m;
- }
-
- /**
- * Set whether or not this parser runs in real time. If viewID has already
- * been set, this will also attempt to open the view.
- */
- public void setRealTime(boolean val) {
- realTime = val;
-
- }
-
- /**
- * Set the viewID to use for this parser -- see the callgraph.core view
- * extension point. If realTime is set to true, this will also attempt to
- * open the view.
- */
- public void setViewID(String value) {
- viewID = value;
- }
-
- /**
- * Called at the end of a non-realtime run.
- * Feel free to override this method if using non-realtime functions.
- * The setData method will be called after executeParsing() is run.
- * The getData() method will be used by the SystemTapView to get the
- * data associated with this parser.
- * <br><br>
- * Alternatively, you can cast the parser within SystemTapView to your
- * own parser class and access its data structures that way.
- */
- public void setData(Object obj) {
- data = obj;
- }
-
- /**
- * Sends a message to cancel the job. Job may not terminate immediately.
- */
- public void cancelJob() {
- done = true;
- }
-
- public boolean isDone() {
- return done;
- }
-
- public void setKillButtonEnabled(boolean val) {
- if (view != null) {
- view.setKillButtonEnabled(val);
- }
- }
-
- public void setSecondaryID(String secondaryID) {
- this.secondaryID = secondaryID;
- }
-
- public String getSecondaryID() {
- return secondaryID;
- }
+ protected IProgressMonitor monitor;
+ protected String sourcePath;
+ protected String viewID;
+ protected SystemTapView view;
+ protected boolean realTime = false;
+ protected Object data;
+ protected Object internalData;
+ private String secondaryID = ""; //$NON-NLS-1$
+
+ public boolean done;
+
+ public SystemTapParser() {
+ super("Parsing data"); //$NON-NLS-1$
+ this.sourcePath = PluginConstants.getDefaultIOPath();
+ this.viewID = null;
+ initialize();
+ done = false;
+
+ //PURELY FOR TESTING
+ if (monitor == null){
+ monitor = new NullProgressMonitor();
+ }
+ }
+
+
+ public SystemTapParser(String name, String filePath) {
+ super(name);
+ // BY DEFAULT READ/WRITE FROM HERE
+ if (filePath != null) {
+ this.sourcePath = filePath;
+ } else {
+ this.sourcePath = PluginConstants.getDefaultIOPath();
+ }
+ this.viewID = null;
+ initialize();
+ }
+
+
+ /**
+ * Initialize will be called in the constructors for this class. Use this
+ * method to initialize variables.
+ */
+ protected abstract void initialize();
+
+
+ /**
+ * Implement this method to execute parsing. The return from
+ * executeParsing() will be the return value of the run command.
+ *
+ * SystemTapParser will call executeParsing() within its run method. (i.e.
+ * will execute in a separate, non-UI thread)
+ *
+ * @return
+ */
+ public abstract IStatus nonRealTimeParsing();
+
+
+ /**
+ * Implement this method if your parser is to execute in realtime. This method
+ * will be called as part of a while loop in a separate Job. Use the setInternalData
+ * method to initialize some data object for use in realTimeParsing. The default
+ * setInternalMethod method will set internalData to a BufferedReader
+ * <br> <br>
+ * After the isDone flag is set to true, the realTimeParsing() method will
+ * be run one more time to catch any stragglers.
+ */
+ public abstract IStatus realTimeParsing();
+
+
+ /**
+ * Cleans names of form 'name").return', returning just the name
+ *
+ * @param name
+ */
+ protected String cleanFunctionName(String name) {
+ return name.split("\"")[0]; //$NON-NLS-1$
+ }
+
+ /**
+ * Checks for quotations and brackets in the function name
+ *
+ * @param name
+ */
+ protected boolean isFunctionNameClean(String name) {
+ if (name.contains("\"") || name.contains(")")) //$NON-NLS-1$ //$NON-NLS-2$
+ return false;
+ return true;
+ }
+
+ /**
+ * Creates a popup error dialog in a separate UI thread. Dialog title is
+ * 'Unexpected symbol,' name is 'ParseError' and body is the specified
+ * message.
+ *
+ * @param message
+ */
+ protected void parsingError(String message) {
+ SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
+ Messages.getString("SystemTapParser.ParseErr"), //$NON-NLS-1$
+ Messages.getString("SystemTapParser.ErrSymbol"), //$NON-NLS-1$
+ message);
+ mess.schedule();
+ }
+
+ /**
+ * Load the specified viewID by creating a StapUIJob. Does not return until the StapUIJob has.
+ * Returns true if the makeView was successful, false otherwise.
+ */
+ private boolean makeView() {
+ // Create a UIJob to handle the rest
+ if (viewID != null && viewID.length() > 0) {
+ try {
+ StapUIJob uijob = new StapUIJob(
+ Messages.getString("StapGraphParser.JobName"), this, viewID); //$NON-NLS-1$
+ uijob.schedule();
+ uijob.join();
+ view = uijob.getViewer();
+ return true;
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ return false;
+ }
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ // Generate real-time job
+ IStatus returnStatus = Status.CANCEL_STATUS;
+ this.monitor = monitor;
+ if (this.monitor == null) {
+ this.monitor = new NullProgressMonitor();
+ }
+
+ makeView();
+ if (realTime) {
+ try {
+ setInternalData();
+ while (!done){
+ returnStatus = realTimeParsing();
+ if (monitor.isCanceled() || returnStatus == Status.CANCEL_STATUS) {
+ done = true;
+ return Status.CANCEL_STATUS;
+ }
+
+ Thread.sleep(500);
+ }
+ if (!monitor.isCanceled()) returnStatus = realTimeParsing();
+ done = true;
+ return returnStatus;
+ } catch (InterruptedException e) {
+ SystemTapUIErrorMessages m = new SystemTapUIErrorMessages(
+ Messages.getString("SystemTapParser.InternalData"), //$NON-NLS-1$
+ Messages.getString("SystemTapParser.FailedToSetData"), //$NON-NLS-1$
+ Messages.getString("SystemTapParser.FailedToSetDataMessage")); //$NON-NLS-1$
+ m.schedule();
+ return Status.CANCEL_STATUS;
+ } catch (FileNotFoundException e) {
+ SystemTapUIErrorMessages m = new SystemTapUIErrorMessages(
+ Messages.getString("SystemTapParser.InternalData"), //$NON-NLS-1$
+ Messages.getString("SystemTapParser.FailedToSetData"), //$NON-NLS-1$
+ Messages.getString("SystemTapParser.FailedToSetDataMessage")); //$NON-NLS-1$
+ m.schedule();
+ return Status.CANCEL_STATUS;
+ }
+ } else {
+ returnStatus = nonRealTimeParsing();
+ if (!returnStatus.isOK()){
+ return returnStatus;
+ }
+
+ setData(this);
+ return returnStatus;
+ }
+
+ }
+
+ /**
+ * For easier JUnit testing only. Allows public access to run method without
+ * scheduling an extra job.
+ *
+ * @param m
+ * @return
+ */
+ public IStatus testRun(IProgressMonitor m, boolean realTime) {
+ try {
+ internalData = new BufferedReader(new FileReader(new File(
+ sourcePath)));
+ if (realTime) {
+ return realTimeParsing();
+ } else {
+ return nonRealTimeParsing();
+ }
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ }
+ return Status.CANCEL_STATUS;
+ }
+
+
+ /**
+ * @return the Data object
+ */
+ public Object getData() {
+ return data;
+ }
+
+ /**
+ * Generic method for setting the internalData object. This will be called
+ * by a real-time-parser immediately before its main polling loop. By default,
+ * this method will attempt to create a bufferedReader around File(filePath)
+ * @throws FileNotFoundException
+ */
+ protected void setInternalData() throws FileNotFoundException {
+ File file = new File(sourcePath);
+ internalData = new BufferedReader(new FileReader(file));
+ }
+
+ /**
+ * Gets the file to read from
+ *
+ * @return
+ */
+ public String getFile() {
+ return sourcePath;
+ }
+
+ /**
+ * Sets the file to read from
+ *
+ * @param source
+ */
+ public void setSourcePath(String source) {
+ this.sourcePath = source;
+ }
+
+ /**
+ * Will terminate the parser at the next opportunity (~once every 0.5s)s
+ *
+ * @param val
+ */
+ public void setDone(boolean val) {
+ done = val;
+ }
+
+ public void setMonitor(IProgressMonitor m) {
+ this.monitor = m;
+ }
+
+ /**
+ * Set whether or not this parser runs in real time. If viewID has already
+ * been set, this will also attempt to open the view.
+ */
+ public void setRealTime(boolean val) {
+ realTime = val;
+
+ }
+
+ /**
+ * Set the viewID to use for this parser -- see the callgraph.core view
+ * extension point. If realTime is set to true, this will also attempt to
+ * open the view.
+ */
+ public void setViewID(String value) {
+ viewID = value;
+ }
+
+ /**
+ * Called at the end of a non-realtime run.
+ * Feel free to override this method if using non-realtime functions.
+ * The setData method will be called after executeParsing() is run.
+ * The getData() method will be used by the SystemTapView to get the
+ * data associated with this parser.
+ * <br><br>
+ * Alternatively, you can cast the parser within SystemTapView to your
+ * own parser class and access its data structures that way.
+ */
+ public void setData(Object obj) {
+ data = obj;
+ }
+
+ /**
+ * Sends a message to cancel the job. Job may not terminate immediately.
+ */
+ public void cancelJob() {
+ done = true;
+ }
+
+ public boolean isDone() {
+ return done;
+ }
+
+ public void setKillButtonEnabled(boolean val) {
+ if (view != null) {
+ view.setKillButtonEnabled(val);
+ }
+ }
+
+ public void setSecondaryID(String secondaryID) {
+ this.secondaryID = secondaryID;
+ }
+
+ public String getSecondaryID() {
+ return secondaryID;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapTextParser.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapTextParser.java
index c658ee2f70..14ee480726 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapTextParser.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapTextParser.java
@@ -18,47 +18,47 @@ import org.eclipse.core.runtime.Status;
public class SystemTapTextParser extends SystemTapParser{
- protected String contents;
+ protected String contents;
- @Override
- public IStatus nonRealTimeParsing() {
- contents = Helper.readFile(sourcePath);
- System.out.println(contents);
- return Status.OK_STATUS;
- }
+ @Override
+ public IStatus nonRealTimeParsing() {
+ contents = Helper.readFile(sourcePath);
+ System.out.println(contents);
+ return Status.OK_STATUS;
+ }
- @Override
- protected void initialize() {
- // Empty
- }
+ @Override
+ protected void initialize() {
+ // Empty
+ }
- @Override
- public IStatus realTimeParsing() {
- if (!(internalData instanceof BufferedReader)) {
- return Status.CANCEL_STATUS;
- }
+ @Override
+ public IStatus realTimeParsing() {
+ if (!(internalData instanceof BufferedReader)) {
+ return Status.CANCEL_STATUS;
+ }
- BufferedReader buff = (BufferedReader) internalData;
- StringBuffer text = new StringBuffer();
+ BufferedReader buff = (BufferedReader) internalData;
+ StringBuffer text = new StringBuffer();
- String line;
- try {
- while ((line = buff.readLine()) != null) {
- if (monitor.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
- text.append(line + "\n"); //$NON-NLS-1$
- }
- setData(text.toString());
- if (text.length() > 0) {
- System.out.println(text.toString());
- }
- view.update();
- } catch (IOException|InterruptedException e) {
- e.printStackTrace();
- }
+ String line;
+ try {
+ while ((line = buff.readLine()) != null) {
+ if (monitor.isCanceled()) {
+ return Status.CANCEL_STATUS;
+ }
+ text.append(line + "\n"); //$NON-NLS-1$
+ }
+ setData(text.toString());
+ if (text.length() > 0) {
+ System.out.println(text.toString());
+ }
+ view.update();
+ } catch (IOException|InterruptedException e) {
+ e.printStackTrace();
+ }
- return Status.OK_STATUS;
- }
+ return Status.OK_STATUS;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapTextView.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapTextView.java
index 493cc5e707..b646b14162 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapTextView.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapTextView.java
@@ -26,209 +26,209 @@ import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
public class SystemTapTextView extends SystemTapView {
- private StyledText viewer;
-
- private Display display;
- private int previousEnd;
-
-
- /**
- * Passing the focus request to the viewer's control.
- */
- @Override
- public void setFocus() {
- if (viewer != null && !viewer.isDisposed()) {
- viewer.setFocus();
- }
- }
-
- private void createViewer(Composite parent) {
- viewer = new StyledText(parent, SWT.READ_ONLY | SWT.MULTI
- | SWT.V_SCROLL | SWT.WRAP);
-
- viewer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Font font = new Font(parent.getDisplay(), "Monospace", 11, SWT.NORMAL); //$NON-NLS-1$
- viewer.setFont(font);
- masterComposite = parent;
- display = masterComposite.getDisplay();
- }
-
- /**
- * Print with colour codes. Colour codes accepted in the form of ~(R,G,B)~,
- * and apply for the rest of the line or until another code is encountered
- * @param text
- */
- private void prettyPrintln(String text) {
- List<StyleRange> styles = new ArrayList<>();
- String[] txt = text.split("\\n"); //$NON-NLS-1$
- int lineOffset = 0;
- int inLineOffset;
-
- // txt[] contains text, with one entry for each new line
- for (String line: txt) {
-
- // Skip blank strings
- if (line.isEmpty()) {
- viewer.append(PluginConstants.NEW_LINE);
- continue;
- }
-
- // Search for colour codes, if none exist then continue
- String[] split_txt = line.split("~\\("); //$NON-NLS-1$
- if (split_txt.length == 1) {
- viewer.append(split_txt[0]);
- viewer.append(PluginConstants.NEW_LINE);
- continue;
- }
-
- inLineOffset = 0;
- for (String split: split_txt) {
- // Skip blank substrings
- if (split.isEmpty()) {
- continue;
- }
-
- // Split for the number codes
- String[] coloursAndText = split.split("\\)~"); //$NON-NLS-1$
-
- // If the string is properly formatted, colours should be length
- // 2
- // If it is not properly formatted, don't colour (just print)
- if (coloursAndText.length != 2) {
- for (String colourAndText: coloursAndText) {
- viewer.append(colourAndText);
- inLineOffset += colourAndText.length();
- }
- continue;
- }
-
- // The first element in the array should contain the colours
- String[] colours = coloursAndText[0].split(","); //$NON-NLS-1$
- if (colours.length < 3) {
- continue;
- }
-
- // The second element in the array should contain the text
- viewer.append(coloursAndText[1]);
-
- // Create a colour based on the 3 integers (if there are any
- // more integers, just ignore)
- int R = new Integer(colours[0].replaceAll(" ", "")).intValue(); //$NON-NLS-1$ //$NON-NLS-2$
- int G = new Integer(colours[1].replaceAll(" ", "")).intValue(); //$NON-NLS-1$ //$NON-NLS-2$
- int B = new Integer(colours[2].replaceAll(" ", "")).intValue(); //$NON-NLS-1$ //$NON-NLS-2$
-
- if (R > 255) R = 255;
- if (G > 255) G = 255;
- if (B > 255) B = 255;
-
- if (R < 0) R = 0;
- if (G < 0) G = 0;
- if (B < 0) B = 0;
-
- Color newColor = new Color(display, R, G, B);
-
- // Find the offset of the current line
- lineOffset = viewer.getOffsetAtLine(viewer.getLineCount() - 1);
-
- // Create a new style that lasts no further than the length of
- // the line
- StyleRange newStyle = new StyleRange(lineOffset + inLineOffset,
- coloursAndText[1].length(), newColor, null);
- styles.add(newStyle);
-
- inLineOffset += coloursAndText[1].length();
- }
-
- viewer.append(PluginConstants.NEW_LINE);
- }
-
- // Create a new style range
- StyleRange[] s = new StyleRange[styles.size()];
- styles.toArray(s);
-
- int cnt = viewer.getCharCount();
-
- // Using replaceStyleRanges with previousEnd, etc, effectively adds
- // the StyleRange to the existing set of Style Ranges (so we don't
- // waste time fudging with old style ranges that haven't changed)
- viewer.replaceStyleRanges(previousEnd, cnt - previousEnd, s);
- previousEnd = cnt;
-
- // Change focus and update
- viewer.setTopIndex(viewer.getLineCount() - 1);
- viewer.update();
- }
-
- /**
- * Default print, just dumps text into the viewer.
- * @param text
- */
- public void println(String text) {
- if (viewer != null && !viewer.isDisposed()) {
- viewer.append(text);
- viewer.setTopIndex(viewer.getLineCount() - 1);
- viewer.update();
- }
- }
-
- public void clearAll() {
- if (viewer != null && !viewer.isDisposed()) {
- previousEnd = 0;
- viewer.setText(""); //$NON-NLS-1$
- viewer.update();
- }
- }
-
- /**
- * Testing convenience method to see what was printed
- *
- * @return viewer text
- */
- public String getText() {
- return viewer.getText();
- }
-
-
- @Override
- public IStatus initializeView(Display targetDisplay, IProgressMonitor monitor) {
- previousEnd = 0;
- viewer.setText(""); //$NON-NLS-1$
- viewer.update();
- return Status.OK_STATUS;
- }
-
- @Override
- public void createPartControl(Composite parent) {
- createViewer(parent);
-
- addKillButton();
- addFileMenu();
- addHelpMenu();
- ViewFactory.addView(this);
- }
-
- @Override
- public void updateMethod() {
- if (getParser().getData() instanceof String) {
- String data = (String) getParser().getData();
- if (data.length() > 0) {
- prettyPrintln((String) getParser().getData());
- }
- }
- }
-
- @Override
- public void setViewID() {
- viewID = "org.eclipse.linuxtools.callgraph.core.staptextview"; //$NON-NLS-1$
- }
-
- @Override
- protected boolean createOpenAction() {
- return false;
- }
-
- @Override
- protected boolean createOpenDefaultAction() {
- return false;
- }
+ private StyledText viewer;
+
+ private Display display;
+ private int previousEnd;
+
+
+ /**
+ * Passing the focus request to the viewer's control.
+ */
+ @Override
+ public void setFocus() {
+ if (viewer != null && !viewer.isDisposed()) {
+ viewer.setFocus();
+ }
+ }
+
+ private void createViewer(Composite parent) {
+ viewer = new StyledText(parent, SWT.READ_ONLY | SWT.MULTI
+ | SWT.V_SCROLL | SWT.WRAP);
+
+ viewer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ Font font = new Font(parent.getDisplay(), "Monospace", 11, SWT.NORMAL); //$NON-NLS-1$
+ viewer.setFont(font);
+ masterComposite = parent;
+ display = masterComposite.getDisplay();
+ }
+
+ /**
+ * Print with colour codes. Colour codes accepted in the form of ~(R,G,B)~,
+ * and apply for the rest of the line or until another code is encountered
+ * @param text
+ */
+ private void prettyPrintln(String text) {
+ List<StyleRange> styles = new ArrayList<>();
+ String[] txt = text.split("\\n"); //$NON-NLS-1$
+ int lineOffset = 0;
+ int inLineOffset;
+
+ // txt[] contains text, with one entry for each new line
+ for (String line: txt) {
+
+ // Skip blank strings
+ if (line.isEmpty()) {
+ viewer.append(PluginConstants.NEW_LINE);
+ continue;
+ }
+
+ // Search for colour codes, if none exist then continue
+ String[] split_txt = line.split("~\\("); //$NON-NLS-1$
+ if (split_txt.length == 1) {
+ viewer.append(split_txt[0]);
+ viewer.append(PluginConstants.NEW_LINE);
+ continue;
+ }
+
+ inLineOffset = 0;
+ for (String split: split_txt) {
+ // Skip blank substrings
+ if (split.isEmpty()) {
+ continue;
+ }
+
+ // Split for the number codes
+ String[] coloursAndText = split.split("\\)~"); //$NON-NLS-1$
+
+ // If the string is properly formatted, colours should be length
+ // 2
+ // If it is not properly formatted, don't colour (just print)
+ if (coloursAndText.length != 2) {
+ for (String colourAndText: coloursAndText) {
+ viewer.append(colourAndText);
+ inLineOffset += colourAndText.length();
+ }
+ continue;
+ }
+
+ // The first element in the array should contain the colours
+ String[] colours = coloursAndText[0].split(","); //$NON-NLS-1$
+ if (colours.length < 3) {
+ continue;
+ }
+
+ // The second element in the array should contain the text
+ viewer.append(coloursAndText[1]);
+
+ // Create a colour based on the 3 integers (if there are any
+ // more integers, just ignore)
+ int R = new Integer(colours[0].replaceAll(" ", "")).intValue(); //$NON-NLS-1$ //$NON-NLS-2$
+ int G = new Integer(colours[1].replaceAll(" ", "")).intValue(); //$NON-NLS-1$ //$NON-NLS-2$
+ int B = new Integer(colours[2].replaceAll(" ", "")).intValue(); //$NON-NLS-1$ //$NON-NLS-2$
+
+ if (R > 255) R = 255;
+ if (G > 255) G = 255;
+ if (B > 255) B = 255;
+
+ if (R < 0) R = 0;
+ if (G < 0) G = 0;
+ if (B < 0) B = 0;
+
+ Color newColor = new Color(display, R, G, B);
+
+ // Find the offset of the current line
+ lineOffset = viewer.getOffsetAtLine(viewer.getLineCount() - 1);
+
+ // Create a new style that lasts no further than the length of
+ // the line
+ StyleRange newStyle = new StyleRange(lineOffset + inLineOffset,
+ coloursAndText[1].length(), newColor, null);
+ styles.add(newStyle);
+
+ inLineOffset += coloursAndText[1].length();
+ }
+
+ viewer.append(PluginConstants.NEW_LINE);
+ }
+
+ // Create a new style range
+ StyleRange[] s = new StyleRange[styles.size()];
+ styles.toArray(s);
+
+ int cnt = viewer.getCharCount();
+
+ // Using replaceStyleRanges with previousEnd, etc, effectively adds
+ // the StyleRange to the existing set of Style Ranges (so we don't
+ // waste time fudging with old style ranges that haven't changed)
+ viewer.replaceStyleRanges(previousEnd, cnt - previousEnd, s);
+ previousEnd = cnt;
+
+ // Change focus and update
+ viewer.setTopIndex(viewer.getLineCount() - 1);
+ viewer.update();
+ }
+
+ /**
+ * Default print, just dumps text into the viewer.
+ * @param text
+ */
+ public void println(String text) {
+ if (viewer != null && !viewer.isDisposed()) {
+ viewer.append(text);
+ viewer.setTopIndex(viewer.getLineCount() - 1);
+ viewer.update();
+ }
+ }
+
+ public void clearAll() {
+ if (viewer != null && !viewer.isDisposed()) {
+ previousEnd = 0;
+ viewer.setText(""); //$NON-NLS-1$
+ viewer.update();
+ }
+ }
+
+ /**
+ * Testing convenience method to see what was printed
+ *
+ * @return viewer text
+ */
+ public String getText() {
+ return viewer.getText();
+ }
+
+
+ @Override
+ public IStatus initializeView(Display targetDisplay, IProgressMonitor monitor) {
+ previousEnd = 0;
+ viewer.setText(""); //$NON-NLS-1$
+ viewer.update();
+ return Status.OK_STATUS;
+ }
+
+ @Override
+ public void createPartControl(Composite parent) {
+ createViewer(parent);
+
+ addKillButton();
+ addFileMenu();
+ addHelpMenu();
+ ViewFactory.addView(this);
+ }
+
+ @Override
+ public void updateMethod() {
+ if (getParser().getData() instanceof String) {
+ String data = (String) getParser().getData();
+ if (data.length() > 0) {
+ prettyPrintln((String) getParser().getData());
+ }
+ }
+ }
+
+ @Override
+ public void setViewID() {
+ viewID = "org.eclipse.linuxtools.callgraph.core.staptextview"; //$NON-NLS-1$
+ }
+
+ @Override
+ protected boolean createOpenAction() {
+ return false;
+ }
+
+ @Override
+ protected boolean createOpenDefaultAction() {
+ return false;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapUIErrorMessages.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapUIErrorMessages.java
index c7ec1b3bf6..ead7506ca6 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapUIErrorMessages.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapUIErrorMessages.java
@@ -24,35 +24,35 @@ import org.eclipse.ui.progress.UIJob;
*
*/
public class SystemTapUIErrorMessages extends UIJob {
- private String title, message;
- private static boolean active = true;
+ private String title, message;
+ private static boolean active = true;
- public SystemTapUIErrorMessages(String name, String title, String message) {
- super(name);
- this.title = title;
- this.message = message;
- }
+ public SystemTapUIErrorMessages(String name, String title, String message) {
+ super(name);
+ this.title = title;
+ this.message = message;
+ }
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- if (!active) {
- return Status.CANCEL_STATUS;
- }
- //Test that this job is running in the UI thread
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ if (!active) {
+ return Status.CANCEL_STATUS;
+ }
+ //Test that this job is running in the UI thread
+ IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window == null) {
- return Status.CANCEL_STATUS; //Something is wrong!
- }
+ if (window == null) {
+ return Status.CANCEL_STATUS; //Something is wrong!
+ }
- Shell sh = new Shell();
+ Shell sh = new Shell();
- MessageDialog.openError(sh, title, message);
- return Status.OK_STATUS;
- }
+ MessageDialog.openError(sh, title, message);
+ return Status.OK_STATUS;
+ }
- public static void setActive(boolean val) {
- active = val;
- }
+ public static void setActive(boolean val) {
+ active = val;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapView.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapView.java
index fd74e61757..5294858310 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapView.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/SystemTapView.java
@@ -140,7 +140,7 @@ public abstract class SystemTapView extends ViewPart {
* @return
*/
public SystemTapParser getParser() {
- return parser;
+ return parser;
}
/**
@@ -152,11 +152,11 @@ public abstract class SystemTapView extends ViewPart {
* @return
*/
public boolean setParser(SystemTapParser parser) {
- this.parser = parser;
- if (this.parser == null) {
- return false;
+ this.parser = parser;
+ if (this.parser == null) {
+ return false;
}
- return true;
+ return true;
}
/**
@@ -231,9 +231,9 @@ public abstract class SystemTapView extends ViewPart {
private void createHelpActions() {
helpVersion = new Action(Messages.getString("SystemTapView.Version")) { //$NON-NLS-1$
@Override
- public void run() {
+ public void run() {
try {
- Process pr = RuntimeProcessFactory.getFactory().exec("stap -V", null); //$NON-NLS-1$
+ Process pr = RuntimeProcessFactory.getFactory().exec("stap -V", null); //$NON-NLS-1$
BufferedReader buf = new BufferedReader(
new InputStreamReader(pr.getErrorStream()));
String line = ""; //$NON-NLS-1$
@@ -265,7 +265,7 @@ public abstract class SystemTapView extends ViewPart {
//Save callgraph.out
saveFile = new Action(Messages.getString("SystemTapView.SaveMenu")){ //$NON-NLS-1$
@Override
- public void run(){
+ public void run(){
Shell sh = new Shell();
FileDialog dialog = new FileDialog(sh, SWT.SAVE);
String filePath = dialog.open();
@@ -283,7 +283,7 @@ public abstract class SystemTapView extends ViewPart {
kill = new Action(Messages.getString("SystemTapView.StopScript"), //$NON-NLS-1$
AbstractUIPlugin.imageDescriptorFromPlugin(CallgraphCorePlugin.PLUGIN_ID, "icons/progress_stop.gif")) { //$NON-NLS-1$
@Override
- public void run() {
+ public void run() {
getParser().cancelJob();
}
};
@@ -306,33 +306,33 @@ public abstract class SystemTapView extends ViewPart {
* @param sourcePath
*/
public void saveData(String targetFile) {
- try {
- File file = new File(targetFile);
- file.delete();
- file.createNewFile();
-
- File sFile = new File(sourcePath);
- if (!sFile.exists()) {
- return;
- }
-
- try (FileInputStream fileIn = new FileInputStream(sFile); FileOutputStream fileOut = new FileOutputStream(file);
- FileChannel channelIn = fileIn.getChannel(); FileChannel channelOut = fileOut.getChannel()){
-
- if (channelIn == null || channelOut == null) {
- return;
- }
-
- long size = channelIn.size();
- MappedByteBuffer buf = channelIn.map(
- FileChannel.MapMode.READ_ONLY, 0, size);
-
- channelOut.write(buf);
- }
- } catch (IOException e) {
- CallgraphCorePlugin.logException(e);
- }
- }
+ try {
+ File file = new File(targetFile);
+ file.delete();
+ file.createNewFile();
+
+ File sFile = new File(sourcePath);
+ if (!sFile.exists()) {
+ return;
+ }
+
+ try (FileInputStream fileIn = new FileInputStream(sFile); FileOutputStream fileOut = new FileOutputStream(file);
+ FileChannel channelIn = fileIn.getChannel(); FileChannel channelOut = fileOut.getChannel()){
+
+ if (channelIn == null || channelOut == null) {
+ return;
+ }
+
+ long size = channelIn.size();
+ MappedByteBuffer buf = channelIn.map(
+ FileChannel.MapMode.READ_ONLY, 0, size);
+
+ channelOut.write(buf);
+ }
+ } catch (IOException e) {
+ CallgraphCorePlugin.logException(e);
+ }
+ }
public void setSourcePath(String file) {
sourcePath = file;
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/ViewFactory.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/ViewFactory.java
index 265e98243e..ca31107d83 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/ViewFactory.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/ViewFactory.java
@@ -25,75 +25,75 @@ import org.eclipse.ui.PlatformUI;
*/
public class ViewFactory {
- private static List<IViewPart> views;
- private static SystemTapView newView;
+ private static List<IViewPart> views;
+ private static SystemTapView newView;
- /**
- * Create a view of type designated by the viewID argument
- * @param viewID : A string corresponding to a type of View
- * @return : The view object that corresponds to the viewID
- */
- public static SystemTapView createView(final String viewID) {
- Display.getDefault().syncExec(new Runnable() {
+ /**
+ * Create a view of type designated by the viewID argument
+ * @param viewID : A string corresponding to a type of View
+ * @return : The view object that corresponds to the viewID
+ */
+ public static SystemTapView createView(final String viewID) {
+ Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- try {
- IViewPart view = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage().
- showView(viewID);
- if (!(view instanceof SystemTapView)) {
- return;
- }
+ @Override
+ public void run() {
+ try {
+ IViewPart view = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage().
+ showView(viewID);
+ if (!(view instanceof SystemTapView)) {
+ return;
+ }
- newView = ((SystemTapView) view);
- newView.setViewID();
- } catch (PartInitException e) {
- e.printStackTrace();
- }
- }
- });
+ newView = ((SystemTapView) view);
+ newView.setViewID();
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ }
+ });
- addView(newView);
- return newView;
- }
+ addView(newView);
+ return newView;
+ }
- /**
- * Create a view of type designated by the viewID argument
- * @param viewID : A string corresponding to a type of View
- * @return : The view object that corresponds to the viewID
- */
- public static SystemTapView createView(final String viewID, final String secondaryID) {
- Display.getDefault().syncExec(new Runnable() {
+ /**
+ * Create a view of type designated by the viewID argument
+ * @param viewID : A string corresponding to a type of View
+ * @return : The view object that corresponds to the viewID
+ */
+ public static SystemTapView createView(final String viewID, final String secondaryID) {
+ Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- try {
- IViewPart view = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage().showView(viewID, secondaryID, IWorkbenchPage.VIEW_VISIBLE);
- if (!(view instanceof SystemTapView)) {
- return;
- }
- newView = ((SystemTapView) view);
- newView.setViewID();
- } catch (PartInitException e) {
- e.printStackTrace();
- }
- }
- });
+ @Override
+ public void run() {
+ try {
+ IViewPart view = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage().showView(viewID, secondaryID, IWorkbenchPage.VIEW_VISIBLE);
+ if (!(view instanceof SystemTapView)) {
+ return;
+ }
+ newView = ((SystemTapView) view);
+ newView.setViewID();
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ }
+ });
- addView(newView);
- return newView;
- }
+ addView(newView);
+ return newView;
+ }
- /**
- * Adds a view to the factory's list of active SystemTapViews.
- */
- public static void addView(SystemTapView view) {
- if (views == null) {
- views = new ArrayList<>();
- }
- views.add(view);
- }
+ /**
+ * Adds a view to the factory's list of active SystemTapViews.
+ */
+ public static void addView(SystemTapView view) {
+ if (views == null) {
+ views = new ArrayList<>();
+ }
+ views.add(view);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/XMLParser.java b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/XMLParser.java
index 70d78cf9ad..8f39292c15 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/XMLParser.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.core/src/org/eclipse/linuxtools/internal/callgraph/core/XMLParser.java
@@ -21,168 +21,168 @@ import java.util.Map;
public class XMLParser {
- private Map<Integer, HashMap<String,String>> keyValues;
- private List<Integer> idList;
- private int id;
- private int currentlyIn;
- private static final String ATTR_NAME = "name"; //$NON-NLS-1$
- private static final String ATTR_TEXT = "text"; //$NON-NLS-1$
- private static final String noName = "NoName"; //$NON-NLS-1$
- private boolean textMode;
- XMLParser() {
- id = 0;
- currentlyIn = 0;
- if (keyValues != null) {
- keyValues.clear();
- }
- keyValues = new HashMap<>();
-
- if (idList != null) {
- idList.clear();
- }
- idList = new ArrayList<>();
-
- textMode = false;
- }
-
- /**
- * Helper method to call parse on the contents of a file.
- * @param file
- */
- public void parse(File file) {
- parse(getContents(file));
- }
-
-
- /**
- * Parses a String according to XML formatting rules. Will return a HashMap indexed by an
- * identification number, where each value is a further HashMap of String, String pairs representing
- * attributes.
- * @param message
- */
- public void parse(String message) {
- String tabstrip = message.replaceAll("\t", ""); //$NON-NLS-1$ //$NON-NLS-2$
- String[] lines = tabstrip.split("\n"); //$NON-NLS-1$
-
- for (String line : lines) {
- if (line.length() < 1) {
- continue;
- }
-
- if (line.charAt(0) == '<') {
- //Either an open or close tag
- if (line.charAt(1) == '/') {
- //Closing tag -- assume properly formed
- idList.remove((Integer) currentlyIn);
- currentlyIn = -1;
- if (idList.size() > 0) {
- currentlyIn = idList.get(idList.size()-1);
- }
- setTextMode(true);
-
- } else if (line.substring(line.length()-2, line.length() - 1).equals("/>")) { //$NON-NLS-1$
- //This tag opens and closes in one line
- id++;
- String[] tokens = line.split(" "); //$NON-NLS-1$
- HashMap<String,String> map = new HashMap<>();
- map.put(ATTR_NAME, tokens[0]);
- keyValues.put(id,map);
- textMode = false;
- addAttributes(currentlyIn, tokens, 1);
-
- } else {
- //Open tag
- idList.add(id);
- id++;
- currentlyIn = id;
-
- String[] tokens = line.split(" "); //$NON-NLS-1$
-
- //Add name variable
- HashMap<String,String> map = new HashMap<>();
- map.put(ATTR_NAME, tokens[0]);
- keyValues.put(id,map);
-
- addAttributes(currentlyIn, tokens, 1);
- }
- } else {
- //Attribute addition
- if (currentlyIn < 0 ) {
- continue;
- }
-
- if (textMode) {
- HashMap<String,String> map = keyValues.get(currentlyIn);
- map.put(ATTR_TEXT, line);
- }
-
- String[] tokens = line.split(" "); //$NON-NLS-1$
- addAttributes(currentlyIn, tokens, 0);
- }
- }
- }
-
- /**
- * Turns an array of Strings of form attribute=value into attribute/value pairings for the specified node.
- * Starts looking at token number start.
- * @param tokens
- * @param start
- */
- private void addAttributes(int id, String[] tokens, int start) {
- HashMap<String,String> map = keyValues.get(id);
- int nameless = 0;
-
-
- for (int j = start; j < tokens.length; j++) {
- String[] kvPair = tokens[j].split("="); //$NON-NLS-1$
- String value = ""; //$NON-NLS-1$
- String key = ""; //$NON-NLS-1$
- if (kvPair.length < 1) {
- continue;
- }
-
- if (kvPair.length < 2) {
- value = kvPair[0];
- if (value.charAt(value.length() - 1) == '>') {
-
- setTextMode(true);
- value = value.substring(0, value.length()-1);
- }
- map.put(noName + nameless, value);
- nameless++;
- continue;
- }
-
- value = kvPair[0];
- key = kvPair[1];
- if (value.charAt(value.length() - 1) == '>') {
- setTextMode(true);
- value = value.substring(0, value.length()-1);
- }
-
- map.put(key, value);
- }
-
- keyValues.put(id, map);
- }
-
- private static String getContents(File file) {
- StringBuilder contents = new StringBuilder();
-
- try (BufferedReader input = new BufferedReader(new FileReader(file))) {
- String line = null;
- while ((line = input.readLine()) != null) {
- contents.append(line);
- contents.append("\n"); //$NON-NLS-1$
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
-
- return contents.toString();
- }
-
- private void setTextMode(boolean val) {
- textMode = val;
- }
+ private Map<Integer, HashMap<String,String>> keyValues;
+ private List<Integer> idList;
+ private int id;
+ private int currentlyIn;
+ private static final String ATTR_NAME = "name"; //$NON-NLS-1$
+ private static final String ATTR_TEXT = "text"; //$NON-NLS-1$
+ private static final String noName = "NoName"; //$NON-NLS-1$
+ private boolean textMode;
+ XMLParser() {
+ id = 0;
+ currentlyIn = 0;
+ if (keyValues != null) {
+ keyValues.clear();
+ }
+ keyValues = new HashMap<>();
+
+ if (idList != null) {
+ idList.clear();
+ }
+ idList = new ArrayList<>();
+
+ textMode = false;
+ }
+
+ /**
+ * Helper method to call parse on the contents of a file.
+ * @param file
+ */
+ public void parse(File file) {
+ parse(getContents(file));
+ }
+
+
+ /**
+ * Parses a String according to XML formatting rules. Will return a HashMap indexed by an
+ * identification number, where each value is a further HashMap of String, String pairs representing
+ * attributes.
+ * @param message
+ */
+ public void parse(String message) {
+ String tabstrip = message.replaceAll("\t", ""); //$NON-NLS-1$ //$NON-NLS-2$
+ String[] lines = tabstrip.split("\n"); //$NON-NLS-1$
+
+ for (String line : lines) {
+ if (line.length() < 1) {
+ continue;
+ }
+
+ if (line.charAt(0) == '<') {
+ //Either an open or close tag
+ if (line.charAt(1) == '/') {
+ //Closing tag -- assume properly formed
+ idList.remove((Integer) currentlyIn);
+ currentlyIn = -1;
+ if (idList.size() > 0) {
+ currentlyIn = idList.get(idList.size()-1);
+ }
+ setTextMode(true);
+
+ } else if (line.substring(line.length()-2, line.length() - 1).equals("/>")) { //$NON-NLS-1$
+ //This tag opens and closes in one line
+ id++;
+ String[] tokens = line.split(" "); //$NON-NLS-1$
+ HashMap<String,String> map = new HashMap<>();
+ map.put(ATTR_NAME, tokens[0]);
+ keyValues.put(id,map);
+ textMode = false;
+ addAttributes(currentlyIn, tokens, 1);
+
+ } else {
+ //Open tag
+ idList.add(id);
+ id++;
+ currentlyIn = id;
+
+ String[] tokens = line.split(" "); //$NON-NLS-1$
+
+ //Add name variable
+ HashMap<String,String> map = new HashMap<>();
+ map.put(ATTR_NAME, tokens[0]);
+ keyValues.put(id,map);
+
+ addAttributes(currentlyIn, tokens, 1);
+ }
+ } else {
+ //Attribute addition
+ if (currentlyIn < 0 ) {
+ continue;
+ }
+
+ if (textMode) {
+ HashMap<String,String> map = keyValues.get(currentlyIn);
+ map.put(ATTR_TEXT, line);
+ }
+
+ String[] tokens = line.split(" "); //$NON-NLS-1$
+ addAttributes(currentlyIn, tokens, 0);
+ }
+ }
+ }
+
+ /**
+ * Turns an array of Strings of form attribute=value into attribute/value pairings for the specified node.
+ * Starts looking at token number start.
+ * @param tokens
+ * @param start
+ */
+ private void addAttributes(int id, String[] tokens, int start) {
+ HashMap<String,String> map = keyValues.get(id);
+ int nameless = 0;
+
+
+ for (int j = start; j < tokens.length; j++) {
+ String[] kvPair = tokens[j].split("="); //$NON-NLS-1$
+ String value = ""; //$NON-NLS-1$
+ String key = ""; //$NON-NLS-1$
+ if (kvPair.length < 1) {
+ continue;
+ }
+
+ if (kvPair.length < 2) {
+ value = kvPair[0];
+ if (value.charAt(value.length() - 1) == '>') {
+
+ setTextMode(true);
+ value = value.substring(0, value.length()-1);
+ }
+ map.put(noName + nameless, value);
+ nameless++;
+ continue;
+ }
+
+ value = kvPair[0];
+ key = kvPair[1];
+ if (value.charAt(value.length() - 1) == '>') {
+ setTextMode(true);
+ value = value.substring(0, value.length()-1);
+ }
+
+ map.put(key, value);
+ }
+
+ keyValues.put(id, map);
+ }
+
+ private static String getContents(File file) {
+ StringBuilder contents = new StringBuilder();
+
+ try (BufferedReader input = new BufferedReader(new FileReader(file))) {
+ String line = null;
+ while ((line = input.readLine()) != null) {
+ contents.append(line);
+ contents.append("\n"); //$NON-NLS-1$
+ }
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ }
+
+ return contents.toString();
+ }
+
+ private void setTextMode(boolean val) {
+ textMode = val;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.docs/build-doc.xml b/systemtap/org.eclipse.linuxtools.callgraph.docs/build-doc.xml
index c19d6e84d6..4b6161bf65 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.docs/build-doc.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph.docs/build-doc.xml
@@ -11,62 +11,62 @@
-->
<project name="org.eclipse.mylyn.wikitext.example" default="all">
- <description>
+ <description>
Generate Eclipse help content from the Eclipsepedia wiki
</description>
- <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
- <property name="imageFolder" value="images" />
+ <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
+ <property name="imageFolder" value="images" />
- <path id="wikitext.tasks.classpath">
- <!-- Replace dir with the dir you have wikitext installed into.-->
- <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
- <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
- </fileset>
- </path>
+ <path id="wikitext.tasks.classpath">
+ <!-- Replace dir with the dir you have wikitext installed into.-->
+ <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
+ <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
+ </fileset>
+ </path>
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
- <target name="all" description="Generate Eclipse help content for the Linux Tools Callgraph user guide">
- <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="Callgraph User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
+ <target name="all" description="Generate Eclipse help content for the Linux Tools Callgraph user guide">
+ <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="Callgraph User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*">
- <path name="Linux_Tools_Project/Callgraph/User_Guide" title="Callgraph User Guide" generateToc="false" />
- <stylesheet url="book.css" />
- <pageAppendum>
- = Updating This Document =
+ <path name="Linux_Tools_Project/Callgraph/User_Guide" title="Callgraph User Guide" generateToc="false" />
+ <stylesheet url="book.css" />
+ <pageAppendum>
+ = Updating This Document =
- This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
- http://wiki.eclipse.org/Linux_Tools_Project/Callgraph/User_Guide .
- </pageAppendum>
- </mediawiki-to-eclipse-help>
- <antcall target="test" />
- </target>
+ This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
+ http://wiki.eclipse.org/Linux_Tools_Project/Callgraph/User_Guide .
+ </pageAppendum>
+ </mediawiki-to-eclipse-help>
+ <antcall target="test" />
+ </target>
- <target name="test" description="verify that all of the HTML files are well-formed XML">
- <echo level="info">
+ <target name="test" description="verify that all of the HTML files are well-formed XML">
+ <echo level="info">
Validating help content XML and HTML files: The Eclipse help system expects well-formed XML
-
+
If validation fails it is because either:
-
+
* the userguide source code is poorly formed, or
* the WikiText MediaWiki parser has a bug
-
+
Problems with userguide source are usually caused by improper use of HTML markup in the MediaWiki source,
or inadvertently starting a line with a space character (in MediaWiki this starts a preformatted block)
- </echo>
+ </echo>
- <!--
- Don't bother with DTD validation: we only care if the files are well-formed.
- We therefore provide an empty DTD
- -->
- <echo file="tmp/__empty.dtd" message="" />
- <xmlvalidate lenient="true">
- <fileset dir="Linux_Tools_Project">
- <include name="**/*.html" />
- </fileset>
- <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
- </xmlvalidate>
- <delete dir="tmp" />
- </target>
+ <!--
+ Don't bother with DTD validation: we only care if the files are well-formed.
+ We therefore provide an empty DTD
+ -->
+ <echo file="tmp/__empty.dtd" message="" />
+ <xmlvalidate lenient="true">
+ <fileset dir="Linux_Tools_Project">
+ <include name="**/*.html" />
+ </fileset>
+ <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
+ </xmlvalidate>
+ <delete dir="tmp" />
+ </target>
</project>
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.docs/toc-doc.xml b/systemtap/org.eclipse.linuxtools.callgraph.docs/toc-doc.xml
index 87e0e40bff..03325308b8 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.docs/toc-doc.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph.docs/toc-doc.xml
@@ -1,5 +1,5 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/Callgraph/User_Guide/User-Guide.html" label="Callgraph User Guide">
-<link toc="toc.xml" />
-<topic href="notices.html" label="Legal" />
+<link toc="toc.xml" />
+<topic href="notices.html" label="Legal" />
</toc>
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.docs/toc.xml b/systemtap/org.eclipse.linuxtools.callgraph.docs/toc.xml
index 1431d7206f..e8f26b1f31 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.docs/toc.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph.docs/toc.xml
@@ -1,21 +1,21 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/Callgraph/User_Guide/User-Guide.html" label="Callgraph User Guide">
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/User-Guide.html" label="Callgraph User Guide">
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/User-Guide.html" label="Overview"></topic>
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/Installation.html" label="Installation"></topic>
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage.html" label="General Usage"></topic>
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/Callgraph-Perspectives.html" label="Callgraph Perspectives">
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/Callgraph-Perspectives.html#Radial_View" label="Radial View"></topic>
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/Callgraph-Perspectives.html#Tree_View" label="Tree View"></topic>
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/Callgraph-Perspectives.html#Level_View" label="Level View"></topic>
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/Callgraph-Perspectives.html#Aggregate_View" label="Aggregate View"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage2.html" label="General Usage">
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage2.html#Collapse_Mode" label="Collapse Mode"></topic>
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage2.html#Watching_function_calls_in_chronological_order" label="Watching function calls in chronological order"></topic>
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage2.html#Code_link" label="Code link"></topic>
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage2.html#Save.2Fload_profile_runs" label="Save/load profile runs"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Callgraph/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
- </topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/User-Guide.html" label="Callgraph User Guide">
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/User-Guide.html" label="Overview"></topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/Installation.html" label="Installation"></topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage.html" label="General Usage"></topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/Callgraph-Perspectives.html" label="Callgraph Perspectives">
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/Callgraph-Perspectives.html#Radial_View" label="Radial View"></topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/Callgraph-Perspectives.html#Tree_View" label="Tree View"></topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/Callgraph-Perspectives.html#Level_View" label="Level View"></topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/Callgraph-Perspectives.html#Aggregate_View" label="Aggregate View"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage2.html" label="General Usage">
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage2.html#Collapse_Mode" label="Collapse Mode"></topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage2.html#Watching_function_calls_in_chronological_order" label="Watching function calls in chronological order"></topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage2.html#Code_link" label="Code link"></topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/General-Usage2.html#Save.2Fload_profile_runs" label="Save/load profile runs"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Callgraph/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
+ </topic>
</toc> \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/pom.xml b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/pom.xml
index c462f3b22f..aad27f361f 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/pom.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/pom.xml
@@ -35,7 +35,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.callgraph.launch.tests</testSuite>
<testClass>org.eclipse.linuxtools.callgraph.launch.tests.AllTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.platform.ide</product>
</configuration>
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.jdt.ui/dialog_settings.xml b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.jdt.ui/dialog_settings.xml
index f11bde40cd..13431f198f 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.jdt.ui/dialog_settings.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.jdt.ui/dialog_settings.xml
@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<section name="Workbench">
- <section name="org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart">
- <item value="true" key="group_libraries"/>
- <item value="false" key="linkWithEditor"/>
- <item value="2" key="layout"/>
- <item value="1" key="rootMode"/>
- <item value="&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#x0A;&lt;packageExplorer group_libraries=&quot;1&quot; layout=&quot;2&quot; linkWithEditor=&quot;0&quot; rootMode=&quot;1&quot; workingSetName=&quot;Aggregate for window 1253542278535&quot;&gt;&#x0A;&lt;customFilters userDefinedPatternsEnabled=&quot;false&quot;&gt;&#x0A;&lt;xmlDefinedFilters&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.LibraryFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.LocalTypesFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.StaticsFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.pde.ui.ExternalPluginLibrariesFilter1&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.ClosedProjectsFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.NonSharedProjectsFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.NonJavaElementFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.ContainedLibraryFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.CuAndClassFileFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.NonJavaProjectsFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.internal.ui.PackageExplorer.EmptyInnerPackageFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.PackageDeclarationFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.internal.ui.PackageExplorer.EmptyPackageFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.ImportDeclarationFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.FieldsFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.internal.ui.PackageExplorer.HideInnerClassFilesFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.NonPublicFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer_patternFilterId_.*&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.EmptyLibraryContainerFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.pde.ui.BinaryProjectFilter1&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.SyntheticMembersFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.mylyn.java.ui.MembersFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;/xmlDefinedFilters&gt;&#x0A;&lt;/customFilters&gt;&#x0A;&lt;/packageExplorer&gt;" key="memento"/>
- </section>
+ <section name="org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart">
+ <item value="true" key="group_libraries"/>
+ <item value="false" key="linkWithEditor"/>
+ <item value="2" key="layout"/>
+ <item value="1" key="rootMode"/>
+ <item value="&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&#x0A;&lt;packageExplorer group_libraries=&quot;1&quot; layout=&quot;2&quot; linkWithEditor=&quot;0&quot; rootMode=&quot;1&quot; workingSetName=&quot;Aggregate for window 1253542278535&quot;&gt;&#x0A;&lt;customFilters userDefinedPatternsEnabled=&quot;false&quot;&gt;&#x0A;&lt;xmlDefinedFilters&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.LibraryFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.LocalTypesFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.StaticsFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.pde.ui.ExternalPluginLibrariesFilter1&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.ClosedProjectsFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.NonSharedProjectsFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.NonJavaElementFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.ContainedLibraryFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.CuAndClassFileFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.NonJavaProjectsFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.internal.ui.PackageExplorer.EmptyInnerPackageFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.PackageDeclarationFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.internal.ui.PackageExplorer.EmptyPackageFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.ImportDeclarationFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.FieldsFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.internal.ui.PackageExplorer.HideInnerClassFilesFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.NonPublicFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer_patternFilterId_.*&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.EmptyLibraryContainerFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.pde.ui.BinaryProjectFilter1&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.jdt.ui.PackageExplorer.SyntheticMembersFilter&quot; isEnabled=&quot;true&quot;/&gt;&#x0A;&lt;child filterId=&quot;org.eclipse.mylyn.java.ui.MembersFilter&quot; isEnabled=&quot;false&quot;/&gt;&#x0A;&lt;/xmlDefinedFilters&gt;&#x0A;&lt;/customFilters&gt;&#x0A;&lt;/packageExplorer&gt;" key="memento"/>
+ </section>
</section>
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ltk.ui.refactoring/dialog_settings.xml b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ltk.ui.refactoring/dialog_settings.xml
index 27eb4040f4..d8e25565f4 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ltk.ui.refactoring/dialog_settings.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ltk.ui.refactoring/dialog_settings.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<section name="Workbench">
- <section name="RefactoringWizard.preview">
- <item value="400" key="height"/>
- <item value="600" key="width"/>
- </section>
+ <section name="RefactoringWizard.preview">
+ <item value="400" key="height"/>
+ <item value="600" key="width"/>
+ </section>
</section>
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ui.ide/dialog_settings.xml b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ui.ide/dialog_settings.xml
index eed015db7b..554cbca74e 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ui.ide/dialog_settings.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ui.ide/dialog_settings.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<section name="Workbench">
- <section name="ExternalProjectImportWizard">
- <item value="false" key="WizardProjectsImportPage.STORE_ARCHIVE_SELECTED"/>
- <item value="true" key="WizardProjectsImportPage.STORE_COPY_PROJECT_ID"/>
- </section>
+ <section name="ExternalProjectImportWizard">
+ <item value="false" key="WizardProjectsImportPage.STORE_ARCHIVE_SELECTED"/>
+ <item value="true" key="WizardProjectsImportPage.STORE_COPY_PROJECT_ID"/>
+ </section>
</section>
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ui.workbench/dialog_settings.xml b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ui.workbench/dialog_settings.xml
index 5b583c4bea..7c9d4e8b32 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ui.workbench/dialog_settings.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/resources/.metadata/.plugins/org.eclipse.ui.workbench/dialog_settings.xml
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<section name="Workbench">
- <section name="ImportExportAction">
- </section>
+ <section name="ImportExportAction">
+ </section>
</section>
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/AbstractStapTest.java b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/AbstractStapTest.java
index 6fab0e16ec..f3d3504079 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/AbstractStapTest.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/AbstractStapTest.java
@@ -30,42 +30,42 @@ import org.osgi.framework.FrameworkUtil;
public class AbstractStapTest extends AbstractTest {
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(PluginConstants.CONFIGURATION_TYPE_ID);
- }
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(PluginConstants.CONFIGURATION_TYPE_ID);
+ }
- @Override
- protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- ILaunchConfigurationTab tab = new SystemTapOptionsTab();
- tab.setDefaults(wc);
- }
+ @Override
+ protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ ILaunchConfigurationTab tab = new SystemTapOptionsTab();
+ tab.setDefaults(wc);
+ }
- protected ICProject createProjectAndBuild(String projname) throws Exception {
- return createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), projname);
- }
+ protected ICProject createProjectAndBuild(String projname) throws Exception {
+ return createProjectAndBuild(FrameworkUtil.getBundle(this.getClass()), projname);
+ }
- public void killStap() {
- try {
- RuntimeProcessFactory.getFactory().exec("kill stap", null);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
+ public void killStap() {
+ try {
+ RuntimeProcessFactory.getFactory().exec("kill stap", null);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
- private List<ILaunch> launches;
+ private List<ILaunch> launches;
- @Before
- public void setUp() {
- launches = new ArrayList<>();
- }
+ @Before
+ public void setUp() {
+ launches = new ArrayList<>();
+ }
- @After
- public void tearDown() {
- if (!launches.isEmpty()) {
- DebugPlugin.getDefault().getLaunchManager().removeLaunches(launches.toArray(new ILaunch[launches.size()]));
- launches.clear();
- }
- }
+ @After
+ public void tearDown() {
+ if (!launches.isEmpty()) {
+ DebugPlugin.getDefault().getLaunchManager().removeLaunches(launches.toArray(new ILaunch[launches.size()]));
+ launches.clear();
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/AllTests.java b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/AllTests.java
index bb21b2d9d3..c8cddd4cfd 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/AllTests.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/AllTests.java
@@ -15,7 +15,7 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ SystemTapCommandTest.class, ConfigurationTest.class,
- SystemTapCommandGeneratorTest.class, SystemTapTabTest.class,
- LaunchShortcutsTest.class, SystemTapErrorHandlerTest.class })
+ SystemTapCommandGeneratorTest.class, SystemTapTabTest.class,
+ LaunchShortcutsTest.class, SystemTapErrorHandlerTest.class })
public class AllTests {
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/ConfigurationTest.java b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/ConfigurationTest.java
index d24d0db486..7ebb84f85e 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/ConfigurationTest.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/ConfigurationTest.java
@@ -26,86 +26,86 @@ import org.junit.Test;
public class ConfigurationTest extends AbstractStapTest {
- /**
- * This test checks if the commands sent by SystemTap match exactly the options
- * that are set. Uses the delegate.launch() function.
- *
- * Activates all options!
- * @throws CoreException
- */
- @Test
- public void testConfig() throws CoreException {
-
- LaunchStapGraph shortcut = new LaunchStapGraph();
-
- String testCDirectives = "-DRandomjunk -DMoreJunk";
- String testOutputPath = "/tmp/ThisFileDoesNothingDeleteIt";
- String testBinaryPath = "/path/to/binary";
- String testScriptPath = "/tmp/NotAScriptFile.stp";
- String testArguments = "/path/to/binary";
- int testPid = 413;
- int testBuffer = 100;
- int testPass = 10;
-
- ILaunchConfiguration config = shortcut.outsideGetLaunchConfigType()
- .newInstance(null, "Temp name");
- ILaunchConfigurationWorkingCopy wc = config
- .copy("Testing configuration");
-
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_VERBOSE, 1);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_KEEP_TEMPORARY,
- true);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_GURU, true);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_PROLOGUE_SEARCH,
- true);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_NO_CODE_ELISION,
- true);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_DISABLE_WARNINGS,
- true);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_BULK_MODE, true);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_TIMING_INFO, true);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_SKIP_BADVARS, true);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_IGNORE_DWARF, true);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_TAPSET_COVERAGE,
- true);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_LEAVE_RUNNING,
- true);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_PASS, testPass);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_BUFFER_BYTES,
- testBuffer);
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_TARGET_PID,
- testPid);
-
- wc.setAttribute(LaunchConfigurationConstants.COMMAND_C_DIRECTIVES,
- testCDirectives);
- wc.setAttribute(LaunchConfigurationConstants.BINARY_PATH,
- testBinaryPath);
- wc.setAttribute(LaunchConfigurationConstants.SCRIPT_PATH,
- testScriptPath);
- wc.setAttribute(LaunchConfigurationConstants.ARGUMENTS, testArguments);
- wc.setAttribute(LaunchConfigurationConstants.OUTPUT_PATH,
- testOutputPath);
-
- config = wc.doSave();
-
- SystemTapLaunchConfigurationDelegate del = new SystemTapLaunchConfigurationDelegate();
- del.launch(config, "profile", null, null);
-
- assertEquals("stap -v -p" + testPass + " -k -g -P -u -w -b -t -s"
- + testBuffer + " -x" + testPid + " " + testCDirectives
- + " -F --skip-badvars --ignore-dwarf -q " + " -c '" + testBinaryPath
- + "' " + testScriptPath + " --runtime=dyninst " + testArguments + " >& "
- + testOutputPath,
- del.generateCommand());
-
- killStap();
- }
-
- @After
- public void deleteFiles() {
- File file = new File("/tmp/ThisFileDoesNothingDeleteIt");
- if (file.exists()) {
- file.delete();
- }
- }
+ /**
+ * This test checks if the commands sent by SystemTap match exactly the options
+ * that are set. Uses the delegate.launch() function.
+ *
+ * Activates all options!
+ * @throws CoreException
+ */
+ @Test
+ public void testConfig() throws CoreException {
+
+ LaunchStapGraph shortcut = new LaunchStapGraph();
+
+ String testCDirectives = "-DRandomjunk -DMoreJunk";
+ String testOutputPath = "/tmp/ThisFileDoesNothingDeleteIt";
+ String testBinaryPath = "/path/to/binary";
+ String testScriptPath = "/tmp/NotAScriptFile.stp";
+ String testArguments = "/path/to/binary";
+ int testPid = 413;
+ int testBuffer = 100;
+ int testPass = 10;
+
+ ILaunchConfiguration config = shortcut.outsideGetLaunchConfigType()
+ .newInstance(null, "Temp name");
+ ILaunchConfigurationWorkingCopy wc = config
+ .copy("Testing configuration");
+
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_VERBOSE, 1);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_KEEP_TEMPORARY,
+ true);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_GURU, true);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_PROLOGUE_SEARCH,
+ true);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_NO_CODE_ELISION,
+ true);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_DISABLE_WARNINGS,
+ true);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_BULK_MODE, true);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_TIMING_INFO, true);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_SKIP_BADVARS, true);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_IGNORE_DWARF, true);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_TAPSET_COVERAGE,
+ true);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_LEAVE_RUNNING,
+ true);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_PASS, testPass);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_BUFFER_BYTES,
+ testBuffer);
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_TARGET_PID,
+ testPid);
+
+ wc.setAttribute(LaunchConfigurationConstants.COMMAND_C_DIRECTIVES,
+ testCDirectives);
+ wc.setAttribute(LaunchConfigurationConstants.BINARY_PATH,
+ testBinaryPath);
+ wc.setAttribute(LaunchConfigurationConstants.SCRIPT_PATH,
+ testScriptPath);
+ wc.setAttribute(LaunchConfigurationConstants.ARGUMENTS, testArguments);
+ wc.setAttribute(LaunchConfigurationConstants.OUTPUT_PATH,
+ testOutputPath);
+
+ config = wc.doSave();
+
+ SystemTapLaunchConfigurationDelegate del = new SystemTapLaunchConfigurationDelegate();
+ del.launch(config, "profile", null, null);
+
+ assertEquals("stap -v -p" + testPass + " -k -g -P -u -w -b -t -s"
+ + testBuffer + " -x" + testPid + " " + testCDirectives
+ + " -F --skip-badvars --ignore-dwarf -q " + " -c '" + testBinaryPath
+ + "' " + testScriptPath + " --runtime=dyninst " + testArguments + " >& "
+ + testOutputPath,
+ del.generateCommand());
+
+ killStap();
+ }
+
+ @After
+ public void deleteFiles() {
+ File file = new File("/tmp/ThisFileDoesNothingDeleteIt");
+ if (file.exists()) {
+ file.delete();
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/LaunchShortcutsTest.java b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/LaunchShortcutsTest.java
index bbf83bb2aa..6592b663b9 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/LaunchShortcutsTest.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/LaunchShortcutsTest.java
@@ -20,39 +20,39 @@ import org.junit.Test;
public class LaunchShortcutsTest extends AbstractStapTest {
- /**
- * Checks that the scripts are correct/exist and that the expected command
- * is sent.
- */
-
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
- }
-
- @After
- public void clean() throws Exception {
- deleteProject(proj);
- }
-
- @Test
- public void testLaunchCallGraph() throws CModelException {
- SystemTapUIErrorMessages.setActive(false);
-
- LaunchStapGraph launch = new LaunchStapGraph();
- launch.setTestMode(true);
-
- IBinary bin = proj.getBinaryContainer().getBinaries()[0];
- launch.launch(bin, "profile");
- String script = launch.getScript();
-
- assert(script
- .contains("probe process(@1).function(\"calledOnce\").call{ callFunction(probefunc()) } probe process(@1).function(\"calledOnce\").return{ returnFunction(probefunc()) }"));
- assert(script
- .contains("probe process(@1).function(\"calledTwice\").call{ callFunction(probefunc()) } probe process(@1).function(\"calledTwice\").return{ returnFunction(probefunc()) }"));
- assert(script
- .contains("probe process(@1).function(\"main\").call{ callFunction(probefunc()) } probe process(@1).function(\"main\").return{ returnFunction(probefunc()) }"));
-
- }
+ /**
+ * Checks that the scripts are correct/exist and that the expected command
+ * is sent.
+ */
+
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+ }
+
+ @After
+ public void clean() throws Exception {
+ deleteProject(proj);
+ }
+
+ @Test
+ public void testLaunchCallGraph() throws CModelException {
+ SystemTapUIErrorMessages.setActive(false);
+
+ LaunchStapGraph launch = new LaunchStapGraph();
+ launch.setTestMode(true);
+
+ IBinary bin = proj.getBinaryContainer().getBinaries()[0];
+ launch.launch(bin, "profile");
+ String script = launch.getScript();
+
+ assert(script
+ .contains("probe process(@1).function(\"calledOnce\").call{ callFunction(probefunc()) } probe process(@1).function(\"calledOnce\").return{ returnFunction(probefunc()) }"));
+ assert(script
+ .contains("probe process(@1).function(\"calledTwice\").call{ callFunction(probefunc()) } probe process(@1).function(\"calledTwice\").return{ returnFunction(probefunc()) }"));
+ assert(script
+ .contains("probe process(@1).function(\"main\").call{ callFunction(probefunc()) } probe process(@1).function(\"main\").return{ returnFunction(probefunc()) }"));
+
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapCommandGeneratorTest.java b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapCommandGeneratorTest.java
index b18b7c257f..595f86ac5e 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapCommandGeneratorTest.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapCommandGeneratorTest.java
@@ -20,56 +20,56 @@ import org.junit.Test;
public class SystemTapCommandGeneratorTest extends AbstractStapTest {
- // HACK TO GET THE PATH TO THE TESTING PROJECT
- File file = new File("");
- private String location = file.getAbsolutePath() + "/";
- SystemTapCommandGenerator stapgen = new SystemTapCommandGenerator();
+ // HACK TO GET THE PATH TO THE TESTING PROJECT
+ File file = new File("");
+ private String location = file.getAbsolutePath() + "/";
+ SystemTapCommandGenerator stapgen = new SystemTapCommandGenerator();
- @Test
- public void testExecutionWithScriptAndBinaryAndArgument() {
+ @Test
+ public void testExecutionWithScriptAndBinaryAndArgument() {
- String binaryFilePath = location + "factorial";
- String scriptPath = location + "function_count.stp";
+ String binaryFilePath = location + "factorial";
+ String scriptPath = location + "function_count.stp";
- // RUN
- String cmd = SystemTapCommandGenerator.generateCommand(scriptPath,
- binaryFilePath, "", true, true, binaryFilePath, "",
- PluginConstants.STAP_PATH);
+ // RUN
+ String cmd = SystemTapCommandGenerator.generateCommand(scriptPath,
+ binaryFilePath, "", true, true, binaryFilePath, "",
+ PluginConstants.STAP_PATH);
- assertEquals("stap -c '" + binaryFilePath + "' " + scriptPath
- + " --runtime=dyninst " + binaryFilePath, cmd);
- killStap();
- // END
- }
+ assertEquals("stap -c '" + binaryFilePath + "' " + scriptPath
+ + " --runtime=dyninst " + binaryFilePath, cmd);
+ killStap();
+ // END
+ }
- @Test
- public void testScriptExecution() {
+ @Test
+ public void testScriptExecution() {
- String scriptPath = location + "simple.stp";
+ String scriptPath = location + "simple.stp";
- // RUN
- String cmd = SystemTapCommandGenerator.generateCommand(scriptPath, "",
- "", false, false, "", "", PluginConstants.STAP_PATH);
+ // RUN
+ String cmd = SystemTapCommandGenerator.generateCommand(scriptPath, "",
+ "", false, false, "", "", PluginConstants.STAP_PATH);
- assertEquals("stap " + scriptPath, cmd);
- // END
- }
+ assertEquals("stap " + scriptPath, cmd);
+ // END
+ }
- @Test
- public void testExecutionWithScriptAndBinary() {
+ @Test
+ public void testExecutionWithScriptAndBinary() {
- // RUN
- String binaryFilePath = location + "factorial";
- String scriptPath = location + "allsyscall.stp";
+ // RUN
+ String binaryFilePath = location + "factorial";
+ String scriptPath = location + "allsyscall.stp";
- String cmd = SystemTapCommandGenerator.generateCommand(scriptPath,
- binaryFilePath, "", true, false, "", "",
- PluginConstants.STAP_PATH);
+ String cmd = SystemTapCommandGenerator.generateCommand(scriptPath,
+ binaryFilePath, "", true, false, "", "",
+ PluginConstants.STAP_PATH);
- assertEquals("stap -c '" + binaryFilePath + "' " + scriptPath, cmd);
- // END
+ assertEquals("stap -c '" + binaryFilePath + "' " + scriptPath, cmd);
+ // END
- killStap();
- }
+ killStap();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapCommandTest.java b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapCommandTest.java
index 1df109bfb3..8ea5a65796 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapCommandTest.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapCommandTest.java
@@ -21,29 +21,29 @@ import org.junit.Test;
public class SystemTapCommandTest {
- /**
- * Tests if SystemTapCommand is properly obtaining output from the runtime
- * process
- *
- * @throws FileNotFoundException
- */
- @Test
- public void testCommand() throws IOException {
- // Set up variables
- String testText = "CORRECT";
- String tempLocation = ResourcesPlugin.getWorkspace().getRoot()
- .getLocation().toString()
- + "/DeleteThisScript.stp";
+ /**
+ * Tests if SystemTapCommand is properly obtaining output from the runtime
+ * process
+ *
+ * @throws FileNotFoundException
+ */
+ @Test
+ public void testCommand() throws IOException {
+ // Set up variables
+ String testText = "CORRECT";
+ String tempLocation = ResourcesPlugin.getWorkspace().getRoot()
+ .getLocation().toString()
+ + "/DeleteThisScript.stp";
- // Create temporary file containing the test script
- File temporaryScript = new File(tempLocation);
+ // Create temporary file containing the test script
+ File temporaryScript = new File(tempLocation);
- try (FileOutputStream output = new FileOutputStream(temporaryScript);
- PrintStream printer = new PrintStream(output)) {
- printer.println("probe begin { printf(\"" + testText
- + "\") exit() }");
- }
- // Cleanup
- temporaryScript.delete();
- }
+ try (FileOutputStream output = new FileOutputStream(temporaryScript);
+ PrintStream printer = new PrintStream(output)) {
+ printer.println("probe begin { printf(\"" + testText
+ + "\") exit() }");
+ }
+ // Cleanup
+ temporaryScript.delete();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapErrorHandlerTest.java b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapErrorHandlerTest.java
index 61e333b57e..9f9538a400 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapErrorHandlerTest.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapErrorHandlerTest.java
@@ -21,72 +21,72 @@ import org.junit.Test;
public class SystemTapErrorHandlerTest {
- private SystemTapErrorHandler errHandler;
- private String errorString;
+ private SystemTapErrorHandler errHandler;
+ private String errorString;
- @Before
- public void setUp() {
- errHandler = new SystemTapErrorHandler();
- }
+ @Before
+ public void setUp() {
+ errHandler = new SystemTapErrorHandler();
+ }
- @Test
- public void testErrorNotRecognized(){
+ @Test
+ public void testErrorNotRecognized(){
- errorString = "This error will not be caught \n" +
- "Not even this one \n" +
- "Unrecognized \n" +
- "Not found \n" +
- "Error";
+ errorString = "This error will not be caught \n" +
+ "Not even this one \n" +
+ "Unrecognized \n" +
+ "Not found \n" +
+ "Error";
- errHandler.handle(new NullProgressMonitor(), errorString);
+ errHandler.handle(new NullProgressMonitor(), errorString);
- assertFalse(errHandler.isErrorRecognized());
- }
+ assertFalse(errHandler.isErrorRecognized());
+ }
- @Test
- public void testErrorRecognized(){
+ @Test
+ public void testErrorRecognized(){
- errorString = "As long as the word stapusr or stapdev is here, error is recognized";
+ errorString = "As long as the word stapusr or stapdev is here, error is recognized";
- errHandler.handle(new NullProgressMonitor(), errorString);
+ errHandler.handle(new NullProgressMonitor(), errorString);
- assertTrue(errHandler.isErrorRecognized());
- }
+ assertTrue(errHandler.isErrorRecognized());
+ }
- @Test
- public void testUserGroupError(){
+ @Test
+ public void testUserGroupError(){
- errorString = "ERROR: You are trying to run systemtap as a normal user.\n" +
- "You should either be root, or be part of the group \"stapusr\" and " +
- "possibly one of the groups \"stapsys\" or \"stapdev\".";
+ errorString = "ERROR: You are trying to run systemtap as a normal user.\n" +
+ "You should either be root, or be part of the group \"stapusr\" and " +
+ "possibly one of the groups \"stapsys\" or \"stapdev\".";
- errHandler.handle(new NullProgressMonitor(), errorString);
+ errHandler.handle(new NullProgressMonitor(), errorString);
- assertTrue(errHandler.isErrorRecognized());
- assertTrue(errHandler.getErrorMessage().contains("Please add yourself to the 'stapdev' or 'stapusr' group in order to run stap."));
- }
+ assertTrue(errHandler.isErrorRecognized());
+ assertTrue(errHandler.getErrorMessage().contains("Please add yourself to the 'stapdev' or 'stapusr' group in order to run stap."));
+ }
- @Test
- public void testDebugInfoError(){
+ @Test
+ public void testDebugInfoError(){
- errorString = "missing [architecture] kernel/module debuginfo under '[kernel-build-tree]'";
+ errorString = "missing [architecture] kernel/module debuginfo under '[kernel-build-tree]'";
- errHandler.handle(new NullProgressMonitor(), errorString);
+ errHandler.handle(new NullProgressMonitor(), errorString);
- assertTrue(errHandler.isErrorRecognized());
- assertTrue(errHandler.getErrorMessage().contains("No debuginfo could be found. Make sure you have yum-utils installed, and run debuginfo-install kernel as root."));
- }
+ assertTrue(errHandler.isErrorRecognized());
+ assertTrue(errHandler.getErrorMessage().contains("No debuginfo could be found. Make sure you have yum-utils installed, and run debuginfo-install kernel as root."));
+ }
- @Test
- public void testUprobesError(){
+ @Test
+ public void testUprobesError(){
- errorString = "SystemTap's version of uprobes is out of date. As root, or a member of the 'root' group, run \"make -C /usr/local/share/systemtap/runtime/uprobes\".";
+ errorString = "SystemTap's version of uprobes is out of date. As root, or a member of the 'root' group, run \"make -C /usr/local/share/systemtap/runtime/uprobes\".";
- errHandler.handle(new NullProgressMonitor(), errorString);
+ errHandler.handle(new NullProgressMonitor(), errorString);
- assertTrue(errHandler.isErrorRecognized());
- System.out.println(errHandler.getErrorMessage());
- assertTrue(errHandler.getErrorMessage().contains("SystemTap's version of uprobes is out of date."));
- assertTrue(errHandler.getErrorMessage().contains("make -C /usr/local/share/systemtap/runtime/uprobes\"."));
- }
+ assertTrue(errHandler.isErrorRecognized());
+ System.out.println(errHandler.getErrorMessage());
+ assertTrue(errHandler.getErrorMessage().contains("SystemTap's version of uprobes is out of date."));
+ assertTrue(errHandler.getErrorMessage().contains("make -C /usr/local/share/systemtap/runtime/uprobes\"."));
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapTabTest.java b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapTabTest.java
index 4253d384fe..20e16fd0d6 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapTabTest.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch.tests/src/org/eclipse/linuxtools/callgraph/launch/tests/SystemTapTabTest.java
@@ -22,24 +22,24 @@ import org.eclipse.swt.widgets.Shell;
import org.junit.Test;
public class SystemTapTabTest {
- @Test
- public void testTabs() throws CoreException{
- Shell sh = new Shell();
- Composite cmp = new Composite(sh, SWT.NONE);
+ @Test
+ public void testTabs() throws CoreException{
+ Shell sh = new Shell();
+ Composite cmp = new Composite(sh, SWT.NONE);
- LaunchStapGraph shortCut = new LaunchStapGraph();
- SystemTapOptionsTab stp = new SystemTapOptionsTab();
- stp.createControl(cmp);
- ILaunchConfiguration configuration;
- configuration = shortCut.outsideGetLaunchConfigType().newInstance(
- null,
- (DebugPlugin.getDefault().getLaunchManager())
- .generateLaunchConfigurationName("invalid"));
- ILaunchConfigurationWorkingCopy wc = configuration.getWorkingCopy();
- stp.setDefaults(wc);
- stp.performApply(wc);
- wc.doSave();
- stp.initializeFrom(configuration);
- sh.open();
- }
+ LaunchStapGraph shortCut = new LaunchStapGraph();
+ SystemTapOptionsTab stp = new SystemTapOptionsTab();
+ stp.createControl(cmp);
+ ILaunchConfiguration configuration;
+ configuration = shortCut.outsideGetLaunchConfigType().newInstance(
+ null,
+ (DebugPlugin.getDefault().getLaunchManager())
+ .generateLaunchConfigurationName("invalid"));
+ ILaunchConfigurationWorkingCopy wc = configuration.getWorkingCopy();
+ stp.setDefaults(wc);
+ stp.performApply(wc);
+ wc.doSave();
+ stp.initializeFrom(configuration);
+ sh.open();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/plugin.xml b/systemtap/org.eclipse.linuxtools.callgraph.launch/plugin.xml
index b9f12a6b5a..bf0efbcb53 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/plugin.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/plugin.xml
@@ -21,9 +21,9 @@
sourcePathComputerId="org.eclipse.cdt.debug.core.sourcePathComputer">
</launchConfigurationType>
</extension>
-
-
-
+
+
+
<extension
point="org.eclipse.debug.ui.launchConfigurationTabGroups">
<launchConfigurationTabGroup
@@ -33,9 +33,9 @@
type="org.eclipse.linuxtools.callgraph.launch.systemtapLaunch">
</launchConfigurationTabGroup>
</extension>
-
-
- <extension
+
+
+ <extension
point="org.eclipse.debug.ui.launchShortcuts">
<shortcut
class="org.eclipse.linuxtools.internal.callgraph.launch.LaunchStapGraph"
@@ -106,6 +106,6 @@
type="timing">
</provider>
</extension>
-
+
</plugin>
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/ConfigurationOptionsSetter.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/ConfigurationOptionsSetter.java
index 008709716f..39734f8018 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/ConfigurationOptionsSetter.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/ConfigurationOptionsSetter.java
@@ -16,131 +16,131 @@ import org.eclipse.linuxtools.internal.callgraph.core.LaunchConfigurationConstan
public class ConfigurationOptionsSetter {
- /**
- * Returns a SystemTap command string containing the options specified in
- * the configuration.
- *
- * @param config
- * @return
- */
- public static String setOptions(ILaunchConfiguration config) {
- StringBuilder options = new StringBuilder();
- try {
-
- int verboseLevel = config.getAttribute(
- LaunchConfigurationConstants.COMMAND_VERBOSE,
- LaunchConfigurationConstants.DEFAULT_COMMAND_VERBOSE);
- if (verboseLevel > 0) {
- StringBuilder builder = new StringBuilder();
- builder.append("-"); //$NON-NLS-1$
- for (int i = 0; i < verboseLevel; i++)
- builder.append("v"); //$NON-NLS-1$
- builder.append(" "); //$NON-NLS-1$
- options.append(builder.toString());
- }
-
- if (config.getAttribute(LaunchConfigurationConstants.COMMAND_PASS,
- LaunchConfigurationConstants.DEFAULT_COMMAND_PASS) > 0) {
- options.append("-p" + config.getAttribute(LaunchConfigurationConstants.COMMAND_PASS, LaunchConfigurationConstants.DEFAULT_COMMAND_PASS) + " "); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (config
- .getAttribute(
- LaunchConfigurationConstants.COMMAND_KEEP_TEMPORARY,
- LaunchConfigurationConstants.DEFAULT_COMMAND_KEEP_TEMPORARY)) {
- options.append("-k "); //$NON-NLS-1$
- }
-
- if (config.getAttribute(LaunchConfigurationConstants.COMMAND_GURU,
- LaunchConfigurationConstants.DEFAULT_COMMAND_GURU)) {
- options.append("-g "); //$NON-NLS-1$
- }
-
- if (config
- .getAttribute(
- LaunchConfigurationConstants.COMMAND_PROLOGUE_SEARCH,
- LaunchConfigurationConstants.DEFAULT_COMMAND_PROLOGUE_SEARCH)) {
- options.append("-P "); //$NON-NLS-1$
- }
-
- if (config
- .getAttribute(
- LaunchConfigurationConstants.COMMAND_NO_CODE_ELISION,
- LaunchConfigurationConstants.DEFAULT_COMMAND_NO_CODE_ELISION)) {
- options.append("-u "); //$NON-NLS-1$
- }
-
- if (config
- .getAttribute(
- LaunchConfigurationConstants.COMMAND_DISABLE_WARNINGS,
- LaunchConfigurationConstants.DEFAULT_COMMAND_DISABLE_WARNINGS)) {
- options.append("-w "); //$NON-NLS-1$
- }
-
- if (config.getAttribute(
- LaunchConfigurationConstants.COMMAND_BULK_MODE,
- LaunchConfigurationConstants.DEFAULT_COMMAND_BULK_MODE)) {
- options.append("-b "); //$NON-NLS-1$
- }
-
- if (config.getAttribute(
- LaunchConfigurationConstants.COMMAND_TIMING_INFO,
- LaunchConfigurationConstants.DEFAULT_COMMAND_TIMING_INFO)) {
- options.append("-t "); //$NON-NLS-1$
- }
-
- if (config.getAttribute(
- LaunchConfigurationConstants.COMMAND_BUFFER_BYTES,
- LaunchConfigurationConstants.DEFAULT_COMMAND_BUFFER_BYTES) > 0) {
- options.append("-s" + config.getAttribute(LaunchConfigurationConstants.COMMAND_BUFFER_BYTES, LaunchConfigurationConstants.DEFAULT_COMMAND_BUFFER_BYTES) + " "); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (config.getAttribute(
- LaunchConfigurationConstants.COMMAND_TARGET_PID,
- LaunchConfigurationConstants.DEFAULT_COMMAND_TARGET_PID) > 0) {
- options.append("-x" + config.getAttribute(LaunchConfigurationConstants.COMMAND_TARGET_PID, LaunchConfigurationConstants.DEFAULT_COMMAND_TARGET_PID) + " "); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (config.getAttribute(
- LaunchConfigurationConstants.COMMAND_C_DIRECTIVES,
- LaunchConfigurationConstants.DEFAULT_COMMAND_C_DIRECTIVES) != LaunchConfigurationConstants.DEFAULT_COMMAND_C_DIRECTIVES) {
- options.append(config
- .getAttribute(
- LaunchConfigurationConstants.COMMAND_C_DIRECTIVES,
- LaunchConfigurationConstants.DEFAULT_COMMAND_C_DIRECTIVES)
- + " "); //$NON-NLS-1$
- }
-
- if (config.getAttribute(
- LaunchConfigurationConstants.COMMAND_LEAVE_RUNNING,
- LaunchConfigurationConstants.DEFAULT_COMMAND_LEAVE_RUNNING)) {
- options.append("-F "); //$NON-NLS-1$
- }
-
- if (config.getAttribute(
- LaunchConfigurationConstants.COMMAND_SKIP_BADVARS,
- LaunchConfigurationConstants.DEFAULT_COMMAND_SKIP_BADVARS)) {
- options.append("--skip-badvars "); //$NON-NLS-1$
- }
-
- if (config.getAttribute(
- LaunchConfigurationConstants.COMMAND_IGNORE_DWARF,
- LaunchConfigurationConstants.DEFAULT_COMMAND_IGNORE_DWARF)) {
- options.append("--ignore-dwarf "); //$NON-NLS-1$
- }
-
- if (config
- .getAttribute(
- LaunchConfigurationConstants.COMMAND_TAPSET_COVERAGE,
- LaunchConfigurationConstants.DEFAULT_COMMAND_TAPSET_COVERAGE)) {
- options.append("-q "); //$NON-NLS-1$
- }
- return options.toString();
-
- } catch (CoreException e) {
- e.printStackTrace();
- }
-
- return null;
- }
+ /**
+ * Returns a SystemTap command string containing the options specified in
+ * the configuration.
+ *
+ * @param config
+ * @return
+ */
+ public static String setOptions(ILaunchConfiguration config) {
+ StringBuilder options = new StringBuilder();
+ try {
+
+ int verboseLevel = config.getAttribute(
+ LaunchConfigurationConstants.COMMAND_VERBOSE,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_VERBOSE);
+ if (verboseLevel > 0) {
+ StringBuilder builder = new StringBuilder();
+ builder.append("-"); //$NON-NLS-1$
+ for (int i = 0; i < verboseLevel; i++)
+ builder.append("v"); //$NON-NLS-1$
+ builder.append(" "); //$NON-NLS-1$
+ options.append(builder.toString());
+ }
+
+ if (config.getAttribute(LaunchConfigurationConstants.COMMAND_PASS,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_PASS) > 0) {
+ options.append("-p" + config.getAttribute(LaunchConfigurationConstants.COMMAND_PASS, LaunchConfigurationConstants.DEFAULT_COMMAND_PASS) + " "); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ if (config
+ .getAttribute(
+ LaunchConfigurationConstants.COMMAND_KEEP_TEMPORARY,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_KEEP_TEMPORARY)) {
+ options.append("-k "); //$NON-NLS-1$
+ }
+
+ if (config.getAttribute(LaunchConfigurationConstants.COMMAND_GURU,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_GURU)) {
+ options.append("-g "); //$NON-NLS-1$
+ }
+
+ if (config
+ .getAttribute(
+ LaunchConfigurationConstants.COMMAND_PROLOGUE_SEARCH,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_PROLOGUE_SEARCH)) {
+ options.append("-P "); //$NON-NLS-1$
+ }
+
+ if (config
+ .getAttribute(
+ LaunchConfigurationConstants.COMMAND_NO_CODE_ELISION,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_NO_CODE_ELISION)) {
+ options.append("-u "); //$NON-NLS-1$
+ }
+
+ if (config
+ .getAttribute(
+ LaunchConfigurationConstants.COMMAND_DISABLE_WARNINGS,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_DISABLE_WARNINGS)) {
+ options.append("-w "); //$NON-NLS-1$
+ }
+
+ if (config.getAttribute(
+ LaunchConfigurationConstants.COMMAND_BULK_MODE,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_BULK_MODE)) {
+ options.append("-b "); //$NON-NLS-1$
+ }
+
+ if (config.getAttribute(
+ LaunchConfigurationConstants.COMMAND_TIMING_INFO,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_TIMING_INFO)) {
+ options.append("-t "); //$NON-NLS-1$
+ }
+
+ if (config.getAttribute(
+ LaunchConfigurationConstants.COMMAND_BUFFER_BYTES,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_BUFFER_BYTES) > 0) {
+ options.append("-s" + config.getAttribute(LaunchConfigurationConstants.COMMAND_BUFFER_BYTES, LaunchConfigurationConstants.DEFAULT_COMMAND_BUFFER_BYTES) + " "); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ if (config.getAttribute(
+ LaunchConfigurationConstants.COMMAND_TARGET_PID,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_TARGET_PID) > 0) {
+ options.append("-x" + config.getAttribute(LaunchConfigurationConstants.COMMAND_TARGET_PID, LaunchConfigurationConstants.DEFAULT_COMMAND_TARGET_PID) + " "); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ if (config.getAttribute(
+ LaunchConfigurationConstants.COMMAND_C_DIRECTIVES,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_C_DIRECTIVES) != LaunchConfigurationConstants.DEFAULT_COMMAND_C_DIRECTIVES) {
+ options.append(config
+ .getAttribute(
+ LaunchConfigurationConstants.COMMAND_C_DIRECTIVES,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_C_DIRECTIVES)
+ + " "); //$NON-NLS-1$
+ }
+
+ if (config.getAttribute(
+ LaunchConfigurationConstants.COMMAND_LEAVE_RUNNING,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_LEAVE_RUNNING)) {
+ options.append("-F "); //$NON-NLS-1$
+ }
+
+ if (config.getAttribute(
+ LaunchConfigurationConstants.COMMAND_SKIP_BADVARS,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_SKIP_BADVARS)) {
+ options.append("--skip-badvars "); //$NON-NLS-1$
+ }
+
+ if (config.getAttribute(
+ LaunchConfigurationConstants.COMMAND_IGNORE_DWARF,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_IGNORE_DWARF)) {
+ options.append("--ignore-dwarf "); //$NON-NLS-1$
+ }
+
+ if (config
+ .getAttribute(
+ LaunchConfigurationConstants.COMMAND_TAPSET_COVERAGE,
+ LaunchConfigurationConstants.DEFAULT_COMMAND_TAPSET_COVERAGE)) {
+ options.append("-q "); //$NON-NLS-1$
+ }
+ return options.toString();
+
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+
+ return null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/LaunchStapGraph.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/LaunchStapGraph.java
index 37c9c062af..0c7b671dd6 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/LaunchStapGraph.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/LaunchStapGraph.java
@@ -27,176 +27,176 @@ import org.eclipse.ui.IEditorPart;
public class LaunchStapGraph extends SystemTapLaunchShortcut {
- //TODO: Do not let this class persist, or otherwise change it so persistence doesn't matter.
- private String partialScriptPath;
- private String funcs;
- private List<String> exclusions;
- private String projectName;
- protected static final String ATTR_PARSER = "org.eclipse.linuxtools.callgraph.graphparser"; //$NON-NLS-1$
- protected static final String ATTR_VIEWER = "org.eclipse.linuxtools.callgraph.callgraphview"; //$NON-NLS-1$
-
- public LaunchStapGraph() {
- funcs = null;
- exclusions = new ArrayList<>();
- projectName = null;
- }
-
- @Override
- public void launch(IEditorPart ed, String mode) {
- resourceToSearchFor = ed.getTitle();
- searchForResource = true;
-
- //Note: This launch will eventually end up calling
- //launch(IBinary bin, String mode) below
- super.launch(ed, mode);
- }
-
- @Override
- public void launch(IBinary bin, String mode) {
- launch(bin, mode, null);
- }
-
- public void launch(IBinary bin, String mode, ILaunchConfigurationWorkingCopy wc) {
- super.initialize();
- this.bin = bin;
- name = "SystemTapGraph"; //$NON-NLS-1$
- binName = getName(bin);
- partialScriptPath = PluginConstants.getPluginLocation()
- + "parse_function_partial.stp"; //$NON-NLS-1$
-
- viewID = "org.eclipse.linuxtools.callgraph.callgraphview"; //$NON-NLS-1$
-
-
-
- projectName = bin.getCProject().getElementName();
-
- try {
- if (wc == null) {
- wc = createConfiguration(bin, name);
- }
- binaryPath = bin.getResource().getLocation().toString();
- arguments = binaryPath;
- outputPath = PluginConstants.getDefaultIOPath();
-
- if (writeFunctionListToScript(resourceToSearchFor) == null) {
- return;
- }
- if (funcs == null || funcs.length() < 0) {
- return;
- }
-
- needToGenerate = true;
- finishLaunch(name, mode, wc);
-
- } catch (IOException e) {
- SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
- "LaunchShortcutScriptGen", //$NON-NLS-1$
- Messages.getString("LaunchStapGraph.ScriptGenErr"), //$NON-NLS-1$
- Messages.getString("LaunchStapGraph.ScriptGenErrMsg")); //$NON-NLS-1$
- mess.schedule();
- e.printStackTrace();
- } finally {
- resourceToSearchFor = ""; //$NON-NLS-1$
- searchForResource = false;
- }
-
-
- }
-
- /**
- * Generates the call and return function probes for the specified function
- * @param function
- * @return
- */
- private String generateProbe(String function) {
- String output = "probe process(@1).function(\"" + function + "\").call ? { if ( ! isinstr(\"" + function + "\", \"___STAP_MARKER___\")) { callFunction(\"" + function + "\",tid()) } } probe process(@1).function(\"" + function + "\").return ? { if ( ! isinstr(\"" + function + "\", \"___STAP_MARKER___\")) returnFunction(\"" + function + "\",tid()) else { printf(\"?%d,,%s\\n\", tid(), user_string(strtol(tokenize($$return, \"return=\"),16)))}}\n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- return output;
- }
-
- /**
- * Prompts the user for a list of functions to probe
- *
- * @param bw
- * @return
- */
- private String writeFunctionListToScript(String resourceToSearchFor) {
- String toWrite = getFunctionsFromBinary(bin, resourceToSearchFor);
-
- if (toWrite == null || toWrite.length() < 1) {
- return null;
- }
-
- StringBuffer output = new StringBuffer();
-
- for (String func : toWrite.split(" ")) { //$NON-NLS-1$
- if (func.length() > 0
- && (exclusions == null || exclusions.size() < 1 || exclusions
- .contains(func))) {
- output.append(generateProbe(func));
- }
- }
-
- funcs = output.toString();
- return funcs;
- }
-
- /**
- * Copies the contents of the specified partial script. You should call writeStapMarkers first
- * if you want StapMarkers to function properly.
- *
- * @param bw
- * @return
- * @throws IOException
- */
- private String writeFromPartialScript(String projectName) throws IOException {
- String toWrite = ""; //$NON-NLS-1$
- String temp = ""; //$NON-NLS-1$
- toWrite += "\nprobe begin{\n" + //$NON-NLS-1$
- "printf(\"\\nPROBE_BEGIN\\n\")\n" + //$NON-NLS-1$
- "serial=1\n" + //$NON-NLS-1$
- "startTime = 0;\n" + //$NON-NLS-1$
- "printf(\"" + projectName + "\\n\")\n" + //$NON-NLS-1$ //$NON-NLS-2$
- "}"; //$NON-NLS-1$
- File partialScript = new File(partialScriptPath);
- try (BufferedReader scriptReader = new BufferedReader(new FileReader(
- partialScript))) {
- while ((temp = scriptReader.readLine()) != null) {
- toWrite += temp + "\n"; //$NON-NLS-1$
- }
- scriptReader.close();
- }
-
- return toWrite;
- }
-
-
- @Override
- public String generateScript() throws IOException {
-
- String scriptContents = ""; //$NON-NLS-1$
-
- scriptContents += funcs;
-
- scriptContents += writeFromPartialScript(projectName);
-
- return scriptContents;
- }
-
- @Override
- public String setScriptPath() {
- scriptPath = PluginConstants.getDefaultOutput()
- + "callgraphGen.stp"; //$NON-NLS-1$
- return scriptPath;
- }
-
- @Override
- public String setParserID() {
- parserID = ATTR_PARSER;
- return parserID;
- }
-
- @Override
- public String setViewID() {
- return ATTR_VIEWER;
- }
+ //TODO: Do not let this class persist, or otherwise change it so persistence doesn't matter.
+ private String partialScriptPath;
+ private String funcs;
+ private List<String> exclusions;
+ private String projectName;
+ protected static final String ATTR_PARSER = "org.eclipse.linuxtools.callgraph.graphparser"; //$NON-NLS-1$
+ protected static final String ATTR_VIEWER = "org.eclipse.linuxtools.callgraph.callgraphview"; //$NON-NLS-1$
+
+ public LaunchStapGraph() {
+ funcs = null;
+ exclusions = new ArrayList<>();
+ projectName = null;
+ }
+
+ @Override
+ public void launch(IEditorPart ed, String mode) {
+ resourceToSearchFor = ed.getTitle();
+ searchForResource = true;
+
+ //Note: This launch will eventually end up calling
+ //launch(IBinary bin, String mode) below
+ super.launch(ed, mode);
+ }
+
+ @Override
+ public void launch(IBinary bin, String mode) {
+ launch(bin, mode, null);
+ }
+
+ public void launch(IBinary bin, String mode, ILaunchConfigurationWorkingCopy wc) {
+ super.initialize();
+ this.bin = bin;
+ name = "SystemTapGraph"; //$NON-NLS-1$
+ binName = getName(bin);
+ partialScriptPath = PluginConstants.getPluginLocation()
+ + "parse_function_partial.stp"; //$NON-NLS-1$
+
+ viewID = "org.eclipse.linuxtools.callgraph.callgraphview"; //$NON-NLS-1$
+
+
+
+ projectName = bin.getCProject().getElementName();
+
+ try {
+ if (wc == null) {
+ wc = createConfiguration(bin, name);
+ }
+ binaryPath = bin.getResource().getLocation().toString();
+ arguments = binaryPath;
+ outputPath = PluginConstants.getDefaultIOPath();
+
+ if (writeFunctionListToScript(resourceToSearchFor) == null) {
+ return;
+ }
+ if (funcs == null || funcs.length() < 0) {
+ return;
+ }
+
+ needToGenerate = true;
+ finishLaunch(name, mode, wc);
+
+ } catch (IOException e) {
+ SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
+ "LaunchShortcutScriptGen", //$NON-NLS-1$
+ Messages.getString("LaunchStapGraph.ScriptGenErr"), //$NON-NLS-1$
+ Messages.getString("LaunchStapGraph.ScriptGenErrMsg")); //$NON-NLS-1$
+ mess.schedule();
+ e.printStackTrace();
+ } finally {
+ resourceToSearchFor = ""; //$NON-NLS-1$
+ searchForResource = false;
+ }
+
+
+ }
+
+ /**
+ * Generates the call and return function probes for the specified function
+ * @param function
+ * @return
+ */
+ private String generateProbe(String function) {
+ String output = "probe process(@1).function(\"" + function + "\").call ? { if ( ! isinstr(\"" + function + "\", \"___STAP_MARKER___\")) { callFunction(\"" + function + "\",tid()) } } probe process(@1).function(\"" + function + "\").return ? { if ( ! isinstr(\"" + function + "\", \"___STAP_MARKER___\")) returnFunction(\"" + function + "\",tid()) else { printf(\"?%d,,%s\\n\", tid(), user_string(strtol(tokenize($$return, \"return=\"),16)))}}\n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ return output;
+ }
+
+ /**
+ * Prompts the user for a list of functions to probe
+ *
+ * @param bw
+ * @return
+ */
+ private String writeFunctionListToScript(String resourceToSearchFor) {
+ String toWrite = getFunctionsFromBinary(bin, resourceToSearchFor);
+
+ if (toWrite == null || toWrite.length() < 1) {
+ return null;
+ }
+
+ StringBuffer output = new StringBuffer();
+
+ for (String func : toWrite.split(" ")) { //$NON-NLS-1$
+ if (func.length() > 0
+ && (exclusions == null || exclusions.size() < 1 || exclusions
+ .contains(func))) {
+ output.append(generateProbe(func));
+ }
+ }
+
+ funcs = output.toString();
+ return funcs;
+ }
+
+ /**
+ * Copies the contents of the specified partial script. You should call writeStapMarkers first
+ * if you want StapMarkers to function properly.
+ *
+ * @param bw
+ * @return
+ * @throws IOException
+ */
+ private String writeFromPartialScript(String projectName) throws IOException {
+ String toWrite = ""; //$NON-NLS-1$
+ String temp = ""; //$NON-NLS-1$
+ toWrite += "\nprobe begin{\n" + //$NON-NLS-1$
+ "printf(\"\\nPROBE_BEGIN\\n\")\n" + //$NON-NLS-1$
+ "serial=1\n" + //$NON-NLS-1$
+ "startTime = 0;\n" + //$NON-NLS-1$
+ "printf(\"" + projectName + "\\n\")\n" + //$NON-NLS-1$ //$NON-NLS-2$
+ "}"; //$NON-NLS-1$
+ File partialScript = new File(partialScriptPath);
+ try (BufferedReader scriptReader = new BufferedReader(new FileReader(
+ partialScript))) {
+ while ((temp = scriptReader.readLine()) != null) {
+ toWrite += temp + "\n"; //$NON-NLS-1$
+ }
+ scriptReader.close();
+ }
+
+ return toWrite;
+ }
+
+
+ @Override
+ public String generateScript() throws IOException {
+
+ String scriptContents = ""; //$NON-NLS-1$
+
+ scriptContents += funcs;
+
+ scriptContents += writeFromPartialScript(projectName);
+
+ return scriptContents;
+ }
+
+ @Override
+ public String setScriptPath() {
+ scriptPath = PluginConstants.getDefaultOutput()
+ + "callgraphGen.stp"; //$NON-NLS-1$
+ return scriptPath;
+ }
+
+ @Override
+ public String setParserID() {
+ parserID = ATTR_PARSER;
+ return parserID;
+ }
+
+ @Override
+ public String setViewID() {
+ return ATTR_VIEWER;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/LaunchWizard.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/LaunchWizard.java
index 1d580b72d4..dc517d134c 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/LaunchWizard.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/LaunchWizard.java
@@ -46,242 +46,242 @@ import org.eclipse.ui.views.navigator.ResourceComparator;
public class LaunchWizard extends SystemTapLaunchShortcut {
- private Text scriptLocation;
- private Text binaryLocation;
- private Text argumentsLocation;
- private String workspacePath;
- private String mode;
-
- private Shell sh;
- private Composite fileComp;
-
- private static final int WIDTH = 670;
- private static final int HEIGHT = 630;
-
- /**
- * The following protected parameters are provided by SystemTapLaunchShortcut:
- *
- * Optional customization parameters:
- * protected String name;
- * protected String binaryPath;
- * protected String arguments;
- * protected String outputPath;
- * protected String dirPath;
- * protected String generatedScript;
- * protected boolean needToGenerate;
- * protected boolean overwrite;
- *
- * Mandatory:
- * protected String scriptPath;
- * protected ILaunchConfiguration config;
- */
-
-
- /**
- * Launch method for a generated script that executes on a binary
- *
- * MUST specify (String) scriptPath and call config = createConfiguration(bin)!
- *
- * Noteworthy defaults:
- * name defaults to "", but please set it (for usability)
- * overwrite defaults to true - don't change it unless you really have to.
- *
- * To create new launches:
- * -Copy shortcut code in xml, changing class name and label accordingly
- * -Create a class that extends SystemTapLaunchShortcut with a function
- * launch(IBinary bin, String mode)
- * -Call super.Init()
- * -Set name (this is shortcut-specific)
- * -If a binary is used, call binName = getName(bin)
- * -Call createConfiguration(bin, name)
- *
- * -Specify whichever of the optional parameters you need
- * -Set scriptPath
- * -Set an ILaunchConfiguration
- * -Call finishLaunch or finishLaunchWithoutBinary
- */
-
- @Override
- public void launch(IEditorPart ed, String mode) {
- super.initialize();
- promptForInputs();
-
- this.mode = mode;
- }
-
- @Override
- public void launch(ISelection selection, String mode) {
- super.initialize();
- promptForInputs();
-
- this.mode = mode;
- }
-
- private void promptForInputs() {
- InputDialog id = new InputDialog(new Shell(), Messages.getString("LaunchWizard.WelcomeWizard"), //$NON-NLS-1$
- Messages.getString("LaunchWizard.Text1") + //$NON-NLS-1$
- Messages.getString("LaunchWizard.Text2") + //$NON-NLS-1$
- Messages.getString("LaunchWizard.Text3"), //$NON-NLS-1$
- getLaunchManager().generateLaunchConfigurationName(
- Messages.getString("LaunchWizard.NamePrefix")), null); //$NON-NLS-1$
- id.open();
-
- if (id.getReturnCode() == Window.CANCEL){
- return;
- }
-
- name = id.getValue();
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceRoot root = workspace.getRoot();
- IPath location = root.getLocation();
- workspacePath = location.toString();
-
- sh = new Shell();
- sh.setSize(WIDTH,HEIGHT);
- sh.setLayout(new GridLayout(1, false));
- sh.setText(name);
-
-
- Image img = new Image(sh.getDisplay(), PluginConstants.getPluginLocation() + "systemtapbanner.png"); //$NON-NLS-1$
- Composite imageCmp = new Composite(sh, SWT.BORDER);
- imageCmp.setLayout(new FillLayout());
- GridData imageData = new GridData(650, 157);
- imageData.horizontalAlignment = SWT.CENTER;
- imageCmp.setLayoutData(imageData);
- imageCmp.setBackgroundImage(img);
-
- fileComp = new Composite(sh, SWT.NONE);
- fileComp.setLayout(new GridLayout(2, false));
- fileComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
-
- GridDataFactory labelData = GridDataFactory.fillDefaults().grab(true, false)
- .span(2,1);
-
- Label scriptLabel = new Label(fileComp, SWT.HORIZONTAL);
- scriptLabel.setText(Messages.getString("LaunchWizard.Script")); //$NON-NLS-1$
- labelData.applyTo(scriptLabel);
-
- GridDataFactory textData = GridDataFactory.fillDefaults().grab( true, false )
- .hint(WIDTH, SWT.DEFAULT);
-
- scriptLocation = new Text(fileComp, SWT.SINGLE | SWT.BORDER);
- textData.applyTo(scriptLocation);
- Button scriptButton = new Button(fileComp, SWT.PUSH);
- scriptButton.setText(Messages.getString("SystemTapOptionsTab.BrowseFiles")); //$NON-NLS-1$
- scriptButton.setLayoutData(new GridData());
- scriptButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String filePath = scriptLocation.getText();
- FileDialog dialog = new FileDialog(sh, SWT.SAVE);
- filePath = dialog.open();
- if (filePath != null) {
- scriptLocation.setText(filePath);
- }
- }
- });
-
-
- GridData gd2 = new GridData();
- gd2.horizontalSpan = 3;
- Label binaryLabel= new Label(fileComp, SWT.HORIZONTAL);
- binaryLabel.setText(Messages.getString("LaunchWizard.BinFile")); //$NON-NLS-1$
- labelData.applyTo(binaryLabel);
-
- binaryLocation = new Text(fileComp, SWT.SINGLE | SWT.BORDER);
- textData.applyTo(binaryLocation);
- Button binaryButton = new Button(fileComp, SWT.PUSH);
- binaryButton.setText(Messages.getString("SystemTapOptionsTab.WorkspaceButton2")); //$NON-NLS-1$
- binaryButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(sh, new WorkbenchLabelProvider(), new WorkbenchContentProvider());
- dialog.setTitle(Messages.getString("SystemTapOptionsTab.SelectResource")); //$NON-NLS-1$
- dialog.setMessage(Messages.getString("SystemTapOptionsTab.SelectSuppressions")); //$NON-NLS-1$
- dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
- dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- if (dialog.open() == IDialogConstants.OK_ID) {
- IResource resource = (IResource) dialog.getFirstResult();
- String arg = resource.getFullPath().toString();
- binaryLocation.setText(workspacePath + arg);
- }
- }
- });
-
- Composite argumentsComp = new Composite(sh, SWT.BORDER_DASH);
- argumentsComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- argumentsComp.setLayout(new GridLayout(2, false));
-
- Label argumentsLabel= new Label(argumentsComp, SWT.HORIZONTAL);
- argumentsLabel.setText(Messages.getString("LaunchWizard.Args")); //$NON-NLS-1$
- labelData.applyTo(argumentsLabel);
-
- argumentsLocation = new Text(argumentsComp, SWT.MULTI | SWT.WRAP | SWT.BORDER);
- GridData gd3 = new GridData(GridData.FILL_HORIZONTAL);
- gd3.heightHint=200;
- argumentsLocation.setLayoutData(gd3);
- Button argumentsButton = new Button(argumentsComp, SWT.PUSH);
- argumentsButton.setText(Messages.getString("LaunchWizard.Func")); //$NON-NLS-1$
- argumentsButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- argumentsLocation.setText(
- argumentsLocation.getText() + " process(\"" //$NON-NLS-1$
- + binaryLocation.getText() + "\").function(\"\")"); //$NON-NLS-1$
- }
- });
-
-
- //TODO: Don't use blank labels to move button to the right column :P
- Label blankLabel2 = new Label(argumentsComp, SWT.HORIZONTAL);
- blankLabel2.setText(""); //$NON-NLS-1$
-
-
- Button launch = new Button(sh, SWT.PUSH);
- launch.setLayoutData(new GridData(GridData.CENTER, GridData.BEGINNING, false, false));
- launch.setText(Messages.getString("LaunchWizard.Launch")); //$NON-NLS-1$
- launch.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- scriptPath = scriptLocation.getText();
- binaryPath = binaryLocation.getText();
- arguments = argumentsLocation.getText();
- ILaunchConfigurationWorkingCopy wc = createConfiguration(null, name);
- try {
- finishLaunch(scriptPath + ": " + binName, mode, wc);//$NON-NLS-1$
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- sh.dispose();
- }
-
- });
-
- //TODO: Verify that this works
- Display.getCurrent().asyncExec(new Runnable() {
- @Override
- public void run() {
- sh.open();
- }
- });
- }
-
- @Override
- public String setScriptPath() {
- scriptPath = "IMPLEMENT"; //$NON-NLS-1$
- return scriptPath;
- }
-
- @Override
- public String setParserID() {
- return null;
- }
-
- @Override
- public String setViewID() {
- return null;
- }
+ private Text scriptLocation;
+ private Text binaryLocation;
+ private Text argumentsLocation;
+ private String workspacePath;
+ private String mode;
+
+ private Shell sh;
+ private Composite fileComp;
+
+ private static final int WIDTH = 670;
+ private static final int HEIGHT = 630;
+
+ /**
+ * The following protected parameters are provided by SystemTapLaunchShortcut:
+ *
+ * Optional customization parameters:
+ * protected String name;
+ * protected String binaryPath;
+ * protected String arguments;
+ * protected String outputPath;
+ * protected String dirPath;
+ * protected String generatedScript;
+ * protected boolean needToGenerate;
+ * protected boolean overwrite;
+ *
+ * Mandatory:
+ * protected String scriptPath;
+ * protected ILaunchConfiguration config;
+ */
+
+
+ /**
+ * Launch method for a generated script that executes on a binary
+ *
+ * MUST specify (String) scriptPath and call config = createConfiguration(bin)!
+ *
+ * Noteworthy defaults:
+ * name defaults to "", but please set it (for usability)
+ * overwrite defaults to true - don't change it unless you really have to.
+ *
+ * To create new launches:
+ * -Copy shortcut code in xml, changing class name and label accordingly
+ * -Create a class that extends SystemTapLaunchShortcut with a function
+ * launch(IBinary bin, String mode)
+ * -Call super.Init()
+ * -Set name (this is shortcut-specific)
+ * -If a binary is used, call binName = getName(bin)
+ * -Call createConfiguration(bin, name)
+ *
+ * -Specify whichever of the optional parameters you need
+ * -Set scriptPath
+ * -Set an ILaunchConfiguration
+ * -Call finishLaunch or finishLaunchWithoutBinary
+ */
+
+ @Override
+ public void launch(IEditorPart ed, String mode) {
+ super.initialize();
+ promptForInputs();
+
+ this.mode = mode;
+ }
+
+ @Override
+ public void launch(ISelection selection, String mode) {
+ super.initialize();
+ promptForInputs();
+
+ this.mode = mode;
+ }
+
+ private void promptForInputs() {
+ InputDialog id = new InputDialog(new Shell(), Messages.getString("LaunchWizard.WelcomeWizard"), //$NON-NLS-1$
+ Messages.getString("LaunchWizard.Text1") + //$NON-NLS-1$
+ Messages.getString("LaunchWizard.Text2") + //$NON-NLS-1$
+ Messages.getString("LaunchWizard.Text3"), //$NON-NLS-1$
+ getLaunchManager().generateLaunchConfigurationName(
+ Messages.getString("LaunchWizard.NamePrefix")), null); //$NON-NLS-1$
+ id.open();
+
+ if (id.getReturnCode() == Window.CANCEL){
+ return;
+ }
+
+ name = id.getValue();
+
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IWorkspaceRoot root = workspace.getRoot();
+ IPath location = root.getLocation();
+ workspacePath = location.toString();
+
+ sh = new Shell();
+ sh.setSize(WIDTH,HEIGHT);
+ sh.setLayout(new GridLayout(1, false));
+ sh.setText(name);
+
+
+ Image img = new Image(sh.getDisplay(), PluginConstants.getPluginLocation() + "systemtapbanner.png"); //$NON-NLS-1$
+ Composite imageCmp = new Composite(sh, SWT.BORDER);
+ imageCmp.setLayout(new FillLayout());
+ GridData imageData = new GridData(650, 157);
+ imageData.horizontalAlignment = SWT.CENTER;
+ imageCmp.setLayoutData(imageData);
+ imageCmp.setBackgroundImage(img);
+
+ fileComp = new Composite(sh, SWT.NONE);
+ fileComp.setLayout(new GridLayout(2, false));
+ fileComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+
+ GridDataFactory labelData = GridDataFactory.fillDefaults().grab(true, false)
+ .span(2,1);
+
+ Label scriptLabel = new Label(fileComp, SWT.HORIZONTAL);
+ scriptLabel.setText(Messages.getString("LaunchWizard.Script")); //$NON-NLS-1$
+ labelData.applyTo(scriptLabel);
+
+ GridDataFactory textData = GridDataFactory.fillDefaults().grab( true, false )
+ .hint(WIDTH, SWT.DEFAULT);
+
+ scriptLocation = new Text(fileComp, SWT.SINGLE | SWT.BORDER);
+ textData.applyTo(scriptLocation);
+ Button scriptButton = new Button(fileComp, SWT.PUSH);
+ scriptButton.setText(Messages.getString("SystemTapOptionsTab.BrowseFiles")); //$NON-NLS-1$
+ scriptButton.setLayoutData(new GridData());
+ scriptButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ String filePath = scriptLocation.getText();
+ FileDialog dialog = new FileDialog(sh, SWT.SAVE);
+ filePath = dialog.open();
+ if (filePath != null) {
+ scriptLocation.setText(filePath);
+ }
+ }
+ });
+
+
+ GridData gd2 = new GridData();
+ gd2.horizontalSpan = 3;
+ Label binaryLabel= new Label(fileComp, SWT.HORIZONTAL);
+ binaryLabel.setText(Messages.getString("LaunchWizard.BinFile")); //$NON-NLS-1$
+ labelData.applyTo(binaryLabel);
+
+ binaryLocation = new Text(fileComp, SWT.SINGLE | SWT.BORDER);
+ textData.applyTo(binaryLocation);
+ Button binaryButton = new Button(fileComp, SWT.PUSH);
+ binaryButton.setText(Messages.getString("SystemTapOptionsTab.WorkspaceButton2")); //$NON-NLS-1$
+ binaryButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(sh, new WorkbenchLabelProvider(), new WorkbenchContentProvider());
+ dialog.setTitle(Messages.getString("SystemTapOptionsTab.SelectResource")); //$NON-NLS-1$
+ dialog.setMessage(Messages.getString("SystemTapOptionsTab.SelectSuppressions")); //$NON-NLS-1$
+ dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
+ dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
+ if (dialog.open() == IDialogConstants.OK_ID) {
+ IResource resource = (IResource) dialog.getFirstResult();
+ String arg = resource.getFullPath().toString();
+ binaryLocation.setText(workspacePath + arg);
+ }
+ }
+ });
+
+ Composite argumentsComp = new Composite(sh, SWT.BORDER_DASH);
+ argumentsComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ argumentsComp.setLayout(new GridLayout(2, false));
+
+ Label argumentsLabel= new Label(argumentsComp, SWT.HORIZONTAL);
+ argumentsLabel.setText(Messages.getString("LaunchWizard.Args")); //$NON-NLS-1$
+ labelData.applyTo(argumentsLabel);
+
+ argumentsLocation = new Text(argumentsComp, SWT.MULTI | SWT.WRAP | SWT.BORDER);
+ GridData gd3 = new GridData(GridData.FILL_HORIZONTAL);
+ gd3.heightHint=200;
+ argumentsLocation.setLayoutData(gd3);
+ Button argumentsButton = new Button(argumentsComp, SWT.PUSH);
+ argumentsButton.setText(Messages.getString("LaunchWizard.Func")); //$NON-NLS-1$
+ argumentsButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ argumentsLocation.setText(
+ argumentsLocation.getText() + " process(\"" //$NON-NLS-1$
+ + binaryLocation.getText() + "\").function(\"\")"); //$NON-NLS-1$
+ }
+ });
+
+
+ //TODO: Don't use blank labels to move button to the right column :P
+ Label blankLabel2 = new Label(argumentsComp, SWT.HORIZONTAL);
+ blankLabel2.setText(""); //$NON-NLS-1$
+
+
+ Button launch = new Button(sh, SWT.PUSH);
+ launch.setLayoutData(new GridData(GridData.CENTER, GridData.BEGINNING, false, false));
+ launch.setText(Messages.getString("LaunchWizard.Launch")); //$NON-NLS-1$
+ launch.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ scriptPath = scriptLocation.getText();
+ binaryPath = binaryLocation.getText();
+ arguments = argumentsLocation.getText();
+ ILaunchConfigurationWorkingCopy wc = createConfiguration(null, name);
+ try {
+ finishLaunch(scriptPath + ": " + binName, mode, wc);//$NON-NLS-1$
+ } catch (Exception e1) {
+ e1.printStackTrace();
+ }
+ sh.dispose();
+ }
+
+ });
+
+ //TODO: Verify that this works
+ Display.getCurrent().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ sh.open();
+ }
+ });
+ }
+
+ @Override
+ public String setScriptPath() {
+ scriptPath = "IMPLEMENT"; //$NON-NLS-1$
+ return scriptPath;
+ }
+
+ @Override
+ public String setParserID() {
+ return null;
+ }
+
+ @Override
+ public String setViewID() {
+ return null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/ListTreeContentProvider.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/ListTreeContentProvider.java
index fc6526a7d9..c9814f484e 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/ListTreeContentProvider.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/ListTreeContentProvider.java
@@ -21,130 +21,130 @@ import org.eclipse.jface.viewers.Viewer;
public class ListTreeContentProvider implements ITreeContentProvider {
- @Override
- public Object[] getChildren(Object parentElement) {
-
- ArrayList<Object> output = new ArrayList<>();
-
- if (parentElement instanceof ICContainer) {
- try {
- Object[] list =((ICContainer) parentElement).getChildren();
- for (Object item : list) {
- if (item instanceof ICContainer) {
- if (checkForValidChildren((ICContainer) item))
- output.add(item);
- } else if (item instanceof ICElement) {
- ICElement el = (ICElement) item;
- if (SystemTapLaunchShortcut.validElement(el))
- output.add(el);
- }
-
-
- }
-
- return output.toArray();
- } catch (CModelException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
-
- /**
- * A container is valid if any of its children are valid c/cpp elements
- * or if it contains another container for which the above holds
- * @param cont
- * @return
- */
- private boolean checkForValidChildren(ICContainer cont) {
- try {
- for (ICElement child : cont.getChildren()) {
-
- if ((child != null)
- && SystemTapLaunchShortcut.validElement(child))
- return true;
- if ((child instanceof ICContainer)
- && checkForValidChildren((ICContainer) child)) {
- return true;
- }
- }
- } catch (CModelException e) {
- e.printStackTrace();
- }
-
- return false;
-
- }
-
- @Override
- public Object getParent(Object element) {
- if (element instanceof ICElement) {
- return ((ICElement)element).getAncestor(ICElement.C_CCONTAINER);
- }
- return null;
- }
-
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof ICContainer) {
- try {
- if (((ICContainer) element).getChildren().length > 0)
- return true;
- } catch (CModelException e) {
- e.printStackTrace();
- }
- }
- return false;
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof List) {
- for (Object element : (List<?>) inputElement)
- if (element instanceof ICContainer)
- try {
- ICElement[] array = ((ICContainer) element).getChildren();
- ArrayList<ICElement> output = new ArrayList<>();
-
- for (ICElement item : array) {
- if ((item instanceof ICContainer)
- && checkForValidChildren((ICContainer) item)) {
- output.add(item);
- }
-
- if (SystemTapLaunchShortcut.validElement(item)) {
- output.add(item);
- }
- }
- return output.toArray();
- } catch (CModelException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
-
- @Override
- public void dispose() {
-
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
-
- public Object[] findElements(Object inputElement) {
- ArrayList<Object> output = new ArrayList<>();
-
- if (inputElement instanceof List) {
- for (Object element : (List<?>) inputElement) {
- Object[] list = (getChildren(element));
- for (Object o : list) {
- output.add(o);
- }
- }
- }
- return output.toArray();
- }
+ @Override
+ public Object[] getChildren(Object parentElement) {
+
+ ArrayList<Object> output = new ArrayList<>();
+
+ if (parentElement instanceof ICContainer) {
+ try {
+ Object[] list =((ICContainer) parentElement).getChildren();
+ for (Object item : list) {
+ if (item instanceof ICContainer) {
+ if (checkForValidChildren((ICContainer) item))
+ output.add(item);
+ } else if (item instanceof ICElement) {
+ ICElement el = (ICElement) item;
+ if (SystemTapLaunchShortcut.validElement(el))
+ output.add(el);
+ }
+
+
+ }
+
+ return output.toArray();
+ } catch (CModelException e) {
+ e.printStackTrace();
+ }
+ }
+ return null;
+ }
+
+ /**
+ * A container is valid if any of its children are valid c/cpp elements
+ * or if it contains another container for which the above holds
+ * @param cont
+ * @return
+ */
+ private boolean checkForValidChildren(ICContainer cont) {
+ try {
+ for (ICElement child : cont.getChildren()) {
+
+ if ((child != null)
+ && SystemTapLaunchShortcut.validElement(child))
+ return true;
+ if ((child instanceof ICContainer)
+ && checkForValidChildren((ICContainer) child)) {
+ return true;
+ }
+ }
+ } catch (CModelException e) {
+ e.printStackTrace();
+ }
+
+ return false;
+
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ if (element instanceof ICElement) {
+ return ((ICElement)element).getAncestor(ICElement.C_CCONTAINER);
+ }
+ return null;
+ }
+
+ @Override
+ public boolean hasChildren(Object element) {
+ if (element instanceof ICContainer) {
+ try {
+ if (((ICContainer) element).getChildren().length > 0)
+ return true;
+ } catch (CModelException e) {
+ e.printStackTrace();
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof List) {
+ for (Object element : (List<?>) inputElement)
+ if (element instanceof ICContainer)
+ try {
+ ICElement[] array = ((ICContainer) element).getChildren();
+ ArrayList<ICElement> output = new ArrayList<>();
+
+ for (ICElement item : array) {
+ if ((item instanceof ICContainer)
+ && checkForValidChildren((ICContainer) item)) {
+ output.add(item);
+ }
+
+ if (SystemTapLaunchShortcut.validElement(item)) {
+ output.add(item);
+ }
+ }
+ return output.toArray();
+ } catch (CModelException e) {
+ e.printStackTrace();
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public void dispose() {
+
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+
+
+ public Object[] findElements(Object inputElement) {
+ ArrayList<Object> output = new ArrayList<>();
+
+ if (inputElement instanceof List) {
+ for (Object element : (List<?>) inputElement) {
+ Object[] list = (getChildren(element));
+ for (Object o : list) {
+ output.add(o);
+ }
+ }
+ }
+ return output.toArray();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/Messages.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/Messages.java
index 8a806b998f..5ed0e607ef 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/Messages.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -14,19 +14,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.callgraph.launch.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.callgraph.launch.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/RuledTreeSelectionDialog.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/RuledTreeSelectionDialog.java
index c67d54d3e8..9ca155cd97 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/RuledTreeSelectionDialog.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/RuledTreeSelectionDialog.java
@@ -6,11 +6,11 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * IBM Corporation - initial API and implementation
- * Sebastian Davids <sdavids@gmx.de> - Fix for bug 19346 - Dialog font should be
- * activated and used by other components.
- * Lubomir Marinov <lubomir.marinov@gmail.com> - Fix for bug 182122 -[Dialogs]
- * CheckedTreeSelectionDialog#createSelectionButtons(Composite) fails to
+ * IBM Corporation - initial API and implementation
+ * Sebastian Davids <sdavids@gmx.de> - Fix for bug 19346 - Dialog font should be
+ * activated and used by other components.
+ * Lubomir Marinov <lubomir.marinov@gmail.com> - Fix for bug 182122 -[Dialogs]
+ * CheckedTreeSelectionDialog#createSelectionButtons(Composite) fails to
* align the selection buttons to the right
*******************************************************************************/
package org.eclipse.linuxtools.internal.callgraph.launch;
@@ -30,36 +30,36 @@ import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog;
/**
* A class to select elements out of a tree structure.
- *
+ *
* @since 2.0
*/
public class RuledTreeSelectionDialog extends CheckedTreeSelectionDialog {
public RuledTreeSelectionDialog(Shell parent, ILabelProvider labelProvider,
- ITreeContentProvider contentProvider) {
- super(parent, labelProvider, contentProvider);
- }
+ ITreeContentProvider contentProvider) {
+ super(parent, labelProvider, contentProvider);
+ }
- /*
+ /*
* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
- protected Control createDialogArea(Composite parent) {
- Composite composite = (Composite) super.createDialogArea(parent);
-
+ protected Control createDialogArea(Composite parent) {
+ Composite composite = (Composite) super.createDialogArea(parent);
+
Label line = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL
| SWT.BOLD);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 2;
line.setLayoutData(gridData);
- GridLayout lay = (GridLayout) composite.getLayout();
- lay.marginHeight=0;
- composite.setLayout(lay);
-
+ GridLayout lay = (GridLayout) composite.getLayout();
+ lay.marginHeight=0;
+ composite.setLayout(lay);
+
return composite;
}
-
+
/*
* @see Dialog#createButtonBar(Composite)
@@ -77,33 +77,33 @@ public class RuledTreeSelectionDialog extends CheckedTreeSelectionDialog {
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
composite.setFont(font);
- /*
- * Create the rest of the button bar, but tell it not to
- * create a help button (we've already created it).
- */
- boolean helpAvailable = isHelpAvailable();
- setHelpAvailable(false);
- Composite c = (Composite) super.createButtonBar(composite);
- GridLayout lay = (GridLayout) c.getLayout();
- lay.marginHeight=0;
- c.setLayout(lay);
- composite.setLayout(layout);
-
- setHelpAvailable(helpAvailable);
+ /*
+ * Create the rest of the button bar, but tell it not to
+ * create a help button (we've already created it).
+ */
+ boolean helpAvailable = isHelpAvailable();
+ setHelpAvailable(false);
+ Composite c = (Composite) super.createButtonBar(composite);
+ GridLayout lay = (GridLayout) c.getLayout();
+ lay.marginHeight=0;
+ c.setLayout(lay);
+ composite.setLayout(layout);
+
+ setHelpAvailable(helpAvailable);
return composite;
}
-
+
@Override
- protected Label createMessageArea(Composite composite) {
- Label label = new Label(composite, SWT.NONE);
- if (this.getMessage() != null) {
- label.setText(this.getMessage());
- }
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.verticalIndent=10;
- label.setLayoutData(gd);
-
- label.setFont(composite.getFont());
- return label;
- }
+ protected Label createMessageArea(Composite composite) {
+ Label label = new Label(composite, SWT.NONE);
+ if (this.getMessage() != null) {
+ label.setText(this.getMessage());
+ }
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.verticalIndent=10;
+ label.setLayoutData(gd);
+
+ label.setFont(composite.getFont());
+ return label;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchConfigurationDelegate.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
index ff75530241..37a553d5d4 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
@@ -49,386 +49,386 @@ import org.eclipse.linuxtools.tools.launch.core.factory.CdtSpawnerProcessFactory
*/
public class SystemTapLaunchConfigurationDelegate extends AbstractCLaunchDelegate {
- private static final String [] escapableChars = new String [] {"(", ")", " "}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- private static final String TEMP_ERROR_OUTPUT =
- PluginConstants.getDefaultOutput() + "stapTempError.error"; //$NON-NLS-1$
- private String cmd;
- private File temporaryScript = null;
- private String arguments = ""; //$NON-NLS-1$
- private String scriptPath = ""; //$NON-NLS-1$
- private String binaryPath = ""; //$NON-NLS-1$
- private String outputPath = ""; //$NON-NLS-1$
- private boolean needsBinary = false; // Set to false if we want to use SystemTap
- private boolean needsArguments = false;
- private String binaryArguments = ""; //$NON-NLS-1$
- private String partialCommand = ""; //$NON-NLS-1$
- private String stap = ""; //$NON-NLS-1$
-
- @Override
- protected String getPluginID() {
- return null;
- }
-
- /**
- * Sets strings to blank, booleans to false and everything else to null
- */
- private void initialize() {
- temporaryScript = null;
- arguments = ""; //$NON-NLS-1$
- scriptPath = ""; //$NON-NLS-1$
- binaryPath = ""; //$NON-NLS-1$
- outputPath = ""; //$NON-NLS-1$
- needsBinary = false; // Set to false if we want to use SystemTap
- needsArguments = false;
- binaryArguments = ""; //$NON-NLS-1$
- }
-
- @Override
- public void launch(ILaunchConfiguration config, String mode,
- ILaunch launch, IProgressMonitor m) throws CoreException {
-
- if (m == null) {
- m = new NullProgressMonitor();
- }
- SubMonitor monitor = SubMonitor.convert(m,
- "SystemTap runtime monitor", 5); //$NON-NLS-1$
- initialize();
-
- // check for cancellation
- if (monitor.isCanceled()) {
- return;
- }
-
- /*
- * Set variables
- */
- if (!config.getAttribute(LaunchConfigurationConstants.ARGUMENTS,
- LaunchConfigurationConstants.DEFAULT_ARGUMENTS).equals(
- LaunchConfigurationConstants.DEFAULT_ARGUMENTS)) {
- arguments = config.getAttribute(
- LaunchConfigurationConstants.ARGUMENTS,
- LaunchConfigurationConstants.DEFAULT_ARGUMENTS);
- needsArguments = true;
- }
- if (!config.getAttribute(LaunchConfigurationConstants.BINARY_PATH,
- LaunchConfigurationConstants.DEFAULT_BINARY_PATH).equals(
- LaunchConfigurationConstants.DEFAULT_BINARY_PATH)) {
- binaryPath = config.getAttribute(
- LaunchConfigurationConstants.BINARY_PATH,
- LaunchConfigurationConstants.DEFAULT_BINARY_PATH);
- needsBinary = true;
- }
- if (!config.getAttribute(LaunchConfigurationConstants.BINARY_ARGUMENTS,
- LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS).equals(
- LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS)) {
- binaryArguments = config.getAttribute(
- LaunchConfigurationConstants.BINARY_ARGUMENTS,
- LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS);
- }
- if (!config.getAttribute(LaunchConfigurationConstants.SCRIPT_PATH,
- LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH).equals(
- LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH)) {
- scriptPath = config.getAttribute(
- LaunchConfigurationConstants.SCRIPT_PATH,
- LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH);
- }
- // Generate script if needed
- if (config.getAttribute(LaunchConfigurationConstants.NEED_TO_GENERATE,
- LaunchConfigurationConstants.DEFAULT_NEED_TO_GENERATE)) {
- temporaryScript = new File(scriptPath);
- temporaryScript.delete();
- try {
- temporaryScript.createNewFile();
- try (FileWriter fstream = new FileWriter(temporaryScript);
- BufferedWriter out = new BufferedWriter(fstream)) {
- out.write(config
- .getAttribute(
- LaunchConfigurationConstants.GENERATED_SCRIPT,
- LaunchConfigurationConstants.DEFAULT_GENERATED_SCRIPT));
- }
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
-
- stap = config.getAttribute(LaunchConfigurationConstants.COMMAND,
- PluginConstants.STAP_PATH);
-
- /**
- * Generate partial command
- */
- partialCommand = ConfigurationOptionsSetter.setOptions(config);
-
- outputPath = config.getAttribute(
- LaunchConfigurationConstants.OUTPUT_PATH,
- PluginConstants.getDefaultOutput());
-
- boolean fileExists = true;
- try {
- //Make sure the output file exists
- File tempFile = new File(outputPath);
- tempFile.delete();
- fileExists = tempFile.createNewFile();
- } catch (IOException e1) {
- fileExists = false;
- }
-
- // check for cancellation
- if ( !fileExists || monitor.isCanceled() ) {
- SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.0"), //$NON-NLS-1$
- Messages.getString("SystemTapLaunchConfigurationDelegate.1"), Messages.getString("SystemTapLaunchConfigurationDelegate.2") + outputPath + //$NON-NLS-1$ //$NON-NLS-2$
- Messages.getString("SystemTapLaunchConfigurationDelegate.3")); //$NON-NLS-1$
- mess.schedule();
- return;
- }
-
- finishLaunch(launch, config, m);
- }
-
- /**
- * Returns the current SystemTap command, or returns an error message.
- * @return
- */
- public String getCommand() {
- if (!cmd.isEmpty()) {
- return cmd;
- } else {
- return Messages.getString("SystemTapLaunchConfigurationDelegate.NoCommand"); //$NON-NLS-1$
- }
- }
-
- private void finishLaunch(ILaunch launch, ILaunchConfiguration config,
- IProgressMonitor monitor) {
-
- try {
- // Check for cancellation
- if (monitor.isCanceled() || launch == null) {
- return;
- }
- monitor.worked(1);
-
- // set the default source locator if required
- setDefaultSourceLocator(launch, config);
-
- /*
- * Fetch a parser
- */
- String parserClass = config.getAttribute(LaunchConfigurationConstants.PARSER_CLASS,
- LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
- IExtensionRegistry reg = Platform.getExtensionRegistry();
- IConfigurationElement[] extensions = reg
- .getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
- PluginConstants.PARSER_NAME,
- parserClass);
- if (extensions == null || extensions.length < 1) {
- SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
- Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
- Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser2") + //$NON-NLS-1$
- Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser3") + parserClass); //$NON-NLS-1$
- mess.schedule();
- return;
- }
-
- IConfigurationElement element = extensions[0];
- SystemTapParser parser =
- (SystemTapParser) element.createExecutableExtension(PluginConstants.ATTR_CLASS);
-
- //Set parser options
- parser.setViewID(config.getAttribute(LaunchConfigurationConstants.VIEW_CLASS,
- LaunchConfigurationConstants.VIEW_CLASS));
- parser.setSourcePath(outputPath);
- parser.setMonitor(SubMonitor.convert(monitor));
- parser.setDone(false);
- parser.setSecondaryID(config.getAttribute(LaunchConfigurationConstants.SECONDARY_VIEW_ID,
- LaunchConfigurationConstants.DEFAULT_SECONDARY_VIEW_ID));
-
- parser.setKillButtonEnabled(true);
-
- monitor.worked(1);
-
- /*
- * Launch
- */
-
- File workDir = getWorkingDirectory(config);
- if (workDir == null) {
- workDir = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- //Put command into a shell script
- String cmd = generateCommand();
- File script = File.createTempFile("org.eclipse.linuxtools.profiling.launch" + System.currentTimeMillis(), ".sh"); //$NON-NLS-1$ //$NON-NLS-2$
- String data = "#!/bin/sh\nexec " + cmd; //$NON-NLS-1$
- try (FileOutputStream out = new FileOutputStream(script)){
- out.write(data.getBytes());
- }
-
- String [] commandArray = new String [] {"sh", script.getAbsolutePath()}; //$NON-NLS-1$
-
- Process subProcess = CdtSpawnerProcessFactory.getFactory().exec(commandArray, getEnvironment(config),
- workDir, true);
-
- IProcess process = DebugPlugin.newProcess(launch, subProcess,
- renderProcessLabel(commandArray[0]));
- // set the command line used
- process.setAttribute(IProcess.ATTR_CMDLINE,cmd);
-
- monitor.worked(1);
-
- StreamListener s = new StreamListener();
- process.getStreamsProxy().getErrorStreamMonitor().addListener(s);
-
- while (!process.isTerminated()) {
- Thread.sleep(100);
- if ((monitor != null && monitor.isCanceled()) || parser.isDone()) {
- parser.cancelJob();
- process.terminate();
- return;
- }
- }
- Thread.sleep(100);
- s.close();
- parser.setKillButtonEnabled(false);
-
- if (process.getExitValue() != 0) {
- parser.cancelJob();
- //exit code for command not found
- if (process.getExitValue() == 127){
- SystemTapUIErrorMessages errorDialog = new SystemTapUIErrorMessages(
- Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
- Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
- Messages.getString("SystemTapLaunchConfigurationDelegate.stapNotFound")); //$NON-NLS-1$
-
- errorDialog.schedule();
- }else{
- SystemTapErrorHandler errorHandler = new SystemTapErrorHandler();
-
- //Prepare stap information
- errorHandler.appendToLog(config.getName() + Messages.getString("SystemTapLaunchConfigurationDelegate.stap_command") + cmd+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE);//$NON-NLS-1$
-
- //Handle error from TEMP_ERROR_OUTPUT
- errorHandler.handle(monitor, new FileReader(TEMP_ERROR_OUTPUT));
- if ((monitor != null && monitor.isCanceled())) {
- return;
- }
-
- errorHandler.finishHandling();
- if (errorHandler.isErrorRecognized()) {
- SystemTapUIErrorMessages errorDialog = new SystemTapUIErrorMessages(
- Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
- Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
- errorHandler.getErrorMessage());
-
- errorDialog.schedule();
- }
- }
- return;
- }
-
- if (element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) {
- parser.setRealTime(true);
- }
-
- parser.schedule();
- monitor.worked(1);
-
- String message = generateErrorMessage(config.getName(), binaryArguments);
-
- DocWriter dw = new DocWriter(Messages.getString("SystemTapLaunchConfigurationDelegate.DocWriterName"), //$NON-NLS-1$
- (Helper.getConsoleByName(config.getName())), message);
- dw.schedule();
-
- } catch (IOException|InterruptedException|CoreException e) {
- e.printStackTrace();
- } finally {
- monitor.done();
-
- }
- }
-
- private String generateErrorMessage(String configName, String binaryCommand) {
- String output = ""; //$NON-NLS-1$
-
- if (binaryCommand == null || binaryCommand.length() < 0) {
- output = PluginConstants.NEW_LINE +
- PluginConstants.NEW_LINE + "-------------" + //$NON-NLS-1$
- PluginConstants.NEW_LINE +
- Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch10") //$NON-NLS-1$
- + configName + PluginConstants.NEW_LINE +
- Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch8") + //$NON-NLS-1$
- Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch9") + //$NON-NLS-1$
- "configuration in Profile As --> Profile Configurations." + //$NON-NLS-1$
- PluginConstants.NEW_LINE + PluginConstants.NEW_LINE;
- } else {
- output = PluginConstants.NEW_LINE
- + PluginConstants.NEW_LINE +"-------------" //$NON-NLS-1$
- + PluginConstants.NEW_LINE
- + Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage1") //$NON-NLS-1$
- + configName + PluginConstants.NEW_LINE +
- Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage2") //$NON-NLS-1$
- + binaryCommand + PluginConstants.NEW_LINE +
- Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage3") + //$NON-NLS-1$
- Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage4") + //$NON-NLS-1$
- Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage5") + //$NON-NLS-1$
- PluginConstants.NEW_LINE + PluginConstants.NEW_LINE;
- }
-
- return output;
- }
-
- private static class StreamListener implements IStreamListener{
- private int counter;
- private BufferedWriter bw;
-
- public StreamListener() throws IOException {
- File file = new File(TEMP_ERROR_OUTPUT);
- file.delete();
- file.createNewFile();
- bw = Helper.setBufferedWriter(TEMP_ERROR_OUTPUT);
- counter = 0;
- }
-
- @Override
- public void streamAppended(String text, IStreamMonitor monitor) {
- try {
- if (text.length() < 1) {
- return;
- }
- counter++;
- if (counter < PluginConstants.MAX_ERRORS) {
- bw.append(text);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- public void close() throws IOException {
- bw.close();
- }
- }
-
- public String generateCommand() {
- // Generate the command
- cmd = SystemTapCommandGenerator.generateCommand(escapeSpecialCharacters(scriptPath), escapeSpecialCharacters(binaryPath),
- partialCommand, needsBinary, needsArguments, escapeSpecialCharacters(arguments), binaryArguments, stap);
- cmd += " >& " + escapeSpecialCharacters(outputPath); //$NON-NLS-1$
- return cmd;
- }
-
- /**
- * Escapes special characters in the target string
- *
- * @param script the script to be executed by the shell.
- * @return the formatted string that will be executed.
- */
- private String escapeSpecialCharacters(String str) {
- // Modify script to catch escapable characters.
- String res = str;
- for (int i = 0; i < escapableChars.length; i++) {
- res = res.replace(escapableChars[i], "\\" + escapableChars[i]); //$NON-NLS-1$
- }
- return res;
- }
+ private static final String [] escapableChars = new String [] {"(", ")", " "}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ private static final String TEMP_ERROR_OUTPUT =
+ PluginConstants.getDefaultOutput() + "stapTempError.error"; //$NON-NLS-1$
+ private String cmd;
+ private File temporaryScript = null;
+ private String arguments = ""; //$NON-NLS-1$
+ private String scriptPath = ""; //$NON-NLS-1$
+ private String binaryPath = ""; //$NON-NLS-1$
+ private String outputPath = ""; //$NON-NLS-1$
+ private boolean needsBinary = false; // Set to false if we want to use SystemTap
+ private boolean needsArguments = false;
+ private String binaryArguments = ""; //$NON-NLS-1$
+ private String partialCommand = ""; //$NON-NLS-1$
+ private String stap = ""; //$NON-NLS-1$
+
+ @Override
+ protected String getPluginID() {
+ return null;
+ }
+
+ /**
+ * Sets strings to blank, booleans to false and everything else to null
+ */
+ private void initialize() {
+ temporaryScript = null;
+ arguments = ""; //$NON-NLS-1$
+ scriptPath = ""; //$NON-NLS-1$
+ binaryPath = ""; //$NON-NLS-1$
+ outputPath = ""; //$NON-NLS-1$
+ needsBinary = false; // Set to false if we want to use SystemTap
+ needsArguments = false;
+ binaryArguments = ""; //$NON-NLS-1$
+ }
+
+ @Override
+ public void launch(ILaunchConfiguration config, String mode,
+ ILaunch launch, IProgressMonitor m) throws CoreException {
+
+ if (m == null) {
+ m = new NullProgressMonitor();
+ }
+ SubMonitor monitor = SubMonitor.convert(m,
+ "SystemTap runtime monitor", 5); //$NON-NLS-1$
+ initialize();
+
+ // check for cancellation
+ if (monitor.isCanceled()) {
+ return;
+ }
+
+ /*
+ * Set variables
+ */
+ if (!config.getAttribute(LaunchConfigurationConstants.ARGUMENTS,
+ LaunchConfigurationConstants.DEFAULT_ARGUMENTS).equals(
+ LaunchConfigurationConstants.DEFAULT_ARGUMENTS)) {
+ arguments = config.getAttribute(
+ LaunchConfigurationConstants.ARGUMENTS,
+ LaunchConfigurationConstants.DEFAULT_ARGUMENTS);
+ needsArguments = true;
+ }
+ if (!config.getAttribute(LaunchConfigurationConstants.BINARY_PATH,
+ LaunchConfigurationConstants.DEFAULT_BINARY_PATH).equals(
+ LaunchConfigurationConstants.DEFAULT_BINARY_PATH)) {
+ binaryPath = config.getAttribute(
+ LaunchConfigurationConstants.BINARY_PATH,
+ LaunchConfigurationConstants.DEFAULT_BINARY_PATH);
+ needsBinary = true;
+ }
+ if (!config.getAttribute(LaunchConfigurationConstants.BINARY_ARGUMENTS,
+ LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS).equals(
+ LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS)) {
+ binaryArguments = config.getAttribute(
+ LaunchConfigurationConstants.BINARY_ARGUMENTS,
+ LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS);
+ }
+ if (!config.getAttribute(LaunchConfigurationConstants.SCRIPT_PATH,
+ LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH).equals(
+ LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH)) {
+ scriptPath = config.getAttribute(
+ LaunchConfigurationConstants.SCRIPT_PATH,
+ LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH);
+ }
+ // Generate script if needed
+ if (config.getAttribute(LaunchConfigurationConstants.NEED_TO_GENERATE,
+ LaunchConfigurationConstants.DEFAULT_NEED_TO_GENERATE)) {
+ temporaryScript = new File(scriptPath);
+ temporaryScript.delete();
+ try {
+ temporaryScript.createNewFile();
+ try (FileWriter fstream = new FileWriter(temporaryScript);
+ BufferedWriter out = new BufferedWriter(fstream)) {
+ out.write(config
+ .getAttribute(
+ LaunchConfigurationConstants.GENERATED_SCRIPT,
+ LaunchConfigurationConstants.DEFAULT_GENERATED_SCRIPT));
+ }
+ } catch (IOException e1) {
+ e1.printStackTrace();
+ }
+ }
+
+ stap = config.getAttribute(LaunchConfigurationConstants.COMMAND,
+ PluginConstants.STAP_PATH);
+
+ /**
+ * Generate partial command
+ */
+ partialCommand = ConfigurationOptionsSetter.setOptions(config);
+
+ outputPath = config.getAttribute(
+ LaunchConfigurationConstants.OUTPUT_PATH,
+ PluginConstants.getDefaultOutput());
+
+ boolean fileExists = true;
+ try {
+ //Make sure the output file exists
+ File tempFile = new File(outputPath);
+ tempFile.delete();
+ fileExists = tempFile.createNewFile();
+ } catch (IOException e1) {
+ fileExists = false;
+ }
+
+ // check for cancellation
+ if ( !fileExists || monitor.isCanceled() ) {
+ SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.0"), //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchConfigurationDelegate.1"), Messages.getString("SystemTapLaunchConfigurationDelegate.2") + outputPath + //$NON-NLS-1$ //$NON-NLS-2$
+ Messages.getString("SystemTapLaunchConfigurationDelegate.3")); //$NON-NLS-1$
+ mess.schedule();
+ return;
+ }
+
+ finishLaunch(launch, config, m);
+ }
+
+ /**
+ * Returns the current SystemTap command, or returns an error message.
+ * @return
+ */
+ public String getCommand() {
+ if (!cmd.isEmpty()) {
+ return cmd;
+ } else {
+ return Messages.getString("SystemTapLaunchConfigurationDelegate.NoCommand"); //$NON-NLS-1$
+ }
+ }
+
+ private void finishLaunch(ILaunch launch, ILaunchConfiguration config,
+ IProgressMonitor monitor) {
+
+ try {
+ // Check for cancellation
+ if (monitor.isCanceled() || launch == null) {
+ return;
+ }
+ monitor.worked(1);
+
+ // set the default source locator if required
+ setDefaultSourceLocator(launch, config);
+
+ /*
+ * Fetch a parser
+ */
+ String parserClass = config.getAttribute(LaunchConfigurationConstants.PARSER_CLASS,
+ LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
+ IExtensionRegistry reg = Platform.getExtensionRegistry();
+ IConfigurationElement[] extensions = reg
+ .getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
+ PluginConstants.PARSER_NAME,
+ parserClass);
+ if (extensions == null || extensions.length < 1) {
+ SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser2") + //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser3") + parserClass); //$NON-NLS-1$
+ mess.schedule();
+ return;
+ }
+
+ IConfigurationElement element = extensions[0];
+ SystemTapParser parser =
+ (SystemTapParser) element.createExecutableExtension(PluginConstants.ATTR_CLASS);
+
+ //Set parser options
+ parser.setViewID(config.getAttribute(LaunchConfigurationConstants.VIEW_CLASS,
+ LaunchConfigurationConstants.VIEW_CLASS));
+ parser.setSourcePath(outputPath);
+ parser.setMonitor(SubMonitor.convert(monitor));
+ parser.setDone(false);
+ parser.setSecondaryID(config.getAttribute(LaunchConfigurationConstants.SECONDARY_VIEW_ID,
+ LaunchConfigurationConstants.DEFAULT_SECONDARY_VIEW_ID));
+
+ parser.setKillButtonEnabled(true);
+
+ monitor.worked(1);
+
+ /*
+ * Launch
+ */
+
+ File workDir = getWorkingDirectory(config);
+ if (workDir == null) {
+ workDir = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ //Put command into a shell script
+ String cmd = generateCommand();
+ File script = File.createTempFile("org.eclipse.linuxtools.profiling.launch" + System.currentTimeMillis(), ".sh"); //$NON-NLS-1$ //$NON-NLS-2$
+ String data = "#!/bin/sh\nexec " + cmd; //$NON-NLS-1$
+ try (FileOutputStream out = new FileOutputStream(script)){
+ out.write(data.getBytes());
+ }
+
+ String [] commandArray = new String [] {"sh", script.getAbsolutePath()}; //$NON-NLS-1$
+
+ Process subProcess = CdtSpawnerProcessFactory.getFactory().exec(commandArray, getEnvironment(config),
+ workDir, true);
+
+ IProcess process = DebugPlugin.newProcess(launch, subProcess,
+ renderProcessLabel(commandArray[0]));
+ // set the command line used
+ process.setAttribute(IProcess.ATTR_CMDLINE,cmd);
+
+ monitor.worked(1);
+
+ StreamListener s = new StreamListener();
+ process.getStreamsProxy().getErrorStreamMonitor().addListener(s);
+
+ while (!process.isTerminated()) {
+ Thread.sleep(100);
+ if ((monitor != null && monitor.isCanceled()) || parser.isDone()) {
+ parser.cancelJob();
+ process.terminate();
+ return;
+ }
+ }
+ Thread.sleep(100);
+ s.close();
+ parser.setKillButtonEnabled(false);
+
+ if (process.getExitValue() != 0) {
+ parser.cancelJob();
+ //exit code for command not found
+ if (process.getExitValue() == 127){
+ SystemTapUIErrorMessages errorDialog = new SystemTapUIErrorMessages(
+ Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchConfigurationDelegate.stapNotFound")); //$NON-NLS-1$
+
+ errorDialog.schedule();
+ }else{
+ SystemTapErrorHandler errorHandler = new SystemTapErrorHandler();
+
+ //Prepare stap information
+ errorHandler.appendToLog(config.getName() + Messages.getString("SystemTapLaunchConfigurationDelegate.stap_command") + cmd+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE);//$NON-NLS-1$
+
+ //Handle error from TEMP_ERROR_OUTPUT
+ errorHandler.handle(monitor, new FileReader(TEMP_ERROR_OUTPUT));
+ if ((monitor != null && monitor.isCanceled())) {
+ return;
+ }
+
+ errorHandler.finishHandling();
+ if (errorHandler.isErrorRecognized()) {
+ SystemTapUIErrorMessages errorDialog = new SystemTapUIErrorMessages(
+ Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchConfigurationDelegate.CallGraphGenericError"), //$NON-NLS-1$
+ errorHandler.getErrorMessage());
+
+ errorDialog.schedule();
+ }
+ }
+ return;
+ }
+
+ if (element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) {
+ parser.setRealTime(true);
+ }
+
+ parser.schedule();
+ monitor.worked(1);
+
+ String message = generateErrorMessage(config.getName(), binaryArguments);
+
+ DocWriter dw = new DocWriter(Messages.getString("SystemTapLaunchConfigurationDelegate.DocWriterName"), //$NON-NLS-1$
+ (Helper.getConsoleByName(config.getName())), message);
+ dw.schedule();
+
+ } catch (IOException|InterruptedException|CoreException e) {
+ e.printStackTrace();
+ } finally {
+ monitor.done();
+
+ }
+ }
+
+ private String generateErrorMessage(String configName, String binaryCommand) {
+ String output = ""; //$NON-NLS-1$
+
+ if (binaryCommand == null || binaryCommand.length() < 0) {
+ output = PluginConstants.NEW_LINE +
+ PluginConstants.NEW_LINE + "-------------" + //$NON-NLS-1$
+ PluginConstants.NEW_LINE +
+ Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch10") //$NON-NLS-1$
+ + configName + PluginConstants.NEW_LINE +
+ Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch8") + //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch9") + //$NON-NLS-1$
+ "configuration in Profile As --> Profile Configurations." + //$NON-NLS-1$
+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE;
+ } else {
+ output = PluginConstants.NEW_LINE
+ + PluginConstants.NEW_LINE +"-------------" //$NON-NLS-1$
+ + PluginConstants.NEW_LINE
+ + Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage1") //$NON-NLS-1$
+ + configName + PluginConstants.NEW_LINE +
+ Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage2") //$NON-NLS-1$
+ + binaryCommand + PluginConstants.NEW_LINE +
+ Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage3") + //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage4") + //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage5") + //$NON-NLS-1$
+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE;
+ }
+
+ return output;
+ }
+
+ private static class StreamListener implements IStreamListener{
+ private int counter;
+ private BufferedWriter bw;
+
+ public StreamListener() throws IOException {
+ File file = new File(TEMP_ERROR_OUTPUT);
+ file.delete();
+ file.createNewFile();
+ bw = Helper.setBufferedWriter(TEMP_ERROR_OUTPUT);
+ counter = 0;
+ }
+
+ @Override
+ public void streamAppended(String text, IStreamMonitor monitor) {
+ try {
+ if (text.length() < 1) {
+ return;
+ }
+ counter++;
+ if (counter < PluginConstants.MAX_ERRORS) {
+ bw.append(text);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void close() throws IOException {
+ bw.close();
+ }
+ }
+
+ public String generateCommand() {
+ // Generate the command
+ cmd = SystemTapCommandGenerator.generateCommand(escapeSpecialCharacters(scriptPath), escapeSpecialCharacters(binaryPath),
+ partialCommand, needsBinary, needsArguments, escapeSpecialCharacters(arguments), binaryArguments, stap);
+ cmd += " >& " + escapeSpecialCharacters(outputPath); //$NON-NLS-1$
+ return cmd;
+ }
+
+ /**
+ * Escapes special characters in the target string
+ *
+ * @param script the script to be executed by the shell.
+ * @return the formatted string that will be executed.
+ */
+ private String escapeSpecialCharacters(String str) {
+ // Modify script to catch escapable characters.
+ String res = str;
+ for (int i = 0; i < escapableChars.length; i++) {
+ res = res.replace(escapableChars[i], "\\" + escapableChars[i]); //$NON-NLS-1$
+ }
+ return res;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchConfigurationTabGroup.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchConfigurationTabGroup.java
index cedcca98de..24a622f6d6 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchConfigurationTabGroup.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchConfigurationTabGroup.java
@@ -26,18 +26,18 @@ import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTabGrou
*/
public class SystemTapLaunchConfigurationTabGroup extends ProfileLaunchConfigurationTabGroup {
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- return new AbstractLaunchConfigurationTab[] {
- new SystemTapOptionsTab()
- };
- }
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ return new AbstractLaunchConfigurationTab[] {
+ new SystemTapOptionsTab()
+ };
+ }
- @Override
- public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
- ArrayList<AbstractLaunchConfigurationTab> tabs = new ArrayList<>();
+ @Override
+ public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
+ ArrayList<AbstractLaunchConfigurationTab> tabs = new ArrayList<>();
- tabs.addAll(Arrays.asList(getProfileTabs()));
- setTabs(tabs.toArray(new AbstractLaunchConfigurationTab[tabs.size()]));
- }
+ tabs.addAll(Arrays.asList(getProfileTabs()));
+ setTabs(tabs.toArray(new AbstractLaunchConfigurationTab[tabs.size()]));
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchShortcut.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchShortcut.java
index 23c16add7d..556d96c23c 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchShortcut.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapLaunchShortcut.java
@@ -90,735 +90,735 @@ import org.eclipse.ui.model.WorkbenchLabelProvider;
* </ul>
*<br>
*<br>
- * The following protected parameters are provided by
- * SystemTapLaunchShortcut:
- *<br> <br>
- * Optional customization parameters: <code> protected String name; protected
- * String binaryPath; protected String arguments; protected String
- * outputPath; protected String dirPath; protected String generatedScript;
- * protected boolean needToGenerate; protected boolean overwrite;</code>
- * <br> <br>
- * Mandatory: <code> protected String scriptPath; protected ILaunchConfiguration
- * config;</code>
+ * The following protected parameters are provided by
+ * SystemTapLaunchShortcut:
+ *<br> <br>
+ * Optional customization parameters: <code> protected String name; protected
+ * String binaryPath; protected String arguments; protected String
+ * outputPath; protected String dirPath; protected String generatedScript;
+ * protected boolean needToGenerate; protected boolean overwrite;</code>
+ * <br> <br>
+ * Mandatory: <code> protected String scriptPath; protected ILaunchConfiguration
+ * config;</code>
*/
public abstract class SystemTapLaunchShortcut extends ProfileLaunchShortcut {
- protected IEditorPart editor;
-
- private static final String USER_SELECTED_ALL = "ALL"; //$NON-NLS-1$
- private static final String MAIN_FUNC_NAME = "main"; //$NON-NLS-1$
-
- protected String name;
- protected String binaryPath;
- protected String scriptPath;
- protected String arguments;
- protected String outputPath;
- protected String binName;
- protected String generatedScript;
- protected String parserID;
- protected String viewID;
- protected boolean needToGenerate;
- protected boolean overwrite;
- protected boolean useColours;
- protected String resourceToSearchFor;
- protected boolean searchForResource;
- protected IBinary bin;
-
- private boolean testMode = false;
- protected String secondaryID = ""; //$NON-NLS-1$
-
- /**
- * Initialize variables. Highly recommend calling this function within the
- * launch methods. Will call setScriptPath, setParserID and setViewID.
- */
- public void initialize() {
- name = ""; //$NON-NLS-1$
- binaryPath = LaunchConfigurationConstants.DEFAULT_BINARY_PATH;
- arguments = LaunchConfigurationConstants.DEFAULT_ARGUMENTS;
- outputPath = PluginConstants.getDefaultIOPath();
- overwrite = true;
- generatedScript = LaunchConfigurationConstants.DEFAULT_GENERATED_SCRIPT;
- needToGenerate = false;
- useColours = false;
- secondaryID = ""; //$NON-NLS-1$
- }
-
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(
- PluginConstants.CONFIGURATION_TYPE_ID);
- }
-
- @Override
- protected void setDefaultProfileAttributes(
- ILaunchConfigurationWorkingCopy wc) {
- SystemTapOptionsTab tab = new SystemTapOptionsTab();
- tab.setDefaults(wc);
- }
-
- /**
- * Helper function to complete launches. Uses protected parameters (Strings)
- * scriptPath, binaryPath, arguments, outputPath and (boolean) overwrite.
- * These must be set by the calling function (or else nonsensical results
- * will occur). <br>
- * If scriptPath has not been set, the setScriptPath() method will be
- * called.
- *
- * @param name : Used to generate the name of the new configuration
- * @param bin : Affiliated executable
- * @param mode : Mode setting
- * @param wc : A working copy of the launch configuration
- * @throws IOException
- */
- protected void finishLaunch(String name, String mode, ILaunchConfigurationWorkingCopy wc) throws IOException {
- if (!finishLaunchHelper()) {
- return;
- }
-
- if (wc != null) {
-
- wc.setAttribute(LaunchConfigurationConstants.SCRIPT_PATH,scriptPath);
-
- if (!invalid(binaryPath)) {
- wc.setAttribute(LaunchConfigurationConstants.BINARY_PATH,binaryPath);
- }
-
- wc.setAttribute(LaunchConfigurationConstants.OUTPUT_PATH,outputPath);
- wc.setAttribute(LaunchConfigurationConstants.ARGUMENTS, arguments);
- wc.setAttribute(LaunchConfigurationConstants.GENERATED_SCRIPT,generatedScript);
- wc.setAttribute(LaunchConfigurationConstants.NEED_TO_GENERATE,needToGenerate);
- wc.setAttribute(LaunchConfigurationConstants.OVERWRITE, overwrite);
- wc.setAttribute(LaunchConfigurationConstants.USE_COLOUR,useColours);
- wc.setAttribute(LaunchConfigurationConstants.PARSER_CLASS,parserID);
- wc.setAttribute(LaunchConfigurationConstants.VIEW_CLASS, viewID);
- wc.setAttribute(LaunchConfigurationConstants.SECONDARY_VIEW_ID, ""); //$NON-NLS-1$
-
- if (!testMode) {
- DebugUITools.launch(wc, mode);
- }
- }
-
- }
-
- /**
- * returns true if str == null || str.length() < 1. Convenience method.
- *
- * @param str
- * @return
- */
- private static boolean invalid(String str) {
- return (str == null || str.length() < 1);
- }
-
- /**
- * Helper function for methods common to both types of finishLaunch.
- * @throws IOException
- *
- */
- private boolean finishLaunchHelper() throws IOException {
- if (invalid(scriptPath)) {
- scriptPath = setScriptPath();
- }
- if (invalid(scriptPath)) {
- // Setting the variable didn't work, do not launch.
-
- SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
- Messages
- .getString("SystemTapLaunchShortcut.ErrorMessageName"), //$NON-NLS-1$
- Messages
- .getString("SystemTapLaunchShortcut.ErrorMessageTitle"), Messages.getString("SystemTapLaunchShortcut.ErrorMessage") + name); //$NON-NLS-1$ //$NON-NLS-2$
- mess.schedule();
- return false;
- }
-
- if (invalid(parserID)) {
- parserID = setParserID();
- }
- if (invalid(parserID)) {
- SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
- Messages.getString("SystemTapLaunchShortcut.InvalidParser1"), //$NON-NLS-1$
- Messages.getString("SystemTapLaunchShortcut.InvalidParser2"), Messages.getString("SystemTapLaunchShortcut.InvalidParser3")); //$NON-NLS-1$ //$NON-NLS-2$
- mess.schedule();
- return false;
- }
-
- if (invalid(viewID)) {
- viewID = setViewID();
- }
- if (invalid(viewID)) {
- // Setting the variable didn't work, do not launch.
- SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
- Messages.getString("SystemTapLaunchShortcut.InvalidView1"), //$NON-NLS-1$
- Messages.getString("SystemTapLaunchShortcut.InvalidView2"), Messages.getString("SystemTapLaunchShortcut.InvalidView3")); //$NON-NLS-1$ //$NON-NLS-2$
- mess.schedule();
- return false;
- }
-
- if (needToGenerate) {
- if (invalid(generatedScript)) {
- generatedScript = generateScript();
- }
- if (invalid(generatedScript)) {
- // Setting the variable didn't work, do not launch.
- SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
- Messages
- .getString("SystemTapLaunchShortcut.InvalidGeneration1"), //$NON-NLS-1$
- Messages
- .getString("SystemTapLaunchShortcut.InvalidGeneration2"), Messages.getString("SystemTapLaunchShortcut.InvalidGeneration3"));//$NON-NLS-1$ //$NON-NLS-2$
- mess.schedule();
- return false;
- }
- }
- return true;
- }
-
- /**
- * Returns bin.getPath().toString()
- *
- * @param bin
- * @return
- */
- public String getName(IBinary bin) {
- if (bin != null) {
- binName = bin.getPath().toString();
- } else {
- binName = ""; //$NON-NLS-1$
- }
- return binName;
- }
-
- /**
- * Creates a configuration for the given IBinary
- *
- */
- @Override
- protected ILaunchConfiguration createConfiguration(IBinary bin) {
- if (bin != null) {
- return super.createConfiguration(bin);
- } else {
- try {
- return getLaunchConfigType()
- .newInstance(
- null,
- getLaunchManager()
- .generateLaunchConfigurationName(
- Messages.getString("SystemTapLaunchShortcut.Invalid"))); //$NON-NLS-1$
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
-
- /**
- * Allows null configurations to be launched. Any launch that uses a binary
- * should never call this configuration with a null parameter, and any
- * launch that does not use a binary should never call this function. The
- * null handling is included for ease of testing.
- *
- * @param bin
- * @param name
- * - Customize the name based on the shortcut being launched
- * @return A launch configuration, or null
- */
- protected ILaunchConfigurationWorkingCopy createConfiguration(IBinary bin,
- String name) {
- ILaunchConfigurationWorkingCopy wc = null;
- if (bin != null) {
- try {
- String projectName = bin.getResource().getProjectRelativePath().toString();
- ILaunchConfigurationType configType = getLaunchConfigType();
- wc = configType.newInstance(
- null,
- getLaunchManager().generateLaunchConfigurationName(
- name + " - " + bin.getElementName())); //$NON-NLS-1$
-
- wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,projectName);
- wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, bin.getCProject().getElementName());
- wc.setMappedResources(new IResource[] { bin.getResource(),bin.getResource().getProject() });
- wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY,(String) null);
-
- setDefaultProfileAttributes(wc);
-
- } catch (CoreException e) {
- e.printStackTrace();
- }
- } else {
-
- try {
- wc = getLaunchConfigType().newInstance(
- null,
- getLaunchManager()
- .generateLaunchConfigurationName(name));
- setDefaultProfileAttributes(wc);
- } catch (CoreException e) {
- e.printStackTrace();
- return null;
- }
- }
- return wc;
- }
-
- /*
- * The following are convenience methods for test programs, etc. to check
- * the value of certain protected parameters.
- */
-
- public ILaunchConfigurationType outsideGetLaunchConfigType() {
- return getLaunchConfigType();
- }
-
- public String getArguments() {
- return arguments;
- }
-
- /**
- * Retrieves the names of all functions referenced by the binary. If
- * searchForResource is true, this function will return all function names
- * belonging to an element with name matching the String held by
- * resourceToSearchFor. Otherwise it will create a dialog prompting the user
- * to select from a list of files to profile, or select the only available
- * file if only one file is available.
- *
- *
- * @param bin
- * @return
- */
- protected String getFunctionsFromBinary(IBinary bin, String targetResource) {
- String funcs = ""; //$NON-NLS-1$
- if (bin == null) {
- return funcs;
- }
- try {
- ArrayList<ICContainer> list = new ArrayList<>();
- TranslationUnitVisitor v = new TranslationUnitVisitor();
-
- for (ICElement b : bin.getCProject().getChildrenOfType(
- ICElement.C_CCONTAINER)) {
- ICContainer c = (ICContainer) b;
-
- for (ITranslationUnit tu : c.getTranslationUnits()) {
- if (searchForResource
- && tu.getElementName().contains(targetResource)) {
- tu.accept(v);
- funcs += v.getFunctions();
- return funcs;
- } else {
- if (!list.contains(c)) {
- list.add(c);
- }
- }
- }
-
- // Iterate down to all children, checking for more C_Containers
- while (c.getChildrenOfType(ICElement.C_CCONTAINER).size() > 0) {
- ICContainer e = null;
- for (ICElement d : c
- .getChildrenOfType(ICElement.C_CCONTAINER)) {
- e = (ICContainer) d;
- for (ITranslationUnit tu : e.getTranslationUnits()) {
- if (searchForResource
- && tu.getElementName().contains(
- targetResource)) {
- tu.accept(v);
- funcs += (v.getFunctions());
- return funcs;
- } else {
- if (!list.contains(c)) {
- list.add(c);
- }
- }
- }
- }
- c = e;
- }
- }
-
- int numberOfFiles = numberOfValidFiles(list.toArray());
- if (numberOfFiles == 1) {
- for (ICContainer c : list) {
- for (ITranslationUnit e : c.getTranslationUnits()) {
- if (validElement(e)) {
- e.accept(v);
- funcs += v.getFunctions();
- }
- }
- }
- } else {
-
- Object[] unitList = chooseUnit(list, numberOfFiles);
- if (unitList == null || unitList.length == 0) {
- return null;
- } else if (unitList.length == 1
- && unitList[0].toString().equals(USER_SELECTED_ALL)) {
- funcs = "*"; //$NON-NLS-1$
- return funcs;
- }
-
- StringBuilder tmpFunc = new StringBuilder();
- for (String item : getAllFunctions(bin.getCProject(), unitList)) {
- tmpFunc.append(item);
- tmpFunc.append(" "); //$NON-NLS-1$
- }
- funcs = tmpFunc.toString();
-
- }
-
- return funcs;
-
- } catch (CoreException e) {
- e.printStackTrace();
- }
-
- return null;
- }
-
- /**
- * Creates a dialog that prompts the user to select from the given list of
- * ICElements
- *
- * @param list
- * : list of ICElements
- * @return
- */
- private Object[] chooseUnit(List<ICContainer> list, int numberOfValidFiles) {
- ListTreeContentProvider prov = new ListTreeContentProvider();
-
- RuledTreeSelectionDialog dialog = new RuledTreeSelectionDialog(
- getActiveWorkbenchShell(), new WorkbenchLabelProvider(), prov);
-
- dialog.setTitle(Messages.getString("SystemTapLaunchShortcut.SelectFiles")); //$NON-NLS-1$
- dialog.setMessage(Messages.getString("SystemTapLaunchShortcut.SelectFilesMsg")); //$NON-NLS-1$
- dialog.setInput(list);
- dialog.setHelpAvailable(false);
- dialog.setStatusLineAboveButtons(false);
- dialog.setEmptyListMessage(Messages
- .getString("SystemTapLaunchShortcut.NoFiles")); //$NON-NLS-1$
- dialog.setContainerMode(true);
-
- Object[] topLevel = prov.findElements(list);
- dialog.setInitialSelections(topLevel);
- dialog.setSize(cap(topLevel.length * 10, 30, 55), cap(
- (int) (topLevel.length * 1.5), 3, 13));
-
- dialog.create();
- Button okButton = dialog.getOkButton();
-
- Object[] result = null;
-
- if (testMode) {
- okButton.setSelection(true);
- result = list.toArray();
- ArrayList<Object> output = new ArrayList<>();
- try {
- for (Object obj : result) {
- if (obj instanceof ICContainer) {
- ICElement[] array = ((ICContainer) obj).getChildren();
- for (ICElement c : array) {
- if (!(validElement(c))) {
- continue;
- }
- if (c.getElementName().contains(MAIN_FUNC_NAME) && !output.contains(c)) {
- output.add(c);
- }
- }
- }
- }
-
- if (output.size() >= numberOfValidFiles) {
- output.clear();
- output.add(USER_SELECTED_ALL);
- }
- } catch (CModelException e) {
- e.printStackTrace();
- }
-
- result = output.toArray();
- } else {
- if (dialog.open() == Window.CANCEL) {
- return null;
- }
- result = dialog.getResult();
- }
-
- if (result == null) {
- return null;
- }
-
- ArrayList<Object> output = new ArrayList<>();
- try {
- for (Object obj : result) {
- if (obj instanceof ICContainer) {
- ICElement[] array = ((ICContainer) obj).getChildren();
- for (ICElement c : array) {
- if (!(validElement(c))) {
- continue;
- }
- if (!output.contains(c)) {
- output.add(c);
- }
- }
- } else if ((obj instanceof ICElement)
- && validElement((ICElement) obj)
- && !output.contains(obj)) {
- output.add(obj);
- }
- }
-
- if (output.size() >= numberOfValidFiles) {
- output.clear();
- output.add(USER_SELECTED_ALL);
- }
- } catch (CModelException e) {
- e.printStackTrace();
- }
-
- return output.toArray();
- }
-
- private int numberOfValidFiles(Object[] list) throws CModelException {
- int output = 0;
- for (Object parent : list) {
- if (parent instanceof ICContainer) {
- ICContainer cont = (ICContainer) parent;
- for (ICElement ele : cont.getChildren()) {
- if (ele instanceof ICContainer) {
- output += numberOfValidFiles(((ICContainer) ele)
- .getChildren());
- }
- if (validElement(ele)) {
- output++;
- }
- }
- } else if ((parent instanceof ICElement)
- && validElement((ICElement) parent)) {
- output++;
- }
- }
- return output;
- }
-
- /**
- * @param project
- * : C Project Type
- * @return A String list of all functions contained within the specified C
- * Project
- */
- private static List<String> getAllFunctions(ICProject project,
- Object[] listOfFiles) {
- try {
- GetFunctionsJob j = new GetFunctionsJob(project
- .getHandleIdentifier(), project, listOfFiles);
- j.schedule();
- j.join();
- ArrayList<String> functionList = j.getFunctionList();
-
- return functionList;
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Returns all ICElements in val that contains the given path. WARNING: Uses
- * .contains, so be careful with the String path or you'll get too many
- * hits.
- *
- * @param list
- * @param path
- * @return
- */
- private static boolean specialContains(Object[] list, String path) {
- for (Object val : list) {
- if (val instanceof ICElement) {
- ICElement el = (ICElement) val;
- if (el.getPath().toString().contains(path)) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Returns a number clipped into the range [low,high].
- *
- * @param number
- * @param low
- * @param high
- * @return number if number is in [low,high], low, or high.
- */
- private int cap(int number, int low, int high) {
- if (number > high) {
- return high;
- }
- if (number < low) {
- return low;
- }
- return number;
- }
-
- /**
- * Function for generating scripts. Should be overridden by interested
- * classes
- *
- * @throws IOException
- */
- @SuppressWarnings("unused")
- public String generateScript() throws IOException {
- return null;
- }
-
- private static class GetFunctionsJob extends Job {
- private ArrayList<String> functionList;
- private ICProject project;
- private Object[] listOfFiles;
-
- public GetFunctionsJob(String name, ICProject p, Object[] o) {
- super(name);
- functionList = new ArrayList<>();
- listOfFiles = Arrays.copyOf(o, o.length);
- project = p;
- }
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- IIndexManager manager = CCorePlugin.getIndexManager();
- IIndex index = null;
- IProgressMonitor m = monitor;
-
- if (m == null) {
- m = new NullProgressMonitor();
- }
- m.worked(1);
-
- try {
- index = manager.getIndex(project);
- index.acquireReadLock();
-
- IIndexFile[] blah = index.getAllFiles();
- for (IIndexFile file : blah) {
- String fullFilePath = file.getLocation().getFullPath();
- if (fullFilePath == null
- || !specialContains(listOfFiles, fullFilePath)) {
- continue;
- }
-
- IIndexName[] indexNamesArray = file.findNames(0,
- Integer.MAX_VALUE);
- for (IIndexName name : indexNamesArray) {
- if (name.isDefinition()
- && specialContains(listOfFiles, name.getFile()
- .getLocation().getFullPath())) {
- IIndexBinding binder = index.findBinding(name);
- if (binder instanceof IFunction
- && !functionList.contains(binder.getName())) {
- functionList.add(binder.getName());
- }
- }
- }
-
- m.worked(1);
- }
- index.releaseReadLock();
-
- } catch (CoreException e) {
- e.printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- return Status.OK_STATUS;
- }
-
- public ArrayList<String> getFunctionList() {
- return functionList;
- }
- }
-
-
- /**
- * Set the parserID variable. ParserID should point to the ID of an
- * extension extending the org.eclipse.linuxtools.callgraph.core.parser
- * extension point. This function must return the parserID to be set.
- *
- * If not declared, the parserID will be set to the default SystemTap
- * Text parser with colour support
- *
- * @return a valid parserID
- */
- public String setParserID() {
- return PluginConstants.DEFAULT_PARSER_ID;
- }
-
- public String getScript() {
- return generatedScript;
- }
-
- public void setTestMode(boolean val) {
- testMode = val;
- }
-
- /**
- * Set the viewID variable. ViewID should point to the ID of an extension
- * extending the org.eclipse.ui.views extension point. This function must
- * return the viewID to be set. Defaults to the SystemTap Text View, if
- * not overridden.
- *
- * @return a valid viewID
- */
- public String setViewID() {
- return PluginConstants.DEFAULT_VIEW_ID;
- }
-
- public static boolean validElement(ICElement e) {
- return e.getElementName().endsWith(".c") || //$NON-NLS-1$
- e.getElementName().endsWith(".cpp") || //$NON-NLS-1$
- e.getElementName().endsWith(".h"); //$NON-NLS-1$
- }
-
-
- /**
- * Default implementation of launch. It will run stap with the selected binary
- * as an argument and set the output path to <code>PluginConstants.getDefaultIOPath()</code>.
- * <br>
- * The name of the created launch will be 'DefaultSystemTapLaunch'
- */
- @Override
- public void launch(IBinary bin, String mode) {
- initialize();
- this.bin = bin;
- binName = getName(bin);
- name = "DefaultSystemTapLaunch"; //$NON-NLS-1$
-
- try {
-
- ILaunchConfigurationWorkingCopy wc = createConfiguration(bin, name);
- binaryPath = bin.getResource().getLocation().toString();
- arguments = binaryPath;
- outputPath = PluginConstants.getDefaultIOPath();
- finishLaunch(name, mode, wc);
-
- } catch (IOException e) {
- SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
- "LaunchShortcutScriptGen", //$NON-NLS-1$
- Messages.getString("LaunchStapGraph.ScriptGenErr"), //$NON-NLS-1$
- Messages.getString("LaunchStapGraph.ScriptGenErrMsg")); //$NON-NLS-1$
- mess.schedule();
- e.printStackTrace();
- } finally {
- resourceToSearchFor = ""; //$NON-NLS-1$
- searchForResource = false;
- }
-
-
- }
-
-
- /**
- * Each launch class should define its own script path. Must return the
- * correct script path or launch will fail.
- */
- public abstract String setScriptPath();
+ protected IEditorPart editor;
+
+ private static final String USER_SELECTED_ALL = "ALL"; //$NON-NLS-1$
+ private static final String MAIN_FUNC_NAME = "main"; //$NON-NLS-1$
+
+ protected String name;
+ protected String binaryPath;
+ protected String scriptPath;
+ protected String arguments;
+ protected String outputPath;
+ protected String binName;
+ protected String generatedScript;
+ protected String parserID;
+ protected String viewID;
+ protected boolean needToGenerate;
+ protected boolean overwrite;
+ protected boolean useColours;
+ protected String resourceToSearchFor;
+ protected boolean searchForResource;
+ protected IBinary bin;
+
+ private boolean testMode = false;
+ protected String secondaryID = ""; //$NON-NLS-1$
+
+ /**
+ * Initialize variables. Highly recommend calling this function within the
+ * launch methods. Will call setScriptPath, setParserID and setViewID.
+ */
+ public void initialize() {
+ name = ""; //$NON-NLS-1$
+ binaryPath = LaunchConfigurationConstants.DEFAULT_BINARY_PATH;
+ arguments = LaunchConfigurationConstants.DEFAULT_ARGUMENTS;
+ outputPath = PluginConstants.getDefaultIOPath();
+ overwrite = true;
+ generatedScript = LaunchConfigurationConstants.DEFAULT_GENERATED_SCRIPT;
+ needToGenerate = false;
+ useColours = false;
+ secondaryID = ""; //$NON-NLS-1$
+ }
+
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(
+ PluginConstants.CONFIGURATION_TYPE_ID);
+ }
+
+ @Override
+ protected void setDefaultProfileAttributes(
+ ILaunchConfigurationWorkingCopy wc) {
+ SystemTapOptionsTab tab = new SystemTapOptionsTab();
+ tab.setDefaults(wc);
+ }
+
+ /**
+ * Helper function to complete launches. Uses protected parameters (Strings)
+ * scriptPath, binaryPath, arguments, outputPath and (boolean) overwrite.
+ * These must be set by the calling function (or else nonsensical results
+ * will occur). <br>
+ * If scriptPath has not been set, the setScriptPath() method will be
+ * called.
+ *
+ * @param name : Used to generate the name of the new configuration
+ * @param bin : Affiliated executable
+ * @param mode : Mode setting
+ * @param wc : A working copy of the launch configuration
+ * @throws IOException
+ */
+ protected void finishLaunch(String name, String mode, ILaunchConfigurationWorkingCopy wc) throws IOException {
+ if (!finishLaunchHelper()) {
+ return;
+ }
+
+ if (wc != null) {
+
+ wc.setAttribute(LaunchConfigurationConstants.SCRIPT_PATH,scriptPath);
+
+ if (!invalid(binaryPath)) {
+ wc.setAttribute(LaunchConfigurationConstants.BINARY_PATH,binaryPath);
+ }
+
+ wc.setAttribute(LaunchConfigurationConstants.OUTPUT_PATH,outputPath);
+ wc.setAttribute(LaunchConfigurationConstants.ARGUMENTS, arguments);
+ wc.setAttribute(LaunchConfigurationConstants.GENERATED_SCRIPT,generatedScript);
+ wc.setAttribute(LaunchConfigurationConstants.NEED_TO_GENERATE,needToGenerate);
+ wc.setAttribute(LaunchConfigurationConstants.OVERWRITE, overwrite);
+ wc.setAttribute(LaunchConfigurationConstants.USE_COLOUR,useColours);
+ wc.setAttribute(LaunchConfigurationConstants.PARSER_CLASS,parserID);
+ wc.setAttribute(LaunchConfigurationConstants.VIEW_CLASS, viewID);
+ wc.setAttribute(LaunchConfigurationConstants.SECONDARY_VIEW_ID, ""); //$NON-NLS-1$
+
+ if (!testMode) {
+ DebugUITools.launch(wc, mode);
+ }
+ }
+
+ }
+
+ /**
+ * returns true if str == null || str.length() < 1. Convenience method.
+ *
+ * @param str
+ * @return
+ */
+ private static boolean invalid(String str) {
+ return (str == null || str.length() < 1);
+ }
+
+ /**
+ * Helper function for methods common to both types of finishLaunch.
+ * @throws IOException
+ *
+ */
+ private boolean finishLaunchHelper() throws IOException {
+ if (invalid(scriptPath)) {
+ scriptPath = setScriptPath();
+ }
+ if (invalid(scriptPath)) {
+ // Setting the variable didn't work, do not launch.
+
+ SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
+ Messages
+ .getString("SystemTapLaunchShortcut.ErrorMessageName"), //$NON-NLS-1$
+ Messages
+ .getString("SystemTapLaunchShortcut.ErrorMessageTitle"), Messages.getString("SystemTapLaunchShortcut.ErrorMessage") + name); //$NON-NLS-1$ //$NON-NLS-2$
+ mess.schedule();
+ return false;
+ }
+
+ if (invalid(parserID)) {
+ parserID = setParserID();
+ }
+ if (invalid(parserID)) {
+ SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
+ Messages.getString("SystemTapLaunchShortcut.InvalidParser1"), //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchShortcut.InvalidParser2"), Messages.getString("SystemTapLaunchShortcut.InvalidParser3")); //$NON-NLS-1$ //$NON-NLS-2$
+ mess.schedule();
+ return false;
+ }
+
+ if (invalid(viewID)) {
+ viewID = setViewID();
+ }
+ if (invalid(viewID)) {
+ // Setting the variable didn't work, do not launch.
+ SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
+ Messages.getString("SystemTapLaunchShortcut.InvalidView1"), //$NON-NLS-1$
+ Messages.getString("SystemTapLaunchShortcut.InvalidView2"), Messages.getString("SystemTapLaunchShortcut.InvalidView3")); //$NON-NLS-1$ //$NON-NLS-2$
+ mess.schedule();
+ return false;
+ }
+
+ if (needToGenerate) {
+ if (invalid(generatedScript)) {
+ generatedScript = generateScript();
+ }
+ if (invalid(generatedScript)) {
+ // Setting the variable didn't work, do not launch.
+ SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
+ Messages
+ .getString("SystemTapLaunchShortcut.InvalidGeneration1"), //$NON-NLS-1$
+ Messages
+ .getString("SystemTapLaunchShortcut.InvalidGeneration2"), Messages.getString("SystemTapLaunchShortcut.InvalidGeneration3"));//$NON-NLS-1$ //$NON-NLS-2$
+ mess.schedule();
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Returns bin.getPath().toString()
+ *
+ * @param bin
+ * @return
+ */
+ public String getName(IBinary bin) {
+ if (bin != null) {
+ binName = bin.getPath().toString();
+ } else {
+ binName = ""; //$NON-NLS-1$
+ }
+ return binName;
+ }
+
+ /**
+ * Creates a configuration for the given IBinary
+ *
+ */
+ @Override
+ protected ILaunchConfiguration createConfiguration(IBinary bin) {
+ if (bin != null) {
+ return super.createConfiguration(bin);
+ } else {
+ try {
+ return getLaunchConfigType()
+ .newInstance(
+ null,
+ getLaunchManager()
+ .generateLaunchConfigurationName(
+ Messages.getString("SystemTapLaunchShortcut.Invalid"))); //$NON-NLS-1$
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Allows null configurations to be launched. Any launch that uses a binary
+ * should never call this configuration with a null parameter, and any
+ * launch that does not use a binary should never call this function. The
+ * null handling is included for ease of testing.
+ *
+ * @param bin
+ * @param name
+ * - Customize the name based on the shortcut being launched
+ * @return A launch configuration, or null
+ */
+ protected ILaunchConfigurationWorkingCopy createConfiguration(IBinary bin,
+ String name) {
+ ILaunchConfigurationWorkingCopy wc = null;
+ if (bin != null) {
+ try {
+ String projectName = bin.getResource().getProjectRelativePath().toString();
+ ILaunchConfigurationType configType = getLaunchConfigType();
+ wc = configType.newInstance(
+ null,
+ getLaunchManager().generateLaunchConfigurationName(
+ name + " - " + bin.getElementName())); //$NON-NLS-1$
+
+ wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,projectName);
+ wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, bin.getCProject().getElementName());
+ wc.setMappedResources(new IResource[] { bin.getResource(),bin.getResource().getProject() });
+ wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY,(String) null);
+
+ setDefaultProfileAttributes(wc);
+
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ } else {
+
+ try {
+ wc = getLaunchConfigType().newInstance(
+ null,
+ getLaunchManager()
+ .generateLaunchConfigurationName(name));
+ setDefaultProfileAttributes(wc);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+ return wc;
+ }
+
+ /*
+ * The following are convenience methods for test programs, etc. to check
+ * the value of certain protected parameters.
+ */
+
+ public ILaunchConfigurationType outsideGetLaunchConfigType() {
+ return getLaunchConfigType();
+ }
+
+ public String getArguments() {
+ return arguments;
+ }
+
+ /**
+ * Retrieves the names of all functions referenced by the binary. If
+ * searchForResource is true, this function will return all function names
+ * belonging to an element with name matching the String held by
+ * resourceToSearchFor. Otherwise it will create a dialog prompting the user
+ * to select from a list of files to profile, or select the only available
+ * file if only one file is available.
+ *
+ *
+ * @param bin
+ * @return
+ */
+ protected String getFunctionsFromBinary(IBinary bin, String targetResource) {
+ String funcs = ""; //$NON-NLS-1$
+ if (bin == null) {
+ return funcs;
+ }
+ try {
+ ArrayList<ICContainer> list = new ArrayList<>();
+ TranslationUnitVisitor v = new TranslationUnitVisitor();
+
+ for (ICElement b : bin.getCProject().getChildrenOfType(
+ ICElement.C_CCONTAINER)) {
+ ICContainer c = (ICContainer) b;
+
+ for (ITranslationUnit tu : c.getTranslationUnits()) {
+ if (searchForResource
+ && tu.getElementName().contains(targetResource)) {
+ tu.accept(v);
+ funcs += v.getFunctions();
+ return funcs;
+ } else {
+ if (!list.contains(c)) {
+ list.add(c);
+ }
+ }
+ }
+
+ // Iterate down to all children, checking for more C_Containers
+ while (c.getChildrenOfType(ICElement.C_CCONTAINER).size() > 0) {
+ ICContainer e = null;
+ for (ICElement d : c
+ .getChildrenOfType(ICElement.C_CCONTAINER)) {
+ e = (ICContainer) d;
+ for (ITranslationUnit tu : e.getTranslationUnits()) {
+ if (searchForResource
+ && tu.getElementName().contains(
+ targetResource)) {
+ tu.accept(v);
+ funcs += (v.getFunctions());
+ return funcs;
+ } else {
+ if (!list.contains(c)) {
+ list.add(c);
+ }
+ }
+ }
+ }
+ c = e;
+ }
+ }
+
+ int numberOfFiles = numberOfValidFiles(list.toArray());
+ if (numberOfFiles == 1) {
+ for (ICContainer c : list) {
+ for (ITranslationUnit e : c.getTranslationUnits()) {
+ if (validElement(e)) {
+ e.accept(v);
+ funcs += v.getFunctions();
+ }
+ }
+ }
+ } else {
+
+ Object[] unitList = chooseUnit(list, numberOfFiles);
+ if (unitList == null || unitList.length == 0) {
+ return null;
+ } else if (unitList.length == 1
+ && unitList[0].toString().equals(USER_SELECTED_ALL)) {
+ funcs = "*"; //$NON-NLS-1$
+ return funcs;
+ }
+
+ StringBuilder tmpFunc = new StringBuilder();
+ for (String item : getAllFunctions(bin.getCProject(), unitList)) {
+ tmpFunc.append(item);
+ tmpFunc.append(" "); //$NON-NLS-1$
+ }
+ funcs = tmpFunc.toString();
+
+ }
+
+ return funcs;
+
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+
+ /**
+ * Creates a dialog that prompts the user to select from the given list of
+ * ICElements
+ *
+ * @param list
+ * : list of ICElements
+ * @return
+ */
+ private Object[] chooseUnit(List<ICContainer> list, int numberOfValidFiles) {
+ ListTreeContentProvider prov = new ListTreeContentProvider();
+
+ RuledTreeSelectionDialog dialog = new RuledTreeSelectionDialog(
+ getActiveWorkbenchShell(), new WorkbenchLabelProvider(), prov);
+
+ dialog.setTitle(Messages.getString("SystemTapLaunchShortcut.SelectFiles")); //$NON-NLS-1$
+ dialog.setMessage(Messages.getString("SystemTapLaunchShortcut.SelectFilesMsg")); //$NON-NLS-1$
+ dialog.setInput(list);
+ dialog.setHelpAvailable(false);
+ dialog.setStatusLineAboveButtons(false);
+ dialog.setEmptyListMessage(Messages
+ .getString("SystemTapLaunchShortcut.NoFiles")); //$NON-NLS-1$
+ dialog.setContainerMode(true);
+
+ Object[] topLevel = prov.findElements(list);
+ dialog.setInitialSelections(topLevel);
+ dialog.setSize(cap(topLevel.length * 10, 30, 55), cap(
+ (int) (topLevel.length * 1.5), 3, 13));
+
+ dialog.create();
+ Button okButton = dialog.getOkButton();
+
+ Object[] result = null;
+
+ if (testMode) {
+ okButton.setSelection(true);
+ result = list.toArray();
+ ArrayList<Object> output = new ArrayList<>();
+ try {
+ for (Object obj : result) {
+ if (obj instanceof ICContainer) {
+ ICElement[] array = ((ICContainer) obj).getChildren();
+ for (ICElement c : array) {
+ if (!(validElement(c))) {
+ continue;
+ }
+ if (c.getElementName().contains(MAIN_FUNC_NAME) && !output.contains(c)) {
+ output.add(c);
+ }
+ }
+ }
+ }
+
+ if (output.size() >= numberOfValidFiles) {
+ output.clear();
+ output.add(USER_SELECTED_ALL);
+ }
+ } catch (CModelException e) {
+ e.printStackTrace();
+ }
+
+ result = output.toArray();
+ } else {
+ if (dialog.open() == Window.CANCEL) {
+ return null;
+ }
+ result = dialog.getResult();
+ }
+
+ if (result == null) {
+ return null;
+ }
+
+ ArrayList<Object> output = new ArrayList<>();
+ try {
+ for (Object obj : result) {
+ if (obj instanceof ICContainer) {
+ ICElement[] array = ((ICContainer) obj).getChildren();
+ for (ICElement c : array) {
+ if (!(validElement(c))) {
+ continue;
+ }
+ if (!output.contains(c)) {
+ output.add(c);
+ }
+ }
+ } else if ((obj instanceof ICElement)
+ && validElement((ICElement) obj)
+ && !output.contains(obj)) {
+ output.add(obj);
+ }
+ }
+
+ if (output.size() >= numberOfValidFiles) {
+ output.clear();
+ output.add(USER_SELECTED_ALL);
+ }
+ } catch (CModelException e) {
+ e.printStackTrace();
+ }
+
+ return output.toArray();
+ }
+
+ private int numberOfValidFiles(Object[] list) throws CModelException {
+ int output = 0;
+ for (Object parent : list) {
+ if (parent instanceof ICContainer) {
+ ICContainer cont = (ICContainer) parent;
+ for (ICElement ele : cont.getChildren()) {
+ if (ele instanceof ICContainer) {
+ output += numberOfValidFiles(((ICContainer) ele)
+ .getChildren());
+ }
+ if (validElement(ele)) {
+ output++;
+ }
+ }
+ } else if ((parent instanceof ICElement)
+ && validElement((ICElement) parent)) {
+ output++;
+ }
+ }
+ return output;
+ }
+
+ /**
+ * @param project
+ * : C Project Type
+ * @return A String list of all functions contained within the specified C
+ * Project
+ */
+ private static List<String> getAllFunctions(ICProject project,
+ Object[] listOfFiles) {
+ try {
+ GetFunctionsJob j = new GetFunctionsJob(project
+ .getHandleIdentifier(), project, listOfFiles);
+ j.schedule();
+ j.join();
+ ArrayList<String> functionList = j.getFunctionList();
+
+ return functionList;
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ /**
+ * Returns all ICElements in val that contains the given path. WARNING: Uses
+ * .contains, so be careful with the String path or you'll get too many
+ * hits.
+ *
+ * @param list
+ * @param path
+ * @return
+ */
+ private static boolean specialContains(Object[] list, String path) {
+ for (Object val : list) {
+ if (val instanceof ICElement) {
+ ICElement el = (ICElement) val;
+ if (el.getPath().toString().contains(path)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Returns a number clipped into the range [low,high].
+ *
+ * @param number
+ * @param low
+ * @param high
+ * @return number if number is in [low,high], low, or high.
+ */
+ private int cap(int number, int low, int high) {
+ if (number > high) {
+ return high;
+ }
+ if (number < low) {
+ return low;
+ }
+ return number;
+ }
+
+ /**
+ * Function for generating scripts. Should be overridden by interested
+ * classes
+ *
+ * @throws IOException
+ */
+ @SuppressWarnings("unused")
+ public String generateScript() throws IOException {
+ return null;
+ }
+
+ private static class GetFunctionsJob extends Job {
+ private ArrayList<String> functionList;
+ private ICProject project;
+ private Object[] listOfFiles;
+
+ public GetFunctionsJob(String name, ICProject p, Object[] o) {
+ super(name);
+ functionList = new ArrayList<>();
+ listOfFiles = Arrays.copyOf(o, o.length);
+ project = p;
+ }
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ IIndexManager manager = CCorePlugin.getIndexManager();
+ IIndex index = null;
+ IProgressMonitor m = monitor;
+
+ if (m == null) {
+ m = new NullProgressMonitor();
+ }
+ m.worked(1);
+
+ try {
+ index = manager.getIndex(project);
+ index.acquireReadLock();
+
+ IIndexFile[] blah = index.getAllFiles();
+ for (IIndexFile file : blah) {
+ String fullFilePath = file.getLocation().getFullPath();
+ if (fullFilePath == null
+ || !specialContains(listOfFiles, fullFilePath)) {
+ continue;
+ }
+
+ IIndexName[] indexNamesArray = file.findNames(0,
+ Integer.MAX_VALUE);
+ for (IIndexName name : indexNamesArray) {
+ if (name.isDefinition()
+ && specialContains(listOfFiles, name.getFile()
+ .getLocation().getFullPath())) {
+ IIndexBinding binder = index.findBinding(name);
+ if (binder instanceof IFunction
+ && !functionList.contains(binder.getName())) {
+ functionList.add(binder.getName());
+ }
+ }
+ }
+
+ m.worked(1);
+ }
+ index.releaseReadLock();
+
+ } catch (CoreException e) {
+ e.printStackTrace();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ return Status.OK_STATUS;
+ }
+
+ public ArrayList<String> getFunctionList() {
+ return functionList;
+ }
+ }
+
+
+ /**
+ * Set the parserID variable. ParserID should point to the ID of an
+ * extension extending the org.eclipse.linuxtools.callgraph.core.parser
+ * extension point. This function must return the parserID to be set.
+ *
+ * If not declared, the parserID will be set to the default SystemTap
+ * Text parser with colour support
+ *
+ * @return a valid parserID
+ */
+ public String setParserID() {
+ return PluginConstants.DEFAULT_PARSER_ID;
+ }
+
+ public String getScript() {
+ return generatedScript;
+ }
+
+ public void setTestMode(boolean val) {
+ testMode = val;
+ }
+
+ /**
+ * Set the viewID variable. ViewID should point to the ID of an extension
+ * extending the org.eclipse.ui.views extension point. This function must
+ * return the viewID to be set. Defaults to the SystemTap Text View, if
+ * not overridden.
+ *
+ * @return a valid viewID
+ */
+ public String setViewID() {
+ return PluginConstants.DEFAULT_VIEW_ID;
+ }
+
+ public static boolean validElement(ICElement e) {
+ return e.getElementName().endsWith(".c") || //$NON-NLS-1$
+ e.getElementName().endsWith(".cpp") || //$NON-NLS-1$
+ e.getElementName().endsWith(".h"); //$NON-NLS-1$
+ }
+
+
+ /**
+ * Default implementation of launch. It will run stap with the selected binary
+ * as an argument and set the output path to <code>PluginConstants.getDefaultIOPath()</code>.
+ * <br>
+ * The name of the created launch will be 'DefaultSystemTapLaunch'
+ */
+ @Override
+ public void launch(IBinary bin, String mode) {
+ initialize();
+ this.bin = bin;
+ binName = getName(bin);
+ name = "DefaultSystemTapLaunch"; //$NON-NLS-1$
+
+ try {
+
+ ILaunchConfigurationWorkingCopy wc = createConfiguration(bin, name);
+ binaryPath = bin.getResource().getLocation().toString();
+ arguments = binaryPath;
+ outputPath = PluginConstants.getDefaultIOPath();
+ finishLaunch(name, mode, wc);
+
+ } catch (IOException e) {
+ SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
+ "LaunchShortcutScriptGen", //$NON-NLS-1$
+ Messages.getString("LaunchStapGraph.ScriptGenErr"), //$NON-NLS-1$
+ Messages.getString("LaunchStapGraph.ScriptGenErrMsg")); //$NON-NLS-1$
+ mess.schedule();
+ e.printStackTrace();
+ } finally {
+ resourceToSearchFor = ""; //$NON-NLS-1$
+ searchForResource = false;
+ }
+
+
+ }
+
+
+ /**
+ * Each launch class should define its own script path. Must return the
+ * correct script path or launch will fail.
+ */
+ public abstract String setScriptPath();
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapOptionsTab.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapOptionsTab.java
index 555fe696a0..408e502e55 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapOptionsTab.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/SystemTapOptionsTab.java
@@ -76,897 +76,897 @@ import org.eclipse.ui.views.navigator.ResourceComparator;
*/
public class SystemTapOptionsTab extends CLaunchConfigurationTab{
- //Controls
- private Text scriptFile;
- private Text binaryFile;
- private Text arguments;
- private Text outputFile;
- private Text button_D_text;
- private Text binaryArguments;
- private Text parser;
- private Text viewer;
-
- private Button fileBrowseButton;
- private Button workspaceBrowseButton;
-
- private Button button_k;
- private Button button_u;
- private Button button_w;
- private Button button_b;
- private Button button_g;
- private Button button_P;
- private Button button_t;
- private Button button_F;
- private Button buttonSkipBadvars;
- private Button buttonIgnoreDwarf;
- private Button button_q;
- private Button buttonGraphicsMode;
-
-
- private Spinner button_p_Spinner;
- private Spinner button_s_Spinner;
- private Spinner button_x_Spinner;
- private Spinner button_v_Spinner;
-
- private Button useColourButton;
-
- //Other variables
- private String workspacePath;
- private boolean outputFileHasChanged = false;
- private boolean needsOverwritePermission = false;
- private boolean overwritePermission = false;
- private boolean changeOverwrite = false;
-
- /**
- * The code below is very long, but it boils down to this.
- *
- * The main function is createControl. This function prepares
- * some space for the various tabs and calls the other create*Option
- * functions to create buttons, text fields and spinners.
- *
- * The create*Option functions create their respective sub-tabs.
- *
- * Each of the controls (button, text, spinner) needs to have a listener
- * attached so Eclipse knows what to do with them.
- *
- * There are a bunch of functions to update/set defaults/initialize,
- * and a final
- */
-
- private SelectionListener graphicsModeListener = new SelectionAdapter(){
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (scriptFile.isEnabled()){
- scriptFile.setEnabled(false);
- workspaceBrowseButton.setEnabled(false);
- fileBrowseButton.setEnabled(false);
- scriptFile.setText(PluginConstants.getPluginLocation()+"parse_function.stp"); //$NON-NLS-1$
- }else{
- scriptFile.setEnabled(true);
- workspaceBrowseButton.setEnabled(true);
- fileBrowseButton.setEnabled(true);
- }
- updateLaunchConfigurationDialog();
- }
- };
-
- private SelectionListener selectListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
-
- private ModifyListener modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
-
- private ModifyListener modifyListenerOutput = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- outputFileHasChanged = true;
- }
- };
-
- private FocusListener focusListener = new FocusAdapter() {
-
- @Override
- public void focusLost(FocusEvent e) {
- if (outputFileHasChanged) {
- checkOverwrite();
- }
- outputFileHasChanged = false;
-
- updateLaunchConfigurationDialog();
- }
- };
-
- /**
- * Convenience method to check if the overwrite permissions are consistent
- *
- * Helps ensure validity of configuration.
- */
- private void checkOverwrite() {
- File f = new File(outputFile.getText());
- changeOverwrite = true;
- if (f.exists()) {
- needsOverwritePermission = true;
- Shell sh = new Shell();
- if (MessageDialog.openConfirm(sh, Messages.getString("SystemTapOptionsTab.ConfirmOverwriteFileTitle"), //$NON-NLS-1$
- Messages.getString("SystemTapOptionsTab.ConfirmOverwriteFileMessage"))) { //$NON-NLS-1$
- overwritePermission = true;
- } else {
- overwritePermission = false;
- }
- }
- else
- needsOverwritePermission = false;
- }
-
- /**
- * This function prepares some space for the various
- * tabs and calls and sets the other create*Option
- * functions to create buttons, text fields and spinners.
- */
- @Override
- public void createControl(Composite parent) {
- /*
- * File folder - tab for selecting binary/stp file
- */
- TabFolder fileFolder = new TabFolder(parent, SWT.BORDER);
- fileFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
- setControl(fileFolder);
-
- TabItem fileTab = new TabItem(fileFolder, SWT.NONE);
- fileTab.setText(Messages.getString("SystemTapOptionsTab.FilesTab")); //$NON-NLS-1$
-
- Composite fileTop = new Composite(fileFolder, SWT.NONE);
- fileTop.setLayout(new GridLayout());
- fileTop.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- createFileOption(fileTop);
- fileTab.setControl(fileTop);
-
-
- /*
- * Commands tab - tab for selecting SystemTap commands
- */
-
- TabItem commandTab = new TabItem(fileFolder, SWT.NONE);
- commandTab.setText(Messages.getString("SystemTapOptionsTab.CommandsTab")); //$NON-NLS-1$
-
- Composite commandTop = new Composite(fileFolder, SWT.NONE);
- commandTop.setLayout(new GridLayout());
- commandTop.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- createCommandOption(commandTop);
- commandTab.setControl(commandTop);
-
- /*
- * Arguments tab - tab for selecting script arguments
- */
- TabItem argumentsTab = new TabItem(fileFolder, SWT.NONE);
- argumentsTab.setText(Messages.getString("SystemTapOptionsTab.Arguments")); //$NON-NLS-1$
-
- Composite argumentsTop = new Composite(fileFolder, SWT.NONE);
- argumentsTop.setLayout(new GridLayout());
- argumentsTop.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- createArgumentsOption(argumentsTop);
- argumentsTab.setControl(argumentsTop);
-
-
- /*
- * Binary Argument tab - tab for supplying arguments for a binary
- */
- TabItem binaryArgumentsTab = new TabItem(fileFolder, SWT.NONE);
- binaryArgumentsTab.setText(Messages.getString("SystemTapOptionsTab.44")); //$NON-NLS-1$
-
- Composite binaryArgumentsTop = new Composite(fileFolder, SWT.NONE);
- binaryArgumentsTop.setLayout(new GridLayout());
- binaryArgumentsTop.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- createBinaryArgumentsOption(binaryArgumentsTop);
- binaryArgumentsTab.setControl(binaryArgumentsTop);
-
-
- /*
- * Parser tab -- Tab for selecting a parser and viewer to use
- */
- TabItem parserTab = new TabItem(fileFolder, SWT.NONE);
- parserTab.setText("Parser"); //$NON-NLS-1$
-
- Composite parserTop = new Composite(fileFolder, SWT.NONE);
- parserTop.setLayout(new GridLayout());
- parserTop.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- createParserOption(parserTop);
- parserTab.setControl(parserTop);
- }
-
-
- private void createBinaryArgumentsOption(Composite binaryArgumentsTop) {
- Composite browseTop = new Composite(binaryArgumentsTop, SWT.NONE);
- browseTop.setLayout(new GridLayout(1, false));
- GridData browseData = new GridData(GridData.FILL_HORIZONTAL);
- browseTop.setLayoutData(browseData);
-
- Label suppFileLabel = new Label(browseTop, SWT.NONE);
- suppFileLabel.setText(Messages.getString("SystemTapOptionsTab.45")); //$NON-NLS-1$
-
- binaryArguments = new Text(browseTop,SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.heightHint = 200;
- binaryArguments.setLayoutData(gd);
- binaryArguments.addModifyListener(modifyListener);
- }
-
- private void createParserOption(Composite parserTop) {
- Composite browseTop = new Composite(parserTop, SWT.NONE);
- browseTop.setLayout(new GridLayout(1, false));
- GridData browseData = new GridData(GridData.FILL_HORIZONTAL);
- browseTop.setLayoutData(browseData);
-
- Label suppFileLabel = new Label(browseTop, SWT.NONE);
- suppFileLabel.setText("Parser"); //$NON-NLS-1$
-
- parser = new Text(browseTop, SWT.BORDER);
- parser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- parser.addModifyListener(modifyListener);
-
- Button parserButton = createPushButton(browseTop,
- "Find parsers", null); //$NON-NLS-1$
- parserButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(),
- new ListLabelProvider());
- dialog.setTitle("Select parser"); //$NON-NLS-1$
- dialog.setMessage("Select parser to use."); //$NON-NLS-1$
- IExtensionRegistry reg = Platform.getExtensionRegistry();
- IConfigurationElement[] extensions = reg
- .getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
- PluginConstants.PARSER_NAME);
-
- dialog.setElements(extensions);
- if (dialog.open() == IDialogConstants.OK_ID) {
- String arg = getUsefulLabel(dialog.getFirstResult());
- parser.setText(arg);
- }
- }
- });
-
-
- viewer = new Text(browseTop, SWT.BORDER);
- viewer.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- viewer.addModifyListener(modifyListener);
-
- Button viewerButton = createPushButton(browseTop,
- "Find viewers", null); //$NON-NLS-1$
- viewerButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(),
- new ListLabelProvider());
- dialog.setTitle("Select viewer"); //$NON-NLS-1$
- dialog.setMessage("Select viewer to use."); //$NON-NLS-1$
- IExtensionRegistry reg = Platform.getExtensionRegistry();
- IConfigurationElement[] extensions = reg
- .getConfigurationElementsFor(PluginConstants.VIEW_RESOURCE,
- PluginConstants.VIEW_NAME);
- ArrayList<IConfigurationElement> ext = new ArrayList<>();
- for (IConfigurationElement el : extensions) {
- if (!el.getNamespaceIdentifier().contains("org.eclipse.linuxtools")) //$NON-NLS-1$
- continue;
- //TODO: Rough hack to get all the objects. We restrict to id's containing org.eclipse.linuxtools, then see if the class extends SystemTapView
- try {
- if (el.createExecutableExtension(PluginConstants.ATTR_CLASS)
- instanceof SystemTapView) {
- ext.add(el);
- }
- } catch (CoreException e1) {
- }
- }
-
- dialog.setElements(ext.toArray());
- if (dialog.open() == IDialogConstants.OK_ID) {
- String arg = getUsefulLabel(dialog.getFirstResult());
- viewer.setText(arg);
- }
- }
- });
-
- }
-
- private void createArgumentsOption(Composite argumentsTop) {
- Composite browseTop = new Composite(argumentsTop, SWT.NONE);
- browseTop.setLayout(new GridLayout(1, false));
- GridData browseData = new GridData(GridData.FILL_HORIZONTAL);
- browseTop.setLayoutData(browseData);
-
-
- Label suppFileLabel = new Label(browseTop, SWT.NONE);
- suppFileLabel.setText(Messages.getString("SystemTapOptionsTab.SelectArguments")); //$NON-NLS-1$
-
- arguments = new Text(browseTop,SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
-
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.heightHint = 200;
- arguments.setLayoutData(gd);
- arguments.addModifyListener(modifyListener);
-
-
- Button probeFunctionButton = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.ProbeFunction"), null); //$NON-NLS-1$
- probeFunctionButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- arguments.setText(arguments.getText() + " process(\"" + binaryFile.getText() + "\").function(\"\")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- });
- }
-
- private void createFileOption(Composite top) {
- Composite browseTop = new Composite(top, SWT.NONE);
- browseTop.setLayout(new GridLayout(4, false));
- browseTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Label suppFileLabel = new Label(browseTop, SWT.NONE);
- suppFileLabel.setText(Messages.getString("SystemTapOptionsTab.ScriptSelector")); //$NON-NLS-1$
-
- scriptFile = new Text(browseTop, SWT.BORDER);
- scriptFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- scriptFile.addModifyListener(modifyListener);
-
- workspaceBrowseButton = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.WorkspaceButton"), null); //$NON-NLS-1$
- workspaceBrowseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
- dialog.setTitle(Messages.getString("SystemTapOptionsTab.ResourceButton")); //$NON-NLS-1$
- dialog.setMessage(Messages.getString("SystemTapOptionsTab.SuppresionsFile")); //$NON-NLS-1$
- dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
- dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- if (dialog.open() == IDialogConstants.OK_ID) {
- IResource resource = (IResource) dialog.getFirstResult();
- String arg = resource.getFullPath().toString();
- scriptFile.setText(workspacePath + arg);
- }
- }
- });
-
- fileBrowseButton = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.FileSystem"), null); //$NON-NLS-1$
- fileBrowseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String filePath = scriptFile.getText();
- FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
- filePath = dialog.open();
- if (filePath != null) {
- scriptFile.setText(filePath);
- }
- }
- });
-
-
- Label binaryFileLabel = new Label(browseTop, SWT.NONE);
- binaryFileLabel.setText(Messages.getString("SystemTapOptionsTab.SelectBinary")); //$NON-NLS-1$
-
- binaryFile = new Text(browseTop, SWT.BORDER);
- binaryFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- binaryFile.addModifyListener(modifyListener);
-
-
- Button workspaceBrowseButton2 = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.WorkspaceButton2"), null); //$NON-NLS-1$
- workspaceBrowseButton2.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
- dialog.setTitle(Messages.getString("SystemTapOptionsTab.SelectResource")); //$NON-NLS-1$
- dialog.setMessage(Messages.getString("SystemTapOptionsTab.SelectSuppressions")); //$NON-NLS-1$
- dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
- dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- if (dialog.open() == IDialogConstants.OK_ID) {
- IResource resource = (IResource) dialog.getFirstResult();
- String arg = resource.getFullPath().toString();
- binaryFile.setText(workspacePath + arg);
- }
- }
- });
-
-
- Button fileBrowseButton2 = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.BrowseFiles"), null); //$NON-NLS-1$
- fileBrowseButton2.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String filePath = binaryFile.getText();
- FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
- filePath = dialog.open();
- if (filePath != null) {
- File file = new File(filePath);
- if (file.exists()) binaryFile.setText(filePath);
- }
- }
- });
-
-
- Label outputFileLabel = new Label(browseTop, SWT.NONE);
- outputFileLabel.setText(Messages.getString("SystemTapOptionsTab.SelectOutput")); //$NON-NLS-1$
-
- outputFile = new Text(browseTop, SWT.BORDER);
- outputFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- outputFile.addModifyListener(modifyListenerOutput);
- outputFile.addFocusListener(focusListener);
-
- Button workspaceBrowseButton3 = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.WorkspaceButton2"), null); //$NON-NLS-1$
- workspaceBrowseButton3.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
- dialog.setTitle(Messages.getString("SystemTapOptionsTab.SelectResource")); //$NON-NLS-1$
- dialog.setMessage(Messages.getString("SystemTapOptionsTab.SelectSuppressions")); //$NON-NLS-1$
- dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
- dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- if (dialog.open() == IDialogConstants.OK_ID) {
- IResource resource = (IResource) dialog.getFirstResult();
- String arg = resource.getFullPath().toString();
- outputFile.setText(workspacePath + arg);
- checkOverwrite();
- updateLaunchConfigurationDialog();
-
- }
- }
- });
-
- Button fileBrowseButton3 = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.BrowseFiles"), null); //$NON-NLS-1$
- fileBrowseButton3.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String filePath = outputFile.getText();
- FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
- filePath = dialog.open();
- if (filePath != null) {
- outputFile.setText(filePath);
- checkOverwrite();
- updateLaunchConfigurationDialog();
- }
- }
- });
-
- useColourButton = new Button(browseTop, SWT.CHECK);
- useColourButton.setText(Messages.getString("SystemTapOptionsTab.ColourCodes")); //$NON-NLS-1$
- useColourButton.addSelectionListener(selectListener);
- useColourButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- }
-
-
-
- private void createCommandOption(Composite top) {
- Composite buttonsTop = new Composite(top, SWT.NONE);
- GridLayout gl = new GridLayout(2, true);
- buttonsTop.setLayout( gl );
- GridData buttonsData = new GridData(SWT.FILL, SWT.BEGINNING, true, true);
- buttonsTop.setLayoutData(buttonsData);
-
- button_k = new Button(buttonsTop, SWT.CHECK);
- button_k.setText(Messages.getString("SystemTapOptionsTab.KeepTemp")); //$NON-NLS-1$
- button_k.addSelectionListener(selectListener);
- button_k.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_k.setToolTipText(Messages.getString("SystemTapOptionsTab.KeepTempToolTip")); //$NON-NLS-1$
-
- button_g = new Button(buttonsTop, SWT.CHECK);
- button_g.setText(Messages.getString("SystemTapOptionsTab.Guru")); //$NON-NLS-1$
- button_g.addSelectionListener(selectListener);
- button_g.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_g.setToolTipText(Messages.getString("SystemTapOptionsTab.GuruToolTip")); //$NON-NLS-1$
-
- button_P = new Button(buttonsTop, SWT.CHECK);
- button_P.setText(Messages.getString("SystemTapOptionsTab.Prologue")); //$NON-NLS-1$
- button_P.addSelectionListener(selectListener);
- button_P.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_P.setToolTipText(Messages.getString("SystemTapOptionsTab.PrologueSearchToolTip")); //$NON-NLS-1$
-
- button_u = new Button(buttonsTop, SWT.CHECK);
- button_u.setText(Messages.getString("SystemTapOptionsTab.Unused")); //$NON-NLS-1$
- button_u.addSelectionListener(selectListener);
- button_u.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_u.setToolTipText(
- Messages.getString("SystemTapOptionsTab.12")); //$NON-NLS-1$
-
- button_w = new Button(buttonsTop, SWT.CHECK);
- button_w.setText(Messages.getString("SystemTapOptionsTab.Warnings")); //$NON-NLS-1$
- button_w.addSelectionListener(selectListener);
- button_w.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_w.setToolTipText(Messages.getString("SystemTapOptionsTab.DisableWarningsToolTip")); //$NON-NLS-1$
-
- button_b = new Button(buttonsTop, SWT.CHECK);
- button_b.setText(Messages.getString("SystemTapOptionsTab.Bulk")); //$NON-NLS-1$
- button_b.addSelectionListener(selectListener);
- button_b.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_b.setToolTipText(
- Messages.getString("SystemTapOptionsTab.15")); //$NON-NLS-1$
-
- button_t = new Button(buttonsTop, SWT.CHECK);
- button_t.setText(Messages.getString("SystemTapOptionsTab.Timing")); //$NON-NLS-1$
- button_t.addSelectionListener(selectListener);
- button_t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_t.setToolTipText(Messages.getString("SystemTapOptionsTab.CollectTimingToolTip")); //$NON-NLS-1$
-
- button_F = new Button(buttonsTop, SWT.CHECK);
- button_F.setText(Messages.getString("SystemTapOptionsTab.LeaveProbesRunning")); //$NON-NLS-1$
- button_F.addSelectionListener(selectListener);
- button_F.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_F.setToolTipText(Messages.getString("SystemTapOptionsTab.LeaveProbesToolTip")); //$NON-NLS-1$
-
- buttonSkipBadvars = new Button(buttonsTop, SWT.CHECK);
- buttonSkipBadvars.setText(Messages.getString("SystemTapOptionsTab.IgnoreBadVars")); //$NON-NLS-1$
- buttonSkipBadvars.addSelectionListener(selectListener);
- buttonSkipBadvars.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- buttonSkipBadvars.setToolTipText(
- Messages.getString("SystemTapOptionsTab.30")); //$NON-NLS-1$
-
- buttonIgnoreDwarf = new Button(buttonsTop, SWT.CHECK);
- buttonIgnoreDwarf.setText(Messages.getString("SystemTapOptionsTab.ForTesting")); //$NON-NLS-1$
- buttonIgnoreDwarf.addSelectionListener(selectListener);
- buttonIgnoreDwarf.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- buttonIgnoreDwarf.setToolTipText(Messages.getString("SystemTapOptionsTab.IgnoreDebugToolTip")); //$NON-NLS-1$
-
- button_q = new Button(buttonsTop, SWT.CHECK);
- button_q.setText(Messages.getString("SystemTapOptionsTab.Button_qInfo")); //$NON-NLS-1$
- button_q.addSelectionListener(selectListener);
- button_q.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_q.setToolTipText(Messages.getString("SystemTapOptionsTab.33")); //$NON-NLS-1$
-
- buttonGraphicsMode = new Button(buttonsTop, SWT.CHECK);
- buttonGraphicsMode.setText(Messages.getString("SystemTapOptionsTab.3")); //$NON-NLS-1$
- buttonGraphicsMode.addSelectionListener(graphicsModeListener);
- buttonGraphicsMode.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- buttonGraphicsMode.setToolTipText(
- Messages.getString("SystemTapOptionsTab.41")); //$NON-NLS-1$
-
- Composite button_p_Spinner_Top = new Composite(buttonsTop, SWT.NONE);
- button_p_Spinner_Top.setLayout(new GridLayout(2, true));
- button_p_Spinner_Top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- Label button_p_Spinner_Label = new Label(button_p_Spinner_Top, SWT.NONE);
- button_p_Spinner_Label.setText(Messages.getString("SystemTapOptionsTab.19")); //$NON-NLS-1$
- button_p_Spinner = new Spinner(button_p_Spinner_Top, SWT.BORDER);
- button_p_Spinner.setMaximum(Integer.MAX_VALUE);
- button_p_Spinner.addModifyListener(modifyListener);
- button_p_Spinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_p_Spinner_Label.setToolTipText(Messages.getString("SystemTapOptionsTab.StopAfterPassToolTip")); //$NON-NLS-1$
-
- Composite button_s_Spinner_Top = new Composite(buttonsTop, SWT.NONE);
- button_s_Spinner_Top.setLayout(new GridLayout(2, true));
- button_s_Spinner_Top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- Label button_s_Spinner_Label = new Label(button_s_Spinner_Top, SWT.NONE);
- button_s_Spinner_Label.setText(Messages.getString("SystemTapOptionsTab.BufferWith")); //$NON-NLS-1$
- button_s_Spinner = new Spinner(button_s_Spinner_Top, SWT.BORDER);
- button_s_Spinner.setMaximum(Integer.MAX_VALUE);
- button_s_Spinner.addModifyListener(modifyListener);
- button_s_Spinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_s_Spinner_Label.setToolTipText(Messages.getString("SystemTapOptionsTab.BufferWithToolTip")); //$NON-NLS-1$
-
- Composite button_x_Spinner_Top = new Composite(buttonsTop, SWT.NONE);
- button_x_Spinner_Top.setLayout(new GridLayout(2, true));
- button_x_Spinner_Top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- Label button_x_Spinner_Label = new Label(button_x_Spinner_Top, SWT.NONE);
- button_x_Spinner_Label.setText(Messages.getString("SystemTapOptionsTab.TargetPID")); //$NON-NLS-1$
- button_x_Spinner = new Spinner(button_x_Spinner_Top, SWT.BORDER);
- button_x_Spinner.setMaximum(Integer.MAX_VALUE);
- button_x_Spinner.addModifyListener(modifyListener);
- button_x_Spinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_x_Spinner_Label.setToolTipText(Messages.getString("SystemTapOptionsTab.TargetPIDToolTip")); //$NON-NLS-1$
-
- Composite button_v_Spinner_Top = new Composite(buttonsTop, SWT.NONE);
- button_v_Spinner_Top.setLayout(new GridLayout(2, true));
- button_v_Spinner_Top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- Label button_v_Spinner_Label = new Label(button_v_Spinner_Top, SWT.NONE);
- button_v_Spinner_Label.setText(Messages.getString("SystemTapOptionsTab.18")); //$NON-NLS-1$
- button_v_Spinner = new Spinner(button_v_Spinner_Top, SWT.BORDER);
- button_v_Spinner.setMaximum(3);
- button_v_Spinner.addModifyListener(modifyListener);
- button_v_Spinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_v_Spinner_Label.setToolTipText(Messages.getString("SystemTapOptionsTab.TargetPIDToolTip")); //$NON-NLS-1$
-
-
- Label button_D_label = new Label(buttonsTop, SWT.NONE);
- button_D_label.setText(Messages.getString("SystemTapOptionsTab.PreprocessorDirective")); //$NON-NLS-1$
- button_D_text = new Text(buttonsTop, SWT.BORDER);
- button_D_text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- button_D_text.addModifyListener(modifyListener);
- button_D_label.setToolTipText(
- Messages.getString("SystemTapOptionsTab.PreprocessorToolTip")); //$NON-NLS-1$
- }
-
- @Override
- public String getName() {
- return Messages.getString("SystemTapOptionsTab.MainTabName"); //$NON-NLS-1$
- }
-
- private Shell getActiveWorkbenchShell() {
- return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
- }
-
- private IBinary chooseBinary(IBinary[] binaries) {
- ILabelProvider programLabelProvider = new CElementLabelProvider() {
- @Override
- public String getText(Object element) {
- if (element instanceof IBinary) {
- IBinary bin = (IBinary)element;
- StringBuffer name = new StringBuffer();
- name.append(bin.getPath().lastSegment());
- return name.toString();
- }
- return super.getText(element);
- }
- };
-
- ILabelProvider qualifierLabelProvider = new CElementLabelProvider() {
- @Override
- public String getText(Object element) {
- if (element instanceof IBinary) {
- IBinary bin = (IBinary)element;
- StringBuffer name = new StringBuffer();
- name.append(bin.getCPU() + (bin.isLittleEndian() ? "le" : "be")); //$NON-NLS-1$ //$NON-NLS-2$
- name.append(" - "); //$NON-NLS-1$
- name.append(bin.getPath().toString());
- return name.toString();
- }
- return super.getText(element);
- }
- };
-
- TwoPaneElementSelector dialog = new TwoPaneElementSelector(getActiveWorkbenchShell(), programLabelProvider, qualifierLabelProvider);
- dialog.setElements(binaries);
- dialog.setTitle(Messages.getString("SystemtTapOptionsTab.Callgraph")); //$NON-NLS-1$
- dialog.setMessage(Messages.getString("SystemtTapOptionsTab.Choose_a_local_application")); //$NON-NLS-1$
- dialog.setUpperListLabel(Messages.getString("SystemtTapOptionsTab.Binaries")); //$NON-NLS-1$
- dialog.setLowerListLabel(Messages.getString("SystemtTapOptionsTab.Qualifier")); //$NON-NLS-1$
- dialog.setMultipleSelection(false);
- if (dialog.open() == Window.OK) {
- return (IBinary) dialog.getFirstResult();
- }
-
- return null;
- }
-
- private IBinary getBinary(ILaunchConfiguration config) {
- try {
- ICProject project = CDebugUtils.verifyCProject(config);
- IBinary[] binaries = project.getBinaryContainer().getBinaries();
- if (binaries != null && binaries.length > 0) {
- if (binaries.length == 1 && binaries[0] != null) {
- return binaries[0];
- } else
- return chooseBinary(binaries);
- }
- return null;
- } catch (CoreException e) {
- return null;
- }
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration configuration) {
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceRoot root = workspace.getRoot();
- IPath location = root.getLocation();
- workspacePath = location.toString();
-
- try {
- button_k.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_KEEP_TEMPORARY, LaunchConfigurationConstants.DEFAULT_COMMAND_KEEP_TEMPORARY));
- button_u.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_NO_CODE_ELISION, LaunchConfigurationConstants.DEFAULT_COMMAND_NO_CODE_ELISION));
- button_w.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_DISABLE_WARNINGS, LaunchConfigurationConstants.DEFAULT_COMMAND_DISABLE_WARNINGS));
- button_b.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_BULK_MODE, LaunchConfigurationConstants.DEFAULT_COMMAND_BULK_MODE));
- button_g.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_GURU, LaunchConfigurationConstants.DEFAULT_COMMAND_GURU));
- button_P.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_PROLOGUE_SEARCH, LaunchConfigurationConstants.DEFAULT_COMMAND_PROLOGUE_SEARCH));
- button_t.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_TIMING_INFO, LaunchConfigurationConstants.DEFAULT_COMMAND_TIMING_INFO));
- buttonSkipBadvars.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_SKIP_BADVARS, LaunchConfigurationConstants.DEFAULT_COMMAND_SKIP_BADVARS));
- buttonIgnoreDwarf.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_IGNORE_DWARF, LaunchConfigurationConstants.DEFAULT_COMMAND_IGNORE_DWARF));
- button_q.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_TAPSET_COVERAGE, LaunchConfigurationConstants.DEFAULT_COMMAND_TAPSET_COVERAGE));
- button_F.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_LEAVE_RUNNING, LaunchConfigurationConstants.DEFAULT_COMMAND_LEAVE_RUNNING));
- button_s_Spinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_BUFFER_BYTES, LaunchConfigurationConstants.DEFAULT_COMMAND_BUFFER_BYTES));
- button_x_Spinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_TARGET_PID, LaunchConfigurationConstants.DEFAULT_COMMAND_TARGET_PID));
- button_v_Spinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_VERBOSE, LaunchConfigurationConstants.DEFAULT_COMMAND_VERBOSE));
- button_p_Spinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_PASS, LaunchConfigurationConstants.DEFAULT_COMMAND_PASS));
-
- button_D_text.setText(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_C_DIRECTIVES, LaunchConfigurationConstants.DEFAULT_COMMAND_C_DIRECTIVES));
- binaryFile.setText(configuration.getAttribute(LaunchConfigurationConstants.BINARY_PATH, LaunchConfigurationConstants.DEFAULT_BINARY_PATH));
- scriptFile.setText(configuration.getAttribute(LaunchConfigurationConstants.SCRIPT_PATH, LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH));
- outputFile.setText(configuration.getAttribute(LaunchConfigurationConstants.OUTPUT_PATH, LaunchConfigurationConstants.DEFAULT_OUTPUT_PATH));
- arguments.setText(configuration.getAttribute(LaunchConfigurationConstants.ARGUMENTS, LaunchConfigurationConstants.DEFAULT_ARGUMENTS));
- binaryArguments.setText(configuration.getAttribute(LaunchConfigurationConstants.BINARY_ARGUMENTS, LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS));
-
- parser.setText(configuration.getAttribute(LaunchConfigurationConstants.PARSER_CLASS, LaunchConfigurationConstants.DEFAULT_PARSER_CLASS));
- viewer.setText(configuration.getAttribute(LaunchConfigurationConstants.VIEW_CLASS, LaunchConfigurationConstants.DEFAULT_VIEW_CLASS));
-
- useColourButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.USE_COLOUR, LaunchConfigurationConstants.DEFAULT_USE_COLOUR));
-
- } catch (CoreException e) {
- e.printStackTrace();
- }
-
-
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
-
- getControl().setRedraw(false);
-
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_KEEP_TEMPORARY, button_k.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_GURU, button_g.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_PROLOGUE_SEARCH, button_P.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_NO_CODE_ELISION, button_u.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_DISABLE_WARNINGS, button_w.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_BULK_MODE, button_b.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TIMING_INFO, button_t.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_SKIP_BADVARS, buttonSkipBadvars.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_IGNORE_DWARF, buttonIgnoreDwarf.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TAPSET_COVERAGE, button_q.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_LEAVE_RUNNING, button_F.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_PASS, button_p_Spinner.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_BUFFER_BYTES, button_s_Spinner.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TARGET_PID, button_x_Spinner.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_VERBOSE, button_v_Spinner.getSelection());
-
- configuration.setAttribute(LaunchConfigurationConstants.PARSER_CLASS, parser.getText());
- configuration.setAttribute(LaunchConfigurationConstants.VIEW_CLASS, viewer.getText());
-
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_C_DIRECTIVES, button_D_text.getText());
- configuration.setAttribute(LaunchConfigurationConstants.BINARY_PATH, binaryFile.getText());
- configuration.setAttribute(LaunchConfigurationConstants.SCRIPT_PATH, scriptFile.getText());
- configuration.setAttribute(LaunchConfigurationConstants.ARGUMENTS, arguments.getText());
- configuration.setAttribute(LaunchConfigurationConstants.BINARY_ARGUMENTS, binaryArguments.getText());
- configuration.setAttribute(LaunchConfigurationConstants.OUTPUT_PATH, outputFile.getText());
-
- configuration.setAttribute(LaunchConfigurationConstants.USE_COLOUR, useColourButton.getSelection());
-
- if (buttonGraphicsMode.getSelection()){
- scriptFile.setEnabled(false);
- workspaceBrowseButton.setEnabled(false);
- fileBrowseButton.setEnabled(false);
-
- }else{
- scriptFile.setEnabled(true);
- workspaceBrowseButton.setEnabled(true);
- fileBrowseButton.setEnabled(true);
- }
-
- if (changeOverwrite) {
- if (needsOverwritePermission && overwritePermission || !needsOverwritePermission) {
- configuration.setAttribute(LaunchConfigurationConstants.OVERWRITE, true);
- } else {
- configuration.setAttribute(LaunchConfigurationConstants.OVERWRITE, false);
- }
- changeOverwrite = false;
- }
-
- getControl().setRedraw(true);
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_VERBOSE,LaunchConfigurationConstants.DEFAULT_COMMAND_VERBOSE);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_KEEP_TEMPORARY,LaunchConfigurationConstants.DEFAULT_COMMAND_KEEP_TEMPORARY);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_GURU,LaunchConfigurationConstants.DEFAULT_COMMAND_GURU);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_PROLOGUE_SEARCH,LaunchConfigurationConstants.DEFAULT_COMMAND_PROLOGUE_SEARCH);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_NO_CODE_ELISION,LaunchConfigurationConstants.DEFAULT_COMMAND_NO_CODE_ELISION);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_DISABLE_WARNINGS,LaunchConfigurationConstants.DEFAULT_COMMAND_DISABLE_WARNINGS);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_BULK_MODE,LaunchConfigurationConstants.DEFAULT_COMMAND_BULK_MODE);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TIMING_INFO,LaunchConfigurationConstants.DEFAULT_COMMAND_TIMING_INFO);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_SKIP_BADVARS,LaunchConfigurationConstants.DEFAULT_COMMAND_SKIP_BADVARS);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_IGNORE_DWARF,LaunchConfigurationConstants.DEFAULT_COMMAND_IGNORE_DWARF);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TAPSET_COVERAGE,LaunchConfigurationConstants.DEFAULT_COMMAND_TAPSET_COVERAGE);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_LEAVE_RUNNING,LaunchConfigurationConstants.DEFAULT_COMMAND_LEAVE_RUNNING);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_PASS,LaunchConfigurationConstants.DEFAULT_COMMAND_PASS);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_BUFFER_BYTES,LaunchConfigurationConstants.DEFAULT_COMMAND_BUFFER_BYTES);
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TARGET_PID,LaunchConfigurationConstants.DEFAULT_COMMAND_TARGET_PID);
-
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_C_DIRECTIVES,LaunchConfigurationConstants.DEFAULT_COMMAND_C_DIRECTIVES);
- configuration.setAttribute(LaunchConfigurationConstants.BINARY_PATH,LaunchConfigurationConstants.DEFAULT_BINARY_PATH);
- configuration.setAttribute(LaunchConfigurationConstants.SCRIPT_PATH,LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH);
- configuration.setAttribute(LaunchConfigurationConstants.OUTPUT_PATH,LaunchConfigurationConstants.DEFAULT_OUTPUT_PATH);
- configuration.setAttribute(LaunchConfigurationConstants.ARGUMENTS,LaunchConfigurationConstants.DEFAULT_ARGUMENTS);
- configuration.setAttribute(LaunchConfigurationConstants.BINARY_ARGUMENTS,LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS);
-
- configuration.setAttribute(LaunchConfigurationConstants.GENERATED_SCRIPT, LaunchConfigurationConstants.DEFAULT_GENERATED_SCRIPT);
- configuration.setAttribute(LaunchConfigurationConstants.NEED_TO_GENERATE, LaunchConfigurationConstants.DEFAULT_NEED_TO_GENERATE);
- configuration.setAttribute(LaunchConfigurationConstants.PARSER_CLASS, LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
- configuration.setAttribute(LaunchConfigurationConstants.VIEW_CLASS, LaunchConfigurationConstants.DEFAULT_VIEW_CLASS);
-
- configuration.setAttribute(LaunchConfigurationConstants.USE_COLOUR, LaunchConfigurationConstants.DEFAULT_USE_COLOUR);
-
- configuration.setAttribute(LaunchConfigurationConstants.COMMAND_LIST, ConfigurationOptionsSetter.setOptions(configuration));
-
- ICElement cElement = null;
- cElement = getContext(configuration, getPlatform(configuration));
- if (cElement != null) {
- initializeCProject(cElement, configuration);
- } else {
- // don't want to remember the interim value from before
- configuration.setMappedResources(null);
- }
-
- IBinary bin = getBinary(configuration);
- if (bin != null) {
- String programName = bin.getResource().getProjectRelativePath().toString();
- configuration.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, programName);
- configuration.setAttribute(ICDTLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, (String) null);
-
- LaunchStapGraph launch = new LaunchStapGraph();
- launch.setTestMode(true); //Do not run callgraph
- launch.launch(bin, "", configuration); //$NON-NLS-1$
- }
- }
-
-
- @Override
- public boolean isValid(ILaunchConfiguration launchConfig) {
- // Check that the major options are sane
- boolean valid = true;
- try {
- String sPath = launchConfig.getAttribute(
- LaunchConfigurationConstants.SCRIPT_PATH,
- LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH);
-
- File script = new File(sPath);
-
- if (sPath.equals(LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH) || !script.exists()) {
- //No script path specified or no such script exists
- valid = false;
- }
-
- } catch (CoreException e) {
- e.printStackTrace();
- }
-
- return valid;
- }
-
- private String getUsefulLabel(Object element) {
- if (element instanceof IConfigurationElement) {
- Object o = ((IConfigurationElement) element).getParent();
- if (o instanceof IExtension) {
- IExtension e = (IExtension) ((IConfigurationElement) element).getParent();
- return e.getUniqueIdentifier();
- }
- }
- return Messages.getString("SystemTapOptionsTab.1"); //$NON-NLS-1$
- }
-
- private static class ListLabelProvider extends LabelProvider {
-
- @Override
- public Image getImage(Object element) {
- return null;
- }
-
- @Override
- public String getText(Object element) {
- if (element instanceof IConfigurationElement) {
- Object o = ((IConfigurationElement) element).getParent();
- if (o instanceof IExtension) {
- IExtension e = (IExtension) ((IConfigurationElement) element).getParent();
- return e.getLabel();
- }
- else if (o instanceof IConfigurationElement) {
- IConfigurationElement e = (IConfigurationElement) ((IConfigurationElement) element).getParent();
- return e.getName();
- }
-
- }
- return Messages.getString("SystemTapOptionsTab.46"); //$NON-NLS-1$
- }
-
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
- }
+ //Controls
+ private Text scriptFile;
+ private Text binaryFile;
+ private Text arguments;
+ private Text outputFile;
+ private Text button_D_text;
+ private Text binaryArguments;
+ private Text parser;
+ private Text viewer;
+
+ private Button fileBrowseButton;
+ private Button workspaceBrowseButton;
+
+ private Button button_k;
+ private Button button_u;
+ private Button button_w;
+ private Button button_b;
+ private Button button_g;
+ private Button button_P;
+ private Button button_t;
+ private Button button_F;
+ private Button buttonSkipBadvars;
+ private Button buttonIgnoreDwarf;
+ private Button button_q;
+ private Button buttonGraphicsMode;
+
+
+ private Spinner button_p_Spinner;
+ private Spinner button_s_Spinner;
+ private Spinner button_x_Spinner;
+ private Spinner button_v_Spinner;
+
+ private Button useColourButton;
+
+ //Other variables
+ private String workspacePath;
+ private boolean outputFileHasChanged = false;
+ private boolean needsOverwritePermission = false;
+ private boolean overwritePermission = false;
+ private boolean changeOverwrite = false;
+
+ /**
+ * The code below is very long, but it boils down to this.
+ *
+ * The main function is createControl. This function prepares
+ * some space for the various tabs and calls the other create*Option
+ * functions to create buttons, text fields and spinners.
+ *
+ * The create*Option functions create their respective sub-tabs.
+ *
+ * Each of the controls (button, text, spinner) needs to have a listener
+ * attached so Eclipse knows what to do with them.
+ *
+ * There are a bunch of functions to update/set defaults/initialize,
+ * and a final
+ */
+
+ private SelectionListener graphicsModeListener = new SelectionAdapter(){
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ if (scriptFile.isEnabled()){
+ scriptFile.setEnabled(false);
+ workspaceBrowseButton.setEnabled(false);
+ fileBrowseButton.setEnabled(false);
+ scriptFile.setText(PluginConstants.getPluginLocation()+"parse_function.stp"); //$NON-NLS-1$
+ }else{
+ scriptFile.setEnabled(true);
+ workspaceBrowseButton.setEnabled(true);
+ fileBrowseButton.setEnabled(true);
+ }
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ private SelectionListener selectListener = new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ private ModifyListener modifyListener = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ private ModifyListener modifyListenerOutput = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ outputFileHasChanged = true;
+ }
+ };
+
+ private FocusListener focusListener = new FocusAdapter() {
+
+ @Override
+ public void focusLost(FocusEvent e) {
+ if (outputFileHasChanged) {
+ checkOverwrite();
+ }
+ outputFileHasChanged = false;
+
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ /**
+ * Convenience method to check if the overwrite permissions are consistent
+ *
+ * Helps ensure validity of configuration.
+ */
+ private void checkOverwrite() {
+ File f = new File(outputFile.getText());
+ changeOverwrite = true;
+ if (f.exists()) {
+ needsOverwritePermission = true;
+ Shell sh = new Shell();
+ if (MessageDialog.openConfirm(sh, Messages.getString("SystemTapOptionsTab.ConfirmOverwriteFileTitle"), //$NON-NLS-1$
+ Messages.getString("SystemTapOptionsTab.ConfirmOverwriteFileMessage"))) { //$NON-NLS-1$
+ overwritePermission = true;
+ } else {
+ overwritePermission = false;
+ }
+ }
+ else
+ needsOverwritePermission = false;
+ }
+
+ /**
+ * This function prepares some space for the various
+ * tabs and calls and sets the other create*Option
+ * functions to create buttons, text fields and spinners.
+ */
+ @Override
+ public void createControl(Composite parent) {
+ /*
+ * File folder - tab for selecting binary/stp file
+ */
+ TabFolder fileFolder = new TabFolder(parent, SWT.BORDER);
+ fileFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
+ setControl(fileFolder);
+
+ TabItem fileTab = new TabItem(fileFolder, SWT.NONE);
+ fileTab.setText(Messages.getString("SystemTapOptionsTab.FilesTab")); //$NON-NLS-1$
+
+ Composite fileTop = new Composite(fileFolder, SWT.NONE);
+ fileTop.setLayout(new GridLayout());
+ fileTop.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ createFileOption(fileTop);
+ fileTab.setControl(fileTop);
+
+
+ /*
+ * Commands tab - tab for selecting SystemTap commands
+ */
+
+ TabItem commandTab = new TabItem(fileFolder, SWT.NONE);
+ commandTab.setText(Messages.getString("SystemTapOptionsTab.CommandsTab")); //$NON-NLS-1$
+
+ Composite commandTop = new Composite(fileFolder, SWT.NONE);
+ commandTop.setLayout(new GridLayout());
+ commandTop.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ createCommandOption(commandTop);
+ commandTab.setControl(commandTop);
+
+ /*
+ * Arguments tab - tab for selecting script arguments
+ */
+ TabItem argumentsTab = new TabItem(fileFolder, SWT.NONE);
+ argumentsTab.setText(Messages.getString("SystemTapOptionsTab.Arguments")); //$NON-NLS-1$
+
+ Composite argumentsTop = new Composite(fileFolder, SWT.NONE);
+ argumentsTop.setLayout(new GridLayout());
+ argumentsTop.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ createArgumentsOption(argumentsTop);
+ argumentsTab.setControl(argumentsTop);
+
+
+ /*
+ * Binary Argument tab - tab for supplying arguments for a binary
+ */
+ TabItem binaryArgumentsTab = new TabItem(fileFolder, SWT.NONE);
+ binaryArgumentsTab.setText(Messages.getString("SystemTapOptionsTab.44")); //$NON-NLS-1$
+
+ Composite binaryArgumentsTop = new Composite(fileFolder, SWT.NONE);
+ binaryArgumentsTop.setLayout(new GridLayout());
+ binaryArgumentsTop.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ createBinaryArgumentsOption(binaryArgumentsTop);
+ binaryArgumentsTab.setControl(binaryArgumentsTop);
+
+
+ /*
+ * Parser tab -- Tab for selecting a parser and viewer to use
+ */
+ TabItem parserTab = new TabItem(fileFolder, SWT.NONE);
+ parserTab.setText("Parser"); //$NON-NLS-1$
+
+ Composite parserTop = new Composite(fileFolder, SWT.NONE);
+ parserTop.setLayout(new GridLayout());
+ parserTop.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ createParserOption(parserTop);
+ parserTab.setControl(parserTop);
+ }
+
+
+ private void createBinaryArgumentsOption(Composite binaryArgumentsTop) {
+ Composite browseTop = new Composite(binaryArgumentsTop, SWT.NONE);
+ browseTop.setLayout(new GridLayout(1, false));
+ GridData browseData = new GridData(GridData.FILL_HORIZONTAL);
+ browseTop.setLayoutData(browseData);
+
+ Label suppFileLabel = new Label(browseTop, SWT.NONE);
+ suppFileLabel.setText(Messages.getString("SystemTapOptionsTab.45")); //$NON-NLS-1$
+
+ binaryArguments = new Text(browseTop,SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.heightHint = 200;
+ binaryArguments.setLayoutData(gd);
+ binaryArguments.addModifyListener(modifyListener);
+ }
+
+ private void createParserOption(Composite parserTop) {
+ Composite browseTop = new Composite(parserTop, SWT.NONE);
+ browseTop.setLayout(new GridLayout(1, false));
+ GridData browseData = new GridData(GridData.FILL_HORIZONTAL);
+ browseTop.setLayoutData(browseData);
+
+ Label suppFileLabel = new Label(browseTop, SWT.NONE);
+ suppFileLabel.setText("Parser"); //$NON-NLS-1$
+
+ parser = new Text(browseTop, SWT.BORDER);
+ parser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ parser.addModifyListener(modifyListener);
+
+ Button parserButton = createPushButton(browseTop,
+ "Find parsers", null); //$NON-NLS-1$
+ parserButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(),
+ new ListLabelProvider());
+ dialog.setTitle("Select parser"); //$NON-NLS-1$
+ dialog.setMessage("Select parser to use."); //$NON-NLS-1$
+ IExtensionRegistry reg = Platform.getExtensionRegistry();
+ IConfigurationElement[] extensions = reg
+ .getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
+ PluginConstants.PARSER_NAME);
+
+ dialog.setElements(extensions);
+ if (dialog.open() == IDialogConstants.OK_ID) {
+ String arg = getUsefulLabel(dialog.getFirstResult());
+ parser.setText(arg);
+ }
+ }
+ });
+
+
+ viewer = new Text(browseTop, SWT.BORDER);
+ viewer.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ viewer.addModifyListener(modifyListener);
+
+ Button viewerButton = createPushButton(browseTop,
+ "Find viewers", null); //$NON-NLS-1$
+ viewerButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(),
+ new ListLabelProvider());
+ dialog.setTitle("Select viewer"); //$NON-NLS-1$
+ dialog.setMessage("Select viewer to use."); //$NON-NLS-1$
+ IExtensionRegistry reg = Platform.getExtensionRegistry();
+ IConfigurationElement[] extensions = reg
+ .getConfigurationElementsFor(PluginConstants.VIEW_RESOURCE,
+ PluginConstants.VIEW_NAME);
+ ArrayList<IConfigurationElement> ext = new ArrayList<>();
+ for (IConfigurationElement el : extensions) {
+ if (!el.getNamespaceIdentifier().contains("org.eclipse.linuxtools")) //$NON-NLS-1$
+ continue;
+ //TODO: Rough hack to get all the objects. We restrict to id's containing org.eclipse.linuxtools, then see if the class extends SystemTapView
+ try {
+ if (el.createExecutableExtension(PluginConstants.ATTR_CLASS)
+ instanceof SystemTapView) {
+ ext.add(el);
+ }
+ } catch (CoreException e1) {
+ }
+ }
+
+ dialog.setElements(ext.toArray());
+ if (dialog.open() == IDialogConstants.OK_ID) {
+ String arg = getUsefulLabel(dialog.getFirstResult());
+ viewer.setText(arg);
+ }
+ }
+ });
+
+ }
+
+ private void createArgumentsOption(Composite argumentsTop) {
+ Composite browseTop = new Composite(argumentsTop, SWT.NONE);
+ browseTop.setLayout(new GridLayout(1, false));
+ GridData browseData = new GridData(GridData.FILL_HORIZONTAL);
+ browseTop.setLayoutData(browseData);
+
+
+ Label suppFileLabel = new Label(browseTop, SWT.NONE);
+ suppFileLabel.setText(Messages.getString("SystemTapOptionsTab.SelectArguments")); //$NON-NLS-1$
+
+ arguments = new Text(browseTop,SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
+
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.heightHint = 200;
+ arguments.setLayoutData(gd);
+ arguments.addModifyListener(modifyListener);
+
+
+ Button probeFunctionButton = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.ProbeFunction"), null); //$NON-NLS-1$
+ probeFunctionButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ arguments.setText(arguments.getText() + " process(\"" + binaryFile.getText() + "\").function(\"\")"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ });
+ }
+
+ private void createFileOption(Composite top) {
+ Composite browseTop = new Composite(top, SWT.NONE);
+ browseTop.setLayout(new GridLayout(4, false));
+ browseTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ Label suppFileLabel = new Label(browseTop, SWT.NONE);
+ suppFileLabel.setText(Messages.getString("SystemTapOptionsTab.ScriptSelector")); //$NON-NLS-1$
+
+ scriptFile = new Text(browseTop, SWT.BORDER);
+ scriptFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ scriptFile.addModifyListener(modifyListener);
+
+ workspaceBrowseButton = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.WorkspaceButton"), null); //$NON-NLS-1$
+ workspaceBrowseButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
+ dialog.setTitle(Messages.getString("SystemTapOptionsTab.ResourceButton")); //$NON-NLS-1$
+ dialog.setMessage(Messages.getString("SystemTapOptionsTab.SuppresionsFile")); //$NON-NLS-1$
+ dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
+ dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
+ if (dialog.open() == IDialogConstants.OK_ID) {
+ IResource resource = (IResource) dialog.getFirstResult();
+ String arg = resource.getFullPath().toString();
+ scriptFile.setText(workspacePath + arg);
+ }
+ }
+ });
+
+ fileBrowseButton = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.FileSystem"), null); //$NON-NLS-1$
+ fileBrowseButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ String filePath = scriptFile.getText();
+ FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
+ filePath = dialog.open();
+ if (filePath != null) {
+ scriptFile.setText(filePath);
+ }
+ }
+ });
+
+
+ Label binaryFileLabel = new Label(browseTop, SWT.NONE);
+ binaryFileLabel.setText(Messages.getString("SystemTapOptionsTab.SelectBinary")); //$NON-NLS-1$
+
+ binaryFile = new Text(browseTop, SWT.BORDER);
+ binaryFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ binaryFile.addModifyListener(modifyListener);
+
+
+ Button workspaceBrowseButton2 = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.WorkspaceButton2"), null); //$NON-NLS-1$
+ workspaceBrowseButton2.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
+ dialog.setTitle(Messages.getString("SystemTapOptionsTab.SelectResource")); //$NON-NLS-1$
+ dialog.setMessage(Messages.getString("SystemTapOptionsTab.SelectSuppressions")); //$NON-NLS-1$
+ dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
+ dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
+ if (dialog.open() == IDialogConstants.OK_ID) {
+ IResource resource = (IResource) dialog.getFirstResult();
+ String arg = resource.getFullPath().toString();
+ binaryFile.setText(workspacePath + arg);
+ }
+ }
+ });
+
+
+ Button fileBrowseButton2 = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.BrowseFiles"), null); //$NON-NLS-1$
+ fileBrowseButton2.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ String filePath = binaryFile.getText();
+ FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
+ filePath = dialog.open();
+ if (filePath != null) {
+ File file = new File(filePath);
+ if (file.exists()) binaryFile.setText(filePath);
+ }
+ }
+ });
+
+
+ Label outputFileLabel = new Label(browseTop, SWT.NONE);
+ outputFileLabel.setText(Messages.getString("SystemTapOptionsTab.SelectOutput")); //$NON-NLS-1$
+
+ outputFile = new Text(browseTop, SWT.BORDER);
+ outputFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ outputFile.addModifyListener(modifyListenerOutput);
+ outputFile.addFocusListener(focusListener);
+
+ Button workspaceBrowseButton3 = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.WorkspaceButton2"), null); //$NON-NLS-1$
+ workspaceBrowseButton3.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
+ dialog.setTitle(Messages.getString("SystemTapOptionsTab.SelectResource")); //$NON-NLS-1$
+ dialog.setMessage(Messages.getString("SystemTapOptionsTab.SelectSuppressions")); //$NON-NLS-1$
+ dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
+ dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
+ if (dialog.open() == IDialogConstants.OK_ID) {
+ IResource resource = (IResource) dialog.getFirstResult();
+ String arg = resource.getFullPath().toString();
+ outputFile.setText(workspacePath + arg);
+ checkOverwrite();
+ updateLaunchConfigurationDialog();
+
+ }
+ }
+ });
+
+ Button fileBrowseButton3 = createPushButton(browseTop, Messages.getString("SystemTapOptionsTab.BrowseFiles"), null); //$NON-NLS-1$
+ fileBrowseButton3.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ String filePath = outputFile.getText();
+ FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
+ filePath = dialog.open();
+ if (filePath != null) {
+ outputFile.setText(filePath);
+ checkOverwrite();
+ updateLaunchConfigurationDialog();
+ }
+ }
+ });
+
+ useColourButton = new Button(browseTop, SWT.CHECK);
+ useColourButton.setText(Messages.getString("SystemTapOptionsTab.ColourCodes")); //$NON-NLS-1$
+ useColourButton.addSelectionListener(selectListener);
+ useColourButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ }
+
+
+
+ private void createCommandOption(Composite top) {
+ Composite buttonsTop = new Composite(top, SWT.NONE);
+ GridLayout gl = new GridLayout(2, true);
+ buttonsTop.setLayout( gl );
+ GridData buttonsData = new GridData(SWT.FILL, SWT.BEGINNING, true, true);
+ buttonsTop.setLayoutData(buttonsData);
+
+ button_k = new Button(buttonsTop, SWT.CHECK);
+ button_k.setText(Messages.getString("SystemTapOptionsTab.KeepTemp")); //$NON-NLS-1$
+ button_k.addSelectionListener(selectListener);
+ button_k.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_k.setToolTipText(Messages.getString("SystemTapOptionsTab.KeepTempToolTip")); //$NON-NLS-1$
+
+ button_g = new Button(buttonsTop, SWT.CHECK);
+ button_g.setText(Messages.getString("SystemTapOptionsTab.Guru")); //$NON-NLS-1$
+ button_g.addSelectionListener(selectListener);
+ button_g.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_g.setToolTipText(Messages.getString("SystemTapOptionsTab.GuruToolTip")); //$NON-NLS-1$
+
+ button_P = new Button(buttonsTop, SWT.CHECK);
+ button_P.setText(Messages.getString("SystemTapOptionsTab.Prologue")); //$NON-NLS-1$
+ button_P.addSelectionListener(selectListener);
+ button_P.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_P.setToolTipText(Messages.getString("SystemTapOptionsTab.PrologueSearchToolTip")); //$NON-NLS-1$
+
+ button_u = new Button(buttonsTop, SWT.CHECK);
+ button_u.setText(Messages.getString("SystemTapOptionsTab.Unused")); //$NON-NLS-1$
+ button_u.addSelectionListener(selectListener);
+ button_u.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_u.setToolTipText(
+ Messages.getString("SystemTapOptionsTab.12")); //$NON-NLS-1$
+
+ button_w = new Button(buttonsTop, SWT.CHECK);
+ button_w.setText(Messages.getString("SystemTapOptionsTab.Warnings")); //$NON-NLS-1$
+ button_w.addSelectionListener(selectListener);
+ button_w.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_w.setToolTipText(Messages.getString("SystemTapOptionsTab.DisableWarningsToolTip")); //$NON-NLS-1$
+
+ button_b = new Button(buttonsTop, SWT.CHECK);
+ button_b.setText(Messages.getString("SystemTapOptionsTab.Bulk")); //$NON-NLS-1$
+ button_b.addSelectionListener(selectListener);
+ button_b.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_b.setToolTipText(
+ Messages.getString("SystemTapOptionsTab.15")); //$NON-NLS-1$
+
+ button_t = new Button(buttonsTop, SWT.CHECK);
+ button_t.setText(Messages.getString("SystemTapOptionsTab.Timing")); //$NON-NLS-1$
+ button_t.addSelectionListener(selectListener);
+ button_t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_t.setToolTipText(Messages.getString("SystemTapOptionsTab.CollectTimingToolTip")); //$NON-NLS-1$
+
+ button_F = new Button(buttonsTop, SWT.CHECK);
+ button_F.setText(Messages.getString("SystemTapOptionsTab.LeaveProbesRunning")); //$NON-NLS-1$
+ button_F.addSelectionListener(selectListener);
+ button_F.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_F.setToolTipText(Messages.getString("SystemTapOptionsTab.LeaveProbesToolTip")); //$NON-NLS-1$
+
+ buttonSkipBadvars = new Button(buttonsTop, SWT.CHECK);
+ buttonSkipBadvars.setText(Messages.getString("SystemTapOptionsTab.IgnoreBadVars")); //$NON-NLS-1$
+ buttonSkipBadvars.addSelectionListener(selectListener);
+ buttonSkipBadvars.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ buttonSkipBadvars.setToolTipText(
+ Messages.getString("SystemTapOptionsTab.30")); //$NON-NLS-1$
+
+ buttonIgnoreDwarf = new Button(buttonsTop, SWT.CHECK);
+ buttonIgnoreDwarf.setText(Messages.getString("SystemTapOptionsTab.ForTesting")); //$NON-NLS-1$
+ buttonIgnoreDwarf.addSelectionListener(selectListener);
+ buttonIgnoreDwarf.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ buttonIgnoreDwarf.setToolTipText(Messages.getString("SystemTapOptionsTab.IgnoreDebugToolTip")); //$NON-NLS-1$
+
+ button_q = new Button(buttonsTop, SWT.CHECK);
+ button_q.setText(Messages.getString("SystemTapOptionsTab.Button_qInfo")); //$NON-NLS-1$
+ button_q.addSelectionListener(selectListener);
+ button_q.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_q.setToolTipText(Messages.getString("SystemTapOptionsTab.33")); //$NON-NLS-1$
+
+ buttonGraphicsMode = new Button(buttonsTop, SWT.CHECK);
+ buttonGraphicsMode.setText(Messages.getString("SystemTapOptionsTab.3")); //$NON-NLS-1$
+ buttonGraphicsMode.addSelectionListener(graphicsModeListener);
+ buttonGraphicsMode.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ buttonGraphicsMode.setToolTipText(
+ Messages.getString("SystemTapOptionsTab.41")); //$NON-NLS-1$
+
+ Composite button_p_Spinner_Top = new Composite(buttonsTop, SWT.NONE);
+ button_p_Spinner_Top.setLayout(new GridLayout(2, true));
+ button_p_Spinner_Top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ Label button_p_Spinner_Label = new Label(button_p_Spinner_Top, SWT.NONE);
+ button_p_Spinner_Label.setText(Messages.getString("SystemTapOptionsTab.19")); //$NON-NLS-1$
+ button_p_Spinner = new Spinner(button_p_Spinner_Top, SWT.BORDER);
+ button_p_Spinner.setMaximum(Integer.MAX_VALUE);
+ button_p_Spinner.addModifyListener(modifyListener);
+ button_p_Spinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_p_Spinner_Label.setToolTipText(Messages.getString("SystemTapOptionsTab.StopAfterPassToolTip")); //$NON-NLS-1$
+
+ Composite button_s_Spinner_Top = new Composite(buttonsTop, SWT.NONE);
+ button_s_Spinner_Top.setLayout(new GridLayout(2, true));
+ button_s_Spinner_Top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ Label button_s_Spinner_Label = new Label(button_s_Spinner_Top, SWT.NONE);
+ button_s_Spinner_Label.setText(Messages.getString("SystemTapOptionsTab.BufferWith")); //$NON-NLS-1$
+ button_s_Spinner = new Spinner(button_s_Spinner_Top, SWT.BORDER);
+ button_s_Spinner.setMaximum(Integer.MAX_VALUE);
+ button_s_Spinner.addModifyListener(modifyListener);
+ button_s_Spinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_s_Spinner_Label.setToolTipText(Messages.getString("SystemTapOptionsTab.BufferWithToolTip")); //$NON-NLS-1$
+
+ Composite button_x_Spinner_Top = new Composite(buttonsTop, SWT.NONE);
+ button_x_Spinner_Top.setLayout(new GridLayout(2, true));
+ button_x_Spinner_Top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ Label button_x_Spinner_Label = new Label(button_x_Spinner_Top, SWT.NONE);
+ button_x_Spinner_Label.setText(Messages.getString("SystemTapOptionsTab.TargetPID")); //$NON-NLS-1$
+ button_x_Spinner = new Spinner(button_x_Spinner_Top, SWT.BORDER);
+ button_x_Spinner.setMaximum(Integer.MAX_VALUE);
+ button_x_Spinner.addModifyListener(modifyListener);
+ button_x_Spinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_x_Spinner_Label.setToolTipText(Messages.getString("SystemTapOptionsTab.TargetPIDToolTip")); //$NON-NLS-1$
+
+ Composite button_v_Spinner_Top = new Composite(buttonsTop, SWT.NONE);
+ button_v_Spinner_Top.setLayout(new GridLayout(2, true));
+ button_v_Spinner_Top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ Label button_v_Spinner_Label = new Label(button_v_Spinner_Top, SWT.NONE);
+ button_v_Spinner_Label.setText(Messages.getString("SystemTapOptionsTab.18")); //$NON-NLS-1$
+ button_v_Spinner = new Spinner(button_v_Spinner_Top, SWT.BORDER);
+ button_v_Spinner.setMaximum(3);
+ button_v_Spinner.addModifyListener(modifyListener);
+ button_v_Spinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_v_Spinner_Label.setToolTipText(Messages.getString("SystemTapOptionsTab.TargetPIDToolTip")); //$NON-NLS-1$
+
+
+ Label button_D_label = new Label(buttonsTop, SWT.NONE);
+ button_D_label.setText(Messages.getString("SystemTapOptionsTab.PreprocessorDirective")); //$NON-NLS-1$
+ button_D_text = new Text(buttonsTop, SWT.BORDER);
+ button_D_text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ button_D_text.addModifyListener(modifyListener);
+ button_D_label.setToolTipText(
+ Messages.getString("SystemTapOptionsTab.PreprocessorToolTip")); //$NON-NLS-1$
+ }
+
+ @Override
+ public String getName() {
+ return Messages.getString("SystemTapOptionsTab.MainTabName"); //$NON-NLS-1$
+ }
+
+ private Shell getActiveWorkbenchShell() {
+ return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
+ }
+
+ private IBinary chooseBinary(IBinary[] binaries) {
+ ILabelProvider programLabelProvider = new CElementLabelProvider() {
+ @Override
+ public String getText(Object element) {
+ if (element instanceof IBinary) {
+ IBinary bin = (IBinary)element;
+ StringBuffer name = new StringBuffer();
+ name.append(bin.getPath().lastSegment());
+ return name.toString();
+ }
+ return super.getText(element);
+ }
+ };
+
+ ILabelProvider qualifierLabelProvider = new CElementLabelProvider() {
+ @Override
+ public String getText(Object element) {
+ if (element instanceof IBinary) {
+ IBinary bin = (IBinary)element;
+ StringBuffer name = new StringBuffer();
+ name.append(bin.getCPU() + (bin.isLittleEndian() ? "le" : "be")); //$NON-NLS-1$ //$NON-NLS-2$
+ name.append(" - "); //$NON-NLS-1$
+ name.append(bin.getPath().toString());
+ return name.toString();
+ }
+ return super.getText(element);
+ }
+ };
+
+ TwoPaneElementSelector dialog = new TwoPaneElementSelector(getActiveWorkbenchShell(), programLabelProvider, qualifierLabelProvider);
+ dialog.setElements(binaries);
+ dialog.setTitle(Messages.getString("SystemtTapOptionsTab.Callgraph")); //$NON-NLS-1$
+ dialog.setMessage(Messages.getString("SystemtTapOptionsTab.Choose_a_local_application")); //$NON-NLS-1$
+ dialog.setUpperListLabel(Messages.getString("SystemtTapOptionsTab.Binaries")); //$NON-NLS-1$
+ dialog.setLowerListLabel(Messages.getString("SystemtTapOptionsTab.Qualifier")); //$NON-NLS-1$
+ dialog.setMultipleSelection(false);
+ if (dialog.open() == Window.OK) {
+ return (IBinary) dialog.getFirstResult();
+ }
+
+ return null;
+ }
+
+ private IBinary getBinary(ILaunchConfiguration config) {
+ try {
+ ICProject project = CDebugUtils.verifyCProject(config);
+ IBinary[] binaries = project.getBinaryContainer().getBinaries();
+ if (binaries != null && binaries.length > 0) {
+ if (binaries.length == 1 && binaries[0] != null) {
+ return binaries[0];
+ } else
+ return chooseBinary(binaries);
+ }
+ return null;
+ } catch (CoreException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration configuration) {
+
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IWorkspaceRoot root = workspace.getRoot();
+ IPath location = root.getLocation();
+ workspacePath = location.toString();
+
+ try {
+ button_k.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_KEEP_TEMPORARY, LaunchConfigurationConstants.DEFAULT_COMMAND_KEEP_TEMPORARY));
+ button_u.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_NO_CODE_ELISION, LaunchConfigurationConstants.DEFAULT_COMMAND_NO_CODE_ELISION));
+ button_w.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_DISABLE_WARNINGS, LaunchConfigurationConstants.DEFAULT_COMMAND_DISABLE_WARNINGS));
+ button_b.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_BULK_MODE, LaunchConfigurationConstants.DEFAULT_COMMAND_BULK_MODE));
+ button_g.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_GURU, LaunchConfigurationConstants.DEFAULT_COMMAND_GURU));
+ button_P.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_PROLOGUE_SEARCH, LaunchConfigurationConstants.DEFAULT_COMMAND_PROLOGUE_SEARCH));
+ button_t.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_TIMING_INFO, LaunchConfigurationConstants.DEFAULT_COMMAND_TIMING_INFO));
+ buttonSkipBadvars.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_SKIP_BADVARS, LaunchConfigurationConstants.DEFAULT_COMMAND_SKIP_BADVARS));
+ buttonIgnoreDwarf.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_IGNORE_DWARF, LaunchConfigurationConstants.DEFAULT_COMMAND_IGNORE_DWARF));
+ button_q.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_TAPSET_COVERAGE, LaunchConfigurationConstants.DEFAULT_COMMAND_TAPSET_COVERAGE));
+ button_F.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_LEAVE_RUNNING, LaunchConfigurationConstants.DEFAULT_COMMAND_LEAVE_RUNNING));
+ button_s_Spinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_BUFFER_BYTES, LaunchConfigurationConstants.DEFAULT_COMMAND_BUFFER_BYTES));
+ button_x_Spinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_TARGET_PID, LaunchConfigurationConstants.DEFAULT_COMMAND_TARGET_PID));
+ button_v_Spinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_VERBOSE, LaunchConfigurationConstants.DEFAULT_COMMAND_VERBOSE));
+ button_p_Spinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_PASS, LaunchConfigurationConstants.DEFAULT_COMMAND_PASS));
+
+ button_D_text.setText(configuration.getAttribute(LaunchConfigurationConstants.COMMAND_C_DIRECTIVES, LaunchConfigurationConstants.DEFAULT_COMMAND_C_DIRECTIVES));
+ binaryFile.setText(configuration.getAttribute(LaunchConfigurationConstants.BINARY_PATH, LaunchConfigurationConstants.DEFAULT_BINARY_PATH));
+ scriptFile.setText(configuration.getAttribute(LaunchConfigurationConstants.SCRIPT_PATH, LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH));
+ outputFile.setText(configuration.getAttribute(LaunchConfigurationConstants.OUTPUT_PATH, LaunchConfigurationConstants.DEFAULT_OUTPUT_PATH));
+ arguments.setText(configuration.getAttribute(LaunchConfigurationConstants.ARGUMENTS, LaunchConfigurationConstants.DEFAULT_ARGUMENTS));
+ binaryArguments.setText(configuration.getAttribute(LaunchConfigurationConstants.BINARY_ARGUMENTS, LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS));
+
+ parser.setText(configuration.getAttribute(LaunchConfigurationConstants.PARSER_CLASS, LaunchConfigurationConstants.DEFAULT_PARSER_CLASS));
+ viewer.setText(configuration.getAttribute(LaunchConfigurationConstants.VIEW_CLASS, LaunchConfigurationConstants.DEFAULT_VIEW_CLASS));
+
+ useColourButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.USE_COLOUR, LaunchConfigurationConstants.DEFAULT_USE_COLOUR));
+
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+
+
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy configuration) {
+
+ getControl().setRedraw(false);
+
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_KEEP_TEMPORARY, button_k.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_GURU, button_g.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_PROLOGUE_SEARCH, button_P.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_NO_CODE_ELISION, button_u.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_DISABLE_WARNINGS, button_w.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_BULK_MODE, button_b.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TIMING_INFO, button_t.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_SKIP_BADVARS, buttonSkipBadvars.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_IGNORE_DWARF, buttonIgnoreDwarf.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TAPSET_COVERAGE, button_q.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_LEAVE_RUNNING, button_F.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_PASS, button_p_Spinner.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_BUFFER_BYTES, button_s_Spinner.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TARGET_PID, button_x_Spinner.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_VERBOSE, button_v_Spinner.getSelection());
+
+ configuration.setAttribute(LaunchConfigurationConstants.PARSER_CLASS, parser.getText());
+ configuration.setAttribute(LaunchConfigurationConstants.VIEW_CLASS, viewer.getText());
+
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_C_DIRECTIVES, button_D_text.getText());
+ configuration.setAttribute(LaunchConfigurationConstants.BINARY_PATH, binaryFile.getText());
+ configuration.setAttribute(LaunchConfigurationConstants.SCRIPT_PATH, scriptFile.getText());
+ configuration.setAttribute(LaunchConfigurationConstants.ARGUMENTS, arguments.getText());
+ configuration.setAttribute(LaunchConfigurationConstants.BINARY_ARGUMENTS, binaryArguments.getText());
+ configuration.setAttribute(LaunchConfigurationConstants.OUTPUT_PATH, outputFile.getText());
+
+ configuration.setAttribute(LaunchConfigurationConstants.USE_COLOUR, useColourButton.getSelection());
+
+ if (buttonGraphicsMode.getSelection()){
+ scriptFile.setEnabled(false);
+ workspaceBrowseButton.setEnabled(false);
+ fileBrowseButton.setEnabled(false);
+
+ }else{
+ scriptFile.setEnabled(true);
+ workspaceBrowseButton.setEnabled(true);
+ fileBrowseButton.setEnabled(true);
+ }
+
+ if (changeOverwrite) {
+ if (needsOverwritePermission && overwritePermission || !needsOverwritePermission) {
+ configuration.setAttribute(LaunchConfigurationConstants.OVERWRITE, true);
+ } else {
+ configuration.setAttribute(LaunchConfigurationConstants.OVERWRITE, false);
+ }
+ changeOverwrite = false;
+ }
+
+ getControl().setRedraw(true);
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_VERBOSE,LaunchConfigurationConstants.DEFAULT_COMMAND_VERBOSE);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_KEEP_TEMPORARY,LaunchConfigurationConstants.DEFAULT_COMMAND_KEEP_TEMPORARY);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_GURU,LaunchConfigurationConstants.DEFAULT_COMMAND_GURU);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_PROLOGUE_SEARCH,LaunchConfigurationConstants.DEFAULT_COMMAND_PROLOGUE_SEARCH);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_NO_CODE_ELISION,LaunchConfigurationConstants.DEFAULT_COMMAND_NO_CODE_ELISION);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_DISABLE_WARNINGS,LaunchConfigurationConstants.DEFAULT_COMMAND_DISABLE_WARNINGS);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_BULK_MODE,LaunchConfigurationConstants.DEFAULT_COMMAND_BULK_MODE);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TIMING_INFO,LaunchConfigurationConstants.DEFAULT_COMMAND_TIMING_INFO);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_SKIP_BADVARS,LaunchConfigurationConstants.DEFAULT_COMMAND_SKIP_BADVARS);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_IGNORE_DWARF,LaunchConfigurationConstants.DEFAULT_COMMAND_IGNORE_DWARF);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TAPSET_COVERAGE,LaunchConfigurationConstants.DEFAULT_COMMAND_TAPSET_COVERAGE);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_LEAVE_RUNNING,LaunchConfigurationConstants.DEFAULT_COMMAND_LEAVE_RUNNING);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_PASS,LaunchConfigurationConstants.DEFAULT_COMMAND_PASS);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_BUFFER_BYTES,LaunchConfigurationConstants.DEFAULT_COMMAND_BUFFER_BYTES);
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_TARGET_PID,LaunchConfigurationConstants.DEFAULT_COMMAND_TARGET_PID);
+
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_C_DIRECTIVES,LaunchConfigurationConstants.DEFAULT_COMMAND_C_DIRECTIVES);
+ configuration.setAttribute(LaunchConfigurationConstants.BINARY_PATH,LaunchConfigurationConstants.DEFAULT_BINARY_PATH);
+ configuration.setAttribute(LaunchConfigurationConstants.SCRIPT_PATH,LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH);
+ configuration.setAttribute(LaunchConfigurationConstants.OUTPUT_PATH,LaunchConfigurationConstants.DEFAULT_OUTPUT_PATH);
+ configuration.setAttribute(LaunchConfigurationConstants.ARGUMENTS,LaunchConfigurationConstants.DEFAULT_ARGUMENTS);
+ configuration.setAttribute(LaunchConfigurationConstants.BINARY_ARGUMENTS,LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS);
+
+ configuration.setAttribute(LaunchConfigurationConstants.GENERATED_SCRIPT, LaunchConfigurationConstants.DEFAULT_GENERATED_SCRIPT);
+ configuration.setAttribute(LaunchConfigurationConstants.NEED_TO_GENERATE, LaunchConfigurationConstants.DEFAULT_NEED_TO_GENERATE);
+ configuration.setAttribute(LaunchConfigurationConstants.PARSER_CLASS, LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
+ configuration.setAttribute(LaunchConfigurationConstants.VIEW_CLASS, LaunchConfigurationConstants.DEFAULT_VIEW_CLASS);
+
+ configuration.setAttribute(LaunchConfigurationConstants.USE_COLOUR, LaunchConfigurationConstants.DEFAULT_USE_COLOUR);
+
+ configuration.setAttribute(LaunchConfigurationConstants.COMMAND_LIST, ConfigurationOptionsSetter.setOptions(configuration));
+
+ ICElement cElement = null;
+ cElement = getContext(configuration, getPlatform(configuration));
+ if (cElement != null) {
+ initializeCProject(cElement, configuration);
+ } else {
+ // don't want to remember the interim value from before
+ configuration.setMappedResources(null);
+ }
+
+ IBinary bin = getBinary(configuration);
+ if (bin != null) {
+ String programName = bin.getResource().getProjectRelativePath().toString();
+ configuration.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, programName);
+ configuration.setAttribute(ICDTLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, (String) null);
+
+ LaunchStapGraph launch = new LaunchStapGraph();
+ launch.setTestMode(true); //Do not run callgraph
+ launch.launch(bin, "", configuration); //$NON-NLS-1$
+ }
+ }
+
+
+ @Override
+ public boolean isValid(ILaunchConfiguration launchConfig) {
+ // Check that the major options are sane
+ boolean valid = true;
+ try {
+ String sPath = launchConfig.getAttribute(
+ LaunchConfigurationConstants.SCRIPT_PATH,
+ LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH);
+
+ File script = new File(sPath);
+
+ if (sPath.equals(LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH) || !script.exists()) {
+ //No script path specified or no such script exists
+ valid = false;
+ }
+
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+
+ return valid;
+ }
+
+ private String getUsefulLabel(Object element) {
+ if (element instanceof IConfigurationElement) {
+ Object o = ((IConfigurationElement) element).getParent();
+ if (o instanceof IExtension) {
+ IExtension e = (IExtension) ((IConfigurationElement) element).getParent();
+ return e.getUniqueIdentifier();
+ }
+ }
+ return Messages.getString("SystemTapOptionsTab.1"); //$NON-NLS-1$
+ }
+
+ private static class ListLabelProvider extends LabelProvider {
+
+ @Override
+ public Image getImage(Object element) {
+ return null;
+ }
+
+ @Override
+ public String getText(Object element) {
+ if (element instanceof IConfigurationElement) {
+ Object o = ((IConfigurationElement) element).getParent();
+ if (o instanceof IExtension) {
+ IExtension e = (IExtension) ((IConfigurationElement) element).getParent();
+ return e.getLabel();
+ }
+ else if (o instanceof IConfigurationElement) {
+ IConfigurationElement e = (IConfigurationElement) ((IConfigurationElement) element).getParent();
+ return e.getName();
+ }
+
+ }
+ return Messages.getString("SystemTapOptionsTab.46"); //$NON-NLS-1$
+ }
+
+
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/TranslationUnitVisitor.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/TranslationUnitVisitor.java
index a5cd69cef1..c01b6e75dc 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/TranslationUnitVisitor.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/internal/callgraph/launch/TranslationUnitVisitor.java
@@ -14,23 +14,23 @@ import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ICElementVisitor;
public class TranslationUnitVisitor implements ICElementVisitor {
- private String functions;
+ private String functions;
- public TranslationUnitVisitor() {
- super();
- functions = ""; //$NON-NLS-1$
- }
+ public TranslationUnitVisitor() {
+ super();
+ functions = ""; //$NON-NLS-1$
+ }
- @Override
- public boolean visit(ICElement arg0) {
- if (arg0.getElementType() == ICElement.C_FUNCTION) {
- functions += arg0.getElementName() + " "; //$NON-NLS-1$
- return false;
- }
- return true;
- }
+ @Override
+ public boolean visit(ICElement arg0) {
+ if (arg0.getElementType() == ICElement.C_FUNCTION) {
+ functions += arg0.getElementName() + " "; //$NON-NLS-1$
+ return false;
+ }
+ return true;
+ }
- public String getFunctions() {
- return functions;
- }
+ public String getFunctions() {
+ return functions;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.tests/pom.xml b/systemtap/org.eclipse.linuxtools.callgraph.tests/pom.xml
index 2310972a8f..4d035a0db2 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.tests/pom.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph.tests/pom.xml
@@ -35,7 +35,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.callgraph.tests</testSuite>
<testClass>org.eclipse.linuxtools.callgraph.tests.AllTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.platform.ide</product>
</configuration>
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/Activator.java b/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/Activator.java
index 4939385d72..7ee23e1072 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/Activator.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/Activator.java
@@ -23,19 +23,19 @@ import org.osgi.framework.Bundle;
*/
public class Activator {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.callgraph.tests";
-
- public static String getPluginLocation() {
- Bundle bundle = Platform.getBundle(PLUGIN_ID);
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.callgraph.tests";
- URL locationUrl = FileLocator.find(bundle,new Path("/"), null); //$NON-NLS-1$
- URL fileUrl = null;
- try {
- fileUrl = FileLocator.toFileURL(locationUrl);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return fileUrl.getFile();
- }
+ public static String getPluginLocation() {
+ Bundle bundle = Platform.getBundle(PLUGIN_ID);
+
+ URL locationUrl = FileLocator.find(bundle,new Path("/"), null); //$NON-NLS-1$
+ URL fileUrl = null;
+ try {
+ fileUrl = FileLocator.toFileURL(locationUrl);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return fileUrl.getFile();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/MouseListenerTest.java b/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/MouseListenerTest.java
index 1bf66fc347..d7cf916eed 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/MouseListenerTest.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/MouseListenerTest.java
@@ -23,30 +23,30 @@ import org.junit.Test;
public class MouseListenerTest {
- @Test
- public void test() {
- StapGraphParser parse = new StapGraphParser();
- parse.setSourcePath(Activator.getPluginLocation() + "eag.graph");
- parse.testRun(new NullProgressMonitor(), true);
+ @Test
+ public void test() {
+ StapGraphParser parse = new StapGraphParser();
+ parse.setSourcePath(Activator.getPluginLocation() + "eag.graph");
+ parse.testRun(new NullProgressMonitor(), true);
- CallgraphView cView = (CallgraphView) ViewFactory.createView("org.eclipse.linuxtools.callgraph.callgraphview");
+ CallgraphView cView = (CallgraphView) ViewFactory.createView("org.eclipse.linuxtools.callgraph.callgraphview");
- StapUIJob j = new StapUIJob("Test Graph UI Job", parse,
- CallGraphConstants.VIEW_ID);
- j.runInUIThread(new NullProgressMonitor());
+ StapUIJob j = new StapUIJob("Test Graph UI Job", parse,
+ CallGraphConstants.VIEW_ID);
+ j.runInUIThread(new NullProgressMonitor());
- StapGraphMouseListener mListener = cView.getGraph().getMouseListener();
+ StapGraphMouseListener mListener = cView.getGraph().getMouseListener();
- StapGraph g = cView.getGraph();
- g.setProject(parse.project);
+ StapGraph g = cView.getGraph();
+ g.setProject(parse.project);
- GraphItem[] nodes = { g.getNode(g.getFirstUsefulNode()) };
- g.setSelection(nodes);
+ GraphItem[] nodes = { g.getNode(g.getFirstUsefulNode()) };
+ g.setSelection(nodes);
- mListener.mouseDownEvent(0, 0);
- g.draw(StapGraph.CONSTANT_DRAWMODE_TREE,
- StapGraph.CONSTANT_ANIMATION_FASTEST, g.getFirstUsefulNode());
- mListener.mouseUp(null);
+ mListener.mouseDownEvent(0, 0);
+ g.draw(StapGraph.CONSTANT_DRAWMODE_TREE,
+ StapGraph.CONSTANT_ANIMATION_FASTEST, g.getFirstUsefulNode());
+ mListener.mouseUp(null);
- }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/StapGraphParserTest.java b/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/StapGraphParserTest.java
index c1ea25b893..9ed5eb873b 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/StapGraphParserTest.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/StapGraphParserTest.java
@@ -23,117 +23,117 @@ import org.junit.Test;
public class StapGraphParserTest {
- //RENDER THE GRAPH
- public static StapGraphParser initializeGraph(String filePath){
- StapGraphParser grph = new StapGraphParser();
- grph.setSourcePath(filePath);
- grph.nonRealTimeParsing();
- return grph;
- }
-
- public static void assertSanity(StapGraphParser grph){
- /*if (grph.serialMap.size() == 0 || grph.timeMap.size() == 0
- || grph.outNeighbours.size() == 0 || grph.countMap.size() == 0
- || grph.aggregateTimeMap.size() == 0){
- fail("Parsing Error : One or more data structures were empty.");
- }*/
-
- //SAME NUMBER OF NODES ENTRIES
- assertEquals(grph.serialMap.size(),grph.timeMap.size());
- int nsize = 0;
- for (int key : grph.neighbourMaps.keySet())
- if (grph.neighbourMaps.get(key)!= null)
- nsize+=grph.neighbourMaps.get(key).size();
- assertEquals(grph.serialMap.size(),nsize);
- //ALL UNIQUE FUNCTIONS HAVE A TIME
- //ALL FUNCTIONS HAVE A CUMULATIVE TIME
- for (int val : grph.serialMap.keySet()){
- String fname = grph.serialMap.get(val);
- assertNotNull(grph.timeMap.get(val));
- assertNotNull(grph.aggregateTimeMap.get(fname));
- }
- }
-
-
- public static void assertTimes(StapGraphParser grph){
- //NO FUNCTION HAS TIME/CUMULATIVE TIME LARGER THAN TOTAL
- for (int val : grph.serialMap.keySet()){
- String fname = grph.serialMap.get(val);
- assertTrue(grph.totalTime >= grph.timeMap.get(val));
- assertTrue(grph.totalTime >= grph.aggregateTimeMap.get(fname));
- }
- }
-
-
- public static void assertConnectedness (StapGraphParser grph){
- boolean hasParent;
- //ALL NODES MUST HAVE A PARENT EXCEPT THE ROOT
- for (int key : grph.serialMap.keySet()){
- hasParent = false;
- for (int k:grph.neighbourMaps.keySet()) {
- HashMap<Integer, ArrayList<Integer>> outNeighbours = grph.neighbourMaps.get(k);
- if (outNeighbours != null && outNeighbours.size() > 0)
- for (ArrayList<Integer> list : outNeighbours.values()){
- if (list.contains(key)){
- hasParent = true;
- break;
- }
- }
-
- if (!hasParent){
- for (int other : grph.serialMap.keySet()){
- if (key > other){
- fail(key + " " + grph.serialMap.get(key) + " had no parent");
- }
- }
- }
- }
- }
-
- }
-
-
- public final String currentPath = Activator.getPluginLocation();
- public String graphDataPath= "";
-
- //FOR TESTING THE GRAPH PARSING
- public void executeGraphTests(){
- StapGraphParser grph = StapGraphParserTest.initializeGraph(graphDataPath);
- StapGraphParserTest.assertSanity(grph);
- StapGraphParserTest.assertTimes(grph);
- StapGraphParserTest.assertConnectedness(grph);
- }
+ //RENDER THE GRAPH
+ public static StapGraphParser initializeGraph(String filePath){
+ StapGraphParser grph = new StapGraphParser();
+ grph.setSourcePath(filePath);
+ grph.nonRealTimeParsing();
+ return grph;
+ }
+
+ public static void assertSanity(StapGraphParser grph){
+ /*if (grph.serialMap.size() == 0 || grph.timeMap.size() == 0
+ || grph.outNeighbours.size() == 0 || grph.countMap.size() == 0
+ || grph.aggregateTimeMap.size() == 0){
+ fail("Parsing Error : One or more data structures were empty.");
+ }*/
+
+ //SAME NUMBER OF NODES ENTRIES
+ assertEquals(grph.serialMap.size(),grph.timeMap.size());
+ int nsize = 0;
+ for (int key : grph.neighbourMaps.keySet())
+ if (grph.neighbourMaps.get(key)!= null)
+ nsize+=grph.neighbourMaps.get(key).size();
+ assertEquals(grph.serialMap.size(),nsize);
+ //ALL UNIQUE FUNCTIONS HAVE A TIME
+ //ALL FUNCTIONS HAVE A CUMULATIVE TIME
+ for (int val : grph.serialMap.keySet()){
+ String fname = grph.serialMap.get(val);
+ assertNotNull(grph.timeMap.get(val));
+ assertNotNull(grph.aggregateTimeMap.get(fname));
+ }
+ }
+
+
+ public static void assertTimes(StapGraphParser grph){
+ //NO FUNCTION HAS TIME/CUMULATIVE TIME LARGER THAN TOTAL
+ for (int val : grph.serialMap.keySet()){
+ String fname = grph.serialMap.get(val);
+ assertTrue(grph.totalTime >= grph.timeMap.get(val));
+ assertTrue(grph.totalTime >= grph.aggregateTimeMap.get(fname));
+ }
+ }
+
+
+ public static void assertConnectedness (StapGraphParser grph){
+ boolean hasParent;
+ //ALL NODES MUST HAVE A PARENT EXCEPT THE ROOT
+ for (int key : grph.serialMap.keySet()){
+ hasParent = false;
+ for (int k:grph.neighbourMaps.keySet()) {
+ HashMap<Integer, ArrayList<Integer>> outNeighbours = grph.neighbourMaps.get(k);
+ if (outNeighbours != null && outNeighbours.size() > 0)
+ for (ArrayList<Integer> list : outNeighbours.values()){
+ if (list.contains(key)){
+ hasParent = true;
+ break;
+ }
+ }
+
+ if (!hasParent){
+ for (int other : grph.serialMap.keySet()){
+ if (key > other){
+ fail(key + " " + grph.serialMap.get(key) + " had no parent");
+ }
+ }
+ }
+ }
+ }
+
+ }
+
+
+ public final String currentPath = Activator.getPluginLocation();
+ public String graphDataPath= "";
+
+ //FOR TESTING THE GRAPH PARSING
+ public void executeGraphTests(){
+ StapGraphParser grph = StapGraphParserTest.initializeGraph(graphDataPath);
+ StapGraphParserTest.assertSanity(grph);
+ StapGraphParserTest.assertTimes(grph);
+ StapGraphParserTest.assertConnectedness(grph);
+ }
@Test
- public void testJustMain(){
- graphDataPath = currentPath+"main.graph";
- executeGraphTests();
- }
+ public void testJustMain(){
+ graphDataPath = currentPath+"main.graph";
+ executeGraphTests();
+ }
@Test
- public void testCallGraphRunBasic(){
- graphDataPath = currentPath+"basic.graph";
- executeGraphTests();
- }
+ public void testCallGraphRunBasic(){
+ graphDataPath = currentPath+"basic.graph";
+ executeGraphTests();
+ }
@Test
- public void testCallGraphRunRecursive(){
- graphDataPath = currentPath+"catlan.graph";
- executeGraphTests();
- }
+ public void testCallGraphRunRecursive(){
+ graphDataPath = currentPath+"catlan.graph";
+ executeGraphTests();
+ }
@Test
- public void testManyFuncs(){
- graphDataPath = currentPath+"eag.graph";
- executeGraphTests();
- }
+ public void testManyFuncs(){
+ graphDataPath = currentPath+"eag.graph";
+ executeGraphTests();
+ }
@Test
- public void testComprehensive(){
- graphDataPath = currentPath+"comprehensive.graph";
- executeGraphTests();
- }
+ public void testComprehensive(){
+ graphDataPath = currentPath+"comprehensive.graph";
+ executeGraphTests();
+ }
@Test
- public void testHeavy(){
- graphDataPath = currentPath+"heavy.graph";
- executeGraphTests();
- }
+ public void testHeavy(){
+ graphDataPath = currentPath+"heavy.graph";
+ executeGraphTests();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/SystemTapGraphTest.java b/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/SystemTapGraphTest.java
index 8e35ede8ec..df8e5518c9 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/SystemTapGraphTest.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/SystemTapGraphTest.java
@@ -28,93 +28,93 @@ import org.junit.Test;
public class SystemTapGraphTest {
- private boolean manual = false;
- @Test
- public void testGraphLoading() {
+ private boolean manual = false;
+ @Test
+ public void testGraphLoading() {
- StapGraphParser parse = new StapGraphParser();
- parse.setSourcePath(Activator.getPluginLocation()+"eag.graph");
- assertEquals(Status.OK_STATUS, parse.testRun(new NullProgressMonitor(), true));
+ StapGraphParser parse = new StapGraphParser();
+ parse.setSourcePath(Activator.getPluginLocation()+"eag.graph");
+ assertEquals(Status.OK_STATUS, parse.testRun(new NullProgressMonitor(), true));
- StapUIJob j = new StapUIJob("Test Graph UI Job", parse, CallGraphConstants.VIEW_ID);
- j.runInUIThread(new NullProgressMonitor());
- CallgraphView cView = (CallgraphView) ViewFactory.createView(CallGraphConstants.VIEW_ID);
+ StapUIJob j = new StapUIJob("Test Graph UI Job", parse, CallGraphConstants.VIEW_ID);
+ j.runInUIThread(new NullProgressMonitor());
+ CallgraphView cView = (CallgraphView) ViewFactory.createView(CallGraphConstants.VIEW_ID);
- if (!manual) {
- ArrayList<String> tasks = new ArrayList<>();
+ if (!manual) {
+ ArrayList<String> tasks = new ArrayList<>();
- tasks.add("(Manually) Maximize CallgraphView");
- tasks.add("Refresh");
- tasks.add("Tree View");
- tasks.add("Aggregate View");
- tasks.add("Box View");
- tasks.add("Animation->Fast");
- tasks.add("Collapse");
- tasks.add("Uncollapse");
- tasks.add("Radial View");
- tasks.add("Collapse.");
- tasks.add("(Manually) Double-click node with no children in TreeViewer");
- tasks.add("(Manually) Expand an arrow in the TreeViewer");
- tasks.add("(Manually) Collapse an arrow in the TreeViewer");
- tasks.add("Save file");
- tasks.add("Reload file");
- tasks.add("Maximize");
+ tasks.add("(Manually) Maximize CallgraphView");
+ tasks.add("Refresh");
+ tasks.add("Tree View");
+ tasks.add("Aggregate View");
+ tasks.add("Box View");
+ tasks.add("Animation->Fast");
+ tasks.add("Collapse");
+ tasks.add("Uncollapse");
+ tasks.add("Radial View");
+ tasks.add("Collapse.");
+ tasks.add("(Manually) Double-click node with no children in TreeViewer");
+ tasks.add("(Manually) Expand an arrow in the TreeViewer");
+ tasks.add("(Manually) Collapse an arrow in the TreeViewer");
+ tasks.add("Save file");
+ tasks.add("Reload file");
+ tasks.add("Maximize");
- for (int taskNumber = 0; taskNumber < tasks.size(); taskNumber++) {
+ for (int taskNumber = 0; taskNumber < tasks.size(); taskNumber++) {
- Action act = null;
- switch (taskNumber) {
- case 1:
- break;
- case 2:
- act = cView.getViewRefresh();
- break;
- case 3:
- act = cView.getViewTreeview();
- break;
- case 4:
- act = cView.getViewAggregateview();
- break;
- case 5:
- act = cView.getViewLevelview();
- break;
- case 6:
- act = cView.getAnimationFast();
- break;
- case 7:
- case 8:
- act = cView.getModeCollapsednodes();
- break;
- case 9:
- act = cView.getViewRadialview();
- break;
- case 10:
- act = cView.getModeCollapsednodes();
- break;
- case 14:
- String tempLocation = Activator.getPluginLocation()+"eag.graph2";
- File temp = new File(tempLocation);
- temp.delete();
- cView.saveData(tempLocation);
- temp.delete();
- break;
- case 15:
- StapGraphParser new_parser = new StapGraphParser();
- new_parser.setSourcePath(Activator.getPluginLocation()+"eag.graph");
- new_parser.testRun(new NullProgressMonitor(), true);
- break;
- case 16:
- cView.maximizeIfUnmaximized();
- break;
- default:
- break;
- }
- if (act != null) {
- act.run();
- }
- }
- return;
- }
- }
+ Action act = null;
+ switch (taskNumber) {
+ case 1:
+ break;
+ case 2:
+ act = cView.getViewRefresh();
+ break;
+ case 3:
+ act = cView.getViewTreeview();
+ break;
+ case 4:
+ act = cView.getViewAggregateview();
+ break;
+ case 5:
+ act = cView.getViewLevelview();
+ break;
+ case 6:
+ act = cView.getAnimationFast();
+ break;
+ case 7:
+ case 8:
+ act = cView.getModeCollapsednodes();
+ break;
+ case 9:
+ act = cView.getViewRadialview();
+ break;
+ case 10:
+ act = cView.getModeCollapsednodes();
+ break;
+ case 14:
+ String tempLocation = Activator.getPluginLocation()+"eag.graph2";
+ File temp = new File(tempLocation);
+ temp.delete();
+ cView.saveData(tempLocation);
+ temp.delete();
+ break;
+ case 15:
+ StapGraphParser new_parser = new StapGraphParser();
+ new_parser.setSourcePath(Activator.getPluginLocation()+"eag.graph");
+ new_parser.testRun(new NullProgressMonitor(), true);
+ break;
+ case 16:
+ cView.maximizeIfUnmaximized();
+ break;
+ default:
+ break;
+ }
+ if (act != null) {
+ act.run();
+ }
+ }
+ return;
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/SystemTapGraphViewTest.java b/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/SystemTapGraphViewTest.java
index 4ebe75fdba..cce4bb5ec5 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/SystemTapGraphViewTest.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.tests/src/org/eclipse/linuxtools/callgraph/tests/SystemTapGraphViewTest.java
@@ -18,19 +18,19 @@ import org.eclipse.linuxtools.internal.callgraph.core.ViewFactory;
import org.junit.Test;
public class SystemTapGraphViewTest {
- private SystemTapTextView stapView = new SystemTapTextView();
- private String testText = "blah";
+ private SystemTapTextView stapView = new SystemTapTextView();
+ private String testText = "blah";
- //TODO: write some better tests here
- @Test
- public void test() {
- stapView = (SystemTapTextView) ViewFactory.createView("org.eclipse.linuxtools.callgraph.core.staptextview");
+ //TODO: write some better tests here
+ @Test
+ public void test() {
+ stapView = (SystemTapTextView) ViewFactory.createView("org.eclipse.linuxtools.callgraph.core.staptextview");
- stapView.println(testText);
- assertEquals(stapView.getText(), testText);
+ stapView.println(testText);
+ assertEquals(stapView.getText(), testText);
- stapView.clearAll();
- assertEquals(stapView.getText(), "");
- }
+ stapView.clearAll();
+ assertEquals(stapView.getText(), "");
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/plugin.xml b/systemtap/org.eclipse.linuxtools.callgraph/plugin.xml
index 02fa15ce6b..82723f2a21 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/plugin.xml
+++ b/systemtap/org.eclipse.linuxtools.callgraph/plugin.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
-
+
<extension
point="org.eclipse.ui.perspectiveExtensions">
<perspectiveExtension
@@ -15,7 +15,7 @@
</perspectiveExtension>
</extension>
-
+
<extension
id="org.eclipse.linuxtools.callgraph.callgraphview"
name="%extension.name"
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/AggregateLayoutAlgorithm.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/AggregateLayoutAlgorithm.java
index c2b4963292..e1ee85ddac 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/AggregateLayoutAlgorithm.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/AggregateLayoutAlgorithm.java
@@ -25,59 +25,59 @@ import org.eclipse.zest.layouts.dataStructures.InternalRelationship;
*/
public class AggregateLayoutAlgorithm extends GridLayoutAlgorithm{
- private ArrayList<Long> list;
- private Long totalTime;
- private int graphWidth;
+ private ArrayList<Long> list;
+ private Long totalTime;
+ private int graphWidth;
- /**
- * Layout algorithm for the Aggregate View in Eclipse Callgraph, based on the GridLayoutAlgorithm in Zest.
- * @param styles
- * @param entries
- * @param time
- * @param width
- */
- public AggregateLayoutAlgorithm(int styles, TreeSet<Entry<String, Long>> entries, Long time, int width){
- super(styles);
+ /**
+ * Layout algorithm for the Aggregate View in Eclipse Callgraph, based on the GridLayoutAlgorithm in Zest.
+ * @param styles
+ * @param entries
+ * @param time
+ * @param width
+ */
+ public AggregateLayoutAlgorithm(int styles, TreeSet<Entry<String, Long>> entries, Long time, int width){
+ super(styles);
- list = new ArrayList<>();
- for (Entry<String, Long> ent : entries) {
- list.add(ent.getValue());
- }
+ list = new ArrayList<>();
+ for (Entry<String, Long> ent : entries) {
+ list.add(ent.getValue());
+ }
- this.totalTime = time;
- this.graphWidth = width;
- }
+ this.totalTime = time;
+ this.graphWidth = width;
+ }
- /**
- * Called at the end of the layout algorithm -- change the size and colour
- * of each node according to times called/total time
- */
- @Override
- protected void postLayoutAlgorithm(InternalNode[] entitiesToLayout,
- InternalRelationship[] relationshipsToConsider) {
- final int minimumSize = 40;
- double xcursor = 0.0;
- double ycursor = 0.0;
+ /**
+ * Called at the end of the layout algorithm -- change the size and colour
+ * of each node according to times called/total time
+ */
+ @Override
+ protected void postLayoutAlgorithm(InternalNode[] entitiesToLayout,
+ InternalRelationship[] relationshipsToConsider) {
+ final int minimumSize = 40;
+ double xcursor = 0.0;
+ double ycursor = 0.0;
- for (InternalNode sn : entitiesToLayout) {
- Long time = list.remove(0);
- double percent = (double) time / (double) totalTime;
- double snWidth = (sn.getInternalWidth() * percent) + minimumSize;
- double snHeight = (sn.getInternalHeight() * percent) + minimumSize;
+ for (InternalNode sn : entitiesToLayout) {
+ Long time = list.remove(0);
+ double percent = (double) time / (double) totalTime;
+ double snWidth = (sn.getInternalWidth() * percent) + minimumSize;
+ double snHeight = (sn.getInternalHeight() * percent) + minimumSize;
- sn.setSize(snWidth, snHeight);
- if (xcursor + snWidth > graphWidth) {
- //reaching the end of row, move to lower column
- ycursor += snHeight;
- xcursor = 0;
- sn.setLocation(xcursor, ycursor);
- } else {
- sn.setLocation(xcursor, ycursor);
- xcursor += snWidth;
- }
- }
- }
+ sn.setSize(snWidth, snHeight);
+ if (xcursor + snWidth > graphWidth) {
+ //reaching the end of row, move to lower column
+ ycursor += snHeight;
+ xcursor = 0;
+ sn.setLocation(xcursor, ycursor);
+ } else {
+ sn.setLocation(xcursor, ycursor);
+ xcursor += snWidth;
+ }
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/CallGraphConstants.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/CallGraphConstants.java
index 5fac488bfc..3abf265d41 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/CallGraphConstants.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/CallGraphConstants.java
@@ -13,7 +13,7 @@ package org.eclipse.linuxtools.internal.callgraph;
public interface CallGraphConstants {
- String VIEW_ID = "org.eclipse.linuxtools.callgraph.callgraphview"; //$NON-NLS-1$
- String PLUGIN_ID = "org.eclipse.linuxtools.callgraph"; //$NON-NLS-1$
+ String VIEW_ID = "org.eclipse.linuxtools.callgraph.callgraphview"; //$NON-NLS-1$
+ String PLUGIN_ID = "org.eclipse.linuxtools.callgraph"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/CallgraphView.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/CallgraphView.java
index b8df8287e0..f7506eb8ba 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/CallgraphView.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/CallgraphView.java
@@ -54,985 +54,985 @@ import org.eclipse.swt.widgets.Spinner;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
- * The SystemTap View for displaying output of the 'stap' command, and acts
- * as a container for any graph to be rendered. Any buttons/controls/actions
- * necessary to the smooth running of SystemTap could be placed here.
+ * The SystemTap View for displaying output of the 'stap' command, and acts
+ * as a container for any graph to be rendered. Any buttons/controls/actions
+ * necessary to the smooth running of SystemTap could be placed here.
*/
public class CallgraphView extends SystemTapView {
- private StapGraphParser parser;
-
- private Action viewTreeview;
- private Action viewRadialview;
- private Action viewAggregateview;
- private Action viewLevelview;
- private Action viewRefresh;
- private Action animationSlow;
- private Action animationFast;
- private Action modeCollapsedNodes;
- private Action markersNext;
- private Action markersPrevious;
- private Action limits;
- private Action gotoNext;
- private Action gotoPrevious;
- private Action gotoLast;
- private Action play;
- private Action saveDot;
- private Action saveColDot;
- private Action saveCurDot;
- private Action saveText;
- private ImageDescriptor playImage = getImageDescriptor("icons/perform.png"); //$NON-NLS-1$
- private ImageDescriptor pauseImage = getImageDescriptor("icons/pause.gif"); //$NON-NLS-1$
-
- private Composite graphComp;
- private Composite treeComp;
-
- private StapGraph g;
- private int treeSize = 200;
-
-
-
- /**
- * Initializes the view by creating composites (if necessary) and canvases
- * Calls loadData(), and calls finishLoad() if not in realTime mode (otherwise
- * it is up to the user-defined update methods to finish loading).
- *
- * @return status
- *
- */
- @Override
- public IStatus initializeView(Display targetDisplay, IProgressMonitor monitor) {
-
- if (targetDisplay == null && Display.getCurrent() == null) {
- Display.getDefault();
- }
-
- treeSize = 200;
- makeTreeComp(treeSize);
- makeGraphComp();
- graphComp.setBackgroundMode(SWT.INHERIT_FORCE);
-
- //Create papa canvas
- Canvas papaCanvas = new Canvas(graphComp, SWT.BORDER);
- GridLayout papaLayout = new GridLayout(1, true);
- papaLayout.horizontalSpacing=0;
- papaLayout.verticalSpacing=0;
- papaLayout.marginHeight=0;
- papaLayout.marginWidth=0;
- papaCanvas.setLayout(papaLayout);
- GridData papaGD = new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false);
- papaGD.widthHint=160;
- papaCanvas.setLayoutData(papaGD);
-
- //Add first button
- Image image = getImageDescriptor("icons/up.gif").createImage(); //$NON-NLS-1$
- Button up = new Button(papaCanvas, SWT.PUSH);
- GridData buttonData = new GridData(SWT.CENTER, SWT.CENTER, true, false);
- buttonData.widthHint = 150;
- buttonData.heightHint = 20;
- up.setData(buttonData);
- up.setImage(image);
- up.setToolTipText(Messages.getString("CallgraphView.ThumbNailUp")); //$NON-NLS-1$
-
- //Add thumb canvas
- Canvas thumbCanvas = new Canvas(papaCanvas, SWT.NONE);
-
- //Add second button
- image = getImageDescriptor("icons/down.gif").createImage(); //$NON-NLS-1$
- Button down = new Button(papaCanvas, SWT.PUSH);
- buttonData = new GridData(SWT.CENTER, SWT.CENTER, true, false);
- buttonData.widthHint = 150;
- buttonData.heightHint = 0;
- down.setData(buttonData);
- down.setImage(image);
- down.setToolTipText(Messages.getString("CallgraphView.ThumbNailDown")); //$NON-NLS-1$
-
- //Initialize graph
- g = new StapGraph(graphComp, SWT.BORDER, treeComp, papaCanvas, this);
- g.setLayoutData(new GridData(masterComposite.getBounds().width,Display.getCurrent().getBounds().height - treeSize));
-
- up.addSelectionListener(new AutoScrollSelectionListener(
- AutoScrollSelectionListener.AUTO_SCROLL_UP, g));
- down.addSelectionListener(new AutoScrollSelectionListener(
- AutoScrollSelectionListener.AUTO_SCROLL_DOWN, g));
-
- //Initialize thumbnail
- GridData thumbGD = new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false);
- thumbGD.widthHint=160;
- thumbCanvas.setLayoutData(thumbGD);
- LightweightSystem lws = new LightweightSystem(thumbCanvas);
- ScrollableThumbnail thumb = new ScrollableThumbnail(g.getViewport());
- thumb.setSource(g.getContents());
- lws.setContents(thumb);
-
- loadData(monitor);
- return finishLoad(monitor);
- }
-
- /**
- * Load data.
- * @param mon -- Progress monitor.
- * @return
- */
- private IStatus loadData(IProgressMonitor mon) {
- IProgressMonitor monitor = mon;
- //Dummy node, set start time
- if (g.getNodeData(0) == null) {
- g.loadData(SWT.NONE, 0, StapGraph.CONSTANT_TOP_NODE_NAME,
- 1, 1, -1, false, ""); //$NON-NLS-1$
- }
- g.setStartTime(parser.startTime);
- g.setEndTime(parser.endingTimeInNS);
-
-
- /*
- * Load graph data
- */
- for (int id_parent : parser.serialMap.keySet()) {
- if (id_parent < 0) {
- continue;
- }
- boolean marked = false;
- String msg = ""; //$NON-NLS-1$
- if (g.getNodeData(id_parent) == null) {
- if (parser.markedMap.get(id_parent) != null) {
- marked = true;
- msg = parser.markedMap.remove(id_parent);
- }
- g.loadData(SWT.NONE, id_parent, parser.serialMap.get(id_parent), parser.timeMap.get(id_parent),
- 1, 0, marked, msg);
- }
-
- for (int key :parser.neighbourMaps.keySet()) {
- HashMap<Integer, ArrayList<Integer>> outNeighbours = parser.neighbourMaps.get(key);
- if (outNeighbours == null || outNeighbours.get(id_parent) == null) {
- continue;
- }
- for (int id_child : outNeighbours.get(id_parent)) {
- if (g.getNodeData(id_child) != null && id_child < 0) {
- //Assume this is an additional call of the same node
- //Should only happen in dot-files!!
- g.addCalled(id_child);
- continue;
- } else if (g.getNodeData(id_child) != null) {
- continue;
- }
- if (monitor.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- marked = false;
- msg = ""; //$NON-NLS-1$
- if (parser.markedMap.get(id_child) != null) {
- marked = true;
- msg = parser.markedMap.remove(id_child);
- }
- if (id_child != -1) {
- if (parser.timeMap.get(id_child) == null){
- g.loadData(SWT.NONE, id_child, parser.serialMap
- .get(id_child), parser.timeMap.get(0),
- 1, id_parent, marked,msg);
- }else{
- g.loadData(SWT.NONE, id_child, parser.serialMap
- .get(id_child), parser.timeMap.get(id_child),
- 1, id_parent, marked,msg);
- }
- }
- }
- }
-
- if (parser.neighbourMaps.size() > 1) {
- g.setThreaded();
- }
- }
-
- monitor.worked(1);
- if (parser.markedMap.size() > 0) {
- //Still some markers left
- for (int key : parser.markedMap.keySet()) {
- g.insertMessage(key, parser.markedMap.get(key));
- }
-
- //Erase the remaining nodes, just in case
- parser.markedMap.clear();
- }
-
-
- if (g.aggregateTime == null) {
- g.aggregateTime = new HashMap<>();
- }
- if (g.aggregateCount == null) {
- g.aggregateCount = new HashMap<>();
- }
-
- g.aggregateCount.putAll(parser.countMap);
- g.aggregateTime.putAll(parser.aggregateTimeMap);
- //TODO: Do not set to 0.
- g.setLastFunctionCalled(0);
-
-
- //Finish off by collapsing nodes, initializing the tree and setting options
- g.recursivelyCollapseAllChildrenOfNode(g.getTopNode());
- monitor.worked(1);
- setGraphOptions(true);
- g.initializeTree();
- g.setProject(parser.project);
-
-
- return Status.OK_STATUS;
- }
-
- /**
- * Completes the loading process by calculating aggregate data.
- *
- * @param monitor
- * @return
- */
- private IStatus finishLoad(IProgressMonitor monitor) {
-
- if (g.aggregateCount == null) {
- g.aggregateCount = new HashMap<>();
- }
-
- g.aggregateCount.putAll(parser.countMap);
-
- if (g.aggregateTime == null) {
- g.aggregateTime = new HashMap<>();
- }
- g.aggregateTime.putAll(parser.aggregateTimeMap);
-
- //Set total time
- if (parser.totalTime != -1) {
- g.setTotalTime(parser.totalTime);
- }
-
- //-------------Finish initializations
- //Generate data for collapsed nodes
- if (monitor.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
- g.initializeTree();
-
-
- if (monitor.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
- g.setCallOrderList(parser.callOrderList);
- g.setProject(parser.project);
-
-
- this.initializePartControl();
- return Status.OK_STATUS;
- }
-
-
- /**
- * Enable or Disable the graph options
- * @param visible
- */
- private void setGraphOptions (boolean visible){
- play.setEnabled(visible);
- saveFile.setEnabled(visible);
- saveDot.setEnabled(visible);
- saveColDot.setEnabled(visible);
- saveCurDot.setEnabled(visible);
- saveText.setEnabled(visible);
-
- viewTreeview.setEnabled(visible);
- viewRadialview.setEnabled(visible);
- viewAggregateview.setEnabled(visible);
- viewLevelview.setEnabled(visible);
- viewRefresh.setEnabled(visible);
- limits.setEnabled(visible);
-
- markersNext.setEnabled(visible);
- markersPrevious.setEnabled(visible);
-
- animationSlow.setEnabled(visible);
- animationFast.setEnabled(visible);
- modeCollapsedNodes.setEnabled(visible);
-
- gotoNext.setEnabled(visible);
- gotoPrevious.setEnabled(visible);
- gotoLast.setEnabled(visible);
- }
-
-
-
- private void makeTreeComp(int treeSize) {
- if (treeComp != null && !treeComp.isDisposed()) {
- treeComp.dispose();
- }
-
- treeComp = new Composite(this.masterComposite, SWT.NONE);
- GridData treegd = new GridData(SWT.BEGINNING, SWT.FILL, false, true);
- treegd.widthHint = treeSize;
- treeComp.setLayout(new FillLayout());
- treeComp.setLayoutData(treegd);
- }
-
- private void makeGraphComp() {
- if (graphComp != null && !graphComp.isDisposed()) {
- graphComp.dispose();
- }
- graphComp = new Composite(this.masterComposite, SWT.NONE);
- GridData graphgd = new GridData(SWT.FILL, SWT.FILL, true, true);
- GridLayout gl = new GridLayout(2, false);
- gl.horizontalSpacing=0;
- gl.verticalSpacing=0;
-
- graphComp.setLayout(gl);
- graphComp.setLayoutData(graphgd);
- }
-
-
- /**
- * This must be executed before a Graph is displayed
- */
- private void initializePartControl(){
- setGraphOptions(true);
- if (graphComp == null) {
- return;
- }
- graphComp.setParent(masterComposite);
-
- if (treeComp != null) {
- treeComp.setParent(masterComposite);
- }
-
- graphComp.setSize(masterComposite.getSize().x ,masterComposite.getSize().y);
- }
-
- /**
- * The action performed by saveText.
- */
- private void saveTextAction() {
- //Prints an 80 char table
+ private StapGraphParser parser;
+
+ private Action viewTreeview;
+ private Action viewRadialview;
+ private Action viewAggregateview;
+ private Action viewLevelview;
+ private Action viewRefresh;
+ private Action animationSlow;
+ private Action animationFast;
+ private Action modeCollapsedNodes;
+ private Action markersNext;
+ private Action markersPrevious;
+ private Action limits;
+ private Action gotoNext;
+ private Action gotoPrevious;
+ private Action gotoLast;
+ private Action play;
+ private Action saveDot;
+ private Action saveColDot;
+ private Action saveCurDot;
+ private Action saveText;
+ private ImageDescriptor playImage = getImageDescriptor("icons/perform.png"); //$NON-NLS-1$
+ private ImageDescriptor pauseImage = getImageDescriptor("icons/pause.gif"); //$NON-NLS-1$
+
+ private Composite graphComp;
+ private Composite treeComp;
+
+ private StapGraph g;
+ private int treeSize = 200;
+
+
+
+ /**
+ * Initializes the view by creating composites (if necessary) and canvases
+ * Calls loadData(), and calls finishLoad() if not in realTime mode (otherwise
+ * it is up to the user-defined update methods to finish loading).
+ *
+ * @return status
+ *
+ */
+ @Override
+ public IStatus initializeView(Display targetDisplay, IProgressMonitor monitor) {
+
+ if (targetDisplay == null && Display.getCurrent() == null) {
+ Display.getDefault();
+ }
+
+ treeSize = 200;
+ makeTreeComp(treeSize);
+ makeGraphComp();
+ graphComp.setBackgroundMode(SWT.INHERIT_FORCE);
+
+ //Create papa canvas
+ Canvas papaCanvas = new Canvas(graphComp, SWT.BORDER);
+ GridLayout papaLayout = new GridLayout(1, true);
+ papaLayout.horizontalSpacing=0;
+ papaLayout.verticalSpacing=0;
+ papaLayout.marginHeight=0;
+ papaLayout.marginWidth=0;
+ papaCanvas.setLayout(papaLayout);
+ GridData papaGD = new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false);
+ papaGD.widthHint=160;
+ papaCanvas.setLayoutData(papaGD);
+
+ //Add first button
+ Image image = getImageDescriptor("icons/up.gif").createImage(); //$NON-NLS-1$
+ Button up = new Button(papaCanvas, SWT.PUSH);
+ GridData buttonData = new GridData(SWT.CENTER, SWT.CENTER, true, false);
+ buttonData.widthHint = 150;
+ buttonData.heightHint = 20;
+ up.setData(buttonData);
+ up.setImage(image);
+ up.setToolTipText(Messages.getString("CallgraphView.ThumbNailUp")); //$NON-NLS-1$
+
+ //Add thumb canvas
+ Canvas thumbCanvas = new Canvas(papaCanvas, SWT.NONE);
+
+ //Add second button
+ image = getImageDescriptor("icons/down.gif").createImage(); //$NON-NLS-1$
+ Button down = new Button(papaCanvas, SWT.PUSH);
+ buttonData = new GridData(SWT.CENTER, SWT.CENTER, true, false);
+ buttonData.widthHint = 150;
+ buttonData.heightHint = 0;
+ down.setData(buttonData);
+ down.setImage(image);
+ down.setToolTipText(Messages.getString("CallgraphView.ThumbNailDown")); //$NON-NLS-1$
+
+ //Initialize graph
+ g = new StapGraph(graphComp, SWT.BORDER, treeComp, papaCanvas, this);
+ g.setLayoutData(new GridData(masterComposite.getBounds().width,Display.getCurrent().getBounds().height - treeSize));
+
+ up.addSelectionListener(new AutoScrollSelectionListener(
+ AutoScrollSelectionListener.AUTO_SCROLL_UP, g));
+ down.addSelectionListener(new AutoScrollSelectionListener(
+ AutoScrollSelectionListener.AUTO_SCROLL_DOWN, g));
+
+ //Initialize thumbnail
+ GridData thumbGD = new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false);
+ thumbGD.widthHint=160;
+ thumbCanvas.setLayoutData(thumbGD);
+ LightweightSystem lws = new LightweightSystem(thumbCanvas);
+ ScrollableThumbnail thumb = new ScrollableThumbnail(g.getViewport());
+ thumb.setSource(g.getContents());
+ lws.setContents(thumb);
+
+ loadData(monitor);
+ return finishLoad(monitor);
+ }
+
+ /**
+ * Load data.
+ * @param mon -- Progress monitor.
+ * @return
+ */
+ private IStatus loadData(IProgressMonitor mon) {
+ IProgressMonitor monitor = mon;
+ //Dummy node, set start time
+ if (g.getNodeData(0) == null) {
+ g.loadData(SWT.NONE, 0, StapGraph.CONSTANT_TOP_NODE_NAME,
+ 1, 1, -1, false, ""); //$NON-NLS-1$
+ }
+ g.setStartTime(parser.startTime);
+ g.setEndTime(parser.endingTimeInNS);
+
+
+ /*
+ * Load graph data
+ */
+ for (int id_parent : parser.serialMap.keySet()) {
+ if (id_parent < 0) {
+ continue;
+ }
+ boolean marked = false;
+ String msg = ""; //$NON-NLS-1$
+ if (g.getNodeData(id_parent) == null) {
+ if (parser.markedMap.get(id_parent) != null) {
+ marked = true;
+ msg = parser.markedMap.remove(id_parent);
+ }
+ g.loadData(SWT.NONE, id_parent, parser.serialMap.get(id_parent), parser.timeMap.get(id_parent),
+ 1, 0, marked, msg);
+ }
+
+ for (int key :parser.neighbourMaps.keySet()) {
+ HashMap<Integer, ArrayList<Integer>> outNeighbours = parser.neighbourMaps.get(key);
+ if (outNeighbours == null || outNeighbours.get(id_parent) == null) {
+ continue;
+ }
+ for (int id_child : outNeighbours.get(id_parent)) {
+ if (g.getNodeData(id_child) != null && id_child < 0) {
+ //Assume this is an additional call of the same node
+ //Should only happen in dot-files!!
+ g.addCalled(id_child);
+ continue;
+ } else if (g.getNodeData(id_child) != null) {
+ continue;
+ }
+ if (monitor.isCanceled()) {
+ return Status.CANCEL_STATUS;
+ }
+
+ marked = false;
+ msg = ""; //$NON-NLS-1$
+ if (parser.markedMap.get(id_child) != null) {
+ marked = true;
+ msg = parser.markedMap.remove(id_child);
+ }
+ if (id_child != -1) {
+ if (parser.timeMap.get(id_child) == null){
+ g.loadData(SWT.NONE, id_child, parser.serialMap
+ .get(id_child), parser.timeMap.get(0),
+ 1, id_parent, marked,msg);
+ }else{
+ g.loadData(SWT.NONE, id_child, parser.serialMap
+ .get(id_child), parser.timeMap.get(id_child),
+ 1, id_parent, marked,msg);
+ }
+ }
+ }
+ }
+
+ if (parser.neighbourMaps.size() > 1) {
+ g.setThreaded();
+ }
+ }
+
+ monitor.worked(1);
+ if (parser.markedMap.size() > 0) {
+ //Still some markers left
+ for (int key : parser.markedMap.keySet()) {
+ g.insertMessage(key, parser.markedMap.get(key));
+ }
+
+ //Erase the remaining nodes, just in case
+ parser.markedMap.clear();
+ }
+
+
+ if (g.aggregateTime == null) {
+ g.aggregateTime = new HashMap<>();
+ }
+ if (g.aggregateCount == null) {
+ g.aggregateCount = new HashMap<>();
+ }
+
+ g.aggregateCount.putAll(parser.countMap);
+ g.aggregateTime.putAll(parser.aggregateTimeMap);
+ //TODO: Do not set to 0.
+ g.setLastFunctionCalled(0);
+
+
+ //Finish off by collapsing nodes, initializing the tree and setting options
+ g.recursivelyCollapseAllChildrenOfNode(g.getTopNode());
+ monitor.worked(1);
+ setGraphOptions(true);
+ g.initializeTree();
+ g.setProject(parser.project);
+
+
+ return Status.OK_STATUS;
+ }
+
+ /**
+ * Completes the loading process by calculating aggregate data.
+ *
+ * @param monitor
+ * @return
+ */
+ private IStatus finishLoad(IProgressMonitor monitor) {
+
+ if (g.aggregateCount == null) {
+ g.aggregateCount = new HashMap<>();
+ }
+
+ g.aggregateCount.putAll(parser.countMap);
+
+ if (g.aggregateTime == null) {
+ g.aggregateTime = new HashMap<>();
+ }
+ g.aggregateTime.putAll(parser.aggregateTimeMap);
+
+ //Set total time
+ if (parser.totalTime != -1) {
+ g.setTotalTime(parser.totalTime);
+ }
+
+ //-------------Finish initializations
+ //Generate data for collapsed nodes
+ if (monitor.isCanceled()) {
+ return Status.CANCEL_STATUS;
+ }
+ g.initializeTree();
+
+
+ if (monitor.isCanceled()) {
+ return Status.CANCEL_STATUS;
+ }
+ g.setCallOrderList(parser.callOrderList);
+ g.setProject(parser.project);
+
+
+ this.initializePartControl();
+ return Status.OK_STATUS;
+ }
+
+
+ /**
+ * Enable or Disable the graph options
+ * @param visible
+ */
+ private void setGraphOptions (boolean visible){
+ play.setEnabled(visible);
+ saveFile.setEnabled(visible);
+ saveDot.setEnabled(visible);
+ saveColDot.setEnabled(visible);
+ saveCurDot.setEnabled(visible);
+ saveText.setEnabled(visible);
+
+ viewTreeview.setEnabled(visible);
+ viewRadialview.setEnabled(visible);
+ viewAggregateview.setEnabled(visible);
+ viewLevelview.setEnabled(visible);
+ viewRefresh.setEnabled(visible);
+ limits.setEnabled(visible);
+
+ markersNext.setEnabled(visible);
+ markersPrevious.setEnabled(visible);
+
+ animationSlow.setEnabled(visible);
+ animationFast.setEnabled(visible);
+ modeCollapsedNodes.setEnabled(visible);
+
+ gotoNext.setEnabled(visible);
+ gotoPrevious.setEnabled(visible);
+ gotoLast.setEnabled(visible);
+ }
+
+
+
+ private void makeTreeComp(int treeSize) {
+ if (treeComp != null && !treeComp.isDisposed()) {
+ treeComp.dispose();
+ }
+
+ treeComp = new Composite(this.masterComposite, SWT.NONE);
+ GridData treegd = new GridData(SWT.BEGINNING, SWT.FILL, false, true);
+ treegd.widthHint = treeSize;
+ treeComp.setLayout(new FillLayout());
+ treeComp.setLayoutData(treegd);
+ }
+
+ private void makeGraphComp() {
+ if (graphComp != null && !graphComp.isDisposed()) {
+ graphComp.dispose();
+ }
+ graphComp = new Composite(this.masterComposite, SWT.NONE);
+ GridData graphgd = new GridData(SWT.FILL, SWT.FILL, true, true);
+ GridLayout gl = new GridLayout(2, false);
+ gl.horizontalSpacing=0;
+ gl.verticalSpacing=0;
+
+ graphComp.setLayout(gl);
+ graphComp.setLayoutData(graphgd);
+ }
+
+
+ /**
+ * This must be executed before a Graph is displayed
+ */
+ private void initializePartControl(){
+ setGraphOptions(true);
+ if (graphComp == null) {
+ return;
+ }
+ graphComp.setParent(masterComposite);
+
+ if (treeComp != null) {
+ treeComp.setParent(masterComposite);
+ }
+
+ graphComp.setSize(masterComposite.getSize().x ,masterComposite.getSize().y);
+ }
+
+ /**
+ * The action performed by saveText.
+ */
+ private void saveTextAction() {
+ //Prints an 80 char table
Shell sh = new Shell();
FileDialog dialog = new FileDialog(sh, SWT.SAVE);
String filePath = dialog.open();
if (filePath == null) {
- return;
+ return;
}
File f = new File(filePath);
f.delete();
try (BufferedWriter out = new BufferedWriter(new FileWriter(f))) {
- f.createNewFile();
- StringBuilder builder = new StringBuilder();
- builder.append(" Function | Called | Time\n"); //$NON-NLS-1$
-
- for (StapData k : g.nodeDataMap.values()) {
- if ( (!k.isCollapsed ) && !k.isOnlyChildWithThisName()) {
- continue;
- }
- if (k.isCollapsed) {
- StringBuilder name = new StringBuilder(k.name);
- name = fixString(name, 60);
- builder.append(" " + name + " | "); //$NON-NLS-1$ //$NON-NLS-2$
-
- StringBuilder called = new StringBuilder("" + k.timesCalled); //$NON-NLS-1$
- called = fixString(called, 6);
-
- StringBuilder time = new StringBuilder("" + //$NON-NLS-1$
- StapNode.numberFormat.format((float) k.getTime()/g.getTotalTime() * 100)
- + "%"); //$NON-NLS-1$
- time = fixString(time, 6);
-
- builder.append(called + " | " + time + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (builder.length() > 0) {
- out.append(builder.toString());
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * This is a callback that will allow us to create the viewer and
- * initialize it.
- */
- @Override
- public void createPartControl(Composite parent) {
- if (masterComposite != null) {
- masterComposite.dispose();
- }
- masterComposite = parent;
- GridLayout layout = new GridLayout(2, false);
- layout.horizontalSpacing=0;
- GridData gd = new GridData(100, 100);
-
- parent.setLayout(layout);
- parent.setLayoutData(gd);
-
- // LOAD ALL ACTIONS
- createActions();
-
- //MENU FOR SYSTEMTAP BUTTONS
- IToolBarManager mgr = getViewSite().getActionBars().getToolBarManager();
-
-
- //MENU FOR SYSTEMTAP GRAPH OPTIONS
- IMenuManager menu = getViewSite().getActionBars().getMenuManager();
-
- // ADD OPTIONS TO THE GRAPH MENU
- addFileMenu();
-
- saveCurDot = new Action(Messages.getString("CallgraphView.SaveViewAsDot")) { //$NON-NLS-1$
- @Override
- public void run(){
- writeToDot(g.getCollapseMode(), g.nodeMap.keySet());
- }
-
- };
- saveDot = new Action(Messages.getString("CallgraphView.SaveAllUncollapsedAsDot")) { //$NON-NLS-1$
+ f.createNewFile();
+ StringBuilder builder = new StringBuilder();
+ builder.append(" Function | Called | Time\n"); //$NON-NLS-1$
+
+ for (StapData k : g.nodeDataMap.values()) {
+ if ( (!k.isCollapsed ) && !k.isOnlyChildWithThisName()) {
+ continue;
+ }
+ if (k.isCollapsed) {
+ StringBuilder name = new StringBuilder(k.name);
+ name = fixString(name, 60);
+ builder.append(" " + name + " | "); //$NON-NLS-1$ //$NON-NLS-2$
+
+ StringBuilder called = new StringBuilder("" + k.timesCalled); //$NON-NLS-1$
+ called = fixString(called, 6);
+
+ StringBuilder time = new StringBuilder("" + //$NON-NLS-1$
+ StapNode.numberFormat.format((float) k.getTime()/g.getTotalTime() * 100)
+ + "%"); //$NON-NLS-1$
+ time = fixString(time, 6);
+
+ builder.append(called + " | " + time + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ if (builder.length() > 0) {
+ out.append(builder.toString());
+ }
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * This is a callback that will allow us to create the viewer and
+ * initialize it.
+ */
+ @Override
+ public void createPartControl(Composite parent) {
+ if (masterComposite != null) {
+ masterComposite.dispose();
+ }
+ masterComposite = parent;
+ GridLayout layout = new GridLayout(2, false);
+ layout.horizontalSpacing=0;
+ GridData gd = new GridData(100, 100);
+
+ parent.setLayout(layout);
+ parent.setLayoutData(gd);
+
+ // LOAD ALL ACTIONS
+ createActions();
+
+ //MENU FOR SYSTEMTAP BUTTONS
+ IToolBarManager mgr = getViewSite().getActionBars().getToolBarManager();
+
+
+ //MENU FOR SYSTEMTAP GRAPH OPTIONS
+ IMenuManager menu = getViewSite().getActionBars().getMenuManager();
+
+ // ADD OPTIONS TO THE GRAPH MENU
+ addFileMenu();
+
+ saveCurDot = new Action(Messages.getString("CallgraphView.SaveViewAsDot")) { //$NON-NLS-1$
@Override
- public void run(){
+ public void run(){
+ writeToDot(g.getCollapseMode(), g.nodeMap.keySet());
+ }
+
+ };
+ saveDot = new Action(Messages.getString("CallgraphView.SaveAllUncollapsedAsDot")) { //$NON-NLS-1$
+ @Override
+ public void run(){
writeToDot(false, g.nodeDataMap.keySet());
}
- };
-
- saveColDot = new Action (Messages.getString("CallgraphView.SaveAllCollapsedAsDot")) { //$NON-NLS-1$
- @Override
- public void run(){
- writeToDot(true, g.nodeDataMap.keySet());
- }
-
- };
-
- saveText = new Action (Messages.getString("CallgraphView.SaveCollapsedAsASCII")) { //$NON-NLS-1$
- @Override
- public void run() {
- saveTextAction();
- }
- };
- IMenuManager saveMenu = new MenuManager(Messages.getString("CallgraphView.SaveMenu")); //$NON-NLS-1$
- file.add(saveMenu);
- saveMenu.add(saveCurDot);
- saveMenu.add(saveColDot);
- saveMenu.add(saveText);
- saveMenu.add(saveDot);
- IMenuManager view = new MenuManager(Messages.getString("CallgraphView.ViewMenu")); //$NON-NLS-1$
- IMenuManager animation = new MenuManager(Messages.getString("CallgraphView.AnimationMenu")); //$NON-NLS-1$
- IMenuManager markers = new MenuManager(Messages.getString("CallgraphView.Markers")); //$NON-NLS-1$
- IMenuManager gotoMenu = new MenuManager(Messages.getString("CallgraphView.GoTo")); //$NON-NLS-1$
- menu.add(view);
- menu.add(gotoMenu);
- addHelpMenu();
-
- view.add(viewTreeview);
- view.add(viewRadialview);
- view.add(viewAggregateview);
- view.add(viewLevelview);
- view.add(getViewRefresh());
- view.add(modeCollapsedNodes);
- view.add(limits);
- view.add(animation);
-
-
- gotoMenu.add(play);
- gotoMenu.add(gotoPrevious);
- gotoMenu.add(gotoNext);
- gotoMenu.add(gotoLast);
- gotoMenu.add(markers);
-
- addKillButton();
- mgr.add(play);
- mgr.add(viewRadialview);
- mgr.add(viewTreeview);
- mgr.add(viewLevelview);
- mgr.add(viewAggregateview);
- mgr.add(modeCollapsedNodes);
-
- markers.add(markersNext);
- markers.add(markersPrevious);
-
- animation.add(animationSlow);
- animation.add(animationFast);
-
- setGraphOptions(false);
- }
-
-
- private static StringBuilder fixString(StringBuilder name, int length) {
- if (name.length() > length) {
- name = new StringBuilder(name.substring(0, length - 1));
- } else {
- int diff = length - name.length();
- boolean left = true;
- while (diff > 0) {
- if (left) {
- name.insert(0, " "); //$NON-NLS-1$
- left = false;
- } else {
- name.append(" "); //$NON-NLS-1$
- left = true;
- }
- diff--;
- }
- }
- return name;
- }
-
-
- private void createViewActions() {
- viewTreeview = new Action(Messages.getString("CallgraphView.TreeView")){ //$NON-NLS-1$
- @Override
- public void run() {
- g.draw(StapGraph.CONSTANT_DRAWMODE_TREE,
- g.getAnimationMode(), g.getRootVisibleNodeNumber());
- g.scrollTo(g.getNode(g.getRootVisibleNodeNumber())
- .getLocation().x - g.getBounds().width / 2, g
- .getNode(g.getRootVisibleNodeNumber())
- .getLocation().y);
- if (play != null) {
- play.setEnabled(true);
- }
- }
- };
- ImageDescriptor treeImage = getImageDescriptor("icons/tree_view.gif"); //$NON-NLS-1$
- viewTreeview.setImageDescriptor(treeImage);
-
-
- //Set drawmode to radial view
- viewRadialview = new Action(Messages.getString("CallgraphView.RadialView")){ //$NON-NLS-1$
- @Override
- public void run(){
- g.draw(StapGraph.CONSTANT_DRAWMODE_RADIAL,
- g.getAnimationMode(), g.getRootVisibleNodeNumber());
- if (play != null) {
- play.setEnabled(true);
- }
- }
- };
- ImageDescriptor d = getImageDescriptor("/icons/radial_view.gif"); //$NON-NLS-1$
- viewRadialview.setImageDescriptor(d);
-
- //Set drawmode to aggregate view
- viewAggregateview = new Action(Messages.getString("CallgraphView.AggregateView")){ //$NON-NLS-1$
- @Override
- public void run(){
- g.draw(StapGraph.CONSTANT_DRAWMODE_AGGREGATE,
- g.getAnimationMode(), g.getRootVisibleNodeNumber());
- if (play != null) {
- play.setEnabled(false);
- }
- }
- };
- ImageDescriptor aggregateImage = getImageDescriptor("/icons/view_aggregateview.gif"); //$NON-NLS-1$
- viewAggregateview.setImageDescriptor(aggregateImage);
-
-
- //Set drawmode to level view
- viewLevelview = new Action(Messages.getString("CallgraphView.LevelView")){ //$NON-NLS-1$
- @Override
- public void run(){
- g.draw(StapGraph.CONSTANT_DRAWMODE_LEVEL,
- g.getAnimationMode(), g.getRootVisibleNodeNumber());
- if (play != null) {
- play.setEnabled(true);
- }
- }
- };
- ImageDescriptor levelImage = getImageDescriptor("/icons/showchild_mode.gif"); //$NON-NLS-1$
- viewLevelview.setImageDescriptor(levelImage);
-
-
- this.viewRefresh = new Action(Messages.getString("CallgraphView.Reset")){ //$NON-NLS-1$
- @Override
- public void run(){
- g.reset();
- }
- };
- ImageDescriptor refreshImage = getImageDescriptor("/icons/nav_refresh.gif"); //$NON-NLS-1$
- getViewRefresh().setImageDescriptor(refreshImage);
-
- }
-
- /**
- * Populates Animate menu.
- */
- private void createAnimateActions() {
- //Set animation mode to slow
- animationSlow = new Action(Messages.getString("CallgraphView.AnimationSlow"), IAction.AS_RADIO_BUTTON){ //$NON-NLS-1$
- @Override
- public void run(){
- g.setAnimationMode(StapGraph.CONSTANT_ANIMATION_SLOW);
- this.setChecked(true);
- animationSlow.setChecked(true);
- animationFast.setChecked(false);
- }
- };
-
- animationSlow.setChecked(true);
-
- //Set animation mode to fast
- animationFast = new Action(Messages.getString("CallgraphView.AnimationFast"), IAction.AS_RADIO_BUTTON){ //$NON-NLS-1$
- @Override
- public void run(){
- g.setAnimationMode(StapGraph.CONSTANT_ANIMATION_FASTEST);
- animationSlow.setChecked(false);
- animationFast.setChecked(true);
- }
- };
-
- //Toggle collapse mode
- modeCollapsedNodes = new Action(Messages.getString("CallgraphView.CollapsedMode"), IAction.AS_CHECK_BOX){ //$NON-NLS-1$
- @Override
- public void run(){
-
- if (g.isCollapseMode()) {
- g.setCollapseMode(false);
- g.draw(g.getRootVisibleNodeNumber());
- } else {
- g.setCollapseMode(true);
- g.draw(g.getRootVisibleNodeNumber());
- }
- }
- };
-
- ImageDescriptor newImage = getImageDescriptor("icons/mode_collapsednodes.gif"); //$NON-NLS-1$
- modeCollapsedNodes.setImageDescriptor(newImage);
-
- limits = new Action(Messages.getString("CallgraphView.SetLimits"), IAction.AS_PUSH_BUTTON) { //$NON-NLS-1$
- private Spinner limit;
- private Spinner buffer;
- private Shell sh;
- @Override
- public void run() {
- sh = new Shell();
- sh.setLayout(new GridLayout());
- sh.setSize(150, 200);
- Label limitLabel = new Label(sh, SWT.NONE);
- limitLabel.setLayoutData(new GridData(SWT.CENTER, SWT.DEFAULT, true, false));
- limitLabel.setText(Messages.getString("CallgraphView.MaxNodes")); //$NON-NLS-1$
- limit = new Spinner(sh, SWT.BORDER);
- limit.setMaximum(5000);
- limit.setSelection(g.getMaxNodes());
- limit.setLayoutData(new GridData(SWT.CENTER, SWT.DEFAULT, true, false));
-
- Label bufferLabel = new Label(sh, SWT.NONE);
- bufferLabel.setLayoutData(new GridData(SWT.CENTER, SWT.DEFAULT, true, false));
- bufferLabel.setText(Messages.getString("CallgraphView.MaxDepth")); //$NON-NLS-1$
- buffer = new Spinner(sh, SWT.BORDER);
- buffer.setMaximum(5000);
- buffer.setSelection(g.getLevelBuffer());
- buffer.setLayoutData(new GridData(SWT.CENTER, SWT.DEFAULT, true, false));
-
- Button setLimit = new Button(sh, SWT.PUSH);
- setLimit.setText(Messages.getString("CallgraphView.SetValues")); //$NON-NLS-1$
- setLimit.setLayoutData(new GridData(SWT.CENTER, SWT.DEFAULT, true, false));
- setLimit.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- boolean redraw = false;
- if (limit.getSelection() >= 0 && buffer.getSelection() >= 0) {
- g.setMaxNodes(limit.getSelection());
- g.setLevelBuffer(buffer.getSelection());
-
- if (g.changeLevelLimits(g.getLevelOfNode(g.getRootVisibleNodeNumber()))) {
- SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
- Messages.getString("CallgraphView.BufferTooHigh"), Messages.getString("CallgraphView.BufferTooHigh"), //$NON-NLS-1$ //$NON-NLS-2$
- Messages.getString("CallgraphView.BufferMessage1") + //$NON-NLS-1$
- Messages.getString("CallgraphView.BufferMessage2") + //$NON-NLS-1$
- Messages.getString("CallgraphView.BufferMessage3") + //$NON-NLS-1$
- Messages.getString("CallgraphView.BufferMessage4") + g.getLevelBuffer() + //$NON-NLS-1$
- Messages.getString("CallgraphView.BufferMessage5") + PluginConstants.NEW_LINE + PluginConstants.NEW_LINE + //$NON-NLS-1$
- Messages.getString("CallgraphView.BufferMessage6") + //$NON-NLS-1$
- Messages.getString("CallgraphView.BufferMessage7")); //$NON-NLS-1$
- mess.schedule();
- }
-
- redraw = true;
- }
- sh.dispose();
-
- if (redraw) {
- g.draw();
- }
- }
-
- });
-
-
- sh.open(); }
- };
-
- }
+ };
+
+ saveColDot = new Action (Messages.getString("CallgraphView.SaveAllCollapsedAsDot")) { //$NON-NLS-1$
+ @Override
+ public void run(){
+ writeToDot(true, g.nodeDataMap.keySet());
+ }
+
+ };
+
+ saveText = new Action (Messages.getString("CallgraphView.SaveCollapsedAsASCII")) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ saveTextAction();
+ }
+ };
+ IMenuManager saveMenu = new MenuManager(Messages.getString("CallgraphView.SaveMenu")); //$NON-NLS-1$
+ file.add(saveMenu);
+ saveMenu.add(saveCurDot);
+ saveMenu.add(saveColDot);
+ saveMenu.add(saveText);
+ saveMenu.add(saveDot);
+ IMenuManager view = new MenuManager(Messages.getString("CallgraphView.ViewMenu")); //$NON-NLS-1$
+ IMenuManager animation = new MenuManager(Messages.getString("CallgraphView.AnimationMenu")); //$NON-NLS-1$
+ IMenuManager markers = new MenuManager(Messages.getString("CallgraphView.Markers")); //$NON-NLS-1$
+ IMenuManager gotoMenu = new MenuManager(Messages.getString("CallgraphView.GoTo")); //$NON-NLS-1$
+ menu.add(view);
+ menu.add(gotoMenu);
+ addHelpMenu();
+
+ view.add(viewTreeview);
+ view.add(viewRadialview);
+ view.add(viewAggregateview);
+ view.add(viewLevelview);
+ view.add(getViewRefresh());
+ view.add(modeCollapsedNodes);
+ view.add(limits);
+ view.add(animation);
+
+
+ gotoMenu.add(play);
+ gotoMenu.add(gotoPrevious);
+ gotoMenu.add(gotoNext);
+ gotoMenu.add(gotoLast);
+ gotoMenu.add(markers);
+
+ addKillButton();
+ mgr.add(play);
+ mgr.add(viewRadialview);
+ mgr.add(viewTreeview);
+ mgr.add(viewLevelview);
+ mgr.add(viewAggregateview);
+ mgr.add(modeCollapsedNodes);
+
+ markers.add(markersNext);
+ markers.add(markersPrevious);
+
+ animation.add(animationSlow);
+ animation.add(animationFast);
+
+ setGraphOptions(false);
+ }
+
+
+ private static StringBuilder fixString(StringBuilder name, int length) {
+ if (name.length() > length) {
+ name = new StringBuilder(name.substring(0, length - 1));
+ } else {
+ int diff = length - name.length();
+ boolean left = true;
+ while (diff > 0) {
+ if (left) {
+ name.insert(0, " "); //$NON-NLS-1$
+ left = false;
+ } else {
+ name.append(" "); //$NON-NLS-1$
+ left = true;
+ }
+ diff--;
+ }
+ }
+ return name;
+ }
+
+
+ private void createViewActions() {
+ viewTreeview = new Action(Messages.getString("CallgraphView.TreeView")){ //$NON-NLS-1$
+ @Override
+ public void run() {
+ g.draw(StapGraph.CONSTANT_DRAWMODE_TREE,
+ g.getAnimationMode(), g.getRootVisibleNodeNumber());
+ g.scrollTo(g.getNode(g.getRootVisibleNodeNumber())
+ .getLocation().x - g.getBounds().width / 2, g
+ .getNode(g.getRootVisibleNodeNumber())
+ .getLocation().y);
+ if (play != null) {
+ play.setEnabled(true);
+ }
+ }
+ };
+ ImageDescriptor treeImage = getImageDescriptor("icons/tree_view.gif"); //$NON-NLS-1$
+ viewTreeview.setImageDescriptor(treeImage);
+
+
+ //Set drawmode to radial view
+ viewRadialview = new Action(Messages.getString("CallgraphView.RadialView")){ //$NON-NLS-1$
+ @Override
+ public void run(){
+ g.draw(StapGraph.CONSTANT_DRAWMODE_RADIAL,
+ g.getAnimationMode(), g.getRootVisibleNodeNumber());
+ if (play != null) {
+ play.setEnabled(true);
+ }
+ }
+ };
+ ImageDescriptor d = getImageDescriptor("/icons/radial_view.gif"); //$NON-NLS-1$
+ viewRadialview.setImageDescriptor(d);
+
+ //Set drawmode to aggregate view
+ viewAggregateview = new Action(Messages.getString("CallgraphView.AggregateView")){ //$NON-NLS-1$
+ @Override
+ public void run(){
+ g.draw(StapGraph.CONSTANT_DRAWMODE_AGGREGATE,
+ g.getAnimationMode(), g.getRootVisibleNodeNumber());
+ if (play != null) {
+ play.setEnabled(false);
+ }
+ }
+ };
+ ImageDescriptor aggregateImage = getImageDescriptor("/icons/view_aggregateview.gif"); //$NON-NLS-1$
+ viewAggregateview.setImageDescriptor(aggregateImage);
+
+
+ //Set drawmode to level view
+ viewLevelview = new Action(Messages.getString("CallgraphView.LevelView")){ //$NON-NLS-1$
+ @Override
+ public void run(){
+ g.draw(StapGraph.CONSTANT_DRAWMODE_LEVEL,
+ g.getAnimationMode(), g.getRootVisibleNodeNumber());
+ if (play != null) {
+ play.setEnabled(true);
+ }
+ }
+ };
+ ImageDescriptor levelImage = getImageDescriptor("/icons/showchild_mode.gif"); //$NON-NLS-1$
+ viewLevelview.setImageDescriptor(levelImage);
+
+
+ this.viewRefresh = new Action(Messages.getString("CallgraphView.Reset")){ //$NON-NLS-1$
+ @Override
+ public void run(){
+ g.reset();
+ }
+ };
+ ImageDescriptor refreshImage = getImageDescriptor("/icons/nav_refresh.gif"); //$NON-NLS-1$
+ getViewRefresh().setImageDescriptor(refreshImage);
+
+ }
+
+ /**
+ * Populates Animate menu.
+ */
+ private void createAnimateActions() {
+ //Set animation mode to slow
+ animationSlow = new Action(Messages.getString("CallgraphView.AnimationSlow"), IAction.AS_RADIO_BUTTON){ //$NON-NLS-1$
+ @Override
+ public void run(){
+ g.setAnimationMode(StapGraph.CONSTANT_ANIMATION_SLOW);
+ this.setChecked(true);
+ animationSlow.setChecked(true);
+ animationFast.setChecked(false);
+ }
+ };
+
+ animationSlow.setChecked(true);
+
+ //Set animation mode to fast
+ animationFast = new Action(Messages.getString("CallgraphView.AnimationFast"), IAction.AS_RADIO_BUTTON){ //$NON-NLS-1$
+ @Override
+ public void run(){
+ g.setAnimationMode(StapGraph.CONSTANT_ANIMATION_FASTEST);
+ animationSlow.setChecked(false);
+ animationFast.setChecked(true);
+ }
+ };
+
+ //Toggle collapse mode
+ modeCollapsedNodes = new Action(Messages.getString("CallgraphView.CollapsedMode"), IAction.AS_CHECK_BOX){ //$NON-NLS-1$
+ @Override
+ public void run(){
+
+ if (g.isCollapseMode()) {
+ g.setCollapseMode(false);
+ g.draw(g.getRootVisibleNodeNumber());
+ } else {
+ g.setCollapseMode(true);
+ g.draw(g.getRootVisibleNodeNumber());
+ }
+ }
+ };
+
+ ImageDescriptor newImage = getImageDescriptor("icons/mode_collapsednodes.gif"); //$NON-NLS-1$
+ modeCollapsedNodes.setImageDescriptor(newImage);
+
+ limits = new Action(Messages.getString("CallgraphView.SetLimits"), IAction.AS_PUSH_BUTTON) { //$NON-NLS-1$
+ private Spinner limit;
+ private Spinner buffer;
+ private Shell sh;
+ @Override
+ public void run() {
+ sh = new Shell();
+ sh.setLayout(new GridLayout());
+ sh.setSize(150, 200);
+ Label limitLabel = new Label(sh, SWT.NONE);
+ limitLabel.setLayoutData(new GridData(SWT.CENTER, SWT.DEFAULT, true, false));
+ limitLabel.setText(Messages.getString("CallgraphView.MaxNodes")); //$NON-NLS-1$
+ limit = new Spinner(sh, SWT.BORDER);
+ limit.setMaximum(5000);
+ limit.setSelection(g.getMaxNodes());
+ limit.setLayoutData(new GridData(SWT.CENTER, SWT.DEFAULT, true, false));
+
+ Label bufferLabel = new Label(sh, SWT.NONE);
+ bufferLabel.setLayoutData(new GridData(SWT.CENTER, SWT.DEFAULT, true, false));
+ bufferLabel.setText(Messages.getString("CallgraphView.MaxDepth")); //$NON-NLS-1$
+ buffer = new Spinner(sh, SWT.BORDER);
+ buffer.setMaximum(5000);
+ buffer.setSelection(g.getLevelBuffer());
+ buffer.setLayoutData(new GridData(SWT.CENTER, SWT.DEFAULT, true, false));
+
+ Button setLimit = new Button(sh, SWT.PUSH);
+ setLimit.setText(Messages.getString("CallgraphView.SetValues")); //$NON-NLS-1$
+ setLimit.setLayoutData(new GridData(SWT.CENTER, SWT.DEFAULT, true, false));
+ setLimit.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ boolean redraw = false;
+ if (limit.getSelection() >= 0 && buffer.getSelection() >= 0) {
+ g.setMaxNodes(limit.getSelection());
+ g.setLevelBuffer(buffer.getSelection());
+
+ if (g.changeLevelLimits(g.getLevelOfNode(g.getRootVisibleNodeNumber()))) {
+ SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
+ Messages.getString("CallgraphView.BufferTooHigh"), Messages.getString("CallgraphView.BufferTooHigh"), //$NON-NLS-1$ //$NON-NLS-2$
+ Messages.getString("CallgraphView.BufferMessage1") + //$NON-NLS-1$
+ Messages.getString("CallgraphView.BufferMessage2") + //$NON-NLS-1$
+ Messages.getString("CallgraphView.BufferMessage3") + //$NON-NLS-1$
+ Messages.getString("CallgraphView.BufferMessage4") + g.getLevelBuffer() + //$NON-NLS-1$
+ Messages.getString("CallgraphView.BufferMessage5") + PluginConstants.NEW_LINE + PluginConstants.NEW_LINE + //$NON-NLS-1$
+ Messages.getString("CallgraphView.BufferMessage6") + //$NON-NLS-1$
+ Messages.getString("CallgraphView.BufferMessage7")); //$NON-NLS-1$
+ mess.schedule();
+ }
+
+ redraw = true;
+ }
+ sh.dispose();
+
+ if (redraw) {
+ g.draw();
+ }
+ }
+
+ });
+
+
+ sh.open(); }
+ };
+
+ }
/**
* Convenience method for creating all the various actions
*/
- private void createActions() {
- createViewActions();
- createAnimateActions();
- createMarkerActions();
- createMovementActions();
-
- modeCollapsedNodes.setChecked(true);
-
- }
-
- private void createMovementActions() {
- gotoNext = new Action(Messages.getString("CallgraphView.Next")) { //$NON-NLS-1$
- @Override
- public void run() {
- g.drawNextNode();
- }
- };
-
- gotoPrevious = new Action(Messages.getString("CallgraphView.Previous")) { //$NON-NLS-1$
- @Override
- public void run() {
- if (g.isCollapseMode()) {
- g.setCollapseMode(false);
- }
- int toDraw = g.getPreviousCalledNode(g.getRootVisibleNodeNumber());
- if (toDraw != -1)
- g.draw(toDraw);
- }
- };
-
- gotoLast = new Action(Messages.getString("CallgraphView.Last")) { //$NON-NLS-1$
- @Override
- public void run() {
- if (g.isCollapseMode())
- g.setCollapseMode(false);
- g.draw(g.getLastFunctionCalled());
- }
- };
-
- play = new Action(Messages.getString("CallgraphView.Play")) { //$NON-NLS-1$
- @Override
- public void run() {
- if (g.getDrawMode() != StapGraph.CONSTANT_DRAWMODE_AGGREGATE) {
- g.play();
- togglePlayImage();
- }
- }
- };
- play.setImageDescriptor(playImage);
- }
-
- /**
- * Toggles the play/pause image
- * @param play
- */
- private void togglePlayImage() {
- if (play.getToolTipText() == Messages.getString("CallgraphView.Pause")) { //$NON-NLS-1$
- play.setImageDescriptor(playImage);
- play.setToolTipText(Messages.getString("CallgraphView.Play")); //$NON-NLS-1$
- }
- else {
- play.setImageDescriptor(pauseImage);
- play.setToolTipText(""); //$NON-NLS-1$
- }
- }
-
- private void createMarkerActions() {
- markersNext = new Action(Messages.getString("CallgraphView.nextMarker")) { //$NON-NLS-1$
- @Override
- public void run() {
- g.draw(g.getNextMarkedNode());
- }
- };
-
- markersPrevious = new Action(Messages.getString("CallgraphView.previousMarker")) { //$NON-NLS-1$
- @Override
- public void run() {
- g.draw(g.getPreviousMarkedNode());
- }
- };
- }
-
- @Override
- protected boolean createOpenAction() {
- //Opens from specified location
- openFile = new Action(Messages.getString("CallgraphView.Open")){ //$NON-NLS-1$
- @Override
- public void run(){
- FileDialog dialog = new FileDialog(new Shell(), SWT.DEFAULT);
- String filePath = dialog.open();
- if (filePath != null){
- StapGraphParser new_parser = new StapGraphParser();
- new_parser.setSourcePath(filePath);
- new_parser.setViewID(CallGraphConstants.VIEW_ID);
- new_parser.schedule();
- }
- }
- };
- return true;
- }
-
-
- @Override
- protected boolean createOpenDefaultAction() {
- //Opens from the default location
- openDefault = new Action(Messages.getString("CallgraphView.OpenLastRun")){ //$NON-NLS-1$
- @Override
- public void run(){
- StapGraphParser new_parser = new StapGraphParser();
- new_parser.setViewID(CallGraphConstants.VIEW_ID);
- new_parser.schedule();
- }
- };
-
- return true;
- }
-
- @Override
- public boolean setParser(SystemTapParser newParser) {
- if (newParser instanceof StapGraphParser) {
- parser = (StapGraphParser) newParser;
- return true;
- }
- return false;
-
- }
-
- @Override
- public void setViewID() {
- viewID = "org.eclipse.linuxtools.callgraph.callgraphview"; //$NON-NLS-1$
- }
-
- public Action getAnimationSlow() {
- return animationSlow;
- }
-
- public Action getAnimationFast() {
- return animationFast;
- }
-
- public Action getModeCollapsednodes() {
- return modeCollapsedNodes;
- }
-
- public Action getViewRefresh() {
- return viewRefresh;
- }
-
- public Action getGotoNext() {
- return gotoNext;
- }
-
- public Action getGotoPrevious() {
- return gotoPrevious;
- }
-
- public Action getGotoLast() {
- return gotoLast;
- }
-
- public Action getViewTreeview() {
- return viewTreeview;
- }
-
- public Action getViewRadialview() {
- return viewRadialview;
- }
-
- public Action getViewAggregateview() {
- return viewAggregateview;
- }
-
- public Action getViewLevelview() {
- return viewLevelview;
- }
-
- public Action getPlay() {
- return play;
- }
-
- public StapGraph getGraph() {
- return g;
- }
-
- @Override
- public void setFocus() {
- if(masterComposite != null){
- masterComposite.setFocus();
- }
- }
-
-
- @Override
- public void updateMethod() {
- IProgressMonitor m = new NullProgressMonitor();
- m.beginTask("Updating callgraph", 4); //$NON-NLS-1$
-
- loadData(m);
- m.worked(1);
- if (parser.totalTime > 0) {
- finishLoad(m);
- }
- m.worked(1);
-
- g.draw(StapGraph.CONSTANT_DRAWMODE_RADIAL, StapGraph.CONSTANT_ANIMATION_SLOW, g.getFirstUsefulNode());
- }
-
- @Override
- public SystemTapParser getParser() {
- return parser;
- }
-
- private void writeToDot(boolean mode, Set<Integer> keySet) {
+ private void createActions() {
+ createViewActions();
+ createAnimateActions();
+ createMarkerActions();
+ createMovementActions();
+
+ modeCollapsedNodes.setChecked(true);
+
+ }
+
+ private void createMovementActions() {
+ gotoNext = new Action(Messages.getString("CallgraphView.Next")) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ g.drawNextNode();
+ }
+ };
+
+ gotoPrevious = new Action(Messages.getString("CallgraphView.Previous")) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ if (g.isCollapseMode()) {
+ g.setCollapseMode(false);
+ }
+ int toDraw = g.getPreviousCalledNode(g.getRootVisibleNodeNumber());
+ if (toDraw != -1)
+ g.draw(toDraw);
+ }
+ };
+
+ gotoLast = new Action(Messages.getString("CallgraphView.Last")) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ if (g.isCollapseMode())
+ g.setCollapseMode(false);
+ g.draw(g.getLastFunctionCalled());
+ }
+ };
+
+ play = new Action(Messages.getString("CallgraphView.Play")) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ if (g.getDrawMode() != StapGraph.CONSTANT_DRAWMODE_AGGREGATE) {
+ g.play();
+ togglePlayImage();
+ }
+ }
+ };
+ play.setImageDescriptor(playImage);
+ }
+
+ /**
+ * Toggles the play/pause image
+ * @param play
+ */
+ private void togglePlayImage() {
+ if (play.getToolTipText() == Messages.getString("CallgraphView.Pause")) { //$NON-NLS-1$
+ play.setImageDescriptor(playImage);
+ play.setToolTipText(Messages.getString("CallgraphView.Play")); //$NON-NLS-1$
+ }
+ else {
+ play.setImageDescriptor(pauseImage);
+ play.setToolTipText(""); //$NON-NLS-1$
+ }
+ }
+
+ private void createMarkerActions() {
+ markersNext = new Action(Messages.getString("CallgraphView.nextMarker")) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ g.draw(g.getNextMarkedNode());
+ }
+ };
+
+ markersPrevious = new Action(Messages.getString("CallgraphView.previousMarker")) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ g.draw(g.getPreviousMarkedNode());
+ }
+ };
+ }
+
+ @Override
+ protected boolean createOpenAction() {
+ //Opens from specified location
+ openFile = new Action(Messages.getString("CallgraphView.Open")){ //$NON-NLS-1$
+ @Override
+ public void run(){
+ FileDialog dialog = new FileDialog(new Shell(), SWT.DEFAULT);
+ String filePath = dialog.open();
+ if (filePath != null){
+ StapGraphParser new_parser = new StapGraphParser();
+ new_parser.setSourcePath(filePath);
+ new_parser.setViewID(CallGraphConstants.VIEW_ID);
+ new_parser.schedule();
+ }
+ }
+ };
+ return true;
+ }
+
+
+ @Override
+ protected boolean createOpenDefaultAction() {
+ //Opens from the default location
+ openDefault = new Action(Messages.getString("CallgraphView.OpenLastRun")){ //$NON-NLS-1$
+ @Override
+ public void run(){
+ StapGraphParser new_parser = new StapGraphParser();
+ new_parser.setViewID(CallGraphConstants.VIEW_ID);
+ new_parser.schedule();
+ }
+ };
+
+ return true;
+ }
+
+ @Override
+ public boolean setParser(SystemTapParser newParser) {
+ if (newParser instanceof StapGraphParser) {
+ parser = (StapGraphParser) newParser;
+ return true;
+ }
+ return false;
+
+ }
+
+ @Override
+ public void setViewID() {
+ viewID = "org.eclipse.linuxtools.callgraph.callgraphview"; //$NON-NLS-1$
+ }
+
+ public Action getAnimationSlow() {
+ return animationSlow;
+ }
+
+ public Action getAnimationFast() {
+ return animationFast;
+ }
+
+ public Action getModeCollapsednodes() {
+ return modeCollapsedNodes;
+ }
+
+ public Action getViewRefresh() {
+ return viewRefresh;
+ }
+
+ public Action getGotoNext() {
+ return gotoNext;
+ }
+
+ public Action getGotoPrevious() {
+ return gotoPrevious;
+ }
+
+ public Action getGotoLast() {
+ return gotoLast;
+ }
+
+ public Action getViewTreeview() {
+ return viewTreeview;
+ }
+
+ public Action getViewRadialview() {
+ return viewRadialview;
+ }
+
+ public Action getViewAggregateview() {
+ return viewAggregateview;
+ }
+
+ public Action getViewLevelview() {
+ return viewLevelview;
+ }
+
+ public Action getPlay() {
+ return play;
+ }
+
+ public StapGraph getGraph() {
+ return g;
+ }
+
+ @Override
+ public void setFocus() {
+ if(masterComposite != null){
+ masterComposite.setFocus();
+ }
+ }
+
+
+ @Override
+ public void updateMethod() {
+ IProgressMonitor m = new NullProgressMonitor();
+ m.beginTask("Updating callgraph", 4); //$NON-NLS-1$
+
+ loadData(m);
+ m.worked(1);
+ if (parser.totalTime > 0) {
+ finishLoad(m);
+ }
+ m.worked(1);
+
+ g.draw(StapGraph.CONSTANT_DRAWMODE_RADIAL, StapGraph.CONSTANT_ANIMATION_SLOW, g.getFirstUsefulNode());
+ }
+
+ @Override
+ public SystemTapParser getParser() {
+ return parser;
+ }
+
+ private void writeToDot(boolean mode, Set<Integer> keySet) {
Shell sh = new Shell();
FileDialog dialog = new FileDialog(sh, SWT.SAVE);
String filePath = dialog.open();
if (filePath != null) {
- File f = new File(filePath);
+ File f = new File(filePath);
f.delete();
try {
- f.createNewFile();
- } catch (IOException e) {
- return;
- }
+ f.createNewFile();
+ } catch (IOException e) {
+ return;
+ }
try (BufferedWriter out = new BufferedWriter(new FileWriter(f))) {
- StringBuilder build = new StringBuilder(""); //$NON-NLS-1$
-
- out.write("digraph stapgraph {\n"); //$NON-NLS-1$
- for (int i : keySet) {
- if (i == 0) {
- continue;
- }
- StapData d = g.getNodeData(i);
- if ( (d.isCollapsed != mode) && !d.isOnlyChildWithThisName()) {
- continue;
- }
- build.append(i + " [label=\"" + d.name + " " ); //$NON-NLS-1$ //$NON-NLS-2$
- build.append(StapNode.numberFormat.format((float) d.getTime()/g.getTotalTime() * 100) + "%\"]\n"); //$NON-NLS-1$
- int j = d.parent;
- if (mode) {
- j = d.collapsedParent;
- }
-
- if (!keySet.contains(j) || j == 0) {
- continue;
- }
-
- String called = mode ? " [label=\"" + g.getNodeData(i).timesCalled + "\"]\n" : "\n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- build.append( j + "->" + i ); //$NON-NLS-1$
- build.append( called );
- out.write(build.toString());
- build.setLength(0);
- }
- out.write("}"); //$NON-NLS-1$
- out.flush();
+ StringBuilder build = new StringBuilder(""); //$NON-NLS-1$
+
+ out.write("digraph stapgraph {\n"); //$NON-NLS-1$
+ for (int i : keySet) {
+ if (i == 0) {
+ continue;
+ }
+ StapData d = g.getNodeData(i);
+ if ( (d.isCollapsed != mode) && !d.isOnlyChildWithThisName()) {
+ continue;
+ }
+ build.append(i + " [label=\"" + d.name + " " ); //$NON-NLS-1$ //$NON-NLS-2$
+ build.append(StapNode.numberFormat.format((float) d.getTime()/g.getTotalTime() * 100) + "%\"]\n"); //$NON-NLS-1$
+ int j = d.parent;
+ if (mode) {
+ j = d.collapsedParent;
+ }
+
+ if (!keySet.contains(j) || j == 0) {
+ continue;
+ }
+
+ String called = mode ? " [label=\"" + g.getNodeData(i).timesCalled + "\"]\n" : "\n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ build.append( j + "->" + i ); //$NON-NLS-1$
+ build.append( called );
+ out.write(build.toString());
+ build.setLength(0);
+ }
+ out.write("}"); //$NON-NLS-1$
+ out.flush();
} catch (IOException e) {
- e.printStackTrace();
- }
+ e.printStackTrace();
+ }
}
- }
+ }
- private static ImageDescriptor getImageDescriptor(String path) {
- return AbstractUIPlugin.imageDescriptorFromPlugin(CallGraphConstants.PLUGIN_ID, path);
- }
+ private static ImageDescriptor getImageDescriptor(String path) {
+ return AbstractUIPlugin.imageDescriptorFromPlugin(CallGraphConstants.PLUGIN_ID, path);
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/Messages.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/Messages.java
index fcb6dd5106..49d3929c63 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/Messages.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -14,19 +14,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.callgraph.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.callgraph.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapData.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapData.java
index f7fd655368..1156584555 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapData.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapData.java
@@ -18,34 +18,34 @@ import java.util.List;
*
*/
public class StapData {
- public static final int NOT_PART_OF_COLLAPSED_NODE = -10;
- public boolean hasCollapsedChildren, isCollapsed, marked;
- public boolean onlyChildWithThisName; //Should show up as collapsed and uncollapsed
+ public static final int NOT_PART_OF_COLLAPSED_NODE = -10;
+ public boolean hasCollapsedChildren, isCollapsed, marked;
+ public boolean onlyChildWithThisName; //Should show up as collapsed and uncollapsed
public int id;
public int timesCalled, parent, style;
public int levelOfRecursion;
public int collapsedParent, uncollapsedPiece, partOfCollapsedNode;
- private long time; //execution time of this node
- public String markedMessage; //alt text for this node
- public String name; //text to be displayed
+ private long time; //execution time of this node
+ public String markedMessage; //alt text for this node
+ public String name; //text to be displayed
public List<Integer> children, collapsedChildren;
- private StapGraph graph; //Store a reference to the parent graph
-
-
- /**
- * Initialize StapData object. This object is not intended to be called by users.
- *
- * @param graphModel StapGraph containing the StapNode that matches this StapData
- * @param style
- * @param txt Text to be displayed when rendering the StapNode
- * @param time Time taken for this particular node to execute
- * @param called Number of times this particular node was called
- * @param currentID The unique identifier for this node
- * @param caller The parent of this node
- * @param isMarked
- */
- public StapData(StapGraph graphModel, int style, String txt,
- long time, int called, int currentID, int parent, boolean isMarked) {
+ private StapGraph graph; //Store a reference to the parent graph
+
+
+ /**
+ * Initialize StapData object. This object is not intended to be called by users.
+ *
+ * @param graphModel StapGraph containing the StapNode that matches this StapData
+ * @param style
+ * @param txt Text to be displayed when rendering the StapNode
+ * @param time Time taken for this particular node to execute
+ * @param called Number of times this particular node was called
+ * @param currentID The unique identifier for this node
+ * @param caller The parent of this node
+ * @param isMarked
+ */
+ public StapData(StapGraph graphModel, int style, String txt,
+ long time, int called, int currentID, int parent, boolean isMarked) {
this.time = time;
this.style = style;
this.timesCalled = called;
@@ -65,21 +65,21 @@ public class StapData {
this.uncollapsedPiece = -1;
- //Add this data to the caller's list of IDs
- if (this.parent != -1 && graphModel.getNodeData(this.parent) != null) {
- graphModel.getNodeData(this.parent).addCallee(this.id);
- this.levelOfRecursion = graphModel.getNodeData(this.parent).levelOfRecursion + 1;
- }
+ //Add this data to the caller's list of IDs
+ if (this.parent != -1 && graphModel.getNodeData(this.parent) != null) {
+ graphModel.getNodeData(this.parent).addCallee(this.id);
+ this.levelOfRecursion = graphModel.getNodeData(this.parent).levelOfRecursion + 1;
+ }
- //---------------Recursion management
+ //---------------Recursion management
//Insert new level if necessary
- if (graphModel.levels.get(levelOfRecursion) == null)
- graphModel.levels.put(levelOfRecursion, new ArrayList<Integer>());
+ if (graphModel.levels.get(levelOfRecursion) == null)
+ graphModel.levels.put(levelOfRecursion, new ArrayList<Integer>());
graphModel.levels.get(levelOfRecursion).add(this.id);
- //Keep track of the lowest level of recursion
- if (levelOfRecursion > graphModel.getLowestLevelOfNodesAdded())
- graphModel.setLowestLevelOfNodesAdded(levelOfRecursion);
+ //Keep track of the lowest level of recursion
+ if (levelOfRecursion > graphModel.getLowestLevelOfNodesAdded())
+ graphModel.setLowestLevelOfNodesAdded(levelOfRecursion);
}
@@ -90,8 +90,8 @@ public class StapData {
* @return
*/
private int addCallee(int id) {
- children.add(id);
- return id;
+ children.add(id);
+ return id;
}
/**
@@ -101,7 +101,7 @@ public class StapData {
*/
public StapNode makeNode(StapGraph graphModel) {
- return new StapNode(graphModel, style, this);
+ return new StapNode(graphModel, style, this);
}
/**
@@ -109,57 +109,57 @@ public class StapData {
* uncollapsed mode)
* @param partOfCollapsedNode
*/
- public void setPartOfCollapsedNode(int partOfCollapsedNode) {
- this.partOfCollapsedNode = partOfCollapsedNode;
- }
-
-
- /**
- * Indicate that this StapData was marked by the user
- */
- public void setMarked() {
- marked = true;
- }
-
-
- /**
- * Check if this StapData is marked -- returns the result of
- * marked || markedMessage.length() > 0 (in case marked was not set)
- * @return
- */
- public boolean isMarked() {
- return marked || (markedMessage != null && markedMessage.length() > 0);
- }
-
-
- public boolean isOnlyChildWithThisName() {
- return onlyChildWithThisName;
- }
-
- /**
- * If the node has not yet terminated (i.e. the time is > 1200000000000000000l) this
- * function will return graph.getEndTime() - time. In other words, getTime will assume
- * that only the start time has been recorded if time is abnormally large, and will compensate
- * by assuming that the node 'terminates' at the current endTime.
- *
- * @return long time
- */
- public long getTime() {
- if (time > 1200000000000000000l) {
- return graph.getEndTime() - time;
- }
- return time;
- }
-
-
- /**
- * Sets the time
- *
- * @param time
- */
- public void setTime(long time) {
- this.time = time;
- }
+ public void setPartOfCollapsedNode(int partOfCollapsedNode) {
+ this.partOfCollapsedNode = partOfCollapsedNode;
+ }
+
+
+ /**
+ * Indicate that this StapData was marked by the user
+ */
+ public void setMarked() {
+ marked = true;
+ }
+
+
+ /**
+ * Check if this StapData is marked -- returns the result of
+ * marked || markedMessage.length() > 0 (in case marked was not set)
+ * @return
+ */
+ public boolean isMarked() {
+ return marked || (markedMessage != null && markedMessage.length() > 0);
+ }
+
+
+ public boolean isOnlyChildWithThisName() {
+ return onlyChildWithThisName;
+ }
+
+ /**
+ * If the node has not yet terminated (i.e. the time is > 1200000000000000000l) this
+ * function will return graph.getEndTime() - time. In other words, getTime will assume
+ * that only the start time has been recorded if time is abnormally large, and will compensate
+ * by assuming that the node 'terminates' at the current endTime.
+ *
+ * @return long time
+ */
+ public long getTime() {
+ if (time > 1200000000000000000l) {
+ return graph.getEndTime() - time;
+ }
+ return time;
+ }
+
+
+ /**
+ * Sets the time
+ *
+ * @param time
+ */
+ public void setTime(long time) {
+ this.time = time;
+ }
/**
* Sets the message for this data object to the given string,
@@ -169,41 +169,41 @@ public class StapData {
* @param message
* @return this
*/
- public StapData setMessage(String message) {
- if (message == null || message.length() < 1) {
- return this;
- }
- this.markedMessage = message;
- this.marked = true;
- return this;
- }
-
-
- /**
- * Inserts the message after the current message. No spaces or newlines are appended.
- * @param message
- * @return
- */
- public StapData insertMessage(String message) {
- if (message == null || message.length() < 1) {
- return this;
- }
- String tmp = message;
- if (this.markedMessage != null && this.markedMessage.length() > 0) {
- tmp = this.markedMessage + tmp;
- }
- this.markedMessage = tmp;
- this.marked = true;
- return this;
- }
-
- /**
- * Return true if <code>partOfCollapseNode!= StapData.NOT_PART_OF_COLLAPSED_NODE</code
- * @return
- */
+ public StapData setMessage(String message) {
+ if (message == null || message.length() < 1) {
+ return this;
+ }
+ this.markedMessage = message;
+ this.marked = true;
+ return this;
+ }
+
+
+ /**
+ * Inserts the message after the current message. No spaces or newlines are appended.
+ * @param message
+ * @return
+ */
+ public StapData insertMessage(String message) {
+ if (message == null || message.length() < 1) {
+ return this;
+ }
+ String tmp = message;
+ if (this.markedMessage != null && this.markedMessage.length() > 0) {
+ tmp = this.markedMessage + tmp;
+ }
+ this.markedMessage = tmp;
+ this.marked = true;
+ return this;
+ }
+
+ /**
+ * Return true if <code>partOfCollapseNode!= StapData.NOT_PART_OF_COLLAPSED_NODE</code
+ * @return
+ */
public boolean isPartOfCollapsedNode() {
- return (partOfCollapsedNode != NOT_PART_OF_COLLAPSED_NODE);
- }
+ return (partOfCollapsedNode != NOT_PART_OF_COLLAPSED_NODE);
+ }
/**
@@ -213,7 +213,7 @@ public class StapData {
* @return The collapsed node this node is a part of (if any)
*/
public int getPartOfCollapsedNode() {
- return partOfCollapsedNode;
+ return partOfCollapsedNode;
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapGraphParser.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapGraphParser.java
index f26ddd820b..1e9c9698e0 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapGraphParser.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapGraphParser.java
@@ -41,93 +41,93 @@ import org.eclipse.swt.widgets.Shell;
*/
public class StapGraphParser extends SystemTapParser {
- public Map<Integer, Long> timeMap;
- public Map<Integer, String> serialMap;
- public Map<Integer, HashMap<Integer, ArrayList<Integer>>> neighbourMaps;
- public Map<String, Long> aggregateTimeMap;
- public Map<String, Integer> countMap;
- public List<Integer> callOrderList;
- public Map<Integer, String> markedMap;
- public String markedNodes;
- public int validator;
- public Long endingTimeInNS;
- public long totalTime;
- public Map<Integer, Integer> lastFunctionMap;
- public ICProject project;
- private static final String DELIM = ",,"; //$NON-NLS-1$
-
- private boolean encounteredMain = false;
- private List<Integer> shouldGetEndingTimeForID = new ArrayList <>();
-
- private Map<Integer, List<String>> nameMaps;
- private Map<Integer, List<Integer>> idMaps;
- private boolean skippedDirectives = false;
- private int firstNode = -1;
-
- public long startTime = -1;
-
- public String text;
-
- @Override
- protected void initialize() {
- //INITIALIZE MAPS
- neighbourMaps = new HashMap<>();
- timeMap = new HashMap<>();
- serialMap = new TreeMap<>();
- aggregateTimeMap = new HashMap<>();
- countMap = new HashMap<>();
- endingTimeInNS = 0l;
- callOrderList = new ArrayList<>();
- markedMap = new HashMap<>();
- lastFunctionMap = new HashMap<>();
- nameMaps = new HashMap<>();
- idMaps = new HashMap<>();
- project = null;
- startTime = -1;
- }
-
-
- @Override
- public IStatus nonRealTimeParsing(){
- //Clear maps (in case a previous execution left values hanging)
- neighbourMaps.clear();
- timeMap.clear();
- serialMap.clear();
- aggregateTimeMap.clear();
- countMap.clear();
- text = ""; //$NON-NLS-1$
- callOrderList.clear();
- shouldGetEndingTimeForID.clear();
- nameMaps.clear();
- idMaps.clear();
- encounteredMain = false;
- skippedDirectives = false;
- firstNode = -1;
- startTime = -1;
-
- BufferedReader buff = null;
- try {
- buff = new BufferedReader(new FileReader(sourcePath));
- } catch (FileNotFoundException e1) {
- Display.getDefault().asyncExec(new Runnable() {
-
- @Override
- public void run(){
- MessageDialog.openError(new Shell(), Messages.getString("StapGraphParser.FileNotFound"), //$NON-NLS-1$
- Messages.getString("StapGraphParser.CouldNotOpen") + sourcePath); //$NON-NLS-1$
-
- }
- });
- return Status.CANCEL_STATUS;
- }
- internalData = buff;
- return realTimeParsing();
- }
-
-
- private void parseEnd() {
-
- //CHECK FOR EXIT() CALL
+ public Map<Integer, Long> timeMap;
+ public Map<Integer, String> serialMap;
+ public Map<Integer, HashMap<Integer, ArrayList<Integer>>> neighbourMaps;
+ public Map<String, Long> aggregateTimeMap;
+ public Map<String, Integer> countMap;
+ public List<Integer> callOrderList;
+ public Map<Integer, String> markedMap;
+ public String markedNodes;
+ public int validator;
+ public Long endingTimeInNS;
+ public long totalTime;
+ public Map<Integer, Integer> lastFunctionMap;
+ public ICProject project;
+ private static final String DELIM = ",,"; //$NON-NLS-1$
+
+ private boolean encounteredMain = false;
+ private List<Integer> shouldGetEndingTimeForID = new ArrayList <>();
+
+ private Map<Integer, List<String>> nameMaps;
+ private Map<Integer, List<Integer>> idMaps;
+ private boolean skippedDirectives = false;
+ private int firstNode = -1;
+
+ public long startTime = -1;
+
+ public String text;
+
+ @Override
+ protected void initialize() {
+ //INITIALIZE MAPS
+ neighbourMaps = new HashMap<>();
+ timeMap = new HashMap<>();
+ serialMap = new TreeMap<>();
+ aggregateTimeMap = new HashMap<>();
+ countMap = new HashMap<>();
+ endingTimeInNS = 0l;
+ callOrderList = new ArrayList<>();
+ markedMap = new HashMap<>();
+ lastFunctionMap = new HashMap<>();
+ nameMaps = new HashMap<>();
+ idMaps = new HashMap<>();
+ project = null;
+ startTime = -1;
+ }
+
+
+ @Override
+ public IStatus nonRealTimeParsing(){
+ //Clear maps (in case a previous execution left values hanging)
+ neighbourMaps.clear();
+ timeMap.clear();
+ serialMap.clear();
+ aggregateTimeMap.clear();
+ countMap.clear();
+ text = ""; //$NON-NLS-1$
+ callOrderList.clear();
+ shouldGetEndingTimeForID.clear();
+ nameMaps.clear();
+ idMaps.clear();
+ encounteredMain = false;
+ skippedDirectives = false;
+ firstNode = -1;
+ startTime = -1;
+
+ BufferedReader buff = null;
+ try {
+ buff = new BufferedReader(new FileReader(sourcePath));
+ } catch (FileNotFoundException e1) {
+ Display.getDefault().asyncExec(new Runnable() {
+
+ @Override
+ public void run(){
+ MessageDialog.openError(new Shell(), Messages.getString("StapGraphParser.FileNotFound"), //$NON-NLS-1$
+ Messages.getString("StapGraphParser.CouldNotOpen") + sourcePath); //$NON-NLS-1$
+
+ }
+ });
+ return Status.CANCEL_STATUS;
+ }
+ internalData = buff;
+ return realTimeParsing();
+ }
+
+
+ private void parseEnd() {
+
+ //CHECK FOR EXIT() CALL
for (int key : idMaps.keySet()) {
List<Integer> idList = idMaps.get(key);
int lastFunctionCalled = lastFunctionMap.get(key);
@@ -158,438 +158,438 @@ public class StapGraphParser extends SystemTapParser {
}
}
- //timecheck is true if the total execution time is less than 10ms
- //and the first function is more than 1% off from the total time.
- boolean timeCheck = totalTime < 50000000 &&
- (((float)timeMap.get(firstNode)/totalTime) > 1.01 ||
- ((float)timeMap.get(firstNode)/totalTime) < 0.99);
-
- /*
- * Indicate whether or not we had to manipulate total time, and why
- */
- if (skippedDirectives || timeCheck) {
- totalTime = timeMap.get(firstNode);
- String markedMessage = ""; //$NON-NLS-1$
- if (markedMap.containsKey(firstNode)) {
- markedMessage = markedMap.get(firstNode) + "\n"; //$NON-NLS-1$
- }
- if (skippedDirectives) {
- markedMessage += Messages.getString("StapGraphParser.CDirectives"); //$NON-NLS-1$
- }
- if (timeCheck) {
- markedMessage += Messages.getString("StapGraphParser.TooFast"); //$NON-NLS-1$
- }
-
- markedMessage += Messages.getString("StapGraphParser.TimeForThisNode"); //$NON-NLS-1$
-
- markedMap.put(firstNode, markedMessage);
- }
- }
-
- private void parseMarked(String msg) {
- /*
- * Append message
- */
- String[] parsed = msg.split(",,", 2); //$NON-NLS-1$
-
- int key = Integer.parseInt(parsed[0]);
-
- List<Integer> idList = idMaps.get(key);
- if (idList == null || msg.length() < 1 || idList.size() < 1) {
- return;
- }
- int id = idList.get(idList.size() -1);
- if (parsed[1].equals("<unknown>")) { //$NON-NLS-1$
- parsed[1] = parsed[1] + Messages.getString("StapGraphParser.UnknownMarkers"); //$NON-NLS-1$
- }
- markedMap.put(id, (markedMap.get(id) == null ? "" : markedMap.get(id)) + parsed[1]); //$NON-NLS-1$
- }
-
- private IStatus parse(String s) {
-
- try {
- if (s.length() < 1) {
- return Status.OK_STATUS;
- }
- switch (s.charAt(0)) {
- case '<' :
- /*
- *
- * Open tag -- function call
- *
- *
- */
- String[] args = s.substring(1, s.length()).split(DELIM);
- // args[0] = name
- // args[1] = id
- // arsg[2] = time of event
- int id = Integer.parseInt(args[1]);
- long time = Long.parseLong(args[2]);
- int tid = Integer.parseInt(args[3]);
- String name = args[0];
-
- //If we haven't encountered a main function yet and the name isn't clean,
- //and the name contains "__", then this is probably a C directive
- if (!encounteredMain && !isFunctionNameClean(name) && name.contains("__")) { //$NON-NLS-1$
- skippedDirectives = true;
- break;
- }
-
- List<String> nameList = nameMaps.get(tid);
- if (nameList == null) {
- nameList = new ArrayList<>();
- }
-
- List<Integer> idList = idMaps.get(tid);
- if (idList == null) {
- idList = new ArrayList<>();
- }
-
- HashMap<Integer, ArrayList<Integer>> outNeighbours = neighbourMaps.get(tid);
- if (outNeighbours == null) {
- outNeighbours = new HashMap<>();
- }
-
- if (startTime < 1) {
- startTime = time;
- }
- endingTimeInNS=time;
-
- name = cleanFunctionName(name);
- if (name.equals("main")) { //$NON-NLS-1$
- encounteredMain = true;
- }
- if (firstNode == -1) {
- firstNode = id;
- }
-
- serialMap.put(id, name);
- timeMap.put(id, time);
-
- if (aggregateTimeMap.get(name) == null){
- aggregateTimeMap.put(name, (long) 0);
- }
-
- //IF THERE ARE PREVIOUS FUNCTIONS WITH THE SAME NAME
- //WE ARE IN ONE OF THEM SO DO NOT ADD TO CUMULATIVE TIME
-
-
- if (nameList.indexOf(name) == -1) {
- long cumulativeTime = aggregateTimeMap.get(name) - time;
- aggregateTimeMap.put(name, cumulativeTime);
- shouldGetEndingTimeForID.add(id);
- }
-
-
- if (countMap.get(name) == null){
- countMap.put(name, 0);
- }
- countMap.put(name, countMap.get(name) + 1);
-
- nameList.add(name);
- idList.add(id);
-
-
- if (outNeighbours.get(id) == null){
- outNeighbours.put(id, new ArrayList<Integer>());
- }
-
- if (idList.size() > 1) {
- int parentID = idList.get(idList.size() - 2);
- outNeighbours.get(parentID).add(id);
- }
-
-
- callOrderList.add(id);
- lastFunctionMap.put(tid,id);
-
- neighbourMaps.put(tid, outNeighbours);
- nameMaps.put(tid, nameList);
- idMaps.put(tid, idList);
-
- break;
- case '>' :
-
- /*
- *
- * Close tag -- Function return
- *
- */
-
- args = s.substring(1, s.length()).split(DELIM);
- //args[0] = name
- //args[1] = time of event
- name = args[0];
- tid = Integer.parseInt(args[2]);
-
- nameList = nameMaps.get(tid);
- if (nameList == null) {
- nameList = new ArrayList<>();
- }
-
- idList = idMaps.get(tid);
- if (idList == null) {
- idList = new ArrayList<>();
- }
-
-
- //If we haven't encountered a main function yet and the name isn't clean,
- //and the name contains "__", then this is probably a C directive
- if (!encounteredMain && !isFunctionNameClean(name) && name.contains("__")) { //$NON-NLS-1$
- skippedDirectives = true;
- break;
- }
-
- name = cleanFunctionName(name);
- int lastOccurance = nameList.lastIndexOf(name);
- if (lastOccurance < 0) {
- parsingError(Messages.getString("StapGraphParser.RetMismatch") + name); //$NON-NLS-1$
- return Status.CANCEL_STATUS;
- }
-
- nameList.remove(lastOccurance);
- id = idList.remove(lastOccurance);
-
-
- if (timeMap.get(id) == null) {
- parsingError(Messages.getString("StapGraphParser.NoStartTime") + name); //$NON-NLS-1$
- return Status.CANCEL_STATUS;
- }
- endingTimeInNS=Long.parseLong(args[1]);
- time = endingTimeInNS - timeMap.get(id);
- timeMap.put(id, time);
- if (id == firstNode) {
- showTime(id, time);
- }
-
-
- //IF AN ID IS IN THIS ARRAY IT IS BECAUSE WE NEED THE ENDING TIME
- // TO BE ADDED TO THE CUMULATIVE TIME FOR FUNCTIONS OF THIS NAME
- if (shouldGetEndingTimeForID.contains(id)){
- long cumulativeTime = aggregateTimeMap.get(name) + Long.parseLong(args[1]);
- aggregateTimeMap.put(name, cumulativeTime);
- }
-
- nameMaps.put(tid, nameList);
- idMaps.put(tid, idList);
- break;
- default :
- /*
- *
- * Anything else -- error
- *
- */
-
-// parsingError(Messages.getString("StapGraphParser.14") + s.charAt(0) + //$NON-NLS-1$
-// Messages.getString("StapGraphParser.15") ); //$NON-NLS-1$
- return Status.CANCEL_STATUS;
-
- }
- } catch (NumberFormatException e) {
- SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages
- (Messages.getString("StapGraphParser.BadSymbol"), //$NON-NLS-1$
- Messages.getString("StapGraphParser.BadSymbol"), //$NON-NLS-1$
- Messages.getString("StapGraphParser.BadSymbolMsg1") + //$NON-NLS-1$
- Messages.getString("StapGraphParser.BadSymbolMsg2")); //$NON-NLS-1$
- mess.schedule();
-
- return Status.CANCEL_STATUS;
- }
- return Status.OK_STATUS;
- }
-
-
- private IStatus parseDotFile() {
- if (!(internalData instanceof BufferedReader))
- return Status.CANCEL_STATUS;
-
- BufferedReader buff = (BufferedReader) internalData;
-
- HashMap <Integer, ArrayList<Integer>> outNeighbours= new HashMap<>();
- ArrayList<String> nameList = new ArrayList<>();
- ArrayList<Integer> idList = new ArrayList<>();
- endingTimeInNS =0l;
- totalTime=10000l;
- try {
- String line;
- while ((line = buff.readLine()) != null) {
- if (line.equals("}")) { //$NON-NLS-1$
- break;
- }
- if (monitor.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
- if (line.length() < 1) {
- continue;
- }
-
- String[] args = line.split(" ", 2); //$NON-NLS-1$
- if (args[0].contains("->")) { //$NON-NLS-1$
- //connection
- int[] ids = new int[2];
- int called = 1;
- try {
- ids[0] = Integer.parseInt(args[0].split("->")[0]); //$NON-NLS-1$
- ids[1] = Integer.parseInt(args[0].split("->")[1]); //$NON-NLS-1$
- int index1 = args[1].indexOf("=\""); //$NON-NLS-1$
- int index2 = args[1].indexOf("\"]"); //$NON-NLS-1$
- called = Integer.parseInt(args[1].substring(index1 + 2,index2));
- } catch (NumberFormatException e) {
- SystemTapUIErrorMessages m = new SystemTapUIErrorMessages(
- Messages.getString("StapGraphParser.idOrLabel"), Messages.getString("StapGraphParser.idOrLabel"), //$NON-NLS-1$ //$NON-NLS-2$
- Messages.getString("StapGraphParser.nonNumericLabel")); //$NON-NLS-1$
- m.schedule();
- return Status.CANCEL_STATUS;
- }
-
- //Set neighbour
- ArrayList<Integer> tmpList = outNeighbours.get(ids[0]);
- if (tmpList == null) {
- tmpList = new ArrayList<>();
- }
-
- for (int i = 0; i < called; i++) {
- tmpList.add(ids[1]);
- }
-
- outNeighbours.put(ids[0], tmpList);
- } else {
- //node
- try {
- int id = Integer.parseInt(args[0]);
- if (firstNode == -1) {
- firstNode = id;
- }
- int index = args[1].indexOf("=\""); //$NON-NLS-1$
- String name = args[1].substring(index + 2, args[1].indexOf(" ", index)); //$NON-NLS-1$
- double dtime = 0.0;
- dtime = Double.parseDouble(args[1].substring(args[1].indexOf(" ") + 1, args[1].indexOf("%"))); //$NON-NLS-1$ //$NON-NLS-2$
- long time = (long) (dtime*100);
-
- nameList.add(name);
- idList.add(id);
- timeMap.put(id, time);
- serialMap.put(id, name);
- if (countMap.get(name) == null){
- countMap.put(name, 0);
- }
- countMap.put(name, countMap.get(name) + 1);
-
- long cumulativeTime = (aggregateTimeMap.get(name) != null ? aggregateTimeMap.get(name) : 0) + time;
- aggregateTimeMap.put(name, cumulativeTime);
- } catch (NumberFormatException e) {
- SystemTapUIErrorMessages m = new SystemTapUIErrorMessages(
- Messages.getString("StapGraphParser.idOrTime"), Messages.getString("StapGraphParser.idOrTime"), //$NON-NLS-1$ //$NON-NLS-2$
- Messages.getString("StapGraphParser.nonNumericTime")); //$NON-NLS-1$
- m.schedule();
- return Status.CANCEL_STATUS;
- }
-
- }
-
-
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- buff.close();
- } catch (IOException e) {
- //Do nothing
- }
- }
- neighbourMaps.put(0, outNeighbours);
- nameMaps.put(0, nameList);
- idMaps.put(0, idList);
- try {
- view.update();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- return Status.OK_STATUS;
- }
-
- @Override
- public IStatus realTimeParsing() {
- if (!(internalData instanceof BufferedReader)) {
- return Status.CANCEL_STATUS;
- }
-
- BufferedReader buff = (BufferedReader) internalData;
-
- String line;
- boolean draw = false;
- boolean first = true;
- try {
- while ((line = buff.readLine()) != null) {
- if (monitor.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
- if (line.length() < 1) {
- continue;
- }
- if (first && (line.contains(Messages.getString("StapGraphParser.17")))) { //$NON-NLS-1$
- return parseDotFile();
- }
- first = false;
-
- draw = true;
- if (line.equals("PROBE_BEGIN")) { //$NON-NLS-1$
- buff.mark(100);
- String tmp = buff.readLine();
-
- if (tmp != null && tmp.length() > 0) {
- char tchar = tmp.charAt(0);
- if (tchar != '-' && tchar != '+' && tchar != '?' && tchar != '>' && tchar != '<') {
- project = CoreModel.getDefault().getCModel().getCProject(tmp);
- } else {
- buff.reset();
- }
- }
-
- } else if (line.charAt(0) == '-') {
- endingTimeInNS = Long.parseLong(line.substring(1));
- } else if (line.charAt(0) == '+') {
- totalTime = Long.parseLong(line.substring(1));
- //Total time should be the last line in the output
- parseEnd();
- } else if (line.charAt(0) == '?') {
- if (line.length() > 1) {
- parseMarked(line.substring(1));
- }
- } else {
- if (parse(line) == Status.CANCEL_STATUS) {
- break;
- }
- }
- }
- if (draw && view != null) {
- view.update();
- //Repeat until all lines are read
- realTimeParsing();
- }
- } catch (IOException e) {
- e.printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- return Status.OK_STATUS;
- }
-
- /**
- * Mark node id with a message giving its actual time.
- */
- private void showTime(int id, long time) {
- String tmp = markedMap.get(id);
- if (tmp == null) {
- tmp = ""; //$NON-NLS-1$
- }
- markedMap.put(id, tmp +
- Messages.getString("StapGraphParser.ActualTime") + time/1000000 //$NON-NLS-1$
- + Messages.getString("StapGraphParser.TimeUnits")); //$NON-NLS-1$
- }
+ //timecheck is true if the total execution time is less than 10ms
+ //and the first function is more than 1% off from the total time.
+ boolean timeCheck = totalTime < 50000000 &&
+ (((float)timeMap.get(firstNode)/totalTime) > 1.01 ||
+ ((float)timeMap.get(firstNode)/totalTime) < 0.99);
+
+ /*
+ * Indicate whether or not we had to manipulate total time, and why
+ */
+ if (skippedDirectives || timeCheck) {
+ totalTime = timeMap.get(firstNode);
+ String markedMessage = ""; //$NON-NLS-1$
+ if (markedMap.containsKey(firstNode)) {
+ markedMessage = markedMap.get(firstNode) + "\n"; //$NON-NLS-1$
+ }
+ if (skippedDirectives) {
+ markedMessage += Messages.getString("StapGraphParser.CDirectives"); //$NON-NLS-1$
+ }
+ if (timeCheck) {
+ markedMessage += Messages.getString("StapGraphParser.TooFast"); //$NON-NLS-1$
+ }
+
+ markedMessage += Messages.getString("StapGraphParser.TimeForThisNode"); //$NON-NLS-1$
+
+ markedMap.put(firstNode, markedMessage);
+ }
+ }
+
+ private void parseMarked(String msg) {
+ /*
+ * Append message
+ */
+ String[] parsed = msg.split(",,", 2); //$NON-NLS-1$
+
+ int key = Integer.parseInt(parsed[0]);
+
+ List<Integer> idList = idMaps.get(key);
+ if (idList == null || msg.length() < 1 || idList.size() < 1) {
+ return;
+ }
+ int id = idList.get(idList.size() -1);
+ if (parsed[1].equals("<unknown>")) { //$NON-NLS-1$
+ parsed[1] = parsed[1] + Messages.getString("StapGraphParser.UnknownMarkers"); //$NON-NLS-1$
+ }
+ markedMap.put(id, (markedMap.get(id) == null ? "" : markedMap.get(id)) + parsed[1]); //$NON-NLS-1$
+ }
+
+ private IStatus parse(String s) {
+
+ try {
+ if (s.length() < 1) {
+ return Status.OK_STATUS;
+ }
+ switch (s.charAt(0)) {
+ case '<' :
+ /*
+ *
+ * Open tag -- function call
+ *
+ *
+ */
+ String[] args = s.substring(1, s.length()).split(DELIM);
+ // args[0] = name
+ // args[1] = id
+ // arsg[2] = time of event
+ int id = Integer.parseInt(args[1]);
+ long time = Long.parseLong(args[2]);
+ int tid = Integer.parseInt(args[3]);
+ String name = args[0];
+
+ //If we haven't encountered a main function yet and the name isn't clean,
+ //and the name contains "__", then this is probably a C directive
+ if (!encounteredMain && !isFunctionNameClean(name) && name.contains("__")) { //$NON-NLS-1$
+ skippedDirectives = true;
+ break;
+ }
+
+ List<String> nameList = nameMaps.get(tid);
+ if (nameList == null) {
+ nameList = new ArrayList<>();
+ }
+
+ List<Integer> idList = idMaps.get(tid);
+ if (idList == null) {
+ idList = new ArrayList<>();
+ }
+
+ HashMap<Integer, ArrayList<Integer>> outNeighbours = neighbourMaps.get(tid);
+ if (outNeighbours == null) {
+ outNeighbours = new HashMap<>();
+ }
+
+ if (startTime < 1) {
+ startTime = time;
+ }
+ endingTimeInNS=time;
+
+ name = cleanFunctionName(name);
+ if (name.equals("main")) { //$NON-NLS-1$
+ encounteredMain = true;
+ }
+ if (firstNode == -1) {
+ firstNode = id;
+ }
+
+ serialMap.put(id, name);
+ timeMap.put(id, time);
+
+ if (aggregateTimeMap.get(name) == null){
+ aggregateTimeMap.put(name, (long) 0);
+ }
+
+ //IF THERE ARE PREVIOUS FUNCTIONS WITH THE SAME NAME
+ //WE ARE IN ONE OF THEM SO DO NOT ADD TO CUMULATIVE TIME
+
+
+ if (nameList.indexOf(name) == -1) {
+ long cumulativeTime = aggregateTimeMap.get(name) - time;
+ aggregateTimeMap.put(name, cumulativeTime);
+ shouldGetEndingTimeForID.add(id);
+ }
+
+
+ if (countMap.get(name) == null){
+ countMap.put(name, 0);
+ }
+ countMap.put(name, countMap.get(name) + 1);
+
+ nameList.add(name);
+ idList.add(id);
+
+
+ if (outNeighbours.get(id) == null){
+ outNeighbours.put(id, new ArrayList<Integer>());
+ }
+
+ if (idList.size() > 1) {
+ int parentID = idList.get(idList.size() - 2);
+ outNeighbours.get(parentID).add(id);
+ }
+
+
+ callOrderList.add(id);
+ lastFunctionMap.put(tid,id);
+
+ neighbourMaps.put(tid, outNeighbours);
+ nameMaps.put(tid, nameList);
+ idMaps.put(tid, idList);
+
+ break;
+ case '>' :
+
+ /*
+ *
+ * Close tag -- Function return
+ *
+ */
+
+ args = s.substring(1, s.length()).split(DELIM);
+ //args[0] = name
+ //args[1] = time of event
+ name = args[0];
+ tid = Integer.parseInt(args[2]);
+
+ nameList = nameMaps.get(tid);
+ if (nameList == null) {
+ nameList = new ArrayList<>();
+ }
+
+ idList = idMaps.get(tid);
+ if (idList == null) {
+ idList = new ArrayList<>();
+ }
+
+
+ //If we haven't encountered a main function yet and the name isn't clean,
+ //and the name contains "__", then this is probably a C directive
+ if (!encounteredMain && !isFunctionNameClean(name) && name.contains("__")) { //$NON-NLS-1$
+ skippedDirectives = true;
+ break;
+ }
+
+ name = cleanFunctionName(name);
+ int lastOccurance = nameList.lastIndexOf(name);
+ if (lastOccurance < 0) {
+ parsingError(Messages.getString("StapGraphParser.RetMismatch") + name); //$NON-NLS-1$
+ return Status.CANCEL_STATUS;
+ }
+
+ nameList.remove(lastOccurance);
+ id = idList.remove(lastOccurance);
+
+
+ if (timeMap.get(id) == null) {
+ parsingError(Messages.getString("StapGraphParser.NoStartTime") + name); //$NON-NLS-1$
+ return Status.CANCEL_STATUS;
+ }
+ endingTimeInNS=Long.parseLong(args[1]);
+ time = endingTimeInNS - timeMap.get(id);
+ timeMap.put(id, time);
+ if (id == firstNode) {
+ showTime(id, time);
+ }
+
+
+ //IF AN ID IS IN THIS ARRAY IT IS BECAUSE WE NEED THE ENDING TIME
+ // TO BE ADDED TO THE CUMULATIVE TIME FOR FUNCTIONS OF THIS NAME
+ if (shouldGetEndingTimeForID.contains(id)){
+ long cumulativeTime = aggregateTimeMap.get(name) + Long.parseLong(args[1]);
+ aggregateTimeMap.put(name, cumulativeTime);
+ }
+
+ nameMaps.put(tid, nameList);
+ idMaps.put(tid, idList);
+ break;
+ default :
+ /*
+ *
+ * Anything else -- error
+ *
+ */
+
+// parsingError(Messages.getString("StapGraphParser.14") + s.charAt(0) + //$NON-NLS-1$
+// Messages.getString("StapGraphParser.15") ); //$NON-NLS-1$
+ return Status.CANCEL_STATUS;
+
+ }
+ } catch (NumberFormatException e) {
+ SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages
+ (Messages.getString("StapGraphParser.BadSymbol"), //$NON-NLS-1$
+ Messages.getString("StapGraphParser.BadSymbol"), //$NON-NLS-1$
+ Messages.getString("StapGraphParser.BadSymbolMsg1") + //$NON-NLS-1$
+ Messages.getString("StapGraphParser.BadSymbolMsg2")); //$NON-NLS-1$
+ mess.schedule();
+
+ return Status.CANCEL_STATUS;
+ }
+ return Status.OK_STATUS;
+ }
+
+
+ private IStatus parseDotFile() {
+ if (!(internalData instanceof BufferedReader))
+ return Status.CANCEL_STATUS;
+
+ BufferedReader buff = (BufferedReader) internalData;
+
+ HashMap <Integer, ArrayList<Integer>> outNeighbours= new HashMap<>();
+ ArrayList<String> nameList = new ArrayList<>();
+ ArrayList<Integer> idList = new ArrayList<>();
+ endingTimeInNS =0l;
+ totalTime=10000l;
+ try {
+ String line;
+ while ((line = buff.readLine()) != null) {
+ if (line.equals("}")) { //$NON-NLS-1$
+ break;
+ }
+ if (monitor.isCanceled()) {
+ return Status.CANCEL_STATUS;
+ }
+ if (line.length() < 1) {
+ continue;
+ }
+
+ String[] args = line.split(" ", 2); //$NON-NLS-1$
+ if (args[0].contains("->")) { //$NON-NLS-1$
+ //connection
+ int[] ids = new int[2];
+ int called = 1;
+ try {
+ ids[0] = Integer.parseInt(args[0].split("->")[0]); //$NON-NLS-1$
+ ids[1] = Integer.parseInt(args[0].split("->")[1]); //$NON-NLS-1$
+ int index1 = args[1].indexOf("=\""); //$NON-NLS-1$
+ int index2 = args[1].indexOf("\"]"); //$NON-NLS-1$
+ called = Integer.parseInt(args[1].substring(index1 + 2,index2));
+ } catch (NumberFormatException e) {
+ SystemTapUIErrorMessages m = new SystemTapUIErrorMessages(
+ Messages.getString("StapGraphParser.idOrLabel"), Messages.getString("StapGraphParser.idOrLabel"), //$NON-NLS-1$ //$NON-NLS-2$
+ Messages.getString("StapGraphParser.nonNumericLabel")); //$NON-NLS-1$
+ m.schedule();
+ return Status.CANCEL_STATUS;
+ }
+
+ //Set neighbour
+ ArrayList<Integer> tmpList = outNeighbours.get(ids[0]);
+ if (tmpList == null) {
+ tmpList = new ArrayList<>();
+ }
+
+ for (int i = 0; i < called; i++) {
+ tmpList.add(ids[1]);
+ }
+
+ outNeighbours.put(ids[0], tmpList);
+ } else {
+ //node
+ try {
+ int id = Integer.parseInt(args[0]);
+ if (firstNode == -1) {
+ firstNode = id;
+ }
+ int index = args[1].indexOf("=\""); //$NON-NLS-1$
+ String name = args[1].substring(index + 2, args[1].indexOf(" ", index)); //$NON-NLS-1$
+ double dtime = 0.0;
+ dtime = Double.parseDouble(args[1].substring(args[1].indexOf(" ") + 1, args[1].indexOf("%"))); //$NON-NLS-1$ //$NON-NLS-2$
+ long time = (long) (dtime*100);
+
+ nameList.add(name);
+ idList.add(id);
+ timeMap.put(id, time);
+ serialMap.put(id, name);
+ if (countMap.get(name) == null){
+ countMap.put(name, 0);
+ }
+ countMap.put(name, countMap.get(name) + 1);
+
+ long cumulativeTime = (aggregateTimeMap.get(name) != null ? aggregateTimeMap.get(name) : 0) + time;
+ aggregateTimeMap.put(name, cumulativeTime);
+ } catch (NumberFormatException e) {
+ SystemTapUIErrorMessages m = new SystemTapUIErrorMessages(
+ Messages.getString("StapGraphParser.idOrTime"), Messages.getString("StapGraphParser.idOrTime"), //$NON-NLS-1$ //$NON-NLS-2$
+ Messages.getString("StapGraphParser.nonNumericTime")); //$NON-NLS-1$
+ m.schedule();
+ return Status.CANCEL_STATUS;
+ }
+
+ }
+
+
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ buff.close();
+ } catch (IOException e) {
+ //Do nothing
+ }
+ }
+ neighbourMaps.put(0, outNeighbours);
+ nameMaps.put(0, nameList);
+ idMaps.put(0, idList);
+ try {
+ view.update();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ return Status.OK_STATUS;
+ }
+
+ @Override
+ public IStatus realTimeParsing() {
+ if (!(internalData instanceof BufferedReader)) {
+ return Status.CANCEL_STATUS;
+ }
+
+ BufferedReader buff = (BufferedReader) internalData;
+
+ String line;
+ boolean draw = false;
+ boolean first = true;
+ try {
+ while ((line = buff.readLine()) != null) {
+ if (monitor.isCanceled()) {
+ return Status.CANCEL_STATUS;
+ }
+ if (line.length() < 1) {
+ continue;
+ }
+ if (first && (line.contains(Messages.getString("StapGraphParser.17")))) { //$NON-NLS-1$
+ return parseDotFile();
+ }
+ first = false;
+
+ draw = true;
+ if (line.equals("PROBE_BEGIN")) { //$NON-NLS-1$
+ buff.mark(100);
+ String tmp = buff.readLine();
+
+ if (tmp != null && tmp.length() > 0) {
+ char tchar = tmp.charAt(0);
+ if (tchar != '-' && tchar != '+' && tchar != '?' && tchar != '>' && tchar != '<') {
+ project = CoreModel.getDefault().getCModel().getCProject(tmp);
+ } else {
+ buff.reset();
+ }
+ }
+
+ } else if (line.charAt(0) == '-') {
+ endingTimeInNS = Long.parseLong(line.substring(1));
+ } else if (line.charAt(0) == '+') {
+ totalTime = Long.parseLong(line.substring(1));
+ //Total time should be the last line in the output
+ parseEnd();
+ } else if (line.charAt(0) == '?') {
+ if (line.length() > 1) {
+ parseMarked(line.substring(1));
+ }
+ } else {
+ if (parse(line) == Status.CANCEL_STATUS) {
+ break;
+ }
+ }
+ }
+ if (draw && view != null) {
+ view.update();
+ //Repeat until all lines are read
+ realTimeParsing();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ return Status.OK_STATUS;
+ }
+
+ /**
+ * Mark node id with a message giving its actual time.
+ */
+ private void showTime(int id, long time) {
+ String tmp = markedMap.get(id);
+ if (tmp == null) {
+ tmp = ""; //$NON-NLS-1$
+ }
+ markedMap.put(id, tmp +
+ Messages.getString("StapGraphParser.ActualTime") + time/1000000 //$NON-NLS-1$
+ + Messages.getString("StapGraphParser.TimeUnits")); //$NON-NLS-1$
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapNode.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapNode.java
index a7763b1b1b..4dfb82a9e4 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapNode.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/StapNode.java
@@ -20,84 +20,84 @@ import org.eclipse.zest.core.widgets.GraphNode;
public class StapNode extends GraphNode{
- private static int nodeSize = 20;
- public int id;
- public GraphConnection connection; //Each node should have only one connection (to its caller)
- static NumberFormat numberFormat = NumberFormat.getInstance(Locale.CANADA);
+ private static int nodeSize = 20;
+ public int id;
+ public GraphConnection connection; //Each node should have only one connection (to its caller)
+ static NumberFormat numberFormat = NumberFormat.getInstance(Locale.CANADA);
- public StapNode(StapGraph graphModel, int style, StapData data) {
- super(graphModel, style, Messages.getString("StapNode.0")); //$NON-NLS-1$
- numberFormat.setMaximumFractionDigits(2);
- numberFormat.setMinimumFractionDigits(2);
- if (Display.getCurrent().getPrimaryMonitor().getBounds().width < 1000) {
- nodeSize = 10;
- }
+ public StapNode(StapGraph graphModel, int style, StapData data) {
+ super(graphModel, style, Messages.getString("StapNode.0")); //$NON-NLS-1$
+ numberFormat.setMaximumFractionDigits(2);
+ numberFormat.setMinimumFractionDigits(2);
+ if (Display.getCurrent().getPrimaryMonitor().getBounds().width < 1000) {
+ nodeSize = 10;
+ }
- if (data.name == StapGraph.CONSTANT_TOP_NODE_NAME) {
- this.setText(StapGraph.CONSTANT_TOP_NODE_NAME);
- } else {
- String shortName = data.name;
- if (data.name.length() > nodeSize) {
- shortName = data.name.substring(0, nodeSize - 3) + "..."; //$NON-NLS-1$
- }
- this.setText(shortName + ": " + //$NON-NLS-1$
- numberFormat.format((float) data.getTime()/graphModel.getTotalTime() * 100)
- + "%"); //$NON-NLS-1$
- }
+ if (data.name == StapGraph.CONSTANT_TOP_NODE_NAME) {
+ this.setText(StapGraph.CONSTANT_TOP_NODE_NAME);
+ } else {
+ String shortName = data.name;
+ if (data.name.length() > nodeSize) {
+ shortName = data.name.substring(0, nodeSize - 3) + "..."; //$NON-NLS-1$
+ }
+ this.setText(shortName + ": " + //$NON-NLS-1$
+ numberFormat.format((float) data.getTime()/graphModel.getTotalTime() * 100)
+ + "%"); //$NON-NLS-1$
+ }
- if (data.markedMessage != null && data.markedMessage.length() != 0) {
- Label tooltip = new Label(data.name + ": " + //$NON-NLS-1$
- numberFormat.format((float) data.getTime()/graphModel.getTotalTime() * 100)
- + "%" + "\n " + data.markedMessage); //$NON-NLS-1$ //$NON-NLS-2$
- this.setTooltip(tooltip);
- } else if (data.name.length() > nodeSize) {
- Label tooltip = new Label(data.name + ": " + //$NON-NLS-1$
- numberFormat.format((float) data.getTime()/graphModel.getTotalTime() * 100)
- + "%"); //$NON-NLS-1$
- this.setTooltip(tooltip);
- }
+ if (data.markedMessage != null && data.markedMessage.length() != 0) {
+ Label tooltip = new Label(data.name + ": " + //$NON-NLS-1$
+ numberFormat.format((float) data.getTime()/graphModel.getTotalTime() * 100)
+ + "%" + "\n " + data.markedMessage); //$NON-NLS-1$ //$NON-NLS-2$
+ this.setTooltip(tooltip);
+ } else if (data.name.length() > nodeSize) {
+ Label tooltip = new Label(data.name + ": " + //$NON-NLS-1$
+ numberFormat.format((float) data.getTime()/graphModel.getTotalTime() * 100)
+ + "%"); //$NON-NLS-1$
+ this.setTooltip(tooltip);
+ }
- this.id = data.id;
- this.connection = null;
+ this.id = data.id;
+ this.connection = null;
- if (graphModel.getNode(data.parent) != null) {
- this.connection = new GraphConnection( graphModel, style,
- this, graphModel.getNode(data.parent));
- if (graphModel.isCollapseMode()) {
- connection.setText("" + data.timesCalled); //$NON-NLS-1$
- }
- } else if (graphModel.getNode(data.collapsedParent) != null) {
- this.connection = new GraphConnection( graphModel, style,
- this, graphModel.getNode(data.collapsedParent));
- if (graphModel.isCollapseMode()) {
- connection.setText("" + data.timesCalled); //$NON-NLS-1$
- }
- } //else do not create any connections (this should usually never happen)
- }
+ if (graphModel.getNode(data.parent) != null) {
+ this.connection = new GraphConnection( graphModel, style,
+ this, graphModel.getNode(data.parent));
+ if (graphModel.isCollapseMode()) {
+ connection.setText("" + data.timesCalled); //$NON-NLS-1$
+ }
+ } else if (graphModel.getNode(data.collapsedParent) != null) {
+ this.connection = new GraphConnection( graphModel, style,
+ this, graphModel.getNode(data.collapsedParent));
+ if (graphModel.isCollapseMode()) {
+ connection.setText("" + data.timesCalled); //$NON-NLS-1$
+ }
+ } //else do not create any connections (this should usually never happen)
+ }
- /**
- * Returns the StapData object associated with this node.
- */
- @Override
- public StapData getData() {
- return ((StapGraph) this.getGraphModel()).getNodeData(id);
- }
+ /**
+ * Returns the StapData object associated with this node.
+ */
+ @Override
+ public StapData getData() {
+ return ((StapGraph) this.getGraphModel()).getNodeData(id);
+ }
- /**
- * Creates a connection between this node and the
- * specified node. The connection will have the int called as its text.
- *
- * @param graphModel
- * @param style
- * @param n
- * @param called
- */
- public void makeConnection(int style, StapNode n, int called) {
- this.connection = new GraphConnection(this.getGraphModel(), style, this, n);
- if (((StapGraph)this.getGraphModel()).isCollapseMode()) {
- connection.setText("" + called); //$NON-NLS-1$
- }
- }
+ /**
+ * Creates a connection between this node and the
+ * specified node. The connection will have the int called as its text.
+ *
+ * @param graphModel
+ * @param style
+ * @param n
+ * @param called
+ */
+ public void makeConnection(int style, StapNode n, int called) {
+ this.connection = new GraphConnection(this.getGraphModel(), style, this, n);
+ if (((StapGraph)this.getGraphModel()).isCollapseMode()) {
+ connection.setText("" + called); //$NON-NLS-1$
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/AutoScrollHelper.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/AutoScrollHelper.java
index ba59030633..b0561eadeb 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/AutoScrollHelper.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/AutoScrollHelper.java
@@ -14,45 +14,45 @@ import org.eclipse.linuxtools.internal.callgraph.StapGraph;
public class AutoScrollHelper {
- public static void scrollUp(StapGraph graph) {
-
- if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_LEVEL) {
- int parent = graph.getNodeData(graph.getRootVisibleNodeNumber()).parent;
- if (graph.isCollapseMode()) {
- parent = graph.getNodeData(graph.getRootVisibleNodeNumber()).collapsedParent;
- }
-
- if (graph.getNodeData(parent) != null && graph.getNodeData(parent).levelOfRecursion > 0 ) {
- int animMode = graph.getAnimationMode();
- graph.draw(graph.getDrawMode(), StapGraph.CONSTANT_ANIMATION_FASTEST, parent);
- graph.setAnimationMode(animMode);
- }
- } else if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_TREE) {
- graph.shrinkTree();
- }
- }
-
- public static void scrollDown(StapGraph graph) {
- if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_LEVEL) {
- if (graph.getTopLevel() + graph.levelBuffer <
- graph.getLowestLevelOfNodesAdded()) {
- int newLevel = graph.getTopLevel() + 1;
- if (graph.levels.get(newLevel).get(0) == null) {
- return;
- }
-
- graph.setTopLevelTo(newLevel);
- int animMode = graph.getAnimationMode();
- graph.setAnimationMode(StapGraph.CONSTANT_ANIMATION_FASTEST);
- graph.draw(graph.getDrawMode(), StapGraph.CONSTANT_ANIMATION_FASTEST,
- graph.levels.get(newLevel).get(0));
- graph.setAnimationMode(animMode);
- }
- } else if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_TREE) {
- graph.extendTree();
- }
-
- }
+ public static void scrollUp(StapGraph graph) {
+
+ if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_LEVEL) {
+ int parent = graph.getNodeData(graph.getRootVisibleNodeNumber()).parent;
+ if (graph.isCollapseMode()) {
+ parent = graph.getNodeData(graph.getRootVisibleNodeNumber()).collapsedParent;
+ }
+
+ if (graph.getNodeData(parent) != null && graph.getNodeData(parent).levelOfRecursion > 0 ) {
+ int animMode = graph.getAnimationMode();
+ graph.draw(graph.getDrawMode(), StapGraph.CONSTANT_ANIMATION_FASTEST, parent);
+ graph.setAnimationMode(animMode);
+ }
+ } else if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_TREE) {
+ graph.shrinkTree();
+ }
+ }
+
+ public static void scrollDown(StapGraph graph) {
+ if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_LEVEL) {
+ if (graph.getTopLevel() + graph.levelBuffer <
+ graph.getLowestLevelOfNodesAdded()) {
+ int newLevel = graph.getTopLevel() + 1;
+ if (graph.levels.get(newLevel).get(0) == null) {
+ return;
+ }
+
+ graph.setTopLevelTo(newLevel);
+ int animMode = graph.getAnimationMode();
+ graph.setAnimationMode(StapGraph.CONSTANT_ANIMATION_FASTEST);
+ graph.draw(graph.getDrawMode(), StapGraph.CONSTANT_ANIMATION_FASTEST,
+ graph.levels.get(newLevel).get(0));
+ graph.setAnimationMode(animMode);
+ }
+ } else if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_TREE) {
+ graph.extendTree();
+ }
+
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/AutoScrollSelectionListener.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/AutoScrollSelectionListener.java
index ddee945afb..f02421b776 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/AutoScrollSelectionListener.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/AutoScrollSelectionListener.java
@@ -15,24 +15,24 @@ import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
public class AutoScrollSelectionListener extends SelectionAdapter{
- public static final int AUTO_SCROLL_UP = 0;
- public static final int AUTO_SCROLL_DOWN = 1;
- private final int type;
- private final StapGraph graph;
+ public static final int AUTO_SCROLL_UP = 0;
+ public static final int AUTO_SCROLL_DOWN = 1;
+ private final int type;
+ private final StapGraph graph;
- public AutoScrollSelectionListener(int type, StapGraph g) {
- this.type = type;
- this.graph = g;
- }
+ public AutoScrollSelectionListener(int type, StapGraph g) {
+ this.type = type;
+ this.graph = g;
+ }
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (type == AUTO_SCROLL_UP) {
- AutoScrollHelper.scrollUp(graph);
- }
- if (type == AUTO_SCROLL_DOWN) {
- AutoScrollHelper.scrollDown(graph);
- }
- }
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ if (type == AUTO_SCROLL_UP) {
+ AutoScrollHelper.scrollUp(graph);
+ }
+ if (type == AUTO_SCROLL_DOWN) {
+ AutoScrollHelper.scrollDown(graph);
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/Messages.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/Messages.java
index f319bc4ba0..a7a234ac32 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/Messages.java
@@ -14,15 +14,15 @@ package org.eclipse.linuxtools.internal.callgraph.graphlisteners;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.callgraph.graphlisteners.messages"; //$NON-NLS-1$
- public static String StapGraphMouseMoveListener_0;
- public static String StapGraphMouseMoveListener_1;
- public static String StapGraphMouseMoveListener_2;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.callgraph.graphlisteners.messages"; //$NON-NLS-1$
+ public static String StapGraphMouseMoveListener_0;
+ public static String StapGraphMouseMoveListener_1;
+ public static String StapGraphMouseMoveListener_2;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/Projectionist.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/Projectionist.java
index 32ff572662..3bcc380b71 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/Projectionist.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/Projectionist.java
@@ -23,74 +23,74 @@ import org.eclipse.swt.widgets.Display;
*
*/
public class Projectionist extends Job {
- private StapGraph graph;
- private int frameTime = 2000;
- private boolean pause;
- private boolean busy;
+ private StapGraph graph;
+ private int frameTime = 2000;
+ private boolean pause;
+ private boolean busy;
- /**
- * @param name
- * @param listener -- the keyListener instantiating this class
- * @param time -- Amount of time between frames
- */
- public Projectionist(String name, StapGraph graph, int time) {
- super(name);
- this.graph = graph;
- this.frameTime = time;
- pause = false;
- busy = false;
- }
+ /**
+ * @param name
+ * @param listener -- the keyListener instantiating this class
+ * @param time -- Amount of time between frames
+ */
+ public Projectionist(String name, StapGraph graph, int time) {
+ super(name);
+ this.graph = graph;
+ this.frameTime = time;
+ pause = false;
+ busy = false;
+ }
- @Override
- public IStatus run(IProgressMonitor monitor) {
+ @Override
+ public IStatus run(IProgressMonitor monitor) {
- long snapshot = System.currentTimeMillis();
- while (true) {
- if (busy) {
- try {
- Thread.sleep(300);
- } catch (InterruptedException e1) {
- e1.printStackTrace();
- }
- continue;
- }
+ long snapshot = System.currentTimeMillis();
+ while (true) {
+ if (busy) {
+ try {
+ Thread.sleep(300);
+ } catch (InterruptedException e1) {
+ e1.printStackTrace();
+ }
+ continue;
+ }
- if (pause) {
- return Status.OK_STATUS;
- }
+ if (pause) {
+ return Status.OK_STATUS;
+ }
- if (System.currentTimeMillis() - snapshot >= frameTime) {
- snapshot = System.currentTimeMillis();
- busy = true;
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- graph.drawNextNode();
- busy = false;
- }
- });
+ if (System.currentTimeMillis() - snapshot >= frameTime) {
+ snapshot = System.currentTimeMillis();
+ busy = true;
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ graph.drawNextNode();
+ busy = false;
+ }
+ });
- } else {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- if (monitor.isCanceled()) {
- break;
- }
- }
+ } else {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ if (monitor.isCanceled()) {
+ break;
+ }
+ }
- return Status.CANCEL_STATUS;
- }
+ return Status.CANCEL_STATUS;
+ }
- /**
- * Projectionist will pause -- reschedule job to continue
- */
- public void pause() {
- pause = true;
- }
+ /**
+ * Projectionist will pause -- reschedule job to continue
+ */
+ public void pause() {
+ pause = true;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphFocusListener.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphFocusListener.java
index b4da2b9a9d..3b2fe0b80d 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphFocusListener.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphFocusListener.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -16,19 +16,19 @@ import org.eclipse.swt.events.FocusEvent;
/**
* Set mouseDown flag to false when focus is lost (prevents the graph from
* sticking to the mouse cursor when focus is regained)
- *
+ *
*
*/
public class StapGraphFocusListener extends FocusAdapter{
- private StapGraphMouseMoveListener listener;
+ private StapGraphMouseMoveListener listener;
+
+ public StapGraphFocusListener(StapGraphMouseMoveListener listener) {
+ this.listener = listener;
+ }
- public StapGraphFocusListener(StapGraphMouseMoveListener listener) {
- this.listener = listener;
- }
-
- @Override
- public void focusLost(FocusEvent e) {
- listener.setStop(true);
- }
+ @Override
+ public void focusLost(FocusEvent e) {
+ listener.setStop(true);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphKeyListener.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphKeyListener.java
index 88c8434df7..660bb7b04e 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphKeyListener.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphKeyListener.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -20,32 +20,32 @@ import org.eclipse.swt.events.KeyEvent;
* StapGraph key listener
*/
public class StapGraphKeyListener extends KeyAdapter {
- private CallgraphView callgraphView;
-
- public StapGraphKeyListener(StapGraph g) {
- callgraphView = g.getCallgraphView();
- }
-
- @Override
- public void keyReleased(KeyEvent e) {
- if (e.stateMask != SWT.SHIFT) {
- return;
- }
-
- //TODO: Use accelerator in menu actions instead of this hard-coded stuff
- if (e.character == 'R') {
- callgraphView.getViewRefresh().run();
- }else if (e.character == 'C') {
- callgraphView.getModeCollapsednodes().run();
- } else if (e.character == 'N') {
- callgraphView.getGotoNext().run();
- } else if (e.character == 'P') {
- callgraphView.getGotoPrevious().run();
- } else if (e.character == 'L') {
- callgraphView.getGotoLast().run();
- } else if (e.character == 'D') {
- callgraphView.getPlay().run();
- }
- }
-
+ private CallgraphView callgraphView;
+
+ public StapGraphKeyListener(StapGraph g) {
+ callgraphView = g.getCallgraphView();
+ }
+
+ @Override
+ public void keyReleased(KeyEvent e) {
+ if (e.stateMask != SWT.SHIFT) {
+ return;
+ }
+
+ //TODO: Use accelerator in menu actions instead of this hard-coded stuff
+ if (e.character == 'R') {
+ callgraphView.getViewRefresh().run();
+ }else if (e.character == 'C') {
+ callgraphView.getModeCollapsednodes().run();
+ } else if (e.character == 'N') {
+ callgraphView.getGotoNext().run();
+ } else if (e.character == 'P') {
+ callgraphView.getGotoPrevious().run();
+ } else if (e.character == 'L') {
+ callgraphView.getGotoLast().run();
+ } else if (e.character == 'D') {
+ callgraphView.getPlay().run();
+ }
+ }
+
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseExitListener.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseExitListener.java
index 8c26ec7ac2..06a0d4c0b7 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseExitListener.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseExitListener.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -14,15 +14,15 @@ import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
public class StapGraphMouseExitListener implements Listener{
- private StapGraphMouseMoveListener listener;
-
- public StapGraphMouseExitListener(StapGraphMouseMoveListener l) {
- this.listener = l;
- }
+ private StapGraphMouseMoveListener listener;
- @Override
- public void handleEvent(Event event) {
- listener.setStop(true);
- }
+ public StapGraphMouseExitListener(StapGraphMouseMoveListener l) {
+ this.listener = l;
+ }
+
+ @Override
+ public void handleEvent(Event event) {
+ listener.setStop(true);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseListener.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseListener.java
index 124db98cfa..07d76db6fa 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseListener.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseListener.java
@@ -22,228 +22,228 @@ import org.eclipse.swt.events.MouseListener;
import org.eclipse.zest.core.widgets.GraphNode;
public class StapGraphMouseListener implements MouseListener {
- private StapGraph graph;
- private StapGraphMouseMoveListener listener;
- private StapGraphMouseExitListener exitListener;
-
- public StapGraphMouseListener(StapGraph g) {
- this.graph = g;
- listener = new StapGraphMouseMoveListener(graph);
- exitListener = new StapGraphMouseExitListener(listener);
- }
-
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- if (e.stateMask == SWT.CONTROL) {
- controlDoubleClick();
- return;
- }
-
- if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_RADIAL) {
- StapNode node = getNodeFromSelection();
- if (node == null) {
- return;
- }
-
- graph.getTreeViewer().collapseToLevel(node.getData(), 0);
- graph.getTreeViewer().expandToLevel(node.getData(), 0);
- graph.getTreeViewer().setSelection(new StructuredSelection(node.getData()));
-
- int id = node.getData().id;
-
- graph.scale = 1;
- // Redraw in the current mode with the new id as the center
- // The x,y parameters to draw() are irrelevant for radial mode
- graph.draw(id);
-
- // Unhighlight the center node and give it a normal colour
- node = graph.getNode(id);
- node.unhighlight();
- if (graph.getNodeData(id).isMarked()) {
- node.setBackgroundColor(StapGraph.CONSTANT_MARKED);
- } else {
- node.setBackgroundColor(graph.DEFAULT_NODE_COLOR);
- }
- return;
- } else {
- StapNode node = getNodeFromSelection();
- if (node == null) {
- return;
- }
-
- unhighlightall(node);
- graph.setSelection(null);
-
- // Draw in current modes with 'id' at the top
- int id = node.getData().id;
- graph.draw(id);
- }
-
- graph.setSelection(null);
- }
-
-
- @Override
- public void mouseDown(MouseEvent e) {
- if (graph.getProjectionist() != null) {
- graph.getProjectionist().pause();
- }
- mouseDownEvent(e.x, e.y);
- }
-
- @Override
- public void mouseUp(MouseEvent e) {
- listener.setStop(true);
- graph.removeMouseMoveListener(listener);
- graph.removeListener(SWT.MouseExit, exitListener);
-
- List<StapNode> list = graph.getSelection();
-
- if (list.size() == 1) {
- int id;
- if (list.get(0) != null) {
- id = list.get(0).id;
- } else {
- graph.setSelection(null);
- return;
- }
- graph.setSelection(null);
-
- // ------------Highlighting
- if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_TREE
- || graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_LEVEL) {
- for (StapNode n : (List<StapNode>) graph.getNodes()) {
- unhighlightall(n);
- }
-
- List<Integer> callees = null;
-
- if (graph.isCollapseMode()) {
- callees = graph.getNodeData(id).collapsedChildren;
- } else {
- callees = graph.getNodeData(id).children;
- }
-
- for (int subID : callees) {
- if (graph.getNode(subID) != null) {
- graph.getNode(subID).highlight();
- }
- }
-
- if (graph.getParentNode(id) != null) {
- graph.getParentNode(id).highlight();
- }
- graph.getNode(id).highlight();
- return;
- }
-
- } else if (list.size() == 0 && ! (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_AGGREGATE)) {
- for (StapNode n : (List<StapNode>) graph.getNodes()) {
- unhighlightall(n);
- }
-
- }
- }
-
- private void unhighlightall(StapNode n) {
- int id = n.id;
- List<Integer> callees = null;
-
- if (graph.isCollapseMode()) {
- callees = graph.getNodeData(id).collapsedChildren;
- } else {
- callees = graph.getNodeData(id).children;
- }
- if (callees == null) {
- return;
- }
-
- for (int subID : callees) {
- if (graph.getNode(subID) != null) {
- graph.getNode(subID).unhighlight();
- }
- }
-
- if (graph.getParentNode(id) != null) {
- graph.getParentNode(id).unhighlight();
- }
- n.unhighlight();
- }
-
-
- private StapNode getNodeFromSelection() {
- List<GraphNode> stapNodeList = graph.getSelection();
- if (stapNodeList.isEmpty() || stapNodeList.size() != 1) {
- graph.setSelection(null);
- return null;
- }
-
- StapNode node = null;
- if (stapNodeList.get(0) instanceof StapNode) {
- node = (StapNode) stapNodeList.remove(0);
- } else {
- graph.setSelection(null);
- return null;
- }
- return node;
- }
-
- private GraphNode getAggregateNodeFromSelection() {
- List<GraphNode> graphNodeList = graph.getSelection();
- if (graphNodeList.isEmpty() || graphNodeList.size() != 1) {
- graph.setSelection(null);
- return null;
- }
-
- GraphNode node = null;
- if (graphNodeList.get(0) != null) {
- node = graphNodeList.remove(0);
- } else {
- graph.setSelection(null);
- return null;
- }
- return node;
- }
-
- private void controlDoubleClick() {
- if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_AGGREGATE) {
- GraphNode node = getAggregateNodeFromSelection();
-
- if (node == null) {
- return;
- }
-
- String functionName = (String) node.getData("AGGREGATE_NAME"); //$NON-NLS-1$
- FileFinderOpener.findAndOpen(graph.getProject(), functionName);
- node.unhighlight();
- } else {
- StapNode node = getNodeFromSelection();
-
- if (node == null) {
- return;
- }
-
- int caller = node.getData().id;
-
- if (caller < graph.getFirstUsefulNode()) {
- // The only node that satisfies this condition should be main
- caller = graph.getFirstUsefulNode();
- }
- FileFinderOpener.findAndOpen(graph.getProject(), graph.getNodeData(caller).name);
- node.unhighlight();
- }
-
- graph.setSelection(null);
- }
-
- public void mouseDownEvent(int x, int y) {
- List<?> list = graph.getSelection();
- if (list.size() < 1) {
- listener.setPoint(x, y);
- listener.setStop(false);
- graph.addMouseMoveListener(listener);
- graph.addListener(SWT.MouseExit, exitListener);
- }
- }
+ private StapGraph graph;
+ private StapGraphMouseMoveListener listener;
+ private StapGraphMouseExitListener exitListener;
+
+ public StapGraphMouseListener(StapGraph g) {
+ this.graph = g;
+ listener = new StapGraphMouseMoveListener(graph);
+ exitListener = new StapGraphMouseExitListener(listener);
+ }
+
+ @Override
+ public void mouseDoubleClick(MouseEvent e) {
+ if (e.stateMask == SWT.CONTROL) {
+ controlDoubleClick();
+ return;
+ }
+
+ if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_RADIAL) {
+ StapNode node = getNodeFromSelection();
+ if (node == null) {
+ return;
+ }
+
+ graph.getTreeViewer().collapseToLevel(node.getData(), 0);
+ graph.getTreeViewer().expandToLevel(node.getData(), 0);
+ graph.getTreeViewer().setSelection(new StructuredSelection(node.getData()));
+
+ int id = node.getData().id;
+
+ graph.scale = 1;
+ // Redraw in the current mode with the new id as the center
+ // The x,y parameters to draw() are irrelevant for radial mode
+ graph.draw(id);
+
+ // Unhighlight the center node and give it a normal colour
+ node = graph.getNode(id);
+ node.unhighlight();
+ if (graph.getNodeData(id).isMarked()) {
+ node.setBackgroundColor(StapGraph.CONSTANT_MARKED);
+ } else {
+ node.setBackgroundColor(graph.DEFAULT_NODE_COLOR);
+ }
+ return;
+ } else {
+ StapNode node = getNodeFromSelection();
+ if (node == null) {
+ return;
+ }
+
+ unhighlightall(node);
+ graph.setSelection(null);
+
+ // Draw in current modes with 'id' at the top
+ int id = node.getData().id;
+ graph.draw(id);
+ }
+
+ graph.setSelection(null);
+ }
+
+
+ @Override
+ public void mouseDown(MouseEvent e) {
+ if (graph.getProjectionist() != null) {
+ graph.getProjectionist().pause();
+ }
+ mouseDownEvent(e.x, e.y);
+ }
+
+ @Override
+ public void mouseUp(MouseEvent e) {
+ listener.setStop(true);
+ graph.removeMouseMoveListener(listener);
+ graph.removeListener(SWT.MouseExit, exitListener);
+
+ List<StapNode> list = graph.getSelection();
+
+ if (list.size() == 1) {
+ int id;
+ if (list.get(0) != null) {
+ id = list.get(0).id;
+ } else {
+ graph.setSelection(null);
+ return;
+ }
+ graph.setSelection(null);
+
+ // ------------Highlighting
+ if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_TREE
+ || graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_LEVEL) {
+ for (StapNode n : (List<StapNode>) graph.getNodes()) {
+ unhighlightall(n);
+ }
+
+ List<Integer> callees = null;
+
+ if (graph.isCollapseMode()) {
+ callees = graph.getNodeData(id).collapsedChildren;
+ } else {
+ callees = graph.getNodeData(id).children;
+ }
+
+ for (int subID : callees) {
+ if (graph.getNode(subID) != null) {
+ graph.getNode(subID).highlight();
+ }
+ }
+
+ if (graph.getParentNode(id) != null) {
+ graph.getParentNode(id).highlight();
+ }
+ graph.getNode(id).highlight();
+ return;
+ }
+
+ } else if (list.size() == 0 && ! (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_AGGREGATE)) {
+ for (StapNode n : (List<StapNode>) graph.getNodes()) {
+ unhighlightall(n);
+ }
+
+ }
+ }
+
+ private void unhighlightall(StapNode n) {
+ int id = n.id;
+ List<Integer> callees = null;
+
+ if (graph.isCollapseMode()) {
+ callees = graph.getNodeData(id).collapsedChildren;
+ } else {
+ callees = graph.getNodeData(id).children;
+ }
+ if (callees == null) {
+ return;
+ }
+
+ for (int subID : callees) {
+ if (graph.getNode(subID) != null) {
+ graph.getNode(subID).unhighlight();
+ }
+ }
+
+ if (graph.getParentNode(id) != null) {
+ graph.getParentNode(id).unhighlight();
+ }
+ n.unhighlight();
+ }
+
+
+ private StapNode getNodeFromSelection() {
+ List<GraphNode> stapNodeList = graph.getSelection();
+ if (stapNodeList.isEmpty() || stapNodeList.size() != 1) {
+ graph.setSelection(null);
+ return null;
+ }
+
+ StapNode node = null;
+ if (stapNodeList.get(0) instanceof StapNode) {
+ node = (StapNode) stapNodeList.remove(0);
+ } else {
+ graph.setSelection(null);
+ return null;
+ }
+ return node;
+ }
+
+ private GraphNode getAggregateNodeFromSelection() {
+ List<GraphNode> graphNodeList = graph.getSelection();
+ if (graphNodeList.isEmpty() || graphNodeList.size() != 1) {
+ graph.setSelection(null);
+ return null;
+ }
+
+ GraphNode node = null;
+ if (graphNodeList.get(0) != null) {
+ node = graphNodeList.remove(0);
+ } else {
+ graph.setSelection(null);
+ return null;
+ }
+ return node;
+ }
+
+ private void controlDoubleClick() {
+ if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_AGGREGATE) {
+ GraphNode node = getAggregateNodeFromSelection();
+
+ if (node == null) {
+ return;
+ }
+
+ String functionName = (String) node.getData("AGGREGATE_NAME"); //$NON-NLS-1$
+ FileFinderOpener.findAndOpen(graph.getProject(), functionName);
+ node.unhighlight();
+ } else {
+ StapNode node = getNodeFromSelection();
+
+ if (node == null) {
+ return;
+ }
+
+ int caller = node.getData().id;
+
+ if (caller < graph.getFirstUsefulNode()) {
+ // The only node that satisfies this condition should be main
+ caller = graph.getFirstUsefulNode();
+ }
+ FileFinderOpener.findAndOpen(graph.getProject(), graph.getNodeData(caller).name);
+ node.unhighlight();
+ }
+
+ graph.setSelection(null);
+ }
+
+ public void mouseDownEvent(int x, int y) {
+ List<?> list = graph.getSelection();
+ if (list.size() < 1) {
+ listener.setPoint(x, y);
+ listener.setStop(false);
+ graph.addMouseMoveListener(listener);
+ graph.addListener(SWT.MouseExit, exitListener);
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseMoveListener.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseMoveListener.java
index c7f6ad7798..8f24bc46be 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseMoveListener.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseMoveListener.java
@@ -17,67 +17,67 @@ import org.eclipse.swt.events.MouseMoveListener;
public class StapGraphMouseMoveListener implements MouseMoveListener {
- private StapGraph graph;
- private int prevX;
- private int prevY;
- private static final int INIT = -20000;
- private boolean stop;
- private boolean showMessage;
+ private StapGraph graph;
+ private int prevX;
+ private int prevY;
+ private static final int INIT = -20000;
+ private boolean stop;
+ private boolean showMessage;
- public StapGraphMouseMoveListener(StapGraph graph) {
- this.graph = graph;
- prevX = INIT;
- prevY = INIT;
- showMessage = true;
- }
+ public StapGraphMouseMoveListener(StapGraph graph) {
+ this.graph = graph;
+ prevX = INIT;
+ prevY = INIT;
+ showMessage = true;
+ }
- public void setPoint(int x, int y) {
- prevX = x;
- prevY = y;
- }
+ public void setPoint(int x, int y) {
+ prevX = x;
+ prevY = y;
+ }
- public void setStop(boolean val) {
- stop = val;
- }
+ public void setStop(boolean val) {
+ stop = val;
+ }
- @Override
- public void mouseMove(MouseEvent e) {
- //-------------Panning
- //TODO: Implement panning at this zoom and mode
- //For some reason getting rid of some of the /scale's in drawTree
- //Will fix panning, but at the cost of making the drawTree zoom look weird
+ @Override
+ public void mouseMove(MouseEvent e) {
+ //-------------Panning
+ //TODO: Implement panning at this zoom and mode
+ //For some reason getting rid of some of the /scale's in drawTree
+ //Will fix panning, but at the cost of making the drawTree zoom look weird
- if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_TREE) {
-// if (graph.scale < 0.63) {
- if (showMessage) {
-// SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
-// Messages.StapGraphMouseMoveListener_0, Messages.StapGraphMouseMoveListener_1,
-// Messages.StapGraphMouseMoveListener_2);
-// mess.schedule();
- showMessage = false;
- }
- return;
- }
+ if (graph.getDrawMode() == StapGraph.CONSTANT_DRAWMODE_TREE) {
+// if (graph.scale < 0.63) {
+ if (showMessage) {
+// SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(
+// Messages.StapGraphMouseMoveListener_0, Messages.StapGraphMouseMoveListener_1,
+// Messages.StapGraphMouseMoveListener_2);
+// mess.schedule();
+ showMessage = false;
+ }
+ return;
+ }
- //Initialize
- if (prevX == INIT && prevY == INIT) {
- prevX = e.x;
- prevY = e.y;
- return;
- }
+ //Initialize
+ if (prevX == INIT && prevY == INIT) {
+ prevX = e.x;
+ prevY = e.y;
+ return;
+ }
- if (!stop) {
- int yDiff, xDiff;
- xDiff = prevX - e.x;
- yDiff = prevY - e.y;
- if (graph.scale > 1) {
- graph.scrollSmoothBy((int) (xDiff/graph.scale), (int) (yDiff/graph.scale));
- } else {
- graph.scrollSmoothBy(xDiff, yDiff);
- }
+ if (!stop) {
+ int yDiff, xDiff;
+ xDiff = prevX - e.x;
+ yDiff = prevY - e.y;
+ if (graph.scale > 1) {
+ graph.scrollSmoothBy((int) (xDiff/graph.scale), (int) (yDiff/graph.scale));
+ } else {
+ graph.scrollSmoothBy(xDiff, yDiff);
+ }
- prevX = e.x;
- prevY = e.y;
- }
- }
+ prevX = e.x;
+ prevY = e.y;
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseWheelListener.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseWheelListener.java
index eb3889f8cb..f535ff711c 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseWheelListener.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/graphlisteners/StapGraphMouseWheelListener.java
@@ -4,7 +4,7 @@
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
- *
+ *
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
@@ -20,57 +20,57 @@ import org.eclipse.swt.events.MouseWheelListener;
*
*/
public class StapGraphMouseWheelListener implements MouseWheelListener {
- private StapGraph graph;
-
- public StapGraphMouseWheelListener(StapGraph g) {
- this.graph = g;
- }
-
+ private StapGraph graph;
+
+ public StapGraphMouseWheelListener(StapGraph g) {
+ this.graph = g;
+ }
+
+
+ @Override
+ public void mouseScrolled(MouseEvent e) {
+ if (e.stateMask != SWT.CTRL) {
+ // Scrolling
+ if (e.count > 0) {
+ AutoScrollHelper.scrollUp(graph);
+ } else {
+ AutoScrollHelper.scrollDown(graph);
+ }
+ return;
+ }
+
+ if (graph.getDrawMode() != StapGraph.CONSTANT_DRAWMODE_LEVEL &&
+ graph.getDrawMode() != StapGraph.CONSTANT_DRAWMODE_TREE) {
+ return;
+ }
+
+ if (e.count <= 0) {
+ if (graph.scale < 2){
+ graph.scale /= (10.0 / 11.0);
+ }else{
+ graph.scale = (int)graph.scale + 1;
+ }
+
+ }else {
+ if (graph.scale <= 2){
+ graph.scale *= (10.0 / 11.0);
+ } else {
+ graph.scale = (int) graph.scale - 1;
+ }
+ }
- @Override
- public void mouseScrolled(MouseEvent e) {
- if (e.stateMask != SWT.CTRL) {
- // Scrolling
- if (e.count > 0) {
- AutoScrollHelper.scrollUp(graph);
- } else {
- AutoScrollHelper.scrollDown(graph);
- }
- return;
- }
-
- if (graph.getDrawMode() != StapGraph.CONSTANT_DRAWMODE_LEVEL &&
- graph.getDrawMode() != StapGraph.CONSTANT_DRAWMODE_TREE) {
- return;
- }
+ int currentAnimationMode = graph.getAnimationMode();
+ graph.draw(graph.getDrawMode(), StapGraph.CONSTANT_ANIMATION_FASTEST,
+ graph.getRootVisibleNodeNumber());
+ graph.setAnimationMode(currentAnimationMode);
- if (e.count <= 0) {
- if (graph.scale < 2){
- graph.scale /= (10.0 / 11.0);
- }else{
- graph.scale = (int)graph.scale + 1;
- }
+ int realeX = 3 * (int)(e.x / graph.scale);
+ int realeY = 3 * (int)(e.y / graph.scale);
+ int xDiff = (realeX - graph.getSize().x);
+ int yDiff = (realeY - graph.getSize().y);
- }else {
- if (graph.scale <= 2){
- graph.scale *= (10.0 / 11.0);
- } else {
- graph.scale = (int) graph.scale - 1;
- }
- }
-
- int currentAnimationMode = graph.getAnimationMode();
- graph.draw(graph.getDrawMode(), StapGraph.CONSTANT_ANIMATION_FASTEST,
- graph.getRootVisibleNodeNumber());
- graph.setAnimationMode(currentAnimationMode);
-
- int realeX = 3 * (int)(e.x / graph.scale);
- int realeY = 3 * (int)(e.y / graph.scale);
- int xDiff = (realeX - graph.getSize().x);
- int yDiff = (realeY - graph.getSize().y);
-
- graph.scrollTo(realeX + xDiff, realeY - yDiff);
- }
+ graph.scrollTo(realeX + xDiff, realeY - yDiff);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeContentProvider.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeContentProvider.java
index ca3da627b0..f063184ede 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeContentProvider.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeContentProvider.java
@@ -20,56 +20,56 @@ import org.eclipse.linuxtools.internal.callgraph.StapGraph;
public class StapTreeContentProvider implements ITreeContentProvider{
- private StapGraph graph;
+ private StapGraph graph;
- @Override
- public Object[] getChildren(Object parentElement) {
- List<StapData> empty = new ArrayList<>();
- if (parentElement instanceof StapData) {
- StapData parent = ((StapData) parentElement);
- List<Integer> childrenIDs = parent.collapsedChildren;
- for (int val : childrenIDs) {
- if (graph.getNodeData(val) != null) {
- empty.add(graph.getNodeData(val));
- }
- }
- }
- return empty.toArray();
- }
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ List<StapData> empty = new ArrayList<>();
+ if (parentElement instanceof StapData) {
+ StapData parent = ((StapData) parentElement);
+ List<Integer> childrenIDs = parent.collapsedChildren;
+ for (int val : childrenIDs) {
+ if (graph.getNodeData(val) != null) {
+ empty.add(graph.getNodeData(val));
+ }
+ }
+ }
+ return empty.toArray();
+ }
- @Override
- public Object getParent(Object element) {
- if (element instanceof StapData) {
- return graph.getNodeData(((StapData) element).collapsedParent);
- }
- return null;
- }
+ @Override
+ public Object getParent(Object element) {
+ if (element instanceof StapData) {
+ return graph.getNodeData(((StapData) element).collapsedParent);
+ }
+ return null;
+ }
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof StapData) {
- return ((StapData) element).children.size() > 0;
- }
- return false;
- }
+ @Override
+ public boolean hasChildren(Object element) {
+ if (element instanceof StapData) {
+ return ((StapData) element).children.size() > 0;
+ }
+ return false;
+ }
- @Override
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
+ @Override
+ public Object[] getElements(Object inputElement) {
+ return getChildren(inputElement);
+ }
- @Override
- public void dispose() {
- //Empty
- }
+ @Override
+ public void dispose() {
+ //Empty
+ }
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- //Empty
- }
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ //Empty
+ }
- public void setGraph(StapGraph graph) {
- this.graph = graph;
- }
+ public void setGraph(StapGraph graph) {
+ this.graph = graph;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeDoubleClickListener.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeDoubleClickListener.java
index bfae34c2d7..fe1209fd9f 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeDoubleClickListener.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeDoubleClickListener.java
@@ -21,36 +21,36 @@ import org.eclipse.linuxtools.internal.callgraph.StapGraph;
public class StapTreeDoubleClickListener implements IDoubleClickListener {
- private StapGraph graph;
- private TreeViewer viewer;
-
- public StapTreeDoubleClickListener(TreeViewer t , StapGraph g) {
- this.graph = g;
- this.viewer = t;
- }
-
- @Override
- public void doubleClick(DoubleClickEvent event) {
- if (!(event.getSelection() instanceof IStructuredSelection)) {
- return;
- }
- IStructuredSelection selection = (IStructuredSelection) event.getSelection();
- if (selection.size() != 1) {
- return;
- }
-
-
- //Expand the current node in the tree viewer and on the graph
+ private StapGraph graph;
+ private TreeViewer viewer;
+
+ public StapTreeDoubleClickListener(TreeViewer t , StapGraph g) {
+ this.graph = g;
+ this.viewer = t;
+ }
+
+ @Override
+ public void doubleClick(DoubleClickEvent event) {
+ if (!(event.getSelection() instanceof IStructuredSelection)) {
+ return;
+ }
+ IStructuredSelection selection = (IStructuredSelection) event.getSelection();
+ if (selection.size() != 1) {
+ return;
+ }
+
+
+ //Expand the current node in the tree viewer and on the graph
for (Iterator<?> iterator = selection.iterator(); iterator.hasNext();) {
- StapData data = (StapData) iterator.next();
- viewer.collapseToLevel(data, 1);
- viewer.expandToLevel(data, 1);
- graph.setCollapseMode(true);
- graph.draw(data.id);
- graph.getNode(data.id).unhighlight();
+ StapData data = (StapData) iterator.next();
+ viewer.collapseToLevel(data, 1);
+ viewer.expandToLevel(data, 1);
+ graph.setCollapseMode(true);
+ graph.draw(data.id);
+ graph.getNode(data.id).unhighlight();
}
graph.setFocus();
- }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeLabelProvider.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeLabelProvider.java
index c3a8ae2294..c5228f5ab5 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeLabelProvider.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeLabelProvider.java
@@ -18,24 +18,24 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
public class StapTreeLabelProvider extends LabelProvider {
- @Override
- public Image getImage(Object element) {
- Image im = null;
- if ( ((StapData) element).isMarked()) {
- im = AbstractUIPlugin.imageDescriptorFromPlugin(CallGraphConstants.PLUGIN_ID, "/icons/public_co.gif").createImage(); //$NON-NLS-1$
- } else {
- im = AbstractUIPlugin.imageDescriptorFromPlugin(CallGraphConstants.PLUGIN_ID, "/icons/compare_method.gif").createImage(); //$NON-NLS-1$
- }
- return im;
- }
+ @Override
+ public Image getImage(Object element) {
+ Image im = null;
+ if ( ((StapData) element).isMarked()) {
+ im = AbstractUIPlugin.imageDescriptorFromPlugin(CallGraphConstants.PLUGIN_ID, "/icons/public_co.gif").createImage(); //$NON-NLS-1$
+ } else {
+ im = AbstractUIPlugin.imageDescriptorFromPlugin(CallGraphConstants.PLUGIN_ID, "/icons/compare_method.gif").createImage(); //$NON-NLS-1$
+ }
+ return im;
+ }
- @Override
- public String getText(Object element) {
- return ((StapData) element).timesCalled + ": " + ((StapData) element).name; //$NON-NLS-1$
- }
+ @Override
+ public String getText(Object element) {
+ return ((StapData) element).timesCalled + ": " + ((StapData) element).name; //$NON-NLS-1$
+ }
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeListener.java b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeListener.java
index 42ab297ee0..4e830ddffa 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeListener.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph/src/org/eclipse/linuxtools/internal/callgraph/treeviewer/StapTreeListener.java
@@ -20,51 +20,51 @@ import org.eclipse.linuxtools.internal.callgraph.StapData;
import org.eclipse.swt.widgets.ScrollBar;
public class StapTreeListener implements ITreeViewerListener{
- private static final int INCREMENT = 15;
+ private static final int INCREMENT = 15;
- private int highestLevelOfExpansion;
- private ScrollBar scrollbar;
- private HashMap<Integer, List<Integer>> highestLevelNodes;
- //Level of recursion, list of nodes at that level currently displayed in tree
+ private int highestLevelOfExpansion;
+ private ScrollBar scrollbar;
+ private HashMap<Integer, List<Integer>> highestLevelNodes;
+ //Level of recursion, list of nodes at that level currently displayed in tree
- /**
- * Autoscroll the horizontal scrollbar when there is a collapse event.
- *
- */
- @Override
- public void treeCollapsed(TreeExpansionEvent event) {
- StapData data = (StapData) event.getElement();
- if (highestLevelNodes.get(highestLevelOfExpansion) != null
- && highestLevelNodes.get(highestLevelOfExpansion).remove((Integer) data.id)) {
- scrollbar.setSelection(scrollbar.getSelection() - INCREMENT);
- highestLevelOfExpansion--;
- }
+ /**
+ * Autoscroll the horizontal scrollbar when there is a collapse event.
+ *
+ */
+ @Override
+ public void treeCollapsed(TreeExpansionEvent event) {
+ StapData data = (StapData) event.getElement();
+ if (highestLevelNodes.get(highestLevelOfExpansion) != null
+ && highestLevelNodes.get(highestLevelOfExpansion).remove((Integer) data.id)) {
+ scrollbar.setSelection(scrollbar.getSelection() - INCREMENT);
+ highestLevelOfExpansion--;
+ }
- }
+ }
- /**
- * Autoscroll the horizontal scrollbar when there is an expand event.
- *
- */
- @Override
- public void treeExpanded(TreeExpansionEvent event) {
- StapData d = ((StapData) event.getElement());
- if (d.levelOfRecursion > highestLevelOfExpansion) {
- scrollbar.setSelection(scrollbar.getSelection() + INCREMENT);
- highestLevelOfExpansion = ((StapData) event.getElement()).levelOfRecursion;
- }
+ /**
+ * Autoscroll the horizontal scrollbar when there is an expand event.
+ *
+ */
+ @Override
+ public void treeExpanded(TreeExpansionEvent event) {
+ StapData d = ((StapData) event.getElement());
+ if (d.levelOfRecursion > highestLevelOfExpansion) {
+ scrollbar.setSelection(scrollbar.getSelection() + INCREMENT);
+ highestLevelOfExpansion = ((StapData) event.getElement()).levelOfRecursion;
+ }
- int lvl = d.levelOfRecursion;
- if (highestLevelNodes.get(lvl) == null) {
- highestLevelNodes.put(lvl, new ArrayList<Integer>());
- }
- highestLevelNodes.get(lvl).add(d.id);
- }
+ int lvl = d.levelOfRecursion;
+ if (highestLevelNodes.get(lvl) == null) {
+ highestLevelNodes.put(lvl, new ArrayList<Integer>());
+ }
+ highestLevelNodes.get(lvl).add(d.id);
+ }
- public StapTreeListener(ScrollBar bar) {
- this.highestLevelOfExpansion=0;
- this.scrollbar = bar;
- highestLevelNodes = new HashMap<>();
- }
+ public StapTreeListener(ScrollBar bar) {
+ this.highestLevelOfExpansion=0;
+ this.scrollbar = bar;
+ highestLevelNodes = new HashMap<>();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap-feature/pom.xml b/systemtap/org.eclipse.linuxtools.systemtap-feature/pom.xml
index 5c5ea0f4fe..9f9d49f55e 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap-feature/pom.xml
+++ b/systemtap/org.eclipse.linuxtools.systemtap-feature/pom.xml
@@ -21,7 +21,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools SystemTap IDE and Visualization Tools Feature</name>
-
+
<build>
<plugins>
<plugin>
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/pom.xml b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/pom.xml
index 48b7ad6155..e42c058c13 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/pom.xml
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/pom.xml
@@ -36,7 +36,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.systemtap.graphing.core.tests</testSuite>
<testClass>org.eclipse.linuxtools.systemtap.graphing.core.tests.AllTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.platform.ide</product>
</configuration>
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/AllTests.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/AllTests.java
index 68987c6bf4..0f5b136dd5 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/AllTests.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/AllTests.java
@@ -36,31 +36,31 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({// Aggregates
- AverageAggregateTest.class,
- CountAggregateTest.class,
- MaxAggregateTest.class,
- MinAggregateTest.class,
- SumAggregateTest.class,
+ AverageAggregateTest.class,
+ CountAggregateTest.class,
+ MaxAggregateTest.class,
+ MinAggregateTest.class,
+ SumAggregateTest.class,
- // DataSets
+ // DataSets
- // DataSets.Row
- FilteredRowDataSetTest.class,
- RowDataSetTest.class,
- RowEntryTest.class,
- RowParserTest.class,
+ // DataSets.Row
+ FilteredRowDataSetTest.class,
+ RowDataSetTest.class,
+ RowEntryTest.class,
+ RowParserTest.class,
- // DataSets.Table
- FilteredTableDataSetTest.class, TableDataSetTest.class,
- TableEntryTest.class,
- TableParserTest.class,
+ // DataSets.Table
+ FilteredTableDataSetTest.class, TableDataSetTest.class,
+ TableEntryTest.class,
+ TableParserTest.class,
- // Filters
- MatchFilterTest.class, RangeFilterTest.class, SortFilterTest.class,
- UniqueFilterTest.class,
+ // Filters
+ MatchFilterTest.class, RangeFilterTest.class, SortFilterTest.class,
+ UniqueFilterTest.class,
- // Structures
- ChartStreamDaemonTest.class, NumberTypeTest.class,
- UpdateManagerTest.class })
+ // Structures
+ ChartStreamDaemonTest.class, NumberTypeTest.class,
+ UpdateManagerTest.class })
public class AllTests {
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/MockDataSet.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/MockDataSet.java
index ffd1c8b857..58903d60bb 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/MockDataSet.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/MockDataSet.java
@@ -18,58 +18,58 @@ import org.eclipse.linuxtools.systemtap.graphing.core.datasets.row.RowEntry;
public final class MockDataSet {
- public static RowDataSet buildDataSet(int rows, int cols) {
- String[] titles = new String[cols];
- int i;
- for(i=0; i<cols; i++)
- titles[i] = ""+ i;
-
- RowDataSet data = new RowDataSet(titles);
- RowEntry entry;
-
- int j;
- for(i=0; i<rows; i++) {
- Object[] d = new Object[cols];
- for(j=0; j< cols; j++) {
- d[j] = new Double(i*cols + j);
- }
- entry = new RowEntry();
- entry.putRow(0, d);
- data.append(entry);
- }
- return data;
- }
-
- public static ArrayList<Object>[] buildArray(int width, int height, int wrap) {
- ArrayList<Object>[] list = createArrayList(width, new Object());
-
- for(int i=0; i<width; i++) {
- list[i] = new ArrayList<>();
- for(int j=0; j<height; j++) {
- list[i].add("" + ((j+i) % wrap));
- }
- }
- return list;
- }
-
- @SuppressWarnings("unchecked")
- public static <T> ArrayList<T>[] createArrayList(int size, T instance) {
- return new ArrayList[size];
- }
+ public static RowDataSet buildDataSet(int rows, int cols) {
+ String[] titles = new String[cols];
+ int i;
+ for(i=0; i<cols; i++)
+ titles[i] = ""+ i;
- public static Integer[] buildIntegerArray(int[] arr) {
- Integer[] ints = new Integer[arr.length];
- for(int i=0; i<arr.length; i++) {
- ints[i] = Integer.valueOf(arr[i]);
- }
- return ints;
- }
-
- public static Double[] buildDoubleArray(double[] arr) {
- Double[] doubles = new Double[arr.length];
- for(int i=0; i<arr.length; i++) {
- doubles[i] = Double.valueOf(arr[i]);
- }
- return doubles;
- }
+ RowDataSet data = new RowDataSet(titles);
+ RowEntry entry;
+
+ int j;
+ for(i=0; i<rows; i++) {
+ Object[] d = new Object[cols];
+ for(j=0; j< cols; j++) {
+ d[j] = new Double(i*cols + j);
+ }
+ entry = new RowEntry();
+ entry.putRow(0, d);
+ data.append(entry);
+ }
+ return data;
+ }
+
+ public static ArrayList<Object>[] buildArray(int width, int height, int wrap) {
+ ArrayList<Object>[] list = createArrayList(width, new Object());
+
+ for(int i=0; i<width; i++) {
+ list[i] = new ArrayList<>();
+ for(int j=0; j<height; j++) {
+ list[i].add("" + ((j+i) % wrap));
+ }
+ }
+ return list;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> ArrayList<T>[] createArrayList(int size, T instance) {
+ return new ArrayList[size];
+ }
+
+ public static Integer[] buildIntegerArray(int[] arr) {
+ Integer[] ints = new Integer[arr.length];
+ for(int i=0; i<arr.length; i++) {
+ ints[i] = Integer.valueOf(arr[i]);
+ }
+ return ints;
+ }
+
+ public static Double[] buildDoubleArray(double[] arr) {
+ Double[] doubles = new Double[arr.length];
+ for(int i=0; i<arr.length; i++) {
+ doubles[i] = Double.valueOf(arr[i]);
+ }
+ return doubles;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/AverageAggregateTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/AverageAggregateTest.java
index e82d937afd..2fc5d535e4 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/AverageAggregateTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/AverageAggregateTest.java
@@ -20,41 +20,41 @@ import org.junit.Test;
public class AverageAggregateTest {
- @Test
- public void testAggregate() {
- AverageAggregate aa = new AverageAggregate();
- Number num;
-
- num = aa.aggregate(null);
- assertNull(num);
-
- num = aa.aggregate(new Number[] {});
- assertNull(num);
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,0}));
- assertEquals(0, num.intValue());
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {-1,0,1}));
- assertEquals(0, num.intValue());
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,1}));
- assertEquals(0, num.intValue());
-
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,0}));
- assertEquals(0.0, num.doubleValue(), 0.0);
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {-1,0,1}));
- assertEquals(0.0, num.doubleValue(), 0.0);
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,1}));
- assertEquals(1.0/3.0, num.doubleValue(), 0.0);
- }
-
- @Test
- public void testGetID() {
- AverageAggregate aa = new AverageAggregate();
- assertEquals(AverageAggregate.ID, aa.getID());
- }
-
+ @Test
+ public void testAggregate() {
+ AverageAggregate aa = new AverageAggregate();
+ Number num;
+
+ num = aa.aggregate(null);
+ assertNull(num);
+
+ num = aa.aggregate(new Number[] {});
+ assertNull(num);
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,0}));
+ assertEquals(0, num.intValue());
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {-1,0,1}));
+ assertEquals(0, num.intValue());
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,1}));
+ assertEquals(0, num.intValue());
+
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,0}));
+ assertEquals(0.0, num.doubleValue(), 0.0);
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {-1,0,1}));
+ assertEquals(0.0, num.doubleValue(), 0.0);
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,1}));
+ assertEquals(1.0/3.0, num.doubleValue(), 0.0);
+ }
+
+ @Test
+ public void testGetID() {
+ AverageAggregate aa = new AverageAggregate();
+ assertEquals(AverageAggregate.ID, aa.getID());
+ }
+
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/CountAggregateTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/CountAggregateTest.java
index 5ac79b3643..1aa84d8d90 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/CountAggregateTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/CountAggregateTest.java
@@ -20,41 +20,41 @@ import org.junit.Test;
public class CountAggregateTest {
- @Test
- public void testAggregate() {
- CountAggregate aa = new CountAggregate();
- Number num;
-
- num = aa.aggregate(null);
- assertNull(num);
-
- num = aa.aggregate(new Number[] {});
- assertNull(num);
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,0}));
- assertEquals(3, num.intValue());
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {-1,0}));
- assertEquals(2, num.intValue());
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,1,2,3}));
- assertEquals(5, num.intValue());
-
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,0}));
- assertEquals(3, num.doubleValue(), 0.0);
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {-1,1}));
- assertEquals(2, num.doubleValue(), 0.0);
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,1,4,5}));
- assertEquals(5, num.doubleValue(), 0.0);
- }
-
- @Test
- public void testGetID() {
- CountAggregate aa = new CountAggregate();
- assertEquals(CountAggregate.ID, aa.getID());
- }
-
+ @Test
+ public void testAggregate() {
+ CountAggregate aa = new CountAggregate();
+ Number num;
+
+ num = aa.aggregate(null);
+ assertNull(num);
+
+ num = aa.aggregate(new Number[] {});
+ assertNull(num);
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,0}));
+ assertEquals(3, num.intValue());
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {-1,0}));
+ assertEquals(2, num.intValue());
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,1,2,3}));
+ assertEquals(5, num.intValue());
+
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,0}));
+ assertEquals(3, num.doubleValue(), 0.0);
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {-1,1}));
+ assertEquals(2, num.doubleValue(), 0.0);
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,1,4,5}));
+ assertEquals(5, num.doubleValue(), 0.0);
+ }
+
+ @Test
+ public void testGetID() {
+ CountAggregate aa = new CountAggregate();
+ assertEquals(CountAggregate.ID, aa.getID());
+ }
+
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/MaxAggregateTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/MaxAggregateTest.java
index 4ba2611ae7..591f58a67a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/MaxAggregateTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/MaxAggregateTest.java
@@ -20,40 +20,40 @@ import org.junit.Test;
public class MaxAggregateTest {
- @Test
- public void testAggregate() {
- MaxAggregate aa = new MaxAggregate();
- Number num;
-
- num = aa.aggregate(null);
- assertNull(num);
-
- num = aa.aggregate(new Number[] {});
- assertNull(num);
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,0}));
- assertEquals(0, num.intValue());
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {-1,0,1}));
- assertEquals(1, num.intValue());
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,1}));
- assertEquals(1, num.intValue());
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,0}));
- assertEquals(0.0, num.doubleValue(), 0.0);
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {-1,0,1}));
- assertEquals(1.0, num.doubleValue(), 0.0);
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,1,2}));
- assertEquals(2.0, num.doubleValue(), 0.0);
- }
-
- @Test
- public void testGetID() {
- MaxAggregate aa = new MaxAggregate();
- assertEquals(MaxAggregate.ID, aa.getID());
- }
-
+ @Test
+ public void testAggregate() {
+ MaxAggregate aa = new MaxAggregate();
+ Number num;
+
+ num = aa.aggregate(null);
+ assertNull(num);
+
+ num = aa.aggregate(new Number[] {});
+ assertNull(num);
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,0}));
+ assertEquals(0, num.intValue());
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {-1,0,1}));
+ assertEquals(1, num.intValue());
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,1}));
+ assertEquals(1, num.intValue());
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,0}));
+ assertEquals(0.0, num.doubleValue(), 0.0);
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {-1,0,1}));
+ assertEquals(1.0, num.doubleValue(), 0.0);
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,1,2}));
+ assertEquals(2.0, num.doubleValue(), 0.0);
+ }
+
+ @Test
+ public void testGetID() {
+ MaxAggregate aa = new MaxAggregate();
+ assertEquals(MaxAggregate.ID, aa.getID());
+ }
+
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/MinAggregateTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/MinAggregateTest.java
index b0a3dd69a3..9c1efd3dcd 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/MinAggregateTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/MinAggregateTest.java
@@ -20,41 +20,41 @@ import org.junit.Test;
public class MinAggregateTest {
- @Test
- public void testAggregate() {
- MinAggregate aa = new MinAggregate();
- Number num;
-
- num = aa.aggregate(null);
- assertNull(num);
-
- num = aa.aggregate(new Number[] {});
- assertNull(num);
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,0}));
- assertEquals(0, num.intValue());
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {-1,0,1}));
- assertEquals(-1, num.intValue());
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,1}));
- assertEquals(0, num.intValue());
-
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,0}));
- assertEquals(0.0, num.doubleValue(), 0.0);
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {-1,0,1}));
- assertEquals(-1.0, num.doubleValue(), 0.0);
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,1}));
- assertEquals(0.0, num.doubleValue(), 0.0);
- }
-
- @Test
- public void testGetID() {
- MinAggregate aa = new MinAggregate();
- assertEquals(MinAggregate.ID, aa.getID());
- }
-
+ @Test
+ public void testAggregate() {
+ MinAggregate aa = new MinAggregate();
+ Number num;
+
+ num = aa.aggregate(null);
+ assertNull(num);
+
+ num = aa.aggregate(new Number[] {});
+ assertNull(num);
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,0}));
+ assertEquals(0, num.intValue());
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {-1,0,1}));
+ assertEquals(-1, num.intValue());
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,1}));
+ assertEquals(0, num.intValue());
+
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,0}));
+ assertEquals(0.0, num.doubleValue(), 0.0);
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {-1,0,1}));
+ assertEquals(-1.0, num.doubleValue(), 0.0);
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,1}));
+ assertEquals(0.0, num.doubleValue(), 0.0);
+ }
+
+ @Test
+ public void testGetID() {
+ MinAggregate aa = new MinAggregate();
+ assertEquals(MinAggregate.ID, aa.getID());
+ }
+
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/SumAggregateTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/SumAggregateTest.java
index 8ec07f4f16..e751133400 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/SumAggregateTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/aggregates/SumAggregateTest.java
@@ -20,42 +20,42 @@ import org.junit.Test;
public class SumAggregateTest {
- @Test
- public void testAggregate() {
- SumAggregate aa = new SumAggregate();
- Number num;
-
- num = aa.aggregate(null);
- assertNull(num);
-
- num = aa.aggregate(new Number[] {});
- assertNull(num);
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,0}));
- assertEquals(0, num.intValue());
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {-1,0,1}));
- assertEquals(0, num.intValue());
-
- num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,1}));
- assertEquals(1, num.intValue());
-
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,0}));
- assertEquals(0.0, num.doubleValue(), 0.0);
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {-1,0,1}));
- assertEquals(0.0, num.doubleValue(), 0.0);
-
- num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,1,2}));
- assertEquals(3.0, num.doubleValue(), 0.0);
- }
-
- @Test
- public void testGetID() {
- SumAggregate aa = new SumAggregate();
- assertEquals(SumAggregate.ID, aa.getID());
- }
-
-
+ @Test
+ public void testAggregate() {
+ SumAggregate aa = new SumAggregate();
+ Number num;
+
+ num = aa.aggregate(null);
+ assertNull(num);
+
+ num = aa.aggregate(new Number[] {});
+ assertNull(num);
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,0}));
+ assertEquals(0, num.intValue());
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {-1,0,1}));
+ assertEquals(0, num.intValue());
+
+ num = aa.aggregate(MockDataSet.buildIntegerArray(new int[] {0,0,1}));
+ assertEquals(1, num.intValue());
+
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,0}));
+ assertEquals(0.0, num.doubleValue(), 0.0);
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {-1,0,1}));
+ assertEquals(0.0, num.doubleValue(), 0.0);
+
+ num = aa.aggregate(MockDataSet.buildDoubleArray(new double[] {0,0,1,2}));
+ assertEquals(3.0, num.doubleValue(), 0.0);
+ }
+
+ @Test
+ public void testGetID() {
+ SumAggregate aa = new SumAggregate();
+ assertEquals(SumAggregate.ID, aa.getID());
+ }
+
+
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/FilteredRowDataSetTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/FilteredRowDataSetTest.java
index 6e63a89eb0..c45098f858 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/FilteredRowDataSetTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/FilteredRowDataSetTest.java
@@ -30,262 +30,262 @@ import org.junit.Test;
public class FilteredRowDataSetTest {
- @Before
- public void setUp() {
- data = new RowDataSet(new String[] {"a", "b", "c"});
- fdata = new FilteredRowDataSet(data);
- new FilteredRowDataSet(data.getTitles());
-
- entry0 = new RowEntry();
- entry0.putRow(0, new String[] {"1", "2", "3"});
- data.setData(entry0);
- RowEntry entry = new RowEntry();
- entry.putRow(0, new String[] {"4", "5", "6"});
- data.setData(entry);
- }
-
- //Overwrite methods to insure data is removed from the original DataSet
- @Test
- public void testAppend() {
- assertEquals(2, data.getEntryCount());
- RowEntry entry = new RowEntry();
- entry.putRow(0, new String[] {"1", "2", "3"});
- fdata.append(entry);
- assertEquals(3, data.getEntryCount());
- }
-
- @Test
- public void testRemove() {
- assertFalse(fdata.remove(null));
- assertFalse(fdata.remove(new RowEntry()));
- assertFalse(fdata.remove(-1));
- assertFalse(fdata.remove(10));
- assertEquals(2, fdata.getEntryCount());
-
- IDataEntry entry = data.getEntry(0);
- assertTrue(fdata.remove(entry));
- assertEquals(1, fdata.getEntryCount());
- assertFalse(fdata.remove(entry));
- assertTrue(fdata.remove(0));
- }
- //End overwrite methods to insure data is removed from the original DataSet
-
- //Overwrite to ensure the data returned has all the filters applied
- @Test
- public void testGetColumn() {
- assertNull(fdata.getColumn(-3));
- assertNull(fdata.getColumn(10));
-
- assertNull(fdata.getColumn(-3, 0, 1));
- assertNull(fdata.getColumn(10, 0, 1));
- assertNull(fdata.getColumn(1, 3, 1));
- assertNull(fdata.getColumn(1, -2, 1));
- assertNull(fdata.getColumn(1, 0, 20));
-
- Object[] col = fdata.getColumn(0);
- assertEquals(2, col.length);
- assertSame("1", col[0]);
- assertSame("4", col[1]);
-
- col = fdata.getColumn(IDataSet.COL_ROW_NUM);
- assertEquals(2, col.length);
- assertEquals("1", col[0].toString());
- assertEquals("2", col[1].toString());
-
- col = fdata.getColumn(1, 0, 1);
- assertEquals(1, col.length);
- assertSame("2", col[0]);
- }
-
- @Test
- public void testGetRow() {
- assertNull(fdata.getRow(-3));
- assertNull(fdata.getRow(10));
-
- Object[] row = fdata.getRow(1);
- assertEquals(3, row.length);
- assertSame("5", row[1]);
- }
-
- @Test
- public void testGetHistoricalData() {
- assertNull(fdata.getHistoricalData(null, -3));
- assertNull(fdata.getHistoricalData(null, 10));
-
- assertNull(fdata.getHistoricalData(null, -3, 0, 1));
- assertNull(fdata.getHistoricalData(null, 10, 0, 1));
- assertNull(fdata.getHistoricalData(null, 1, 3, 1));
- assertNull(fdata.getHistoricalData(null, 1, -2, 1));
- assertNull(fdata.getHistoricalData(null, 1, 0, 20));
-
- Object[] col = fdata.getHistoricalData(null, 0);
- assertEquals(2, col.length);
- assertSame("1", col[0]);
- assertSame("4", col[1]);
-
- col = fdata.getHistoricalData(null, IDataSet.COL_ROW_NUM);
- assertEquals(2, col.length);
- assertEquals("1", col[0].toString());
- assertEquals("2", col[1].toString());
-
- col = fdata.getHistoricalData(null, 1, 0, 1);
- assertEquals(1, col.length);
- assertSame("2", col[0]);
- }
-
- @Test
- public void testGetEntryCount() {
- assertEquals(2, fdata.getEntryCount());
- }
-
- @Test
- public void testGetEntry() {
- assertNull(fdata.getEntry(-1));
- assertNull(fdata.getEntry(20));
- assertEquals(entry0, data.getEntry(0));
- }
- //End overwrite to ensure the data returned has all the filters applied
-
- //IFilteredDataSet Methods
- @Test
- public void testAddFilter() {
- data.remove(0);
- data.remove(0);
-
- RowEntry entry;
-
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {3, 2, 5});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {4, 2, 3});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {7, 2, 9});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {2, 2, 6});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {5, 2, 2});
- data.append(entry);
-
- fdata.addFilter(new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS));
-
- assertEquals(3, fdata.getRowCount());
- Object[] row = fdata.getRow(1);
- assertEquals(4, ((Integer)row[0]).intValue());
- assertEquals(3, ((Integer)row[2]).intValue());
-
- row = fdata.getRow(2);
- assertEquals(5, ((Integer)row[0]).intValue());
- assertEquals(2, ((Integer)row[1]).intValue());
-
-
- fdata.addFilter(new SortFilter(2, SortFilter.ASCENDING));
-
- assertEquals(3, fdata.getRowCount());
- row = fdata.getRow(0);
- assertEquals(5, ((Integer)row[0]).intValue());
- assertEquals(2, ((Integer)row[2]).intValue());
-
- row = fdata.getRow(1);
- assertEquals(4, ((Integer)row[0]).intValue());
- assertEquals(3, ((Integer)row[2]).intValue());
- }
-
- @Test
- public void testRemoveFilter() {
- data.remove(0);
- data.remove(0);
-
- RowEntry entry;
-
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {3, 2, 5});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {4, 2, 3});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {7, 2, 9});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {2, 2, 6});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {5, 2, 2});
- data.append(entry);
-
- RangeFilter filter = new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS);
- fdata.addFilter(filter);
- fdata.addFilter(new SortFilter(2, SortFilter.ASCENDING));
- fdata.removeFilter(filter);
-
-
- assertEquals(5, fdata.getRowCount());
- Object[] row = fdata.getRow(0);
- assertEquals(5, ((Integer)row[0]).intValue());
- assertEquals(2, ((Integer)row[2]).intValue());
-
- row = fdata.getRow(1);
- assertEquals(4, ((Integer)row[0]).intValue());
- assertEquals(3, ((Integer)row[2]).intValue());
- }
-
- @Test
- public void testClearFilters() {
- data.remove(0);
- data.remove(0);
-
- RowEntry entry;
-
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {3, 2, 5});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {4, 2, 3});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {7, 2, 9});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {2, 2, 6});
- data.append(entry);
- entry = new RowEntry();
- entry.putRow(0, new Integer[] {5, 2, 2});
- data.append(entry);
-
- RangeFilter filter = new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS);
- fdata.addFilter(filter);
- fdata.addFilter(new SortFilter(2, SortFilter.ASCENDING));
-
- fdata.clearFilters();
-
- assertEquals(5, fdata.getRowCount());
- Object[] row = fdata.getRow(0);
- assertEquals(3, ((Integer)row[0]).intValue());
- assertEquals(5, ((Integer)row[2]).intValue());
-
- row = fdata.getRow(1);
- assertEquals(4, ((Integer)row[0]).intValue());
- assertEquals(3, ((Integer)row[2]).intValue());
- }
- @Test
- public void testGetFilters() {
- assertEquals(0, fdata.getFilters().length);
-
- RangeFilter filter1 = new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS);
- SortFilter filter2 = new SortFilter(2, SortFilter.ASCENDING);
-
- fdata.addFilter(filter1);
- fdata.addFilter(filter2);
-
- IDataSetFilter[] filters = fdata.getFilters();
- assertEquals(2, filters.length);
- }
-
- private RowDataSet data;
- private FilteredRowDataSet fdata;
- private RowEntry entry0;
+ @Before
+ public void setUp() {
+ data = new RowDataSet(new String[] {"a", "b", "c"});
+ fdata = new FilteredRowDataSet(data);
+ new FilteredRowDataSet(data.getTitles());
+
+ entry0 = new RowEntry();
+ entry0.putRow(0, new String[] {"1", "2", "3"});
+ data.setData(entry0);
+ RowEntry entry = new RowEntry();
+ entry.putRow(0, new String[] {"4", "5", "6"});
+ data.setData(entry);
+ }
+
+ //Overwrite methods to insure data is removed from the original DataSet
+ @Test
+ public void testAppend() {
+ assertEquals(2, data.getEntryCount());
+ RowEntry entry = new RowEntry();
+ entry.putRow(0, new String[] {"1", "2", "3"});
+ fdata.append(entry);
+ assertEquals(3, data.getEntryCount());
+ }
+
+ @Test
+ public void testRemove() {
+ assertFalse(fdata.remove(null));
+ assertFalse(fdata.remove(new RowEntry()));
+ assertFalse(fdata.remove(-1));
+ assertFalse(fdata.remove(10));
+ assertEquals(2, fdata.getEntryCount());
+
+ IDataEntry entry = data.getEntry(0);
+ assertTrue(fdata.remove(entry));
+ assertEquals(1, fdata.getEntryCount());
+ assertFalse(fdata.remove(entry));
+ assertTrue(fdata.remove(0));
+ }
+ //End overwrite methods to insure data is removed from the original DataSet
+
+ //Overwrite to ensure the data returned has all the filters applied
+ @Test
+ public void testGetColumn() {
+ assertNull(fdata.getColumn(-3));
+ assertNull(fdata.getColumn(10));
+
+ assertNull(fdata.getColumn(-3, 0, 1));
+ assertNull(fdata.getColumn(10, 0, 1));
+ assertNull(fdata.getColumn(1, 3, 1));
+ assertNull(fdata.getColumn(1, -2, 1));
+ assertNull(fdata.getColumn(1, 0, 20));
+
+ Object[] col = fdata.getColumn(0);
+ assertEquals(2, col.length);
+ assertSame("1", col[0]);
+ assertSame("4", col[1]);
+
+ col = fdata.getColumn(IDataSet.COL_ROW_NUM);
+ assertEquals(2, col.length);
+ assertEquals("1", col[0].toString());
+ assertEquals("2", col[1].toString());
+
+ col = fdata.getColumn(1, 0, 1);
+ assertEquals(1, col.length);
+ assertSame("2", col[0]);
+ }
+
+ @Test
+ public void testGetRow() {
+ assertNull(fdata.getRow(-3));
+ assertNull(fdata.getRow(10));
+
+ Object[] row = fdata.getRow(1);
+ assertEquals(3, row.length);
+ assertSame("5", row[1]);
+ }
+
+ @Test
+ public void testGetHistoricalData() {
+ assertNull(fdata.getHistoricalData(null, -3));
+ assertNull(fdata.getHistoricalData(null, 10));
+
+ assertNull(fdata.getHistoricalData(null, -3, 0, 1));
+ assertNull(fdata.getHistoricalData(null, 10, 0, 1));
+ assertNull(fdata.getHistoricalData(null, 1, 3, 1));
+ assertNull(fdata.getHistoricalData(null, 1, -2, 1));
+ assertNull(fdata.getHistoricalData(null, 1, 0, 20));
+
+ Object[] col = fdata.getHistoricalData(null, 0);
+ assertEquals(2, col.length);
+ assertSame("1", col[0]);
+ assertSame("4", col[1]);
+
+ col = fdata.getHistoricalData(null, IDataSet.COL_ROW_NUM);
+ assertEquals(2, col.length);
+ assertEquals("1", col[0].toString());
+ assertEquals("2", col[1].toString());
+
+ col = fdata.getHistoricalData(null, 1, 0, 1);
+ assertEquals(1, col.length);
+ assertSame("2", col[0]);
+ }
+
+ @Test
+ public void testGetEntryCount() {
+ assertEquals(2, fdata.getEntryCount());
+ }
+
+ @Test
+ public void testGetEntry() {
+ assertNull(fdata.getEntry(-1));
+ assertNull(fdata.getEntry(20));
+ assertEquals(entry0, data.getEntry(0));
+ }
+ //End overwrite to ensure the data returned has all the filters applied
+
+ //IFilteredDataSet Methods
+ @Test
+ public void testAddFilter() {
+ data.remove(0);
+ data.remove(0);
+
+ RowEntry entry;
+
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {3, 2, 5});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {4, 2, 3});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {7, 2, 9});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {2, 2, 6});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {5, 2, 2});
+ data.append(entry);
+
+ fdata.addFilter(new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS));
+
+ assertEquals(3, fdata.getRowCount());
+ Object[] row = fdata.getRow(1);
+ assertEquals(4, ((Integer)row[0]).intValue());
+ assertEquals(3, ((Integer)row[2]).intValue());
+
+ row = fdata.getRow(2);
+ assertEquals(5, ((Integer)row[0]).intValue());
+ assertEquals(2, ((Integer)row[1]).intValue());
+
+
+ fdata.addFilter(new SortFilter(2, SortFilter.ASCENDING));
+
+ assertEquals(3, fdata.getRowCount());
+ row = fdata.getRow(0);
+ assertEquals(5, ((Integer)row[0]).intValue());
+ assertEquals(2, ((Integer)row[2]).intValue());
+
+ row = fdata.getRow(1);
+ assertEquals(4, ((Integer)row[0]).intValue());
+ assertEquals(3, ((Integer)row[2]).intValue());
+ }
+
+ @Test
+ public void testRemoveFilter() {
+ data.remove(0);
+ data.remove(0);
+
+ RowEntry entry;
+
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {3, 2, 5});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {4, 2, 3});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {7, 2, 9});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {2, 2, 6});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {5, 2, 2});
+ data.append(entry);
+
+ RangeFilter filter = new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS);
+ fdata.addFilter(filter);
+ fdata.addFilter(new SortFilter(2, SortFilter.ASCENDING));
+ fdata.removeFilter(filter);
+
+
+ assertEquals(5, fdata.getRowCount());
+ Object[] row = fdata.getRow(0);
+ assertEquals(5, ((Integer)row[0]).intValue());
+ assertEquals(2, ((Integer)row[2]).intValue());
+
+ row = fdata.getRow(1);
+ assertEquals(4, ((Integer)row[0]).intValue());
+ assertEquals(3, ((Integer)row[2]).intValue());
+ }
+
+ @Test
+ public void testClearFilters() {
+ data.remove(0);
+ data.remove(0);
+
+ RowEntry entry;
+
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {3, 2, 5});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {4, 2, 3});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {7, 2, 9});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {2, 2, 6});
+ data.append(entry);
+ entry = new RowEntry();
+ entry.putRow(0, new Integer[] {5, 2, 2});
+ data.append(entry);
+
+ RangeFilter filter = new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS);
+ fdata.addFilter(filter);
+ fdata.addFilter(new SortFilter(2, SortFilter.ASCENDING));
+
+ fdata.clearFilters();
+
+ assertEquals(5, fdata.getRowCount());
+ Object[] row = fdata.getRow(0);
+ assertEquals(3, ((Integer)row[0]).intValue());
+ assertEquals(5, ((Integer)row[2]).intValue());
+
+ row = fdata.getRow(1);
+ assertEquals(4, ((Integer)row[0]).intValue());
+ assertEquals(3, ((Integer)row[2]).intValue());
+ }
+ @Test
+ public void testGetFilters() {
+ assertEquals(0, fdata.getFilters().length);
+
+ RangeFilter filter1 = new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS);
+ SortFilter filter2 = new SortFilter(2, SortFilter.ASCENDING);
+
+ fdata.addFilter(filter1);
+ fdata.addFilter(filter2);
+
+ IDataSetFilter[] filters = fdata.getFilters();
+ assertEquals(2, filters.length);
+ }
+
+ private RowDataSet data;
+ private FilteredRowDataSet fdata;
+ private RowEntry entry0;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowDataSetTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowDataSetTest.java
index 501a7aa2f8..0fea50b723 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowDataSetTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowDataSetTest.java
@@ -26,146 +26,146 @@ import org.junit.Test;
public class RowDataSetTest {
- @Before
- public void setUp() {
- data = new RowDataSet(new String[] {"a", "b", "c"});
- entry0 = new RowEntry();
- entry0.putRow(0, new String[] {"1", "2", "3"});
- data.setData(entry0);
- RowEntry entry = new RowEntry();
- entry.putRow(0, new String[] {"4", "5", "6"});
- data.setData(entry);
- }
-
- @Test
- public void testSetData() {
- assertEquals(2, data.getEntryCount());
- RowEntry entry = new RowEntry();
- entry.putRow(0, new String[] {"1", "2", "3"});
- data.setData(entry);
- assertEquals(3, data.getEntryCount());
- }
-
- @Test
- public void testAppend() {
- assertEquals(2, data.getEntryCount());
- RowEntry entry = new RowEntry();
- entry.putRow(0, new String[] {"1", "2", "3"});
- data.append(entry);
- assertEquals(3, data.getEntryCount());
- }
-
- @Test
- public void testGetTitles() {
- String[] titles = data.getTitles();
- assertEquals(3, titles.length);
- assertSame("a", titles[0]);
- }
- @Test
- public void testGetColumn() {
- assertNull(data.getColumn(-3));
- assertNull(data.getColumn(10));
-
- assertNull(data.getColumn(-3, 0, 1));
- assertNull(data.getColumn(10, 0, 1));
- assertNull(data.getColumn(1, 3, 1));
- assertNull(data.getColumn(1, -2, 1));
- assertNull(data.getColumn(1, 0, 20));
-
- Object[] col = data.getColumn(0);
- assertEquals(2, col.length);
- assertSame("1", col[0]);
- assertSame("4", col[1]);
-
- col = data.getColumn(IDataSet.COL_ROW_NUM);
- assertEquals(2, col.length);
- assertEquals("1", col[0].toString());
- assertEquals("2", col[1].toString());
-
- col = data.getColumn(1, 0, 1);
- assertEquals(1, col.length);
- assertSame("2", col[0]);
- }
- @Test
- public void testGetRow() {
- assertNull(data.getRow(-3));
- assertNull(data.getRow(10));
-
- Object[] row = data.getRow(1);
- assertEquals(3, row.length);
- assertSame("5", row[1]);
- }
- @Test
- public void testGetRowCount() {
- assertEquals(2, data.getRowCount());
- }
- @Test
- public void testGetColCount() {
- assertEquals(3, data.getColCount());
-
- assertEquals(-1, new RowDataSet(null).getColCount());
- }
- @Test
- public void testReadFromFile() {}
- @Test
- public void testWriteToFile() {}
- @Test
- public void testGetID() {
- assertEquals(RowDataSet.ID, data.getID());
- }
- //End IDataSet Methods
-
- //IHistoricalDataSet Methods
- @Test
- public void testGetHistoricalData() {
- assertNull(data.getHistoricalData(null, -3));
- assertNull(data.getHistoricalData(null, 10));
-
- assertNull(data.getHistoricalData(null, -3, 0, 1));
- assertNull(data.getHistoricalData(null, 10, 0, 1));
- assertNull(data.getHistoricalData(null, 1, 3, 1));
- assertNull(data.getHistoricalData(null, 1, -2, 1));
- assertNull(data.getHistoricalData(null, 1, 0, 20));
-
- Object[] col = data.getHistoricalData(null, 0);
- assertEquals(2, col.length);
- assertSame("1", col[0]);
- assertSame("4", col[1]);
-
- col = data.getHistoricalData(null, IDataSet.COL_ROW_NUM);
- assertEquals(2, col.length);
- assertEquals("1", col[0].toString());
- assertEquals("2", col[1].toString());
-
- col = data.getHistoricalData(null, 1, 0, 1);
- assertEquals(1, col.length);
- assertSame("2", col[0]);
- }
- @Test
- public void testGetEntryCount() {
- assertEquals(2, data.getEntryCount());
- }
- @Test
- public void testRemove() {
- assertFalse(data.remove(null));
- assertFalse(data.remove(new RowEntry()));
- assertFalse(data.remove(-1));
- assertFalse(data.remove(10));
- assertEquals(2, data.getEntryCount());
-
- IDataEntry entry = data.getEntry(0);
- assertTrue(data.remove(entry));
- assertEquals(1, data.getEntryCount());
- assertFalse(data.remove(entry));
- assertTrue(data.remove(0));
- }
- @Test
- public void testGetEntry() {
- assertNull(data.getEntry(-1));
- assertNull(data.getEntry(20));
- assertEquals(entry0, data.getEntry(0));
- }
-
- private RowDataSet data;
- private RowEntry entry0;
+ @Before
+ public void setUp() {
+ data = new RowDataSet(new String[] {"a", "b", "c"});
+ entry0 = new RowEntry();
+ entry0.putRow(0, new String[] {"1", "2", "3"});
+ data.setData(entry0);
+ RowEntry entry = new RowEntry();
+ entry.putRow(0, new String[] {"4", "5", "6"});
+ data.setData(entry);
+ }
+
+ @Test
+ public void testSetData() {
+ assertEquals(2, data.getEntryCount());
+ RowEntry entry = new RowEntry();
+ entry.putRow(0, new String[] {"1", "2", "3"});
+ data.setData(entry);
+ assertEquals(3, data.getEntryCount());
+ }
+
+ @Test
+ public void testAppend() {
+ assertEquals(2, data.getEntryCount());
+ RowEntry entry = new RowEntry();
+ entry.putRow(0, new String[] {"1", "2", "3"});
+ data.append(entry);
+ assertEquals(3, data.getEntryCount());
+ }
+
+ @Test
+ public void testGetTitles() {
+ String[] titles = data.getTitles();
+ assertEquals(3, titles.length);
+ assertSame("a", titles[0]);
+ }
+ @Test
+ public void testGetColumn() {
+ assertNull(data.getColumn(-3));
+ assertNull(data.getColumn(10));
+
+ assertNull(data.getColumn(-3, 0, 1));
+ assertNull(data.getColumn(10, 0, 1));
+ assertNull(data.getColumn(1, 3, 1));
+ assertNull(data.getColumn(1, -2, 1));
+ assertNull(data.getColumn(1, 0, 20));
+
+ Object[] col = data.getColumn(0);
+ assertEquals(2, col.length);
+ assertSame("1", col[0]);
+ assertSame("4", col[1]);
+
+ col = data.getColumn(IDataSet.COL_ROW_NUM);
+ assertEquals(2, col.length);
+ assertEquals("1", col[0].toString());
+ assertEquals("2", col[1].toString());
+
+ col = data.getColumn(1, 0, 1);
+ assertEquals(1, col.length);
+ assertSame("2", col[0]);
+ }
+ @Test
+ public void testGetRow() {
+ assertNull(data.getRow(-3));
+ assertNull(data.getRow(10));
+
+ Object[] row = data.getRow(1);
+ assertEquals(3, row.length);
+ assertSame("5", row[1]);
+ }
+ @Test
+ public void testGetRowCount() {
+ assertEquals(2, data.getRowCount());
+ }
+ @Test
+ public void testGetColCount() {
+ assertEquals(3, data.getColCount());
+
+ assertEquals(-1, new RowDataSet(null).getColCount());
+ }
+ @Test
+ public void testReadFromFile() {}
+ @Test
+ public void testWriteToFile() {}
+ @Test
+ public void testGetID() {
+ assertEquals(RowDataSet.ID, data.getID());
+ }
+ //End IDataSet Methods
+
+ //IHistoricalDataSet Methods
+ @Test
+ public void testGetHistoricalData() {
+ assertNull(data.getHistoricalData(null, -3));
+ assertNull(data.getHistoricalData(null, 10));
+
+ assertNull(data.getHistoricalData(null, -3, 0, 1));
+ assertNull(data.getHistoricalData(null, 10, 0, 1));
+ assertNull(data.getHistoricalData(null, 1, 3, 1));
+ assertNull(data.getHistoricalData(null, 1, -2, 1));
+ assertNull(data.getHistoricalData(null, 1, 0, 20));
+
+ Object[] col = data.getHistoricalData(null, 0);
+ assertEquals(2, col.length);
+ assertSame("1", col[0]);
+ assertSame("4", col[1]);
+
+ col = data.getHistoricalData(null, IDataSet.COL_ROW_NUM);
+ assertEquals(2, col.length);
+ assertEquals("1", col[0].toString());
+ assertEquals("2", col[1].toString());
+
+ col = data.getHistoricalData(null, 1, 0, 1);
+ assertEquals(1, col.length);
+ assertSame("2", col[0]);
+ }
+ @Test
+ public void testGetEntryCount() {
+ assertEquals(2, data.getEntryCount());
+ }
+ @Test
+ public void testRemove() {
+ assertFalse(data.remove(null));
+ assertFalse(data.remove(new RowEntry()));
+ assertFalse(data.remove(-1));
+ assertFalse(data.remove(10));
+ assertEquals(2, data.getEntryCount());
+
+ IDataEntry entry = data.getEntry(0);
+ assertTrue(data.remove(entry));
+ assertEquals(1, data.getEntryCount());
+ assertFalse(data.remove(entry));
+ assertTrue(data.remove(0));
+ }
+ @Test
+ public void testGetEntry() {
+ assertNull(data.getEntry(-1));
+ assertNull(data.getEntry(20));
+ assertEquals(entry0, data.getEntry(0));
+ }
+
+ private RowDataSet data;
+ private RowEntry entry0;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowEntryTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowEntryTest.java
index a4d91f0a7a..c6625e4d5a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowEntryTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowEntryTest.java
@@ -25,104 +25,104 @@ import org.junit.Test;
public class RowEntryTest {
- @Before
- public void setUp() {
- entry = new RowEntry();
- data = new Integer[] {2, 5, 4};
- entry.putRow(0, data);
- }
-
- @Test
- public void testGetRowCount() {
- RowEntry entry2 = new RowEntry();
- assertEquals(0, entry2.getRowCount());
-
- entry2 = new RowEntry();
- entry2.putRow(0, null);
- assertEquals(0, entry2.getRowCount());
-
- assertEquals(1, entry.getRowCount());
- }
-
- @Test
- public void testGetColCount() {
- RowEntry entry2 = new RowEntry();
- assertEquals(0, entry2.getColCount());
-
- entry2 = new RowEntry();
- entry2.putRow(0, null);
- assertEquals(0, entry2.getColCount());
-
- assertEquals(3, entry.getColCount());
- }
-
- @Test
- public void testGet() {
- assertEquals(data[1], entry.get(null, 1));
- assertEquals(data[1], entry.get("asdf", 1));
- assertNull(entry.get(null, 10));
- assertNull(entry.get(null, -1));
- }
-
- @Test
- public void testGetRow() {
- assertArrayEquals(data, entry.getRow(0));
- assertNull(entry.getRow(10));
- assertNull(entry.getRow(-1));
-
- assertArrayEquals(data, entry.getRow(null));
- assertArrayEquals(data, entry.getRow("asdf"));
- }
-
- @Test
- public void testGetColumn() {
- assertEquals(data[1], entry.getColumn(1)[0]);
- assertNull(entry.getColumn(10));
- assertNull(entry.getColumn(-1));
- }
-
- @Test
- public void testGetData() {
- assertEquals(data[0], entry.getData()[0][0]);
- assertEquals(data[1], entry.getData()[0][1]);
- }
-
- @Test
- public void testCopy() {
- IDataEntry entry2 = entry.copy();
- assertEquals(entry2.getRowCount(), entry.getRowCount());
- assertEquals(entry2.getColCount(), entry.getColCount());
- assertSame(entry2.getRow(0)[1], entry.getRow(0)[1]);
- }
-
- @Test
- public void testPutRow() {
- Integer[] data2 = new Integer[] {2, 5};
-
- //Can't add to -1 position
- entry.putRow(-1, data2);
- assertEquals(3, entry.getColCount());
-
- //Cant add to non 0 position
- entry.putRow(10, data2);
- assertEquals(3, entry.getColCount());
-
- //Add successful
- entry.putRow(0, data2);
- assertEquals(2, entry.getColCount());
- }
-
- @Test
- public void testRemove() {
- assertFalse(entry.remove(-1));
- assertEquals(3, entry.getColCount());
- assertFalse(entry.remove(10));
- assertEquals(3, entry.getColCount());
-
- assertTrue(entry.remove(0));
- assertEquals(0, entry.getColCount());
- }
-
- private RowEntry entry;
- private Integer[] data;
+ @Before
+ public void setUp() {
+ entry = new RowEntry();
+ data = new Integer[] {2, 5, 4};
+ entry.putRow(0, data);
+ }
+
+ @Test
+ public void testGetRowCount() {
+ RowEntry entry2 = new RowEntry();
+ assertEquals(0, entry2.getRowCount());
+
+ entry2 = new RowEntry();
+ entry2.putRow(0, null);
+ assertEquals(0, entry2.getRowCount());
+
+ assertEquals(1, entry.getRowCount());
+ }
+
+ @Test
+ public void testGetColCount() {
+ RowEntry entry2 = new RowEntry();
+ assertEquals(0, entry2.getColCount());
+
+ entry2 = new RowEntry();
+ entry2.putRow(0, null);
+ assertEquals(0, entry2.getColCount());
+
+ assertEquals(3, entry.getColCount());
+ }
+
+ @Test
+ public void testGet() {
+ assertEquals(data[1], entry.get(null, 1));
+ assertEquals(data[1], entry.get("asdf", 1));
+ assertNull(entry.get(null, 10));
+ assertNull(entry.get(null, -1));
+ }
+
+ @Test
+ public void testGetRow() {
+ assertArrayEquals(data, entry.getRow(0));
+ assertNull(entry.getRow(10));
+ assertNull(entry.getRow(-1));
+
+ assertArrayEquals(data, entry.getRow(null));
+ assertArrayEquals(data, entry.getRow("asdf"));
+ }
+
+ @Test
+ public void testGetColumn() {
+ assertEquals(data[1], entry.getColumn(1)[0]);
+ assertNull(entry.getColumn(10));
+ assertNull(entry.getColumn(-1));
+ }
+
+ @Test
+ public void testGetData() {
+ assertEquals(data[0], entry.getData()[0][0]);
+ assertEquals(data[1], entry.getData()[0][1]);
+ }
+
+ @Test
+ public void testCopy() {
+ IDataEntry entry2 = entry.copy();
+ assertEquals(entry2.getRowCount(), entry.getRowCount());
+ assertEquals(entry2.getColCount(), entry.getColCount());
+ assertSame(entry2.getRow(0)[1], entry.getRow(0)[1]);
+ }
+
+ @Test
+ public void testPutRow() {
+ Integer[] data2 = new Integer[] {2, 5};
+
+ //Can't add to -1 position
+ entry.putRow(-1, data2);
+ assertEquals(3, entry.getColCount());
+
+ //Cant add to non 0 position
+ entry.putRow(10, data2);
+ assertEquals(3, entry.getColCount());
+
+ //Add successful
+ entry.putRow(0, data2);
+ assertEquals(2, entry.getColCount());
+ }
+
+ @Test
+ public void testRemove() {
+ assertFalse(entry.remove(-1));
+ assertEquals(3, entry.getColCount());
+ assertFalse(entry.remove(10));
+ assertEquals(3, entry.getColCount());
+
+ assertTrue(entry.remove(0));
+ assertEquals(0, entry.getColCount());
+ }
+
+ private RowEntry entry;
+ private Integer[] data;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowParserTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowParserTest.java
index 36177b143b..e9ad9d7e2b 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowParserTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/row/RowParserTest.java
@@ -22,25 +22,25 @@ import org.junit.Test;
public class RowParserTest {
- @Before
- public void setUp() {
- parser = new RowParser(new String[] {"\\d+", "(\\D+)", "\\d+", "\\D+"});
- }
-
- @Test
- public void testParse() {
- assertNull(parser.parse(null));
- assertNull(parser.parse(new StringBuilder("")));
- assertNull(parser.parse(new StringBuilder("asdf")));
- assertNull(parser.parse(new StringBuilder("1, ")));
- assertNull(parser.parse(new StringBuilder("1, 3")));
-
- IDataEntry entry = parser.parse(new StringBuilder("1, (2), 3, 4, 5"));
- assertNotNull(entry);
- assertEquals(2, entry.getColCount());
- assertEquals(1, entry.getRowCount());
- assertEquals("1", entry.getRow(0)[0]);
- }
-
- private RowParser parser;
+ @Before
+ public void setUp() {
+ parser = new RowParser(new String[] {"\\d+", "(\\D+)", "\\d+", "\\D+"});
+ }
+
+ @Test
+ public void testParse() {
+ assertNull(parser.parse(null));
+ assertNull(parser.parse(new StringBuilder("")));
+ assertNull(parser.parse(new StringBuilder("asdf")));
+ assertNull(parser.parse(new StringBuilder("1, ")));
+ assertNull(parser.parse(new StringBuilder("1, 3")));
+
+ IDataEntry entry = parser.parse(new StringBuilder("1, (2), 3, 4, 5"));
+ assertNotNull(entry);
+ assertEquals(2, entry.getColCount());
+ assertEquals(1, entry.getRowCount());
+ assertEquals("1", entry.getRow(0)[0]);
+ }
+
+ private RowParser parser;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/FilteredTableDataSetTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/FilteredTableDataSetTest.java
index 257bf4b5bd..97b0adeba9 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/FilteredTableDataSetTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/FilteredTableDataSetTest.java
@@ -31,254 +31,254 @@ import org.junit.Test;
public class FilteredTableDataSetTest {
- @Before
- public void setUp() {
- data = new TableDataSet(new String[] {"a", "b", "c"});
- dataSet = new FilteredTableDataSet(data);
- }
-
- @Test
- public void testFilteredDataSet() {
- FilteredTableDataSet fds = new FilteredTableDataSet(new String[] {"a", "b", "c"});
- assertNotNull(fds);
- assertNotNull(fds.getTitles());
- }
-
- @Test
- public void testAppend() {
- TableEntry entry;
-
- entry = new TableEntry();
- entry.add(new Integer[] {3, 2, 5});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {4, 2, 3});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {7, 2, 9});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {2, 2, 6});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {5, 2, 2});
- dataSet.append(entry);
-
- Object[] row = dataSet.getRow(0);
- assertEquals(5, ((Integer)row[0]).intValue());
- assertEquals(2, ((Integer)row[2]).intValue());
-
- assertNull(dataSet.getRow(2));
- }
-
- @Test
- public void testRemove() {
- assertFalse(dataSet.remove(null));
- assertFalse(dataSet.remove(new RowEntry()));
- assertFalse(dataSet.remove(-1));
- assertFalse(dataSet.remove(10));
- assertEquals(0, dataSet.getEntryCount());
-
- TableEntry entry= new TableEntry();
- entry.add(new String[] {"1", "2", "3"});
- data.append(entry);
-
- entry = (TableEntry)data.getEntry(0);
- assertEquals(1, dataSet.getEntryCount());
- assertTrue(dataSet.remove(entry));
- assertEquals(0, dataSet.getEntryCount());
- assertFalse(dataSet.remove(entry));
- assertFalse(dataSet.remove(0));
- }
- //End overwrite methods to insure data is removed from the original DataSet
- @Test
- public void testGetHistoricalData() {
- TableEntry entry = new TableEntry();
- entry.putRow(0, new String[] {"1", "2", "3"});
- dataSet.setData(entry);
- entry = new TableEntry();
- entry.putRow(0, new String[] {"4", "5", "6"});
- dataSet.setData(entry);
-
- assertNull(dataSet.getHistoricalData(null, -3));
- assertNull(dataSet.getHistoricalData(null, 10));
-
- assertNull(dataSet.getHistoricalData(null, -3, 0, 1));
- assertNull(dataSet.getHistoricalData(null, 10, 0, 1));
- assertNull(dataSet.getHistoricalData(null, 1, 3, 1));
- assertNull(dataSet.getHistoricalData(null, 1, -2, 1));
- assertNull(dataSet.getHistoricalData(null, 1, 0, 20));
-
- Object[] col = dataSet.getHistoricalData(null, 0);
- assertEquals(2, col.length);
- assertEquals("0", col[0].toString());
- assertEquals("0", col[1].toString());
-
- col = dataSet.getHistoricalData(null, IDataSet.COL_ROW_NUM);
- assertEquals(2, col.length);
- assertEquals("1", col[0].toString());
- assertEquals("2", col[1].toString());
-
- col = dataSet.getHistoricalData("4", 1, 1, 2);
- assertEquals(1, col.length);
- assertSame("5", col[0]);
- }
-
- @Test
- public void testGetEntryCount() {
- assertEquals(0, dataSet.getEntryCount());
- }
- @Test
- public void testGetEntry() {
- assertNull(dataSet.getEntry(-1));
- assertNull(dataSet.getEntry(20));
- }
- @Test
- public void testGetData() {
- TableEntry entry= new TableEntry();
- entry.add(new String[] {"1", "2", "3"});
- data.append(entry);
-
- Object[][] d = dataSet.getData();
- assertNotNull(d);
- assertEquals(1, d.length);
- assertEquals("3", d[0][2]);
- }
-
- //Overwrite to ensure the data returned has all the filters applied
- @Test
- public void testGetColumn() {
- TableEntry entry= new TableEntry();
- entry.add(new String[] {"1", "2", "3"});
- data.append(entry);
-
- assertNull(dataSet.getColumn(-3));
- assertNull(dataSet.getColumn(10));
-
- assertNull(dataSet.getColumn(-3, 0, 1));
- assertNull(dataSet.getColumn(10, 0, 1));
- assertNull(dataSet.getColumn(1, 3, 1));
- assertNull(dataSet.getColumn(1, -2, 1));
- assertNull(dataSet.getColumn(1, 0, 20));
-
- Object[] col = dataSet.getColumn(0);
- assertEquals(1, col.length);
- assertSame("1", col[0]);
-
- col = dataSet.getColumn(IDataSet.COL_ROW_NUM);
- assertEquals(1, col.length);
- assertEquals("1", col[0].toString());
-
- col = dataSet.getColumn(1, 0, 1);
- assertEquals(1, col.length);
- assertSame("2", col[0]);
- }
- @Test
- public void testAddFilter() {
- TableEntry entry;
-
- entry = new TableEntry();
- entry.add(new Integer[] {3, 2, 5});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {4, 2, 3});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {7, 2, 9});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {2, 2, 6});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {5, 2, 2});
- dataSet.append(entry);
-
- dataSet.addFilter(new RangeFilter(0, 3, 4, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS));
- assertEquals(0, dataSet.getRowCount());
- dataSet.clearFilters();
- dataSet.addFilter(new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS));
-
- assertEquals(1, dataSet.getRowCount());
- Object[] row = dataSet.getRow(0);
- assertEquals(5, ((Integer)row[0]).intValue());
- assertEquals(2, ((Integer)row[2]).intValue());
- }
- @Test
- public void testRemoveFilter() {
- TableEntry entry;
-
- entry = new TableEntry();
- entry.add(new Integer[] {3, 2, 5});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {4, 2, 3});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {7, 2, 9});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {2, 2, 6});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {5, 2, 2});
- dataSet.append(entry);
-
- RangeFilter filter = new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS);
- dataSet.addFilter(filter);
- dataSet.addFilter(new SortFilter(2, SortFilter.ASCENDING));
- dataSet.removeFilter(filter);
-
- assertEquals(1, dataSet.getRowCount());
- Object[] row = dataSet.getRow(0);
- assertEquals(5, ((Integer)row[0]).intValue());
- assertEquals(2, ((Integer)row[2]).intValue());
- }
- @Test
- public void testClearFilters() {
- TableEntry entry;
-
- entry = new TableEntry();
- entry.add(new Integer[] {3, 2, 5});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {4, 2, 3});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {7, 2, 9});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {2, 2, 6});
- dataSet.append(entry);
- entry = new TableEntry();
- entry.add(new Integer[] {5, 2, 2});
- dataSet.append(entry);
-
- dataSet.addFilter(new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS));
- dataSet.addFilter(new SortFilter(2, SortFilter.ASCENDING));
-
- assertEquals(2, dataSet.getFilters().length);
- dataSet.clearFilters();
-
- assertEquals(1, dataSet.getRowCount());
- Object[] row = dataSet.getRow(0);
- assertEquals(5, ((Integer)row[0]).intValue());
- assertEquals(2, ((Integer)row[2]).intValue());
- assertEquals(0, dataSet.getFilters().length);
- }
- @Test
- public void testGetFilters() {
- assertEquals(0, dataSet.getFilters().length);
-
- RangeFilter filter1 = new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS);
- SortFilter filter2 = new SortFilter(2, SortFilter.ASCENDING);
-
- dataSet.addFilter(filter1);
- dataSet.addFilter(filter2);
-
- IDataSetFilter[] filters = dataSet.getFilters();
- assertEquals(2, filters.length);
- }
-
- private FilteredTableDataSet dataSet;
- private TableDataSet data;
+ @Before
+ public void setUp() {
+ data = new TableDataSet(new String[] {"a", "b", "c"});
+ dataSet = new FilteredTableDataSet(data);
+ }
+
+ @Test
+ public void testFilteredDataSet() {
+ FilteredTableDataSet fds = new FilteredTableDataSet(new String[] {"a", "b", "c"});
+ assertNotNull(fds);
+ assertNotNull(fds.getTitles());
+ }
+
+ @Test
+ public void testAppend() {
+ TableEntry entry;
+
+ entry = new TableEntry();
+ entry.add(new Integer[] {3, 2, 5});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {4, 2, 3});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {7, 2, 9});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {2, 2, 6});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {5, 2, 2});
+ dataSet.append(entry);
+
+ Object[] row = dataSet.getRow(0);
+ assertEquals(5, ((Integer)row[0]).intValue());
+ assertEquals(2, ((Integer)row[2]).intValue());
+
+ assertNull(dataSet.getRow(2));
+ }
+
+ @Test
+ public void testRemove() {
+ assertFalse(dataSet.remove(null));
+ assertFalse(dataSet.remove(new RowEntry()));
+ assertFalse(dataSet.remove(-1));
+ assertFalse(dataSet.remove(10));
+ assertEquals(0, dataSet.getEntryCount());
+
+ TableEntry entry= new TableEntry();
+ entry.add(new String[] {"1", "2", "3"});
+ data.append(entry);
+
+ entry = (TableEntry)data.getEntry(0);
+ assertEquals(1, dataSet.getEntryCount());
+ assertTrue(dataSet.remove(entry));
+ assertEquals(0, dataSet.getEntryCount());
+ assertFalse(dataSet.remove(entry));
+ assertFalse(dataSet.remove(0));
+ }
+ //End overwrite methods to insure data is removed from the original DataSet
+ @Test
+ public void testGetHistoricalData() {
+ TableEntry entry = new TableEntry();
+ entry.putRow(0, new String[] {"1", "2", "3"});
+ dataSet.setData(entry);
+ entry = new TableEntry();
+ entry.putRow(0, new String[] {"4", "5", "6"});
+ dataSet.setData(entry);
+
+ assertNull(dataSet.getHistoricalData(null, -3));
+ assertNull(dataSet.getHistoricalData(null, 10));
+
+ assertNull(dataSet.getHistoricalData(null, -3, 0, 1));
+ assertNull(dataSet.getHistoricalData(null, 10, 0, 1));
+ assertNull(dataSet.getHistoricalData(null, 1, 3, 1));
+ assertNull(dataSet.getHistoricalData(null, 1, -2, 1));
+ assertNull(dataSet.getHistoricalData(null, 1, 0, 20));
+
+ Object[] col = dataSet.getHistoricalData(null, 0);
+ assertEquals(2, col.length);
+ assertEquals("0", col[0].toString());
+ assertEquals("0", col[1].toString());
+
+ col = dataSet.getHistoricalData(null, IDataSet.COL_ROW_NUM);
+ assertEquals(2, col.length);
+ assertEquals("1", col[0].toString());
+ assertEquals("2", col[1].toString());
+
+ col = dataSet.getHistoricalData("4", 1, 1, 2);
+ assertEquals(1, col.length);
+ assertSame("5", col[0]);
+ }
+
+ @Test
+ public void testGetEntryCount() {
+ assertEquals(0, dataSet.getEntryCount());
+ }
+ @Test
+ public void testGetEntry() {
+ assertNull(dataSet.getEntry(-1));
+ assertNull(dataSet.getEntry(20));
+ }
+ @Test
+ public void testGetData() {
+ TableEntry entry= new TableEntry();
+ entry.add(new String[] {"1", "2", "3"});
+ data.append(entry);
+
+ Object[][] d = dataSet.getData();
+ assertNotNull(d);
+ assertEquals(1, d.length);
+ assertEquals("3", d[0][2]);
+ }
+
+ //Overwrite to ensure the data returned has all the filters applied
+ @Test
+ public void testGetColumn() {
+ TableEntry entry= new TableEntry();
+ entry.add(new String[] {"1", "2", "3"});
+ data.append(entry);
+
+ assertNull(dataSet.getColumn(-3));
+ assertNull(dataSet.getColumn(10));
+
+ assertNull(dataSet.getColumn(-3, 0, 1));
+ assertNull(dataSet.getColumn(10, 0, 1));
+ assertNull(dataSet.getColumn(1, 3, 1));
+ assertNull(dataSet.getColumn(1, -2, 1));
+ assertNull(dataSet.getColumn(1, 0, 20));
+
+ Object[] col = dataSet.getColumn(0);
+ assertEquals(1, col.length);
+ assertSame("1", col[0]);
+
+ col = dataSet.getColumn(IDataSet.COL_ROW_NUM);
+ assertEquals(1, col.length);
+ assertEquals("1", col[0].toString());
+
+ col = dataSet.getColumn(1, 0, 1);
+ assertEquals(1, col.length);
+ assertSame("2", col[0]);
+ }
+ @Test
+ public void testAddFilter() {
+ TableEntry entry;
+
+ entry = new TableEntry();
+ entry.add(new Integer[] {3, 2, 5});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {4, 2, 3});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {7, 2, 9});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {2, 2, 6});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {5, 2, 2});
+ dataSet.append(entry);
+
+ dataSet.addFilter(new RangeFilter(0, 3, 4, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS));
+ assertEquals(0, dataSet.getRowCount());
+ dataSet.clearFilters();
+ dataSet.addFilter(new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS));
+
+ assertEquals(1, dataSet.getRowCount());
+ Object[] row = dataSet.getRow(0);
+ assertEquals(5, ((Integer)row[0]).intValue());
+ assertEquals(2, ((Integer)row[2]).intValue());
+ }
+ @Test
+ public void testRemoveFilter() {
+ TableEntry entry;
+
+ entry = new TableEntry();
+ entry.add(new Integer[] {3, 2, 5});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {4, 2, 3});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {7, 2, 9});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {2, 2, 6});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {5, 2, 2});
+ dataSet.append(entry);
+
+ RangeFilter filter = new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS);
+ dataSet.addFilter(filter);
+ dataSet.addFilter(new SortFilter(2, SortFilter.ASCENDING));
+ dataSet.removeFilter(filter);
+
+ assertEquals(1, dataSet.getRowCount());
+ Object[] row = dataSet.getRow(0);
+ assertEquals(5, ((Integer)row[0]).intValue());
+ assertEquals(2, ((Integer)row[2]).intValue());
+ }
+ @Test
+ public void testClearFilters() {
+ TableEntry entry;
+
+ entry = new TableEntry();
+ entry.add(new Integer[] {3, 2, 5});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {4, 2, 3});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {7, 2, 9});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {2, 2, 6});
+ dataSet.append(entry);
+ entry = new TableEntry();
+ entry.add(new Integer[] {5, 2, 2});
+ dataSet.append(entry);
+
+ dataSet.addFilter(new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS));
+ dataSet.addFilter(new SortFilter(2, SortFilter.ASCENDING));
+
+ assertEquals(2, dataSet.getFilters().length);
+ dataSet.clearFilters();
+
+ assertEquals(1, dataSet.getRowCount());
+ Object[] row = dataSet.getRow(0);
+ assertEquals(5, ((Integer)row[0]).intValue());
+ assertEquals(2, ((Integer)row[2]).intValue());
+ assertEquals(0, dataSet.getFilters().length);
+ }
+ @Test
+ public void testGetFilters() {
+ assertEquals(0, dataSet.getFilters().length);
+
+ RangeFilter filter1 = new RangeFilter(0, 3, 5, RangeFilter.INCLUSIVE | RangeFilter.INSIDE_BOUNDS);
+ SortFilter filter2 = new SortFilter(2, SortFilter.ASCENDING);
+
+ dataSet.addFilter(filter1);
+ dataSet.addFilter(filter2);
+
+ IDataSetFilter[] filters = dataSet.getFilters();
+ assertEquals(2, filters.length);
+ }
+
+ private FilteredTableDataSet dataSet;
+ private TableDataSet data;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableDataSetTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableDataSetTest.java
index 333ed29d95..7323311957 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableDataSetTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableDataSetTest.java
@@ -27,152 +27,152 @@ import org.junit.Test;
public class TableDataSetTest {
- @Before
- public void setUp() {
- data = new TableDataSet(new String[] {"a", "b", "c"});
- entry0 = new TableEntry();
- entry0.putRow(0, new String[] {"1", "2", "3"});
- data.setData(entry0);
- TableEntry entry = new TableEntry();
- entry.putRow(0, new String[] {"4", "5", "6"});
- data.setData(entry);
- }
-
- @Test
- public void testSetData() {
- assertEquals(2, data.getEntryCount());
- TableEntry entry = new TableEntry();
- entry.putRow(0, new String[] {"1", "2", "3"});
- data.setData(entry);
- assertEquals(3, data.getEntryCount());
- }
-
- @Test
- public void testAppend() {
- assertEquals(2, data.getEntryCount());
- TableEntry entry = new TableEntry();
- entry.putRow(0, new String[] {"1", "2", "3"});
- data.append(entry);
- assertEquals(3, data.getEntryCount());
- }
- @Test
- public void testGetTitles() {
- String[] titles = data.getTitles();
- assertEquals(3, titles.length);
- assertSame("a", titles[0]);
- }
- @Test
- public void testGetColumn() {
- assertNull(data.getColumn(-3));
- assertNull(data.getColumn(10));
-
- assertNull(data.getColumn(-3, 0, 1));
- assertNull(data.getColumn(10, 0, 1));
- assertNull(data.getColumn(1, 3, 1));
- assertNull(data.getColumn(1, -2, 1));
- assertNull(data.getColumn(1, 0, 20));
-
- Object[] col = data.getColumn(0);
- assertEquals(1, col.length);
- assertSame("4", col[0]);
-
- col = data.getColumn(IDataSet.COL_ROW_NUM);
- assertEquals(1, col.length);
- assertEquals("1", col[0].toString());
-
- col = data.getColumn(1, 0, 1);
- assertEquals(1, col.length);
- assertSame("5", col[0]);
- }
- @Test
- public void testGetRow() {
- assertNull(data.getRow(-3));
- assertNull(data.getRow(10));
-
- assertNull(data.getRow(1));
-
- Object[] row = data.getRow(0);
- assertEquals(3, row.length);
- assertSame("5", row[1]);
- }
- @Test
- public void testGetRowCount() {
- assertEquals(1, data.getRowCount());
- }
- @Test
- public void testGetColCount() {
- assertEquals(3, data.getColCount());
-
- assertEquals(0, new TableDataSet(null).getColCount());
- }
- @Test
- public void testReadFromFile() {}
- @Test
- public void testWriteToFile() {}
- @Test
- public void testGetID() {
- assertEquals(TableDataSet.ID, data.getID());
- }
- //End IDataSet Methods
-
- //IHistoricalDataSet Methods
- @Test
- public void testGetHistoricalData() {
- assertNull(data.getHistoricalData(null, -3));
- assertNull(data.getHistoricalData(null, 10));
-
- assertNull(data.getHistoricalData(null, -3, 0, 1));
- assertNull(data.getHistoricalData(null, 10, 0, 1));
- assertNull(data.getHistoricalData(null, 1, 3, 1));
- assertNull(data.getHistoricalData(null, 1, -2, 1));
- assertNull(data.getHistoricalData(null, 1, 0, 20));
-
- Object[] col = data.getHistoricalData(null, 0);
- assertEquals(2, col.length);
- assertEquals("0", col[0].toString());
- assertEquals("0", col[1].toString());
-
- col = data.getHistoricalData(null, IDataSet.COL_ROW_NUM);
- assertEquals(2, col.length);
- assertEquals("1", col[0].toString());
- assertEquals("2", col[1].toString());
-
- col = data.getHistoricalData("4", 1, 1, 2);
- assertEquals(1, col.length);
- assertSame("5", col[0]);
- }
- @Test
- public void testGetEntryCount() {
- assertEquals(2, data.getEntryCount());
- }
- @Test
- public void testRemove() {
- assertFalse(data.remove(null));
- assertFalse(data.remove(new TableEntry()));
- assertFalse(data.remove(-1));
- assertFalse(data.remove(10));
- assertEquals(2, data.getEntryCount());
-
- IDataEntry entry = data.getEntry(0);
- assertTrue(data.remove(entry));
- assertEquals(1, data.getEntryCount());
- assertFalse(data.remove(entry));
- assertTrue(data.remove(0));
- }
- @Test
- public void testGetEntry() {
- assertNull(data.getEntry(-1));
- assertNull(data.getEntry(20));
- assertEquals(entry0, data.getEntry(0));
- }
- @Test
- public void testGetData() {
- Object[][] d = data.getData();
- assertNotNull(d);
- assertEquals(1, d.length);
- assertEquals("6", d[0][2]);
- }
-
- private TableDataSet data;
- private TableEntry entry0;
+ @Before
+ public void setUp() {
+ data = new TableDataSet(new String[] {"a", "b", "c"});
+ entry0 = new TableEntry();
+ entry0.putRow(0, new String[] {"1", "2", "3"});
+ data.setData(entry0);
+ TableEntry entry = new TableEntry();
+ entry.putRow(0, new String[] {"4", "5", "6"});
+ data.setData(entry);
+ }
+
+ @Test
+ public void testSetData() {
+ assertEquals(2, data.getEntryCount());
+ TableEntry entry = new TableEntry();
+ entry.putRow(0, new String[] {"1", "2", "3"});
+ data.setData(entry);
+ assertEquals(3, data.getEntryCount());
+ }
+
+ @Test
+ public void testAppend() {
+ assertEquals(2, data.getEntryCount());
+ TableEntry entry = new TableEntry();
+ entry.putRow(0, new String[] {"1", "2", "3"});
+ data.append(entry);
+ assertEquals(3, data.getEntryCount());
+ }
+ @Test
+ public void testGetTitles() {
+ String[] titles = data.getTitles();
+ assertEquals(3, titles.length);
+ assertSame("a", titles[0]);
+ }
+ @Test
+ public void testGetColumn() {
+ assertNull(data.getColumn(-3));
+ assertNull(data.getColumn(10));
+
+ assertNull(data.getColumn(-3, 0, 1));
+ assertNull(data.getColumn(10, 0, 1));
+ assertNull(data.getColumn(1, 3, 1));
+ assertNull(data.getColumn(1, -2, 1));
+ assertNull(data.getColumn(1, 0, 20));
+
+ Object[] col = data.getColumn(0);
+ assertEquals(1, col.length);
+ assertSame("4", col[0]);
+
+ col = data.getColumn(IDataSet.COL_ROW_NUM);
+ assertEquals(1, col.length);
+ assertEquals("1", col[0].toString());
+
+ col = data.getColumn(1, 0, 1);
+ assertEquals(1, col.length);
+ assertSame("5", col[0]);
+ }
+ @Test
+ public void testGetRow() {
+ assertNull(data.getRow(-3));
+ assertNull(data.getRow(10));
+
+ assertNull(data.getRow(1));
+
+ Object[] row = data.getRow(0);
+ assertEquals(3, row.length);
+ assertSame("5", row[1]);
+ }
+ @Test
+ public void testGetRowCount() {
+ assertEquals(1, data.getRowCount());
+ }
+ @Test
+ public void testGetColCount() {
+ assertEquals(3, data.getColCount());
+
+ assertEquals(0, new TableDataSet(null).getColCount());
+ }
+ @Test
+ public void testReadFromFile() {}
+ @Test
+ public void testWriteToFile() {}
+ @Test
+ public void testGetID() {
+ assertEquals(TableDataSet.ID, data.getID());
+ }
+ //End IDataSet Methods
+
+ //IHistoricalDataSet Methods
+ @Test
+ public void testGetHistoricalData() {
+ assertNull(data.getHistoricalData(null, -3));
+ assertNull(data.getHistoricalData(null, 10));
+
+ assertNull(data.getHistoricalData(null, -3, 0, 1));
+ assertNull(data.getHistoricalData(null, 10, 0, 1));
+ assertNull(data.getHistoricalData(null, 1, 3, 1));
+ assertNull(data.getHistoricalData(null, 1, -2, 1));
+ assertNull(data.getHistoricalData(null, 1, 0, 20));
+
+ Object[] col = data.getHistoricalData(null, 0);
+ assertEquals(2, col.length);
+ assertEquals("0", col[0].toString());
+ assertEquals("0", col[1].toString());
+
+ col = data.getHistoricalData(null, IDataSet.COL_ROW_NUM);
+ assertEquals(2, col.length);
+ assertEquals("1", col[0].toString());
+ assertEquals("2", col[1].toString());
+
+ col = data.getHistoricalData("4", 1, 1, 2);
+ assertEquals(1, col.length);
+ assertSame("5", col[0]);
+ }
+ @Test
+ public void testGetEntryCount() {
+ assertEquals(2, data.getEntryCount());
+ }
+ @Test
+ public void testRemove() {
+ assertFalse(data.remove(null));
+ assertFalse(data.remove(new TableEntry()));
+ assertFalse(data.remove(-1));
+ assertFalse(data.remove(10));
+ assertEquals(2, data.getEntryCount());
+
+ IDataEntry entry = data.getEntry(0);
+ assertTrue(data.remove(entry));
+ assertEquals(1, data.getEntryCount());
+ assertFalse(data.remove(entry));
+ assertTrue(data.remove(0));
+ }
+ @Test
+ public void testGetEntry() {
+ assertNull(data.getEntry(-1));
+ assertNull(data.getEntry(20));
+ assertEquals(entry0, data.getEntry(0));
+ }
+ @Test
+ public void testGetData() {
+ Object[][] d = data.getData();
+ assertNotNull(d);
+ assertEquals(1, d.length);
+ assertEquals("6", d[0][2]);
+ }
+
+ private TableDataSet data;
+ private TableEntry entry0;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableEntryTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableEntryTest.java
index 28a73b2a9a..8f520d937f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableEntryTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableEntryTest.java
@@ -25,112 +25,112 @@ import org.junit.Test;
public class TableEntryTest {
- @Before
- public void setUp() {
- entry = new TableEntry();
- data = new Integer[] {2, 5, 4};
- entry.add(data);
- data = new Integer[] {5, 1, 3};
- entry.add(data);
- }
-
- @Test
- public void testGetRowCount() {
- TableEntry entry2 = new TableEntry();
- assertEquals(0, entry2.getRowCount());
-
- entry2 = new TableEntry();
- entry2.putRow(0, null);
- assertEquals(0, entry2.getRowCount());
-
- assertEquals(2, entry.getRowCount());
- }
- @Test
- public void testGetColCount() {
- TableEntry entry2 = new TableEntry();
- assertEquals(0, entry2.getColCount());
-
- entry2 = new TableEntry();
- entry2.putRow(0, null);
- assertEquals(0, entry2.getColCount());
-
- assertEquals(3, entry.getColCount());
- }
- @Test
- public void testGet() {
- assertNull(entry.get(null, 1));
- assertNull(entry.get("asdf", 1));
- assertNull(entry.get(null, 10));
- assertNull(entry.get(null, -1));
- assertEquals("5", entry.get("2", 1).toString());
- }
- @Test
- public void testGetData() {
- assertEquals(data[0], entry.getData()[1][0]);
- assertEquals(data[1], entry.getData()[1][1]);
- }
- @Test
- public void testGetRow() {
- assertNull(entry.getRow(10));
- assertNull(entry.getRow(-1));
- assertNotNull(entry.getRow(0));
- assertArrayEquals(data, entry.getRow(1));
-
- assertNull(entry.getRow(null));
- assertNull(entry.getRow("asdf"));
- assertNotNull(entry.getRow("2"));
- assertArrayEquals(data, entry.getRow("5"));
- }
- @Test
- public void testGetColumn() {
- assertEquals(data[1], entry.getColumn(1)[1]);
- assertNull(entry.getColumn(10));
- assertNull(entry.getColumn(-1));
- }
- @Test
- public void testPutRow() {
- Integer[] data2 = new Integer[] {2, 5};
-
- //Can't add to -1 position
- entry.putRow(-1, data2);
- assertEquals(2, entry.getRowCount());
-
- //Cant add wrong sized array
- entry.putRow(10, data2);
- assertEquals(2, entry.getRowCount());
-
- entry.putRow(0, data2);
- assertEquals(2, entry.getRowCount());
-
- //Add successful
- data2 = new Integer[] {2, 5, 6};
- entry.putRow(0, data2);
- assertEquals(2, entry.getRowCount());
- }
- @Test
- public void testAdd() {
- Integer[] data2 = new Integer[] {2, 5};
- entry.add(data2);
- assertEquals(2, entry.getRowCount());
-
- //Add successful
- data2 = new Integer[] {2, 5, 6};
- entry.add(data2);
- assertEquals(3, entry.getRowCount());
- }
- @Test
- public void testCopy() {
- IDataEntry entry2 = entry.copy();
- assertEquals(entry2.getRowCount(), entry.getRowCount());
- assertEquals(entry2.getColCount(), entry.getColCount());
- assertSame(entry2.getRow(0)[1], entry.getRow(0)[1]);
- }
- @Test
- public void testRemove() {
- assertTrue(entry.remove(0));
- assertEquals(1, entry.getRowCount());
- }
-
- private TableEntry entry;
- private Integer[] data;
+ @Before
+ public void setUp() {
+ entry = new TableEntry();
+ data = new Integer[] {2, 5, 4};
+ entry.add(data);
+ data = new Integer[] {5, 1, 3};
+ entry.add(data);
+ }
+
+ @Test
+ public void testGetRowCount() {
+ TableEntry entry2 = new TableEntry();
+ assertEquals(0, entry2.getRowCount());
+
+ entry2 = new TableEntry();
+ entry2.putRow(0, null);
+ assertEquals(0, entry2.getRowCount());
+
+ assertEquals(2, entry.getRowCount());
+ }
+ @Test
+ public void testGetColCount() {
+ TableEntry entry2 = new TableEntry();
+ assertEquals(0, entry2.getColCount());
+
+ entry2 = new TableEntry();
+ entry2.putRow(0, null);
+ assertEquals(0, entry2.getColCount());
+
+ assertEquals(3, entry.getColCount());
+ }
+ @Test
+ public void testGet() {
+ assertNull(entry.get(null, 1));
+ assertNull(entry.get("asdf", 1));
+ assertNull(entry.get(null, 10));
+ assertNull(entry.get(null, -1));
+ assertEquals("5", entry.get("2", 1).toString());
+ }
+ @Test
+ public void testGetData() {
+ assertEquals(data[0], entry.getData()[1][0]);
+ assertEquals(data[1], entry.getData()[1][1]);
+ }
+ @Test
+ public void testGetRow() {
+ assertNull(entry.getRow(10));
+ assertNull(entry.getRow(-1));
+ assertNotNull(entry.getRow(0));
+ assertArrayEquals(data, entry.getRow(1));
+
+ assertNull(entry.getRow(null));
+ assertNull(entry.getRow("asdf"));
+ assertNotNull(entry.getRow("2"));
+ assertArrayEquals(data, entry.getRow("5"));
+ }
+ @Test
+ public void testGetColumn() {
+ assertEquals(data[1], entry.getColumn(1)[1]);
+ assertNull(entry.getColumn(10));
+ assertNull(entry.getColumn(-1));
+ }
+ @Test
+ public void testPutRow() {
+ Integer[] data2 = new Integer[] {2, 5};
+
+ //Can't add to -1 position
+ entry.putRow(-1, data2);
+ assertEquals(2, entry.getRowCount());
+
+ //Cant add wrong sized array
+ entry.putRow(10, data2);
+ assertEquals(2, entry.getRowCount());
+
+ entry.putRow(0, data2);
+ assertEquals(2, entry.getRowCount());
+
+ //Add successful
+ data2 = new Integer[] {2, 5, 6};
+ entry.putRow(0, data2);
+ assertEquals(2, entry.getRowCount());
+ }
+ @Test
+ public void testAdd() {
+ Integer[] data2 = new Integer[] {2, 5};
+ entry.add(data2);
+ assertEquals(2, entry.getRowCount());
+
+ //Add successful
+ data2 = new Integer[] {2, 5, 6};
+ entry.add(data2);
+ assertEquals(3, entry.getRowCount());
+ }
+ @Test
+ public void testCopy() {
+ IDataEntry entry2 = entry.copy();
+ assertEquals(entry2.getRowCount(), entry.getRowCount());
+ assertEquals(entry2.getColCount(), entry.getColCount());
+ assertSame(entry2.getRow(0)[1], entry.getRow(0)[1]);
+ }
+ @Test
+ public void testRemove() {
+ assertTrue(entry.remove(0));
+ assertEquals(1, entry.getRowCount());
+ }
+
+ private TableEntry entry;
+ private Integer[] data;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableParserTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableParserTest.java
index f8522fc2f4..e223505a70 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableParserTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/datasets/table/TableParserTest.java
@@ -22,25 +22,25 @@ import org.junit.Test;
public class TableParserTest {
- @Before
- public void setUp() {
- parser = new TableParser(new String[] {"\\d+", "(\\D+)", "\\d+", "\\D+"}, "\n\n");
- }
-
- @Test
- public void testParse() {
- assertNull(parser.parse(null));
- assertNull(parser.parse(new StringBuilder("")));
- assertNull(parser.parse(new StringBuilder("asdf")));
- assertNull(parser.parse(new StringBuilder("1, ")));
- assertNull(parser.parse(new StringBuilder("1, 3")));
-
- IDataEntry entry = parser.parse(new StringBuilder("1, (2), 3, 4, 5\n\n"));
- assertNotNull(entry);
- assertEquals(2, entry.getColCount());
- assertEquals(2, entry.getRowCount());
- assertEquals("1", entry.getRow(0)[0]);
- }
-
- private TableParser parser;
+ @Before
+ public void setUp() {
+ parser = new TableParser(new String[] {"\\d+", "(\\D+)", "\\d+", "\\D+"}, "\n\n");
+ }
+
+ @Test
+ public void testParse() {
+ assertNull(parser.parse(null));
+ assertNull(parser.parse(new StringBuilder("")));
+ assertNull(parser.parse(new StringBuilder("asdf")));
+ assertNull(parser.parse(new StringBuilder("1, ")));
+ assertNull(parser.parse(new StringBuilder("1, 3")));
+
+ IDataEntry entry = parser.parse(new StringBuilder("1, (2), 3, 4, 5\n\n"));
+ assertNotNull(entry);
+ assertEquals(2, entry.getColCount());
+ assertEquals(2, entry.getRowCount());
+ assertEquals("1", entry.getRow(0)[0]);
+ }
+
+ private TableParser parser;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/MatchFilterTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/MatchFilterTest.java
index dfbf378be3..553e8cd4dc 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/MatchFilterTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/MatchFilterTest.java
@@ -24,44 +24,44 @@ import org.junit.Test;
public class MatchFilterTest {
- @Test
- public void testMatchFilter() {
- MatchFilter filter = new MatchFilter(-1, null, MatchFilter.KEEP_MATCHING);
- assertNotNull(filter);
- }
- @Test
- public void testFilter() {
- int width = 4;
- int height = 10;
- int wrap = height / 3;
- ArrayList<Object>[] data = MockDataSet.buildArray(width, height, wrap);
+ @Test
+ public void testMatchFilter() {
+ MatchFilter filter = new MatchFilter(-1, null, MatchFilter.KEEP_MATCHING);
+ assertNotNull(filter);
+ }
+ @Test
+ public void testFilter() {
+ int width = 4;
+ int height = 10;
+ int wrap = height / 3;
+ ArrayList<Object>[] data = MockDataSet.buildArray(width, height, wrap);
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- MatchFilter filter = new MatchFilter(0, data[0].get(0), MatchFilter.KEEP_MATCHING);
- List<Object>[] data2 = filter.filter(data);
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ MatchFilter filter = new MatchFilter(0, data[0].get(0), MatchFilter.KEEP_MATCHING);
+ List<Object>[] data2 = filter.filter(data);
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- assertEquals(width, data2.length);
- assertEquals((int)Math.ceil(height/((double)wrap)), data2[0].size());
- assertEquals("0", data2[0].get(0));
- assertEquals("0", data2[0].get(1));
- assertEquals("0", data2[0].get(2));
- assertEquals("0", data2[0].get(3));
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ assertEquals(width, data2.length);
+ assertEquals((int)Math.ceil(height/((double)wrap)), data2[0].size());
+ assertEquals("0", data2[0].get(0));
+ assertEquals("0", data2[0].get(1));
+ assertEquals("0", data2[0].get(2));
+ assertEquals("0", data2[0].get(3));
- assertEquals(data[2].get(0), data2[2].get(0));
- assertEquals(data[2].get(3), data2[2].get(1));
- assertEquals(data[2].get(6), data2[2].get(2));
- assertEquals(data[2].get(9), data2[2].get(3));
+ assertEquals(data[2].get(0), data2[2].get(0));
+ assertEquals(data[2].get(3), data2[2].get(1));
+ assertEquals(data[2].get(6), data2[2].get(2));
+ assertEquals(data[2].get(9), data2[2].get(3));
- filter = new MatchFilter(-1, "", MatchFilter.KEEP_MATCHING);
- assertNull(filter.filter(data));
- }
- @Test
- public void testGetID() {
- MatchFilter filter = new MatchFilter(0, "", MatchFilter.KEEP_MATCHING);
- assertEquals(MatchFilter.ID, filter.getID());
- }
+ filter = new MatchFilter(-1, "", MatchFilter.KEEP_MATCHING);
+ assertNull(filter.filter(data));
+ }
+ @Test
+ public void testGetID() {
+ MatchFilter filter = new MatchFilter(0, "", MatchFilter.KEEP_MATCHING);
+ assertEquals(MatchFilter.ID, filter.getID());
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/RangeFilterTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/RangeFilterTest.java
index 3d786866de..20fdbbd340 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/RangeFilterTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/RangeFilterTest.java
@@ -25,181 +25,181 @@ import org.junit.Test;
public class RangeFilterTest {
- @Before
- public void setUp() {
- filter = new RangeFilter(0, 1, 2, RangeFilter.INSIDE_BOUNDS | RangeFilter.INCLUSIVE);
- }
- @Test
- public void testRangeFilter() {
- RangeFilter filter = new RangeFilter(-1, 3, 5, RangeFilter.INSIDE_BOUNDS);
- assertNotNull(filter);
- }
- @Test
- public void testFilter() {
- int width = 4;
- int height = 10;
- int wrap = height / 3;
- ArrayList<Object>[] data = MockDataSet.buildArray(width, height, wrap);
-
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- List<Object>[] data2 = filter.filter(data);
-
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- assertEquals(width, data2.length);
- assertEquals(6, data2[0].size());
- assertEquals("1", data2[0].get(0));
- assertEquals("2", data2[0].get(1));
- assertEquals("1", data2[0].get(2));
- assertEquals("2", data2[0].get(3));
-
- assertEquals(data[2].get(1), data2[2].get(0));
- assertEquals(data[2].get(2), data2[2].get(1));
- assertEquals(data[2].get(4), data2[2].get(2));
- assertEquals(data[2].get(5), data2[2].get(3));
-
-
- filter = new RangeFilter(0, 0, 2, RangeFilter.INSIDE_BOUNDS);
- data2 = filter.filter(data);
-
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- assertEquals(width, data2.length);
- assertEquals(3, data2[0].size());
- assertEquals("1", data2[0].get(0));
- assertEquals("1", data2[0].get(1));
- assertEquals("1", data2[0].get(2));
-
- assertEquals(data[2].get(1), data2[2].get(0));
- assertEquals(data[2].get(4), data2[2].get(1));
- assertEquals(data[2].get(7), data2[2].get(2));
-
-
- filter = new RangeFilter(0, 0, 2, RangeFilter.OUTSIDE_BOUNDS | RangeFilter.INCLUSIVE);
- data2 = filter.filter(data);
-
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- assertEquals(width, data2.length);
- assertEquals(7, data2[0].size());
- assertEquals("0", data2[0].get(0));
- assertEquals("2", data2[0].get(1));
- assertEquals("0", data2[0].get(2));
- assertEquals("2", data2[0].get(3));
-
- assertEquals(data[2].get(0), data2[2].get(0));
- assertEquals(data[2].get(2), data2[2].get(1));
- assertEquals(data[2].get(3), data2[2].get(2));
- assertEquals(data[2].get(5), data2[2].get(3));
-
-
- filter = new RangeFilter(0, 0, 2, RangeFilter.INSIDE_BOUNDS);
- data2 = filter.filter(data);
-
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- assertEquals(width, data2.length);
- assertEquals(3, data2[0].size());
- assertEquals("1", data2[0].get(0));
- assertEquals("1", data2[0].get(1));
- assertEquals("1", data2[0].get(2));
-
- assertEquals(data[2].get(1), data2[2].get(0));
- assertEquals(data[2].get(4), data2[2].get(1));
- assertEquals(data[2].get(7), data2[2].get(2));
-
-
- filter = new RangeFilter(0, 0, 2, RangeFilter.OUTSIDE_BOUNDS);
- data2 = filter.filter(data);
-
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- assertEquals(width, data2.length);
- assertEquals(0, data2[0].size());
-
-
- filter = new RangeFilter(-1, 1, 3, 0);
- assertNull(filter.filter(data));
- }
- @Test
- public void testUnboundedFilters() {
- int width = 4;
- int height = 10;
- int wrap = height / 3;
- ArrayList<Object>[] data = MockDataSet.buildArray(width, height, wrap);
-
- filter = new RangeFilter(1, 1, null, RangeFilter.INCLUSIVE);
- List<Object>[] data2 = filter.filter(data);
-
- assertEquals(width, data.length);
- assertEquals(height, data[1].size());
- assertEquals(width, data2.length);
- assertEquals(7, data2[1].size());
- assertEquals("1", data2[1].get(0));
- assertEquals("2", data2[1].get(1));
- assertEquals("1", data2[1].get(2));
- assertEquals("2", data2[1].get(3));
-
- assertEquals(data[2].get(0), data2[2].get(0));
- assertEquals(data[2].get(1), data2[2].get(1));
- assertEquals(data[2].get(3), data2[2].get(2));
- assertEquals(data[2].get(4), data2[2].get(3));
-
-
- filter = new RangeFilter(1, 1, null, 0);
- data2 = filter.filter(data);
-
- assertEquals(width, data.length);
- assertEquals(height, data[1].size());
- assertEquals(width, data2.length);
- assertEquals(3, data2[1].size());
- assertEquals("2", data2[1].get(0));
- assertEquals("2", data2[1].get(1));
- assertEquals("2", data2[1].get(2));
-
- assertEquals(data[2].get(1), data2[2].get(0));
- assertEquals(data[2].get(4), data2[2].get(1));
- assertEquals(data[2].get(7), data2[2].get(2));
-
-
- filter = new RangeFilter(1, null, 1, RangeFilter.INCLUSIVE);
- data2 = filter.filter(data);
-
- assertEquals(width, data.length);
- assertEquals(height, data[1].size());
- assertEquals(width, data2.length);
- assertEquals(7, data2[1].size());
- assertEquals("1", data2[1].get(0));
- assertEquals("0", data2[1].get(1));
- assertEquals("1", data2[1].get(2));
- assertEquals("0", data2[1].get(3));
-
- assertEquals(data[2].get(0), data2[2].get(0));
- assertEquals(data[2].get(2), data2[2].get(1));
- assertEquals(data[2].get(3), data2[2].get(2));
- assertEquals(data[2].get(5), data2[2].get(3));
-
-
- filter = new RangeFilter(1, null, 1, 0);
- data2 = filter.filter(data);
-
- assertEquals(width, data.length);
- assertEquals(height, data[1].size());
- assertEquals(width, data2.length);
- assertEquals(3, data2[1].size());
- assertEquals("0", data2[1].get(0));
- assertEquals("0", data2[1].get(1));
- assertEquals("0", data2[1].get(2));
-
- assertEquals(data[2].get(2), data2[2].get(0));
- assertEquals(data[2].get(5), data2[2].get(1));
- assertEquals(data[2].get(8), data2[2].get(2));
- }
- @Test
- public void testGetID() {
- assertEquals(RangeFilter.ID, filter.getID());
- }
-
- private RangeFilter filter;
+ @Before
+ public void setUp() {
+ filter = new RangeFilter(0, 1, 2, RangeFilter.INSIDE_BOUNDS | RangeFilter.INCLUSIVE);
+ }
+ @Test
+ public void testRangeFilter() {
+ RangeFilter filter = new RangeFilter(-1, 3, 5, RangeFilter.INSIDE_BOUNDS);
+ assertNotNull(filter);
+ }
+ @Test
+ public void testFilter() {
+ int width = 4;
+ int height = 10;
+ int wrap = height / 3;
+ ArrayList<Object>[] data = MockDataSet.buildArray(width, height, wrap);
+
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ List<Object>[] data2 = filter.filter(data);
+
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ assertEquals(width, data2.length);
+ assertEquals(6, data2[0].size());
+ assertEquals("1", data2[0].get(0));
+ assertEquals("2", data2[0].get(1));
+ assertEquals("1", data2[0].get(2));
+ assertEquals("2", data2[0].get(3));
+
+ assertEquals(data[2].get(1), data2[2].get(0));
+ assertEquals(data[2].get(2), data2[2].get(1));
+ assertEquals(data[2].get(4), data2[2].get(2));
+ assertEquals(data[2].get(5), data2[2].get(3));
+
+
+ filter = new RangeFilter(0, 0, 2, RangeFilter.INSIDE_BOUNDS);
+ data2 = filter.filter(data);
+
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ assertEquals(width, data2.length);
+ assertEquals(3, data2[0].size());
+ assertEquals("1", data2[0].get(0));
+ assertEquals("1", data2[0].get(1));
+ assertEquals("1", data2[0].get(2));
+
+ assertEquals(data[2].get(1), data2[2].get(0));
+ assertEquals(data[2].get(4), data2[2].get(1));
+ assertEquals(data[2].get(7), data2[2].get(2));
+
+
+ filter = new RangeFilter(0, 0, 2, RangeFilter.OUTSIDE_BOUNDS | RangeFilter.INCLUSIVE);
+ data2 = filter.filter(data);
+
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ assertEquals(width, data2.length);
+ assertEquals(7, data2[0].size());
+ assertEquals("0", data2[0].get(0));
+ assertEquals("2", data2[0].get(1));
+ assertEquals("0", data2[0].get(2));
+ assertEquals("2", data2[0].get(3));
+
+ assertEquals(data[2].get(0), data2[2].get(0));
+ assertEquals(data[2].get(2), data2[2].get(1));
+ assertEquals(data[2].get(3), data2[2].get(2));
+ assertEquals(data[2].get(5), data2[2].get(3));
+
+
+ filter = new RangeFilter(0, 0, 2, RangeFilter.INSIDE_BOUNDS);
+ data2 = filter.filter(data);
+
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ assertEquals(width, data2.length);
+ assertEquals(3, data2[0].size());
+ assertEquals("1", data2[0].get(0));
+ assertEquals("1", data2[0].get(1));
+ assertEquals("1", data2[0].get(2));
+
+ assertEquals(data[2].get(1), data2[2].get(0));
+ assertEquals(data[2].get(4), data2[2].get(1));
+ assertEquals(data[2].get(7), data2[2].get(2));
+
+
+ filter = new RangeFilter(0, 0, 2, RangeFilter.OUTSIDE_BOUNDS);
+ data2 = filter.filter(data);
+
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ assertEquals(width, data2.length);
+ assertEquals(0, data2[0].size());
+
+
+ filter = new RangeFilter(-1, 1, 3, 0);
+ assertNull(filter.filter(data));
+ }
+ @Test
+ public void testUnboundedFilters() {
+ int width = 4;
+ int height = 10;
+ int wrap = height / 3;
+ ArrayList<Object>[] data = MockDataSet.buildArray(width, height, wrap);
+
+ filter = new RangeFilter(1, 1, null, RangeFilter.INCLUSIVE);
+ List<Object>[] data2 = filter.filter(data);
+
+ assertEquals(width, data.length);
+ assertEquals(height, data[1].size());
+ assertEquals(width, data2.length);
+ assertEquals(7, data2[1].size());
+ assertEquals("1", data2[1].get(0));
+ assertEquals("2", data2[1].get(1));
+ assertEquals("1", data2[1].get(2));
+ assertEquals("2", data2[1].get(3));
+
+ assertEquals(data[2].get(0), data2[2].get(0));
+ assertEquals(data[2].get(1), data2[2].get(1));
+ assertEquals(data[2].get(3), data2[2].get(2));
+ assertEquals(data[2].get(4), data2[2].get(3));
+
+
+ filter = new RangeFilter(1, 1, null, 0);
+ data2 = filter.filter(data);
+
+ assertEquals(width, data.length);
+ assertEquals(height, data[1].size());
+ assertEquals(width, data2.length);
+ assertEquals(3, data2[1].size());
+ assertEquals("2", data2[1].get(0));
+ assertEquals("2", data2[1].get(1));
+ assertEquals("2", data2[1].get(2));
+
+ assertEquals(data[2].get(1), data2[2].get(0));
+ assertEquals(data[2].get(4), data2[2].get(1));
+ assertEquals(data[2].get(7), data2[2].get(2));
+
+
+ filter = new RangeFilter(1, null, 1, RangeFilter.INCLUSIVE);
+ data2 = filter.filter(data);
+
+ assertEquals(width, data.length);
+ assertEquals(height, data[1].size());
+ assertEquals(width, data2.length);
+ assertEquals(7, data2[1].size());
+ assertEquals("1", data2[1].get(0));
+ assertEquals("0", data2[1].get(1));
+ assertEquals("1", data2[1].get(2));
+ assertEquals("0", data2[1].get(3));
+
+ assertEquals(data[2].get(0), data2[2].get(0));
+ assertEquals(data[2].get(2), data2[2].get(1));
+ assertEquals(data[2].get(3), data2[2].get(2));
+ assertEquals(data[2].get(5), data2[2].get(3));
+
+
+ filter = new RangeFilter(1, null, 1, 0);
+ data2 = filter.filter(data);
+
+ assertEquals(width, data.length);
+ assertEquals(height, data[1].size());
+ assertEquals(width, data2.length);
+ assertEquals(3, data2[1].size());
+ assertEquals("0", data2[1].get(0));
+ assertEquals("0", data2[1].get(1));
+ assertEquals("0", data2[1].get(2));
+
+ assertEquals(data[2].get(2), data2[2].get(0));
+ assertEquals(data[2].get(5), data2[2].get(1));
+ assertEquals(data[2].get(8), data2[2].get(2));
+ }
+ @Test
+ public void testGetID() {
+ assertEquals(RangeFilter.ID, filter.getID());
+ }
+
+ private RangeFilter filter;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/SortFilterTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/SortFilterTest.java
index e5596d3bc8..2219576afe 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/SortFilterTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/SortFilterTest.java
@@ -24,75 +24,75 @@ import org.junit.Before;
import org.junit.Test;
public class SortFilterTest {
- @Before
- public void setUp() {
- filter = new SortFilter(0, SortFilter.ASCENDING);
- }
- @Test
- public void testSortFilter() {
- SortFilter filter = new SortFilter(-1, SortFilter.ASCENDING);
- assertNotNull(filter);
- }
- @Test
- public void testFilter() {
- int width = 4;
- int height = 10;
- int wrap = height / 3;
- ArrayList<Object>[] data = MockDataSet.buildArray(width, height, wrap);
+ @Before
+ public void setUp() {
+ filter = new SortFilter(0, SortFilter.ASCENDING);
+ }
+ @Test
+ public void testSortFilter() {
+ SortFilter filter = new SortFilter(-1, SortFilter.ASCENDING);
+ assertNotNull(filter);
+ }
+ @Test
+ public void testFilter() {
+ int width = 4;
+ int height = 10;
+ int wrap = height / 3;
+ ArrayList<Object>[] data = MockDataSet.buildArray(width, height, wrap);
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- List<Object>[] data2 = filter.filter(data);
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ List<Object>[] data2 = filter.filter(data);
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- assertEquals(width, data2.length);
- assertEquals(height, data2[0].size());
- assertEquals("0", data2[0].get(0));
- assertEquals("0", data2[0].get(1));
- assertEquals("0", data2[0].get(2));
- assertEquals("0", data2[0].get(3));
- assertEquals("1", data2[0].get(4));
- assertEquals("2", data2[0].get(7));
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ assertEquals(width, data2.length);
+ assertEquals(height, data2[0].size());
+ assertEquals("0", data2[0].get(0));
+ assertEquals("0", data2[0].get(1));
+ assertEquals("0", data2[0].get(2));
+ assertEquals("0", data2[0].get(3));
+ assertEquals("1", data2[0].get(4));
+ assertEquals("2", data2[0].get(7));
- assertEquals(data[2].get(0), data2[2].get(0));
- assertEquals(data[2].get(3), data2[2].get(1));
- assertEquals(data[2].get(6), data2[2].get(2));
- assertEquals(data[2].get(9), data2[2].get(3));
+ assertEquals(data[2].get(0), data2[2].get(0));
+ assertEquals(data[2].get(3), data2[2].get(1));
+ assertEquals(data[2].get(6), data2[2].get(2));
+ assertEquals(data[2].get(9), data2[2].get(3));
- filter = new SortFilter(0, SortFilter.DESCENDING);
- data2 = filter.filter(data);
+ filter = new SortFilter(0, SortFilter.DESCENDING);
+ data2 = filter.filter(data);
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- assertEquals(width, data2.length);
- assertEquals(height, data2[0].size());
- assertEquals("2", data2[0].get(0));
- assertEquals("2", data2[0].get(1));
- assertEquals("2", data2[0].get(2));
- assertEquals("1", data2[0].get(3));
- assertEquals("0", data2[0].get(7));
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ assertEquals(width, data2.length);
+ assertEquals(height, data2[0].size());
+ assertEquals("2", data2[0].get(0));
+ assertEquals("2", data2[0].get(1));
+ assertEquals("2", data2[0].get(2));
+ assertEquals("1", data2[0].get(3));
+ assertEquals("0", data2[0].get(7));
- assertEquals(data[2].get(2), data2[2].get(0));
- assertEquals(data[2].get(5), data2[2].get(1));
- assertEquals(data[2].get(8), data2[2].get(2));
- assertEquals(data[2].get(9), data2[2].get(7));
+ assertEquals(data[2].get(2), data2[2].get(0));
+ assertEquals(data[2].get(5), data2[2].get(1));
+ assertEquals(data[2].get(8), data2[2].get(2));
+ assertEquals(data[2].get(9), data2[2].get(7));
- filter = new SortFilter(-1, 0);
- assertNull(filter.filter(data));
+ filter = new SortFilter(-1, 0);
+ assertNull(filter.filter(data));
- data[0].add("a");
- data[0].add("a");
- data[1].add("b");
- data[1].add("c");
- filter = new SortFilter(0, 0);
- assertNotNull(filter.filter(data));
- }
- @Test
- public void testGetID() {
- assertEquals(SortFilter.ID, filter.getID());
- }
+ data[0].add("a");
+ data[0].add("a");
+ data[1].add("b");
+ data[1].add("c");
+ filter = new SortFilter(0, 0);
+ assertNotNull(filter.filter(data));
+ }
+ @Test
+ public void testGetID() {
+ assertEquals(SortFilter.ID, filter.getID());
+ }
- private SortFilter filter;
+ private SortFilter filter;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/UniqueFilterTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/UniqueFilterTest.java
index 489e6d1373..ba2047cefe 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/UniqueFilterTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/filters/UniqueFilterTest.java
@@ -26,57 +26,57 @@ import org.junit.Before;
import org.junit.Test;
public class UniqueFilterTest {
- @Before
- public void setUp() {
- filter = new UniqueFilter(0, new SumAggregate());
- }
- @Test
- public void testUniqueFilter() {
- filter = new UniqueFilter(-1, new MaxAggregate());
- assertNotNull(filter);
- }
- @Test
- public void testFilter() {
- int width = 4;
- int height = 10;
- int wrap = height / 3;
- ArrayList<Object>[] data = MockDataSet.buildArray(width, height, wrap);
+ @Before
+ public void setUp() {
+ filter = new UniqueFilter(0, new SumAggregate());
+ }
+ @Test
+ public void testUniqueFilter() {
+ filter = new UniqueFilter(-1, new MaxAggregate());
+ assertNotNull(filter);
+ }
+ @Test
+ public void testFilter() {
+ int width = 4;
+ int height = 10;
+ int wrap = height / 3;
+ ArrayList<Object>[] data = MockDataSet.buildArray(width, height, wrap);
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
- List<Object>[] data2 = filter.filter(data);
+ List<Object>[] data2 = filter.filter(data);
- assertEquals(width, data.length);
- assertEquals(height, data[0].size());
- assertEquals(width, data2.length);
- assertEquals(wrap, data2[0].size());
- assertEquals("1", data2[0].get(0));
- assertEquals("2", data2[0].get(1));
- assertEquals("0", data2[0].get(2));
+ assertEquals(width, data.length);
+ assertEquals(height, data[0].size());
+ assertEquals(width, data2.length);
+ assertEquals(wrap, data2[0].size());
+ assertEquals("1", data2[0].get(0));
+ assertEquals("2", data2[0].get(1));
+ assertEquals("0", data2[0].get(2));
- assertEquals(0, ((Number)data2[2].get(0)).intValue());
- assertEquals(3, ((Number)data2[2].get(1)).intValue());
- assertEquals(8, ((Number)data2[2].get(2)).intValue());
+ assertEquals(0, ((Number)data2[2].get(0)).intValue());
+ assertEquals(3, ((Number)data2[2].get(1)).intValue());
+ assertEquals(8, ((Number)data2[2].get(2)).intValue());
- filter = new UniqueFilter(-1, new SumAggregate());
- assertNull(filter.filter(null));
+ filter = new UniqueFilter(-1, new SumAggregate());
+ assertNull(filter.filter(null));
- data = MockDataSet.createArrayList(2, new Object());
- data[0] = new ArrayList<>();
- data[1] = new ArrayList<>();
+ data = MockDataSet.createArrayList(2, new Object());
+ data[0] = new ArrayList<>();
+ data[1] = new ArrayList<>();
- data[0].add("a");
- data[0].add("a");
- data[1].add("b");
- data[1].add("c");
- filter = new UniqueFilter(0, new SumAggregate());
- assertNotNull(filter.filter(data));
- }
- @Test
- public void testGetID() {
- assertEquals(UniqueFilter.ID, filter.getID());
- }
+ data[0].add("a");
+ data[0].add("a");
+ data[1].add("b");
+ data[1].add("c");
+ filter = new UniqueFilter(0, new SumAggregate());
+ assertNotNull(filter.filter(data));
+ }
+ @Test
+ public void testGetID() {
+ assertEquals(UniqueFilter.ID, filter.getID());
+ }
- private UniqueFilter filter;
+ private UniqueFilter filter;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/ChartStreamDaemonTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/ChartStreamDaemonTest.java
index 2161a1beb8..9dbf71b1ca 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/ChartStreamDaemonTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/ChartStreamDaemonTest.java
@@ -22,30 +22,30 @@ import org.junit.Before;
import org.junit.Test;
public class ChartStreamDaemonTest {
-
- @Before
- public void setUp() {
- csd = new ChartStreamDaemon(null, null);
- assertNotNull(csd);
- csd1 = new ChartStreamDaemon(new RowDataSet(new String[] {"a"}), new RowParser(new String[] {"\\w", "\\s"}));
- assertNotNull(csd1);
- }
- @Test
- public void testHandleEvent() {
- csd.handleDataEvent("a a a");
- csd1.handleDataEvent("a a a");
- }
- @Test
- public void testIsDisposed() {
- assertFalse(csd1.isDisposed());
- }
- @Test
- public void testDispose() {
- assertFalse(csd1.isDisposed());
- csd1.dispose();
- assertTrue(csd1.isDisposed());
- }
+ @Before
+ public void setUp() {
+ csd = new ChartStreamDaemon(null, null);
+ assertNotNull(csd);
- private ChartStreamDaemon csd, csd1;
+ csd1 = new ChartStreamDaemon(new RowDataSet(new String[] {"a"}), new RowParser(new String[] {"\\w", "\\s"}));
+ assertNotNull(csd1);
+ }
+ @Test
+ public void testHandleEvent() {
+ csd.handleDataEvent("a a a");
+ csd1.handleDataEvent("a a a");
+ }
+ @Test
+ public void testIsDisposed() {
+ assertFalse(csd1.isDisposed());
+ }
+ @Test
+ public void testDispose() {
+ assertFalse(csd1.isDisposed());
+ csd1.dispose();
+ assertTrue(csd1.isDisposed());
+ }
+
+ private ChartStreamDaemon csd, csd1;
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/NumberTypeTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/NumberTypeTest.java
index 648b812390..c2256f5221 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/NumberTypeTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/NumberTypeTest.java
@@ -18,51 +18,51 @@ import org.eclipse.linuxtools.systemtap.graphing.core.structures.NumberType;
import org.junit.Test;
public class NumberTypeTest {
- @Test
- public void testGetNumber() {
- Number n = NumberType.getNumber(3, 3.2);
- assertTrue(n instanceof Integer);
- assertEquals(3, n.intValue());
+ @Test
+ public void testGetNumber() {
+ Number n = NumberType.getNumber(3, 3.2);
+ assertTrue(n instanceof Integer);
+ assertEquals(3, n.intValue());
- n = NumberType.getNumber(3d, 3.2);
- assertTrue(n instanceof Double);
- assertEquals(3.2, n.doubleValue(), 0.0);
+ n = NumberType.getNumber(3d, 3.2);
+ assertTrue(n instanceof Double);
+ assertEquals(3.2, n.doubleValue(), 0.0);
- n = NumberType.getNumber(3f, 3.2);
- assertTrue(n instanceof Float);
- assertEquals(3.2, n.floatValue(), 0.0001);
+ n = NumberType.getNumber(3f, 3.2);
+ assertTrue(n instanceof Float);
+ assertEquals(3.2, n.floatValue(), 0.0001);
- n = NumberType.getNumber(3L, 3.2);
- assertTrue(n instanceof Long);
- assertEquals(3, n.longValue());
+ n = NumberType.getNumber(3L, 3.2);
+ assertTrue(n instanceof Long);
+ assertEquals(3, n.longValue());
- n = NumberType.getNumber((byte)3, 3.2);
- assertTrue(n instanceof Byte);
- assertEquals(3, n.byteValue());
+ n = NumberType.getNumber((byte)3, 3.2);
+ assertTrue(n instanceof Byte);
+ assertEquals(3, n.byteValue());
+
+ n = NumberType.getNumber((short)3, 3.2);
+ assertTrue(n instanceof Short);
+ assertEquals(3, n.shortValue());
+ }
+ @Test
+ public void testObj2num() {
+ Object[] obj = new Object[] {3, 2.3d, 4.2f};
+ Number[] num = NumberType.obj2num(obj);
+
+ assertEquals(0, NumberType.obj2num("a").intValue());
+ assertEquals(3, num.length);
+ assertTrue(num[0] instanceof Integer);
+ assertTrue(num[1] instanceof Double);
+ assertTrue(num[2] instanceof Float);
+ assertEquals(3, num[0].intValue());
+ assertEquals(2.3, num[1].doubleValue(), 0.00001);
+ assertEquals(4.2, num[2].doubleValue(), 0.00001);
+ }
+ @Test
+ public void testCleanObj2Num() {
+ assertEquals(3, NumberType.cleanObj2Num("3").intValue());
+ assertEquals(3.2, NumberType.cleanObj2Num("3.2").doubleValue(), 0.00001);
+ assertEquals(3, NumberType.cleanObj2Num(new Integer(3)).intValue());
+ }
- n = NumberType.getNumber((short)3, 3.2);
- assertTrue(n instanceof Short);
- assertEquals(3, n.shortValue());
- }
- @Test
- public void testObj2num() {
- Object[] obj = new Object[] {3, 2.3d, 4.2f};
- Number[] num = NumberType.obj2num(obj);
-
- assertEquals(0, NumberType.obj2num("a").intValue());
- assertEquals(3, num.length);
- assertTrue(num[0] instanceof Integer);
- assertTrue(num[1] instanceof Double);
- assertTrue(num[2] instanceof Float);
- assertEquals(3, num[0].intValue());
- assertEquals(2.3, num[1].doubleValue(), 0.00001);
- assertEquals(4.2, num[2].doubleValue(), 0.00001);
- }
- @Test
- public void testCleanObj2Num() {
- assertEquals(3, NumberType.cleanObj2Num("3").intValue());
- assertEquals(3.2, NumberType.cleanObj2Num("3.2").doubleValue(), 0.00001);
- assertEquals(3, NumberType.cleanObj2Num(new Integer(3)).intValue());
- }
-
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/UpdateManagerTest.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/UpdateManagerTest.java
index 49944bac84..9799a1f3bd 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/UpdateManagerTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core.tests/src/org/eclipse/linuxtools/systemtap/graphing/core/tests/structures/UpdateManagerTest.java
@@ -20,42 +20,42 @@ import org.junit.Before;
import org.junit.Test;
public class UpdateManagerTest {
- @Before
- public void setUp() {
- manager = new UpdateManager(5);
- }
- @Test
- public void testStop() {
- assertTrue(manager.isRunning());
- manager.stop();
- assertFalse(manager.isRunning());
- }
- @Test
- public void testAddUpdateListener() {
- manager.addUpdateListener(listener);
- }
- @Test
- public void testRemoveUpdateListener() {
- manager.addUpdateListener(listener);
- manager.removeUpdateListener(listener);
- }
- @Test
- public void testIsRunning() {
- assertTrue(manager.isRunning());
- manager.stop();
- assertFalse(manager.isRunning());
- }
- @Test
- public void testDispose() {
- manager.dispose();
- assertFalse(manager.isRunning());
- }
-
- private UpdateManager manager;
- private IUpdateListener listener = new IUpdateListener() {
- @Override
- public void handleUpdateEvent() {
- //Do nothing;
- }
- };
+ @Before
+ public void setUp() {
+ manager = new UpdateManager(5);
+ }
+ @Test
+ public void testStop() {
+ assertTrue(manager.isRunning());
+ manager.stop();
+ assertFalse(manager.isRunning());
+ }
+ @Test
+ public void testAddUpdateListener() {
+ manager.addUpdateListener(listener);
+ }
+ @Test
+ public void testRemoveUpdateListener() {
+ manager.addUpdateListener(listener);
+ manager.removeUpdateListener(listener);
+ }
+ @Test
+ public void testIsRunning() {
+ assertTrue(manager.isRunning());
+ manager.stop();
+ assertFalse(manager.isRunning());
+ }
+ @Test
+ public void testDispose() {
+ manager.dispose();
+ assertFalse(manager.isRunning());
+ }
+
+ private UpdateManager manager;
+ private IUpdateListener listener = new IUpdateListener() {
+ @Override
+ public void handleUpdateEvent() {
+ //Do nothing;
+ }
+ };
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/internal/systemtap/graphing/core/GraphingCorePlugin.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/internal/systemtap/graphing/core/GraphingCorePlugin.java
index 1a1ff00e0d..41655d0feb 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/internal/systemtap/graphing/core/GraphingCorePlugin.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/internal/systemtap/graphing/core/GraphingCorePlugin.java
@@ -17,8 +17,8 @@ import java.util.ArrayList;
*/
public class GraphingCorePlugin {
- @SuppressWarnings("unchecked")
- public static <T> ArrayList<T>[] createArrayList(int size, T instance) {
- return new ArrayList[size];
- }
+ @SuppressWarnings("unchecked")
+ public static <T> ArrayList<T>[] createArrayList(int size, T instance) {
+ return new ArrayList[size];
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/internal/systemtap/graphing/core/Localization.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/internal/systemtap/graphing/core/Localization.java
index 054500907f..82bd41836c 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/internal/systemtap/graphing/core/Localization.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/internal/systemtap/graphing/core/Localization.java
@@ -15,19 +15,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Localization {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.graphing.core.localization"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.graphing.core.localization"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Localization() {
- }
+ private Localization() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/IGraphColorConstants.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/IGraphColorConstants.java
index d35528caa9..c94e0eac82 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/IGraphColorConstants.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/IGraphColorConstants.java
@@ -14,280 +14,280 @@ package org.eclipse.linuxtools.systemtap.graphing.core;
import org.eclipse.swt.graphics.RGB;
public interface IGraphColorConstants {
- RGB[] COLORS = new RGB[] {
+ RGB[] COLORS = new RGB[] {
- new RGB(0,102,204),
- new RGB(51,153,255),
- new RGB(102,204,255),
+ new RGB(0,102,204),
+ new RGB(51,153,255),
+ new RGB(102,204,255),
- new RGB(0,51,153),
- new RGB(153,153,255),
- new RGB(102,102,255),
- new RGB(51,51,255),
- new RGB(102,153,255),
- new RGB(153,204,255),
- new RGB(204,255,255),
- new RGB(102,204,204),
- new RGB(0,153,153),
- new RGB(0,102,102),
- new RGB(0,51,102),
- new RGB(0,153,255),
+ new RGB(0,51,153),
+ new RGB(153,153,255),
+ new RGB(102,102,255),
+ new RGB(51,51,255),
+ new RGB(102,153,255),
+ new RGB(153,204,255),
+ new RGB(204,255,255),
+ new RGB(102,204,204),
+ new RGB(0,153,153),
+ new RGB(0,102,102),
+ new RGB(0,51,102),
+ new RGB(0,153,255),
- new RGB(202,204,255),
+ new RGB(202,204,255),
- /*new RGB(153,102,102),
- new RGB(153,153,153),
- new RGB(204,102,103),
- new RGB(204,153,102),
- new RGB(204,153,51),*/
+ /*new RGB(153,102,102),
+ new RGB(153,153,153),
+ new RGB(204,102,103),
+ new RGB(204,153,102),
+ new RGB(204,153,51),*/
- new RGB(204,153,153),
- new RGB(204,204,204),
- new RGB(255,153,153),
- new RGB(255,204,153),
- new RGB(255,204,102),
- new RGB(204,204,153),
- new RGB(255,255,153),
- new RGB(255,255,51),
- new RGB(255,204,153),
- new RGB(153,204,153),
- new RGB(102,204,204),
- new RGB(153,204,204),
- new RGB(153,153,204),
- new RGB(153,102,153),
- new RGB(204,153,204),
- new RGB(153,153,104),
+ new RGB(204,153,153),
+ new RGB(204,204,204),
+ new RGB(255,153,153),
+ new RGB(255,204,153),
+ new RGB(255,204,102),
+ new RGB(204,204,153),
+ new RGB(255,255,153),
+ new RGB(255,255,51),
+ new RGB(255,204,153),
+ new RGB(153,204,153),
+ new RGB(102,204,204),
+ new RGB(153,204,204),
+ new RGB(153,153,204),
+ new RGB(153,102,153),
+ new RGB(204,153,204),
+ new RGB(153,153,104),
- new RGB(0, 0, 255),
- new RGB(255, 0, 0),
- new RGB(0, 255, 0),
- new RGB(255, 0, 255),
- new RGB(0, 255, 255),
- new RGB(255, 255, 0),
- new RGB(127, 127, 255),
- new RGB(255, 127, 127),
- new RGB(127, 255, 127),
+ new RGB(0, 0, 255),
+ new RGB(255, 0, 0),
+ new RGB(0, 255, 0),
+ new RGB(255, 0, 255),
+ new RGB(0, 255, 255),
+ new RGB(255, 255, 0),
+ new RGB(127, 127, 255),
+ new RGB(255, 127, 127),
+ new RGB(127, 255, 127),
- new RGB(255, 255, 255),
- new RGB(255, 255, 204),
- new RGB(255, 255, 153),
- new RGB(255, 255, 102),
- new RGB(255, 255, 51),
- new RGB(255, 255, 0),
- new RGB(255, 204, 255),
- new RGB(255, 204, 204),
- new RGB(255, 204, 153),
- new RGB(255, 204, 102),
- new RGB(255, 204, 51),
- new RGB(255, 204, 0),
- new RGB(255, 153, 255),
- new RGB(255, 153, 204),
- new RGB(255, 153, 153),
- new RGB(255, 153, 102),
- new RGB(255, 153, 51),
- new RGB(255, 153, 0),
- new RGB(255, 102, 255),
- new RGB(255, 102, 204),
- new RGB(255, 102, 153),
- new RGB(255, 102, 102),
- new RGB(255, 102, 51),
- new RGB(255, 102, 0),
- new RGB(255, 51, 255),
- new RGB(255, 51, 204),
- new RGB(255, 51, 153),
- new RGB(255, 51, 102),
- new RGB(255, 51, 51),
- new RGB(255, 51, 0),
- new RGB(255, 0, 255),
- new RGB(255, 0, 204),
- new RGB(255, 0, 153),
- new RGB(255, 0, 102),
- new RGB(255, 0, 51),
- new RGB(255, 0, 0),
- new RGB(204, 255, 255),
- new RGB(204, 255, 204),
- new RGB(204, 255, 153),
- new RGB(204, 255, 102),
- new RGB(204, 255, 51),
- new RGB(204, 255, 0),
- new RGB(204, 204, 255),
- new RGB(204, 204, 204),
- new RGB(204, 204, 153),
- new RGB(204, 204, 102),
- new RGB(204, 204, 51),
- new RGB(204, 204, 0),
- new RGB(204, 153, 255),
- new RGB(204, 153, 204),
- new RGB(204, 153, 153),
- new RGB(204, 153, 102),
- new RGB(204, 153, 51),
- new RGB(204, 153, 0),
- new RGB(204, 102, 255),
- new RGB(204, 102, 204),
- new RGB(204, 102, 153),
- new RGB(204, 102, 102),
- new RGB(204, 102, 51),
- new RGB(204, 102, 0),
- new RGB(204, 51, 255),
- new RGB(204, 51, 204),
- new RGB(204, 51, 153),
- new RGB(204, 51, 102),
- new RGB(204, 51, 51),
- new RGB(204, 51, 0),
- new RGB(204, 0, 255),
- new RGB(204, 0, 204),
- new RGB(204, 0, 153),
- new RGB(204, 0, 102),
- new RGB(204, 0, 51),
- new RGB(204, 0, 0),
- new RGB(153, 255, 255),
- new RGB(153, 255, 204),
- new RGB(153, 255, 153),
- new RGB(153, 255, 102),
- new RGB(153, 255, 51),
- new RGB(153, 255, 0),
- new RGB(153, 204, 255),
- new RGB(153, 204, 204),
- new RGB(153, 204, 153),
- new RGB(153, 204, 102),
- new RGB(153, 204, 51),
- new RGB(153, 204, 0),
- new RGB(153, 153, 255),
- new RGB(153, 153, 204),
- new RGB(153, 153, 153),
- new RGB(153, 153, 102),
- new RGB(153, 153, 51),
- new RGB(153, 153, 0),
- new RGB(153, 102, 255),
- new RGB(153, 102, 204),
- new RGB(153, 102, 153),
- new RGB(153, 102, 102),
- new RGB(153, 102, 51),
- new RGB(153, 102, 0),
- new RGB(153, 51, 255),
- new RGB(153, 51, 204),
- new RGB(153, 51, 153),
- new RGB(153, 51, 102),
- new RGB(153, 51, 51),
- new RGB(153, 51, 0),
- new RGB(153, 0, 255),
- new RGB(153, 0, 204),
- new RGB(153, 0, 153),
- new RGB(153, 0, 102),
- new RGB(153, 0, 51),
- new RGB(153, 0, 0),
- new RGB(102, 255, 255),
- new RGB(102, 255, 204),
- new RGB(102, 255, 153),
- new RGB(102, 255, 102),
- new RGB(102, 255, 51),
- new RGB(102, 255, 0),
- new RGB(102, 204, 255),
- new RGB(102, 204, 204),
- new RGB(102, 204, 153),
- new RGB(102, 204, 102),
- new RGB(102, 204, 51),
- new RGB(102, 204, 0),
- new RGB(102, 153, 255),
- new RGB(102, 153, 204),
- new RGB(102, 153, 153),
- new RGB(102, 153, 102),
- new RGB(102, 153, 51),
- new RGB(102, 153, 0),
- new RGB(102, 102, 255),
- new RGB(102, 102, 204),
- new RGB(102, 102, 153),
- new RGB(102, 102, 102),
- new RGB(102, 102, 51),
- new RGB(102, 102, 0),
- new RGB(102, 51, 255),
- new RGB(102, 51, 204),
- new RGB(102, 51, 153),
- new RGB(102, 51, 102),
- new RGB(102, 51, 51),
- new RGB(102, 51, 0),
- new RGB(102, 0, 255),
- new RGB(102, 0, 204),
- new RGB(102, 0, 153),
- new RGB(102, 0, 102),
- new RGB(102, 0, 51),
- new RGB(102, 0, 0),
- new RGB(51, 255, 255),
- new RGB(51, 255, 204),
- new RGB(51, 255, 153),
- new RGB(51, 255, 102),
- new RGB(51, 255, 51),
- new RGB(51, 255, 0),
- new RGB(51, 204, 255),
- new RGB(51, 204, 204),
- new RGB(51, 204, 153),
- new RGB(51, 204, 102),
- new RGB(51, 204, 51),
- new RGB(51, 204, 0),
- new RGB(51, 153, 255),
- new RGB(51, 153, 204),
- new RGB(51, 153, 153),
- new RGB(51, 153, 102),
- new RGB(51, 153, 51),
- new RGB(51, 153, 0),
- new RGB(51, 102, 255),
- new RGB(51, 102, 204),
- new RGB(51, 102, 153),
- new RGB(51, 102, 102),
- new RGB(51, 102, 51),
- new RGB(51, 102, 0),
- new RGB(51, 51, 255),
- new RGB(51, 51, 204),
- new RGB(51, 51, 153),
- new RGB(51, 51, 102),
- new RGB(51, 51, 51),
- new RGB(51, 51, 0),
- new RGB(51, 0, 255),
- new RGB(51, 0, 204),
- new RGB(51, 0, 153),
- new RGB(51, 0, 102),
- new RGB(51, 0, 51),
- new RGB(51, 0, 0),
- new RGB(0, 255, 255),
- new RGB(0, 255, 204),
- new RGB(0, 255, 153),
- new RGB(0, 255, 102),
- new RGB(0, 255, 51),
- new RGB(0, 255, 0),
- new RGB(0, 204, 255),
- new RGB(0, 204, 204),
- new RGB(0, 204, 153),
- new RGB(0, 204, 102),
- new RGB(0, 204, 51),
- new RGB(0, 204, 0),
- new RGB(0, 153, 255),
- new RGB(0, 153, 204),
- new RGB(0, 153, 153),
- new RGB(0, 153, 102),
- new RGB(0, 153, 51),
- new RGB(0, 153, 0),
- new RGB(0, 102, 255),
- new RGB(0, 102, 204),
- new RGB(0, 102, 153),
- new RGB(0, 102, 102),
- new RGB(0, 102, 51),
- new RGB(0, 102, 0),
- new RGB(0, 51, 255),
- new RGB(0, 51, 204),
- new RGB(0, 51, 153),
- new RGB(0, 51, 102),
- new RGB(0, 51, 51),
- new RGB(0, 51, 0),
- new RGB(0, 0, 255),
- new RGB(0, 0, 204),
- new RGB(0, 0, 153),
- new RGB(0, 0, 102),
- new RGB(0, 0, 51),
- new RGB(0, 0, 0)
- };
+ new RGB(255, 255, 255),
+ new RGB(255, 255, 204),
+ new RGB(255, 255, 153),
+ new RGB(255, 255, 102),
+ new RGB(255, 255, 51),
+ new RGB(255, 255, 0),
+ new RGB(255, 204, 255),
+ new RGB(255, 204, 204),
+ new RGB(255, 204, 153),
+ new RGB(255, 204, 102),
+ new RGB(255, 204, 51),
+ new RGB(255, 204, 0),
+ new RGB(255, 153, 255),
+ new RGB(255, 153, 204),
+ new RGB(255, 153, 153),
+ new RGB(255, 153, 102),
+ new RGB(255, 153, 51),
+ new RGB(255, 153, 0),
+ new RGB(255, 102, 255),
+ new RGB(255, 102, 204),
+ new RGB(255, 102, 153),
+ new RGB(255, 102, 102),
+ new RGB(255, 102, 51),
+ new RGB(255, 102, 0),
+ new RGB(255, 51, 255),
+ new RGB(255, 51, 204),
+ new RGB(255, 51, 153),
+ new RGB(255, 51, 102),
+ new RGB(255, 51, 51),
+ new RGB(255, 51, 0),
+ new RGB(255, 0, 255),
+ new RGB(255, 0, 204),
+ new RGB(255, 0, 153),
+ new RGB(255, 0, 102),
+ new RGB(255, 0, 51),
+ new RGB(255, 0, 0),
+ new RGB(204, 255, 255),
+ new RGB(204, 255, 204),
+ new RGB(204, 255, 153),
+ new RGB(204, 255, 102),
+ new RGB(204, 255, 51),
+ new RGB(204, 255, 0),
+ new RGB(204, 204, 255),
+ new RGB(204, 204, 204),
+ new RGB(204, 204, 153),
+ new RGB(204, 204, 102),
+ new RGB(204, 204, 51),
+ new RGB(204, 204, 0),
+ new RGB(204, 153, 255),
+ new RGB(204, 153, 204),
+ new RGB(204, 153, 153),
+ new RGB(204, 153, 102),
+ new RGB(204, 153, 51),
+ new RGB(204, 153, 0),
+ new RGB(204, 102, 255),
+ new RGB(204, 102, 204),
+ new RGB(204, 102, 153),
+ new RGB(204, 102, 102),
+ new RGB(204, 102, 51),
+ new RGB(204, 102, 0),
+ new RGB(204, 51, 255),
+ new RGB(204, 51, 204),
+ new RGB(204, 51, 153),
+ new RGB(204, 51, 102),
+ new RGB(204, 51, 51),
+ new RGB(204, 51, 0),
+ new RGB(204, 0, 255),
+ new RGB(204, 0, 204),
+ new RGB(204, 0, 153),
+ new RGB(204, 0, 102),
+ new RGB(204, 0, 51),
+ new RGB(204, 0, 0),
+ new RGB(153, 255, 255),
+ new RGB(153, 255, 204),
+ new RGB(153, 255, 153),
+ new RGB(153, 255, 102),
+ new RGB(153, 255, 51),
+ new RGB(153, 255, 0),
+ new RGB(153, 204, 255),
+ new RGB(153, 204, 204),
+ new RGB(153, 204, 153),
+ new RGB(153, 204, 102),
+ new RGB(153, 204, 51),
+ new RGB(153, 204, 0),
+ new RGB(153, 153, 255),
+ new RGB(153, 153, 204),
+ new RGB(153, 153, 153),
+ new RGB(153, 153, 102),
+ new RGB(153, 153, 51),
+ new RGB(153, 153, 0),
+ new RGB(153, 102, 255),
+ new RGB(153, 102, 204),
+ new RGB(153, 102, 153),
+ new RGB(153, 102, 102),
+ new RGB(153, 102, 51),
+ new RGB(153, 102, 0),
+ new RGB(153, 51, 255),
+ new RGB(153, 51, 204),
+ new RGB(153, 51, 153),
+ new RGB(153, 51, 102),
+ new RGB(153, 51, 51),
+ new RGB(153, 51, 0),
+ new RGB(153, 0, 255),
+ new RGB(153, 0, 204),
+ new RGB(153, 0, 153),
+ new RGB(153, 0, 102),
+ new RGB(153, 0, 51),
+ new RGB(153, 0, 0),
+ new RGB(102, 255, 255),
+ new RGB(102, 255, 204),
+ new RGB(102, 255, 153),
+ new RGB(102, 255, 102),
+ new RGB(102, 255, 51),
+ new RGB(102, 255, 0),
+ new RGB(102, 204, 255),
+ new RGB(102, 204, 204),
+ new RGB(102, 204, 153),
+ new RGB(102, 204, 102),
+ new RGB(102, 204, 51),
+ new RGB(102, 204, 0),
+ new RGB(102, 153, 255),
+ new RGB(102, 153, 204),
+ new RGB(102, 153, 153),
+ new RGB(102, 153, 102),
+ new RGB(102, 153, 51),
+ new RGB(102, 153, 0),
+ new RGB(102, 102, 255),
+ new RGB(102, 102, 204),
+ new RGB(102, 102, 153),
+ new RGB(102, 102, 102),
+ new RGB(102, 102, 51),
+ new RGB(102, 102, 0),
+ new RGB(102, 51, 255),
+ new RGB(102, 51, 204),
+ new RGB(102, 51, 153),
+ new RGB(102, 51, 102),
+ new RGB(102, 51, 51),
+ new RGB(102, 51, 0),
+ new RGB(102, 0, 255),
+ new RGB(102, 0, 204),
+ new RGB(102, 0, 153),
+ new RGB(102, 0, 102),
+ new RGB(102, 0, 51),
+ new RGB(102, 0, 0),
+ new RGB(51, 255, 255),
+ new RGB(51, 255, 204),
+ new RGB(51, 255, 153),
+ new RGB(51, 255, 102),
+ new RGB(51, 255, 51),
+ new RGB(51, 255, 0),
+ new RGB(51, 204, 255),
+ new RGB(51, 204, 204),
+ new RGB(51, 204, 153),
+ new RGB(51, 204, 102),
+ new RGB(51, 204, 51),
+ new RGB(51, 204, 0),
+ new RGB(51, 153, 255),
+ new RGB(51, 153, 204),
+ new RGB(51, 153, 153),
+ new RGB(51, 153, 102),
+ new RGB(51, 153, 51),
+ new RGB(51, 153, 0),
+ new RGB(51, 102, 255),
+ new RGB(51, 102, 204),
+ new RGB(51, 102, 153),
+ new RGB(51, 102, 102),
+ new RGB(51, 102, 51),
+ new RGB(51, 102, 0),
+ new RGB(51, 51, 255),
+ new RGB(51, 51, 204),
+ new RGB(51, 51, 153),
+ new RGB(51, 51, 102),
+ new RGB(51, 51, 51),
+ new RGB(51, 51, 0),
+ new RGB(51, 0, 255),
+ new RGB(51, 0, 204),
+ new RGB(51, 0, 153),
+ new RGB(51, 0, 102),
+ new RGB(51, 0, 51),
+ new RGB(51, 0, 0),
+ new RGB(0, 255, 255),
+ new RGB(0, 255, 204),
+ new RGB(0, 255, 153),
+ new RGB(0, 255, 102),
+ new RGB(0, 255, 51),
+ new RGB(0, 255, 0),
+ new RGB(0, 204, 255),
+ new RGB(0, 204, 204),
+ new RGB(0, 204, 153),
+ new RGB(0, 204, 102),
+ new RGB(0, 204, 51),
+ new RGB(0, 204, 0),
+ new RGB(0, 153, 255),
+ new RGB(0, 153, 204),
+ new RGB(0, 153, 153),
+ new RGB(0, 153, 102),
+ new RGB(0, 153, 51),
+ new RGB(0, 153, 0),
+ new RGB(0, 102, 255),
+ new RGB(0, 102, 204),
+ new RGB(0, 102, 153),
+ new RGB(0, 102, 102),
+ new RGB(0, 102, 51),
+ new RGB(0, 102, 0),
+ new RGB(0, 51, 255),
+ new RGB(0, 51, 204),
+ new RGB(0, 51, 153),
+ new RGB(0, 51, 102),
+ new RGB(0, 51, 51),
+ new RGB(0, 51, 0),
+ new RGB(0, 0, 255),
+ new RGB(0, 0, 204),
+ new RGB(0, 0, 153),
+ new RGB(0, 0, 102),
+ new RGB(0, 0, 51),
+ new RGB(0, 0, 0)
+ };
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/BlockAdapter.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/BlockAdapter.java
index 1aa4f83122..5ff759eb84 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/BlockAdapter.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/BlockAdapter.java
@@ -18,82 +18,82 @@ import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IBlockDataSet;
import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IDataSet;
public class BlockAdapter implements IAdapter {
- public BlockAdapter(IBlockDataSet data, int xSeries, int[] ySeries) {
- this.data = data;
- this.xSeries = xSeries;
- this.ySeries = Arrays.copyOf(ySeries, ySeries.length);
- }
-
- @Override
- public Number getYSeriesMax(int y, int start, int end) {
- return getSeriesMax(ySeries[y], start, end);
- }
-
- @Override
- public Number getSeriesMax(int series, int start, int end) {
- if(start < 0 || end > data.getRowCount() || start > end)
- return null;
-
- Number max = new Double(Double.NEGATIVE_INFINITY);
- Number cur;
-
- Object[] dataColumn = data.getColumn(series, start, end);
- for(int i=0; i<dataColumn.length; i++) {
- try {
- cur = new Double(Double.parseDouble(dataColumn[i].toString()));
- if(max.doubleValue() < cur.doubleValue())
- max = cur;
- } catch (NumberFormatException e) {}
- }
- return max;
- }
-
- @Override
- public String[] getLabels() {
- String[] labels = data.getTitles();
-
- String[] labels2 = new String[ySeries.length + 1];
- labels2[0] = (IDataSet.COL_ROW_NUM == xSeries) ? Localization.getString("BlockAdapter.RowNum") : labels[xSeries]; //$NON-NLS-1$
-
- for(int i=0; i<ySeries.length; i++)
- labels2[i+1] = labels[ySeries[i]];
-
- return labels2;
- }
-
- @Override
- public int getSeriesCount() {
- return ySeries.length;
- }
-
- @Override
- public int getRecordCount() {
- return data.getRowCount();
- }
-
- @Override
- public Object[][] getData() {
- return getData(0, getRecordCount());
- }
-
- //[Row][Column]
- @Override
- public Object[][] getData(int start, int end) {
- Object[][] o = new Object[Math.min(end-start,getRecordCount())][ySeries.length+1];
-
- Object[] row;
- for(int j,i=0; i<o.length; i++) {
- row = data.getRow(i+start);
- o[i][0] = (IDataSet.COL_ROW_NUM == xSeries) ? Integer.valueOf(i) : row[xSeries];
-
- for(j=0; j<ySeries.length; j++)
- o[i][j+1] = row[ySeries[j]];
- }
-
- return o;
- }
-
- private IBlockDataSet data;
- private int xSeries;
- private int[] ySeries;
+ public BlockAdapter(IBlockDataSet data, int xSeries, int[] ySeries) {
+ this.data = data;
+ this.xSeries = xSeries;
+ this.ySeries = Arrays.copyOf(ySeries, ySeries.length);
+ }
+
+ @Override
+ public Number getYSeriesMax(int y, int start, int end) {
+ return getSeriesMax(ySeries[y], start, end);
+ }
+
+ @Override
+ public Number getSeriesMax(int series, int start, int end) {
+ if(start < 0 || end > data.getRowCount() || start > end)
+ return null;
+
+ Number max = new Double(Double.NEGATIVE_INFINITY);
+ Number cur;
+
+ Object[] dataColumn = data.getColumn(series, start, end);
+ for(int i=0; i<dataColumn.length; i++) {
+ try {
+ cur = new Double(Double.parseDouble(dataColumn[i].toString()));
+ if(max.doubleValue() < cur.doubleValue())
+ max = cur;
+ } catch (NumberFormatException e) {}
+ }
+ return max;
+ }
+
+ @Override
+ public String[] getLabels() {
+ String[] labels = data.getTitles();
+
+ String[] labels2 = new String[ySeries.length + 1];
+ labels2[0] = (IDataSet.COL_ROW_NUM == xSeries) ? Localization.getString("BlockAdapter.RowNum") : labels[xSeries]; //$NON-NLS-1$
+
+ for(int i=0; i<ySeries.length; i++)
+ labels2[i+1] = labels[ySeries[i]];
+
+ return labels2;
+ }
+
+ @Override
+ public int getSeriesCount() {
+ return ySeries.length;
+ }
+
+ @Override
+ public int getRecordCount() {
+ return data.getRowCount();
+ }
+
+ @Override
+ public Object[][] getData() {
+ return getData(0, getRecordCount());
+ }
+
+ //[Row][Column]
+ @Override
+ public Object[][] getData(int start, int end) {
+ Object[][] o = new Object[Math.min(end-start,getRecordCount())][ySeries.length+1];
+
+ Object[] row;
+ for(int j,i=0; i<o.length; i++) {
+ row = data.getRow(i+start);
+ o[i][0] = (IDataSet.COL_ROW_NUM == xSeries) ? Integer.valueOf(i) : row[xSeries];
+
+ for(j=0; j<ySeries.length; j++)
+ o[i][j+1] = row[ySeries[j]];
+ }
+
+ return o;
+ }
+
+ private IBlockDataSet data;
+ private int xSeries;
+ private int[] ySeries;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/IAdapter.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/IAdapter.java
index b5d71d9989..79c06650c7 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/IAdapter.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/IAdapter.java
@@ -12,12 +12,12 @@
package org.eclipse.linuxtools.systemtap.graphing.core.adapters;
public interface IAdapter {
- Number getYSeriesMax(int series, int start, int end);
- Number getSeriesMax(int series, int start, int end);
+ Number getYSeriesMax(int series, int start, int end);
+ Number getSeriesMax(int series, int start, int end);
- String[] getLabels();
- int getRecordCount();
- int getSeriesCount();
- Object[][] getData();
- Object[][] getData(int start, int end);
+ String[] getLabels();
+ int getRecordCount();
+ int getSeriesCount();
+ Object[][] getData();
+ Object[][] getData(int start, int end);
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/ScrollAdapter.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/ScrollAdapter.java
index f96ff6d0e7..cd074fc847 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/ScrollAdapter.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/adapters/ScrollAdapter.java
@@ -18,87 +18,87 @@ import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IDataSet;
import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IHistoricalDataSet;
public class ScrollAdapter implements IAdapter {
- public ScrollAdapter(IHistoricalDataSet data, int xSeries, int[] ySeries, String key) {
- this.data = data;
- this.xSeries = xSeries;
- this.ySeries = Arrays.copyOf(ySeries, ySeries.length);
- this.key = key;
- }
-
- @Override
- public Number getYSeriesMax(int y, int start, int end) {
- return getSeriesMax(ySeries[y], start, end);
- }
-
- @Override
- public Number getSeriesMax(int series, int start, int end) {
- if(start < 0 || end > data.getRowCount() || start > end)
- return null;
-
- Number max = new Double(Double.NEGATIVE_INFINITY);
- Number cur;
-
- Object[] dataColumn = data.getHistoricalData(key, series, start, end);
- for(int i=0; i<dataColumn.length; i++) {
- try {
- cur = new Double(Double.parseDouble(dataColumn[i].toString()));
- if(max.doubleValue() < cur.doubleValue())
- max = cur;
- } catch (NumberFormatException e) {}
- }
- return max;
- }
-
- @Override
- public String[] getLabels() {
- String[] labels = data.getTitles();
-
- String[] labels2 = new String[ySeries.length + 1];
- labels2[0] = (IDataSet.COL_ROW_NUM == xSeries) ? Localization.getString("ScrollAdapter.RowNum") : labels[xSeries]; //$NON-NLS-1$
-
- for(int i=0; i<ySeries.length; i++)
- labels2[i+1] = labels[ySeries[i]];
-
- return labels2;
- }
-
- @Override
- public int getSeriesCount() {
- return ySeries.length;
- }
-
- @Override
- public int getRecordCount() {
- return data.getEntryCount();
- }
-
- @Override
- public Object[][] getData() {
- return getData(0, getRecordCount());
- }
-
- //[Row][Column]
- @Override
- public Object[][] getData(int start, int end) {
- Object[][] o = new Object[Math.min(end-start,getRecordCount())][ySeries.length+1];
-
- Object[] x = data.getHistoricalData(key, xSeries, start, end);
- Object[][] y = new Object[ySeries.length][data.getEntryCount()];
-
- for(int i=0; i<ySeries.length; i++)
- y[i] = data.getHistoricalData(key, ySeries[i], start, end);
-
- for(int j,i=0; i<o.length; i++) {
- o[i][0] = x[i];
- for(j=0; j<ySeries.length; j++)
- o[i][j+1] = y[j][i];
- }
-
- return o;
- }
-
- private IHistoricalDataSet data;
- private int xSeries;
- private int[] ySeries;
- private String key;
+ public ScrollAdapter(IHistoricalDataSet data, int xSeries, int[] ySeries, String key) {
+ this.data = data;
+ this.xSeries = xSeries;
+ this.ySeries = Arrays.copyOf(ySeries, ySeries.length);
+ this.key = key;
+ }
+
+ @Override
+ public Number getYSeriesMax(int y, int start, int end) {
+ return getSeriesMax(ySeries[y], start, end);
+ }
+
+ @Override
+ public Number getSeriesMax(int series, int start, int end) {
+ if(start < 0 || end > data.getRowCount() || start > end)
+ return null;
+
+ Number max = new Double(Double.NEGATIVE_INFINITY);
+ Number cur;
+
+ Object[] dataColumn = data.getHistoricalData(key, series, start, end);
+ for(int i=0; i<dataColumn.length; i++) {
+ try {
+ cur = new Double(Double.parseDouble(dataColumn[i].toString()));
+ if(max.doubleValue() < cur.doubleValue())
+ max = cur;
+ } catch (NumberFormatException e) {}
+ }
+ return max;
+ }
+
+ @Override
+ public String[] getLabels() {
+ String[] labels = data.getTitles();
+
+ String[] labels2 = new String[ySeries.length + 1];
+ labels2[0] = (IDataSet.COL_ROW_NUM == xSeries) ? Localization.getString("ScrollAdapter.RowNum") : labels[xSeries]; //$NON-NLS-1$
+
+ for(int i=0; i<ySeries.length; i++)
+ labels2[i+1] = labels[ySeries[i]];
+
+ return labels2;
+ }
+
+ @Override
+ public int getSeriesCount() {
+ return ySeries.length;
+ }
+
+ @Override
+ public int getRecordCount() {
+ return data.getEntryCount();
+ }
+
+ @Override
+ public Object[][] getData() {
+ return getData(0, getRecordCount());
+ }
+
+ //[Row][Column]
+ @Override
+ public Object[][] getData(int start, int end) {
+ Object[][] o = new Object[Math.min(end-start,getRecordCount())][ySeries.length+1];
+
+ Object[] x = data.getHistoricalData(key, xSeries, start, end);
+ Object[][] y = new Object[ySeries.length][data.getEntryCount()];
+
+ for(int i=0; i<ySeries.length; i++)
+ y[i] = data.getHistoricalData(key, ySeries[i], start, end);
+
+ for(int j,i=0; i<o.length; i++) {
+ o[i][0] = x[i];
+ for(j=0; j<ySeries.length; j++)
+ o[i][j+1] = y[j][i];
+ }
+
+ return o;
+ }
+
+ private IHistoricalDataSet data;
+ private int xSeries;
+ private int[] ySeries;
+ private String key;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/AverageAggregate.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/AverageAggregate.java
index 18c56ce017..62f53b084e 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/AverageAggregate.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/AverageAggregate.java
@@ -15,33 +15,33 @@ import org.eclipse.linuxtools.systemtap.graphing.core.structures.NumberType;
public class AverageAggregate implements IDataAggregate {
- /**
- * Ensure column isn't empty, then get the average of all the column's values.
- *
- * @param column The column to average.
- *
- * @return Average of all the column's values.
- */
- @Override
- public Number aggregate(Number[] column) {
- if(column == null || column.length == 0) {
- return null;
- }
-
- double num = 0;
-
- for(int i=0; i<column.length; i++) {
- num += column[i].doubleValue();
- }
-
- num /= column.length;
- return NumberType.getNumber(column[0], num);
- }
-
- @Override
- public String getID() {
- return ID;
- }
-
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.aggregates.AverageAggregate"; //$NON-NLS-1$
+ /**
+ * Ensure column isn't empty, then get the average of all the column's values.
+ *
+ * @param column The column to average.
+ *
+ * @return Average of all the column's values.
+ */
+ @Override
+ public Number aggregate(Number[] column) {
+ if(column == null || column.length == 0) {
+ return null;
+ }
+
+ double num = 0;
+
+ for(int i=0; i<column.length; i++) {
+ num += column[i].doubleValue();
+ }
+
+ num /= column.length;
+ return NumberType.getNumber(column[0], num);
+ }
+
+ @Override
+ public String getID() {
+ return ID;
+ }
+
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.aggregates.AverageAggregate"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/CountAggregate.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/CountAggregate.java
index 625b261c65..cd341265c4 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/CountAggregate.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/CountAggregate.java
@@ -13,32 +13,32 @@ package org.eclipse.linuxtools.systemtap.graphing.core.aggregates;
public class CountAggregate implements IDataAggregate {
- /**
- * Ensure column isn't empty, then get the count of the column's values.
- *
- * @param column The column to count.
- *
- * @return Count of that column's values.
- */
- @Override
- public Number aggregate(Number[] column) {
- if(column == null || column.length == 0) {
- return null;
- }
-
- int num = 0;
-
- for(int i=0; i<column.length; i++) {
- num++;
- }
-
- return Integer.valueOf(num);
- }
-
- @Override
- public String getID() {
- return ID;
- }
-
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.aggregates.CountAggregate"; //$NON-NLS-1$
+ /**
+ * Ensure column isn't empty, then get the count of the column's values.
+ *
+ * @param column The column to count.
+ *
+ * @return Count of that column's values.
+ */
+ @Override
+ public Number aggregate(Number[] column) {
+ if(column == null || column.length == 0) {
+ return null;
+ }
+
+ int num = 0;
+
+ for(int i=0; i<column.length; i++) {
+ num++;
+ }
+
+ return Integer.valueOf(num);
+ }
+
+ @Override
+ public String getID() {
+ return ID;
+ }
+
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.aggregates.CountAggregate"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/IDataAggregate.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/IDataAggregate.java
index adf114570d..d328e22d01 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/IDataAggregate.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/IDataAggregate.java
@@ -12,6 +12,6 @@
package org.eclipse.linuxtools.systemtap.graphing.core.aggregates;
public interface IDataAggregate {
- Number aggregate(Number[] column);
- String getID();
+ Number aggregate(Number[] column);
+ String getID();
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/MaxAggregate.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/MaxAggregate.java
index bd15b03780..b2d521fa45 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/MaxAggregate.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/MaxAggregate.java
@@ -15,34 +15,34 @@ import org.eclipse.linuxtools.systemtap.graphing.core.structures.NumberType;
public class MaxAggregate implements IDataAggregate {
- /**
- * Ensure column isn't empty, then get the maximum of all the column's values.
- *
- * @param column The column to search.
- *
- * @return Maximum of all the column's values.
- */
- @Override
- public Number aggregate(Number[] column) {
- if(column == null || column.length == 0) {
- return null;
- }
-
- double num = Double.NEGATIVE_INFINITY;
-
- for(int i=0; i<column.length; i++) {
- if(num < column[i].doubleValue()) {
- num = column[i].doubleValue();
- }
- }
-
- return NumberType.getNumber(column[0], num);
- }
-
- @Override
- public String getID() {
- return ID;
- }
-
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.aggregates.MaxAggregate"; //$NON-NLS-1$
+ /**
+ * Ensure column isn't empty, then get the maximum of all the column's values.
+ *
+ * @param column The column to search.
+ *
+ * @return Maximum of all the column's values.
+ */
+ @Override
+ public Number aggregate(Number[] column) {
+ if(column == null || column.length == 0) {
+ return null;
+ }
+
+ double num = Double.NEGATIVE_INFINITY;
+
+ for(int i=0; i<column.length; i++) {
+ if(num < column[i].doubleValue()) {
+ num = column[i].doubleValue();
+ }
+ }
+
+ return NumberType.getNumber(column[0], num);
+ }
+
+ @Override
+ public String getID() {
+ return ID;
+ }
+
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.aggregates.MaxAggregate"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/MinAggregate.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/MinAggregate.java
index 951cf2aac4..97369d2528 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/MinAggregate.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/MinAggregate.java
@@ -15,34 +15,34 @@ import org.eclipse.linuxtools.systemtap.graphing.core.structures.NumberType;
public class MinAggregate implements IDataAggregate {
- /**
- * Ensure column isn't empty, then get the minimum of all the column's values.
- *
- * @param column The column to search.
- *
- * @return Minimum of all the column's values.
- */
- @Override
- public Number aggregate(Number[] column) {
- if(column == null || column.length == 0) {
- return null;
- }
-
- double num = Double.POSITIVE_INFINITY;
-
- for(int i=0; i<column.length; i++) {
- if(num > column[i].doubleValue()) {
- num = column[i].doubleValue();
- }
- }
-
- return NumberType.getNumber(column[0], num);
- }
-
- @Override
- public String getID() {
- return ID;
- }
-
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.aggregates.MinAggregate"; //$NON-NLS-1$
+ /**
+ * Ensure column isn't empty, then get the minimum of all the column's values.
+ *
+ * @param column The column to search.
+ *
+ * @return Minimum of all the column's values.
+ */
+ @Override
+ public Number aggregate(Number[] column) {
+ if(column == null || column.length == 0) {
+ return null;
+ }
+
+ double num = Double.POSITIVE_INFINITY;
+
+ for(int i=0; i<column.length; i++) {
+ if(num > column[i].doubleValue()) {
+ num = column[i].doubleValue();
+ }
+ }
+
+ return NumberType.getNumber(column[0], num);
+ }
+
+ @Override
+ public String getID() {
+ return ID;
+ }
+
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.aggregates.MinAggregate"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/SumAggregate.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/SumAggregate.java
index 43dd15cf3c..ec31935828 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/SumAggregate.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/aggregates/SumAggregate.java
@@ -15,32 +15,32 @@ import org.eclipse.linuxtools.systemtap.graphing.core.structures.NumberType;
public class SumAggregate implements IDataAggregate {
- /**
- * Ensure column isn't empty, then get the sum total of all the column's values.
- *
- * @param column The column to total.
- *
- * @return The sum total of all the column's values.
- */
- @Override
- public Number aggregate(Number[] column) {
- if(column == null || column.length == 0) {
- return null;
- }
-
- double num = 0;
-
- for(int i=0; i<column.length; i++) {
- num += column[i].doubleValue();
- }
-
- return NumberType.getNumber(column[0], num);
- }
-
- @Override
- public String getID() {
- return ID;
- }
-
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.aggregates.SumAggregate"; //$NON-NLS-1$
+ /**
+ * Ensure column isn't empty, then get the sum total of all the column's values.
+ *
+ * @param column The column to total.
+ *
+ * @return The sum total of all the column's values.
+ */
+ @Override
+ public Number aggregate(Number[] column) {
+ if(column == null || column.length == 0) {
+ return null;
+ }
+
+ double num = 0;
+
+ for(int i=0; i<column.length; i++) {
+ num += column[i].doubleValue();
+ }
+
+ return NumberType.getNumber(column[0], num);
+ }
+
+ @Override
+ public String getID() {
+ return ID;
+ }
+
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.aggregates.SumAggregate"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IBlockDataSet.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IBlockDataSet.java
index 856e411122..ed8a3b157e 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IBlockDataSet.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IBlockDataSet.java
@@ -12,5 +12,5 @@
package org.eclipse.linuxtools.systemtap.graphing.core.datasets;
public interface IBlockDataSet extends IDataSet {
- Object[][] getData();
+ Object[][] getData();
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataEntry.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataEntry.java
index bb696e82a0..99d5a024ee 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataEntry.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataEntry.java
@@ -12,14 +12,14 @@
package org.eclipse.linuxtools.systemtap.graphing.core.datasets;
public interface IDataEntry {
- int getRowCount();
- int getColCount();
- Object get(String key, int col);
- Object[] getRow(int row);
- Object[] getRow(String key);
- Object[] getColumn(int col);
- Object[][] getData();
- IDataEntry copy();
- void putRow(int row, Object[] data);
- boolean remove(int row);
+ int getRowCount();
+ int getColCount();
+ Object get(String key, int col);
+ Object[] getRow(int row);
+ Object[] getRow(String key);
+ Object[] getColumn(int col);
+ Object[][] getData();
+ IDataEntry copy();
+ void putRow(int row, Object[] data);
+ boolean remove(int row);
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataSet.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataSet.java
index adc1995e1f..236fad5110 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataSet.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataSet.java
@@ -15,20 +15,20 @@ import java.io.File;
public interface IDataSet {
- String[] getTitles();
- String getID();
- boolean writeToFile(File file);
- boolean readFromFile(File file);
+ String[] getTitles();
+ String getID();
+ boolean writeToFile(File file);
+ boolean readFromFile(File file);
- int getRowCount();
- int getColCount();
+ int getRowCount();
+ int getColCount();
- Object[] getRow(int row);
- Object[] getColumn(int col);
- Object[] getColumn(int col, int start, int end);
+ Object[] getRow(int row);
+ Object[] getColumn(int col);
+ Object[] getColumn(int col, int start, int end);
- void setData(IDataEntry entry);
- boolean remove(IDataEntry entry);
+ void setData(IDataEntry entry);
+ boolean remove(IDataEntry entry);
- int COL_ROW_NUM = -1;
+ int COL_ROW_NUM = -1;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataSetParser.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataSetParser.java
index 060ec68686..c39567d06d 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataSetParser.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IDataSetParser.java
@@ -12,5 +12,5 @@
package org.eclipse.linuxtools.systemtap.graphing.core.datasets;
public interface IDataSetParser {
- IDataEntry parse(StringBuilder entry);
+ IDataEntry parse(StringBuilder entry);
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IFilteredDataSet.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IFilteredDataSet.java
index 83b265ace1..53bc24d5e3 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IFilteredDataSet.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IFilteredDataSet.java
@@ -14,8 +14,8 @@ package org.eclipse.linuxtools.systemtap.graphing.core.datasets;
import org.eclipse.linuxtools.systemtap.graphing.core.filters.IDataSetFilter;
public interface IFilteredDataSet extends IDataSet {
- void addFilter(IDataSetFilter filter);
- IDataSetFilter[] getFilters();
- void clearFilters();
- boolean removeFilter(IDataSetFilter filter);
+ void addFilter(IDataSetFilter filter);
+ IDataSetFilter[] getFilters();
+ void clearFilters();
+ boolean removeFilter(IDataSetFilter filter);
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IHistoricalDataSet.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IHistoricalDataSet.java
index 41856b7289..0bbef8d85f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IHistoricalDataSet.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/IHistoricalDataSet.java
@@ -12,10 +12,10 @@
package org.eclipse.linuxtools.systemtap.graphing.core.datasets;
public interface IHistoricalDataSet extends IDataSet {
- void append(IDataEntry entry);
- Object[] getHistoricalData(String key, int col);
- Object[] getHistoricalData(String key, int col, int start, int end);
- int getEntryCount();
- IDataEntry getEntry(int entry);
- boolean remove(int entry);
+ void append(IDataEntry entry);
+ Object[] getHistoricalData(String key, int col);
+ Object[] getHistoricalData(String key, int col, int start, int end);
+ int getEntryCount();
+ IDataEntry getEntry(int entry);
+ boolean remove(int entry);
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/FilteredRowDataSet.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/FilteredRowDataSet.java
index e1bbc6737e..4604cafc29 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/FilteredRowDataSet.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/FilteredRowDataSet.java
@@ -20,149 +20,149 @@ import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IFilteredDataSet;
import org.eclipse.linuxtools.systemtap.graphing.core.filters.IDataSetFilter;
public class FilteredRowDataSet extends RowDataSet implements IFilteredDataSet {
- public FilteredRowDataSet(RowDataSet data) {
- super(data.getTitles());
- original = data;
- this.data = data.data;
- filters = new ArrayList<>();
-
- filtersChanged = false;
- topData = null;
- dataCount = data.getRowCount();
- }
-
- public FilteredRowDataSet(String[] titles) {
- this(new RowDataSet(titles));
- }
-
- //Overwrite methods to insure data is removed from the original DataSet
- @Override
- public void append(IDataEntry entry) {
- original.append(entry);
- }
-
- @Override
- public boolean remove(IDataEntry entry) {
- return original.remove(entry);
- }
-
- @Override
- public boolean remove(int entry) {
- return original.remove(entry);
- }
- //End overwrite methods to insure data is removed from the original DataSet
-
- //Overwrite to ensure the data returned has all the filters applied
- @Override
- public Object[] getColumn(int col, int start, int end) {
- rebuildDataSet();
- return super.getColumn(col, start, end);
- }
-
- @Override
- public Object[] getRow(int row) {
- rebuildDataSet();
- return super.getRow(row);
- }
-
- @Override
- public Object[] getHistoricalData(String key, int col, int start, int end) {
- rebuildDataSet();
- return super.getHistoricalData(key, col, start, end);
- }
-
- @Override
- public int getEntryCount() {
- rebuildDataSet();
- return super.getEntryCount();
- }
-
- @Override
- public IDataEntry getEntry(int entry) {
- rebuildDataSet();
- return super.getEntry(entry);
- }
- //End overwrite to ensure the data returned has all the filters applied
-
- //IFilteredDataSet Methods
- @Override
- public void addFilter(IDataSetFilter filter) {
- filters.add(filter);
- filtersChanged = true;
- }
-
- @Override
- public boolean removeFilter(IDataSetFilter filter) {
- filtersChanged = filters.remove(filter);
- return filtersChanged;
- }
-
- @Override
- public void clearFilters() {
- filters.clear();
- filtersChanged = true;
- }
-
- @Override
- public IDataSetFilter[] getFilters() {
- IDataSetFilter[] f = new IDataSetFilter[filters.size()];
- filters.toArray(f);
- return f;
- }
- //End IFilteredDataSet Methods
-
- private void rebuildDataSet() {
- IDataEntry top = original.getEntry(original.getEntryCount()-1);
-
- if(filtersChanged || dataCount != original.getRowCount() || topData != top) {
- dataCount = original.getRowCount();
- topData = top;
-
- List<Object>[] filterData = getFilterData();
- for(int i=0; i<filters.size(); i++) {
- filterData = filters.get(i).filter(filterData);
- }
- setFilteredData(filterData);
- }
- }
-
- private ArrayList<Object>[] getFilterData() {
- ArrayList<Object>[] data = GraphingCorePlugin.createArrayList(original.getColCount(), new Object());
- for(int i=0; i<data.length; i++) {
- data[i] = new ArrayList<>();
- }
-
- Object[] row;
- for(int j,i=0; i<original.getRowCount(); i++) {
- row = original.getRow(i);
- for(j=0; j<data.length; j++) {
- data[j].add(row[j]);
- }
- }
-
- return data;
- }
-
- private void setFilteredData(List<?>[] data) {
- this.data = new ArrayList<>();
-
- RowEntry entry;
- Object[] row;
- for(int j,i=0; i<data[0].size(); i++) {
- row = new Object[data.length];
- entry = new RowEntry();
- for(j=0; j<data.length; j++) {
- row[j] = data[j].get(i);
- }
- entry.putRow(0, row);
- this.data.add(entry);
- }
- }
-
- private RowDataSet original;
- private List<IDataSetFilter> filters;
-
- private boolean filtersChanged;
- private int dataCount;
- private Object topData;
+ public FilteredRowDataSet(RowDataSet data) {
+ super(data.getTitles());
+ original = data;
+ this.data = data.data;
+ filters = new ArrayList<>();
+
+ filtersChanged = false;
+ topData = null;
+ dataCount = data.getRowCount();
+ }
+
+ public FilteredRowDataSet(String[] titles) {
+ this(new RowDataSet(titles));
+ }
+
+ //Overwrite methods to insure data is removed from the original DataSet
+ @Override
+ public void append(IDataEntry entry) {
+ original.append(entry);
+ }
+
+ @Override
+ public boolean remove(IDataEntry entry) {
+ return original.remove(entry);
+ }
+
+ @Override
+ public boolean remove(int entry) {
+ return original.remove(entry);
+ }
+ //End overwrite methods to insure data is removed from the original DataSet
+
+ //Overwrite to ensure the data returned has all the filters applied
+ @Override
+ public Object[] getColumn(int col, int start, int end) {
+ rebuildDataSet();
+ return super.getColumn(col, start, end);
+ }
+
+ @Override
+ public Object[] getRow(int row) {
+ rebuildDataSet();
+ return super.getRow(row);
+ }
+
+ @Override
+ public Object[] getHistoricalData(String key, int col, int start, int end) {
+ rebuildDataSet();
+ return super.getHistoricalData(key, col, start, end);
+ }
+
+ @Override
+ public int getEntryCount() {
+ rebuildDataSet();
+ return super.getEntryCount();
+ }
+
+ @Override
+ public IDataEntry getEntry(int entry) {
+ rebuildDataSet();
+ return super.getEntry(entry);
+ }
+ //End overwrite to ensure the data returned has all the filters applied
+
+ //IFilteredDataSet Methods
+ @Override
+ public void addFilter(IDataSetFilter filter) {
+ filters.add(filter);
+ filtersChanged = true;
+ }
+
+ @Override
+ public boolean removeFilter(IDataSetFilter filter) {
+ filtersChanged = filters.remove(filter);
+ return filtersChanged;
+ }
+
+ @Override
+ public void clearFilters() {
+ filters.clear();
+ filtersChanged = true;
+ }
+
+ @Override
+ public IDataSetFilter[] getFilters() {
+ IDataSetFilter[] f = new IDataSetFilter[filters.size()];
+ filters.toArray(f);
+ return f;
+ }
+ //End IFilteredDataSet Methods
+
+ private void rebuildDataSet() {
+ IDataEntry top = original.getEntry(original.getEntryCount()-1);
+
+ if(filtersChanged || dataCount != original.getRowCount() || topData != top) {
+ dataCount = original.getRowCount();
+ topData = top;
+
+ List<Object>[] filterData = getFilterData();
+ for(int i=0; i<filters.size(); i++) {
+ filterData = filters.get(i).filter(filterData);
+ }
+ setFilteredData(filterData);
+ }
+ }
+
+ private ArrayList<Object>[] getFilterData() {
+ ArrayList<Object>[] data = GraphingCorePlugin.createArrayList(original.getColCount(), new Object());
+ for(int i=0; i<data.length; i++) {
+ data[i] = new ArrayList<>();
+ }
+
+ Object[] row;
+ for(int j,i=0; i<original.getRowCount(); i++) {
+ row = original.getRow(i);
+ for(j=0; j<data.length; j++) {
+ data[j].add(row[j]);
+ }
+ }
+
+ return data;
+ }
+
+ private void setFilteredData(List<?>[] data) {
+ this.data = new ArrayList<>();
+
+ RowEntry entry;
+ Object[] row;
+ for(int j,i=0; i<data[0].size(); i++) {
+ row = new Object[data.length];
+ entry = new RowEntry();
+ for(j=0; j<data.length; j++) {
+ row[j] = data[j].get(i);
+ }
+ entry.putRow(0, row);
+ this.data.add(entry);
+ }
+ }
+
+ private RowDataSet original;
+ private List<IDataSetFilter> filters;
+
+ private boolean filtersChanged;
+ private int dataCount;
+ private Object topData;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/LineParser.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/LineParser.java
index 7b84757343..e1245b119d 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/LineParser.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/LineParser.java
@@ -20,39 +20,39 @@ import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IDataSetParser;
/**
* A DataSetParser for parsing a string, line-by-line, with a preconstructed
* single-line regex string.
- *
+ *
* @author aferrazz
* @since 1.1
*
*/
public class LineParser implements IDataSetParser {
- public LineParser(String regEx) {
- wholePattern = Pattern.compile(regEx, Pattern.MULTILINE);
- }
-
- @Override
- public IDataEntry parse(StringBuilder s) {
- if(null == s) {
- return null;
- }
-
- RowEntry e = null;
- Matcher wholeMatcher = wholePattern.matcher(s);
-
- if(wholeMatcher.find()) {
- e = new RowEntry();
- int groupCount = wholeMatcher.groupCount();
- Object[] data = new Object[groupCount];
-
- for(int i = 0; i < groupCount; i++) {
- data[i] = wholeMatcher.group(i+1);
- }
- e.putRow(0, data);
- s.delete(0, s.length());
- }
-
- return e;
- }
-
- private Pattern wholePattern;
+ public LineParser(String regEx) {
+ wholePattern = Pattern.compile(regEx, Pattern.MULTILINE);
+ }
+
+ @Override
+ public IDataEntry parse(StringBuilder s) {
+ if(null == s) {
+ return null;
+ }
+
+ RowEntry e = null;
+ Matcher wholeMatcher = wholePattern.matcher(s);
+
+ if(wholeMatcher.find()) {
+ e = new RowEntry();
+ int groupCount = wholeMatcher.groupCount();
+ Object[] data = new Object[groupCount];
+
+ for(int i = 0; i < groupCount; i++) {
+ data[i] = wholeMatcher.group(i+1);
+ }
+ e.putRow(0, data);
+ s.delete(0, s.length());
+ }
+
+ return e;
+ }
+
+ private Pattern wholePattern;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowDataSet.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowDataSet.java
index 26ab101474..9b96fcef74 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowDataSet.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowDataSet.java
@@ -28,181 +28,181 @@ import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IHistoricalDataSe
public class RowDataSet implements IHistoricalDataSet {
- //IDataSet Methods
- public RowDataSet(String[] titles) {
- if (titles != null){
- this.titles = Arrays.copyOf(titles, titles.length);
- }
- data = new ArrayList<>();
- }
-
- @Override
- public void setData(IDataEntry entry) {
- append(entry);
- }
-
- @Override
- public void append(IDataEntry entry) {
- RowEntry dataBlock = (RowEntry)entry;
- if(dataBlock.getRow(null).length != this.getColCount())
- throw new ArrayIndexOutOfBoundsException(Localization.getString("RowDataSet.ArraySizeMismatch") + dataBlock.getRow(null).length + " != " + this.getColCount()); //$NON-NLS-1$ //$NON-NLS-2$
-
- data.add(entry);
- }
-
- @Override
- public String[] getTitles() {
- return titles;
- }
-
- @Override
- public Object[] getColumn(int col) {
- return getColumn(col, 0, getRowCount());
- }
-
- @Override
- public Object[] getColumn(int col, int start, int end) {
- return getHistoricalData(null, col, start, end);
- }
-
- @Override
- public Object[] getRow(int row) {
- IDataEntry entry = getEntry(row);
- if(null != entry) {
- return entry.getRow(null);
- }
- return null;
- }
-
- @Override
- public int getRowCount() {
- return getEntryCount();
- }
-
- @Override
- public int getColCount() {
- if(null == titles) {
- return -1;
- }
- return titles.length;
- }
-
- @Override
- public boolean readFromFile(File file) {
- try (FileReader fr = new FileReader(file);
- BufferedReader br = new BufferedReader(fr)){
- br.readLine(); //Skip the ID
- br.readLine(); //Skip the Titles
- String line;
- RowEntry entry;
- while(null != (line = br.readLine())) {
- entry = new RowEntry();
- entry.putRow(0, line.split(", ")); //$NON-NLS-1$
- append(entry);
- }
- return true;
- } catch(IOException|ArrayIndexOutOfBoundsException e) {
- }
- return false;
- }
-
- @Override
- public boolean writeToFile(File file) {
- try {
- file.createNewFile();
- try (FileOutputStream fos = new FileOutputStream(file);
- PrintStream ps = new PrintStream(fos)) {
-
- String line = ""; //$NON-NLS-1$
- Object[] dataRow;
-
- // ID
- ps.print(ID + "\n"); //$NON-NLS-1$
-
- // Labels
- int i, j;
- for (i = 0; i < titles.length; i++)
- line += titles[i] + ", "; //$NON-NLS-1$
- ps.print(line + "\n"); //$NON-NLS-1$
-
- // Data
- for (i = 0; i < getRowCount(); i++) {
- dataRow = getRow(i);
- line = ""; //$NON-NLS-1$
- for (j = 0; j < dataRow.length; j++)
- line += dataRow[j].toString() + ", "; //$NON-NLS-1$
- ps.print(line + "\n"); //$NON-NLS-1$
- }
- }
- return true;
- } catch (IOException e) {
- }
- return false;
- }
-
- @Override
- public String getID() {
- return ID;
- }
- //End IDataSet Methods
-
- //IHistoricalDataSet Methods
- @Override
- public Object[] getHistoricalData(String key, int col) {
- return getHistoricalData(key, col, 0, getRowCount());
- }
-
- @Override
- public Object[] getHistoricalData(String key, int col, int start, int end) {
- if(start > end || start < 0 || end > getRowCount() || col < COL_ROW_NUM || col >= this.getColCount()) {
- return null;
- }
-
- if(COL_ROW_NUM == col) {
- Integer[] rows = new Integer[Math.min(end-start, data.size())];
- for(int i=0;i<rows.length; i++) {
- rows[i] = Integer.valueOf(start+i+1);
- }
- return rows;
- }
-
- Object[] d = new Object[Math.min(end-start, data.size())];
-
- for(int i=0; i<d.length; i++) {
- d[i] = data.get(start+i).getColumn(col)[0];
- }
- return d;
- }
-
- @Override
- public int getEntryCount() {
- return data.size();
- }
-
- @Override
- public boolean remove(IDataEntry entry) {
- return data.remove(entry);
- }
-
- @Override
- public boolean remove(int entry) {
- if(entry < 0 || entry >= data.size()) {
- return false;
- }
- return (null != data.remove(entry));
- }
-
- @Override
- public IDataEntry getEntry(int entry) {
- if(entry < 0 || entry >= getEntryCount()) {
- return null;
- } else {
- return data.get(entry);
- }
- }
- //End IHistoricalDataSet Methods
-
- protected List<IDataEntry> data;
- private String[] titles;
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.datasets.rowdataset"; //$NON-NLS-1$
+ //IDataSet Methods
+ public RowDataSet(String[] titles) {
+ if (titles != null){
+ this.titles = Arrays.copyOf(titles, titles.length);
+ }
+ data = new ArrayList<>();
+ }
+
+ @Override
+ public void setData(IDataEntry entry) {
+ append(entry);
+ }
+
+ @Override
+ public void append(IDataEntry entry) {
+ RowEntry dataBlock = (RowEntry)entry;
+ if(dataBlock.getRow(null).length != this.getColCount())
+ throw new ArrayIndexOutOfBoundsException(Localization.getString("RowDataSet.ArraySizeMismatch") + dataBlock.getRow(null).length + " != " + this.getColCount()); //$NON-NLS-1$ //$NON-NLS-2$
+
+ data.add(entry);
+ }
+
+ @Override
+ public String[] getTitles() {
+ return titles;
+ }
+
+ @Override
+ public Object[] getColumn(int col) {
+ return getColumn(col, 0, getRowCount());
+ }
+
+ @Override
+ public Object[] getColumn(int col, int start, int end) {
+ return getHistoricalData(null, col, start, end);
+ }
+
+ @Override
+ public Object[] getRow(int row) {
+ IDataEntry entry = getEntry(row);
+ if(null != entry) {
+ return entry.getRow(null);
+ }
+ return null;
+ }
+
+ @Override
+ public int getRowCount() {
+ return getEntryCount();
+ }
+
+ @Override
+ public int getColCount() {
+ if(null == titles) {
+ return -1;
+ }
+ return titles.length;
+ }
+
+ @Override
+ public boolean readFromFile(File file) {
+ try (FileReader fr = new FileReader(file);
+ BufferedReader br = new BufferedReader(fr)){
+ br.readLine(); //Skip the ID
+ br.readLine(); //Skip the Titles
+ String line;
+ RowEntry entry;
+ while(null != (line = br.readLine())) {
+ entry = new RowEntry();
+ entry.putRow(0, line.split(", ")); //$NON-NLS-1$
+ append(entry);
+ }
+ return true;
+ } catch(IOException|ArrayIndexOutOfBoundsException e) {
+ }
+ return false;
+ }
+
+ @Override
+ public boolean writeToFile(File file) {
+ try {
+ file.createNewFile();
+ try (FileOutputStream fos = new FileOutputStream(file);
+ PrintStream ps = new PrintStream(fos)) {
+
+ String line = ""; //$NON-NLS-1$
+ Object[] dataRow;
+
+ // ID
+ ps.print(ID + "\n"); //$NON-NLS-1$
+
+ // Labels
+ int i, j;
+ for (i = 0; i < titles.length; i++)
+ line += titles[i] + ", "; //$NON-NLS-1$
+ ps.print(line + "\n"); //$NON-NLS-1$
+
+ // Data
+ for (i = 0; i < getRowCount(); i++) {
+ dataRow = getRow(i);
+ line = ""; //$NON-NLS-1$
+ for (j = 0; j < dataRow.length; j++)
+ line += dataRow[j].toString() + ", "; //$NON-NLS-1$
+ ps.print(line + "\n"); //$NON-NLS-1$
+ }
+ }
+ return true;
+ } catch (IOException e) {
+ }
+ return false;
+ }
+
+ @Override
+ public String getID() {
+ return ID;
+ }
+ //End IDataSet Methods
+
+ //IHistoricalDataSet Methods
+ @Override
+ public Object[] getHistoricalData(String key, int col) {
+ return getHistoricalData(key, col, 0, getRowCount());
+ }
+
+ @Override
+ public Object[] getHistoricalData(String key, int col, int start, int end) {
+ if(start > end || start < 0 || end > getRowCount() || col < COL_ROW_NUM || col >= this.getColCount()) {
+ return null;
+ }
+
+ if(COL_ROW_NUM == col) {
+ Integer[] rows = new Integer[Math.min(end-start, data.size())];
+ for(int i=0;i<rows.length; i++) {
+ rows[i] = Integer.valueOf(start+i+1);
+ }
+ return rows;
+ }
+
+ Object[] d = new Object[Math.min(end-start, data.size())];
+
+ for(int i=0; i<d.length; i++) {
+ d[i] = data.get(start+i).getColumn(col)[0];
+ }
+ return d;
+ }
+
+ @Override
+ public int getEntryCount() {
+ return data.size();
+ }
+
+ @Override
+ public boolean remove(IDataEntry entry) {
+ return data.remove(entry);
+ }
+
+ @Override
+ public boolean remove(int entry) {
+ if(entry < 0 || entry >= data.size()) {
+ return false;
+ }
+ return (null != data.remove(entry));
+ }
+
+ @Override
+ public IDataEntry getEntry(int entry) {
+ if(entry < 0 || entry >= getEntryCount()) {
+ return null;
+ } else {
+ return data.get(entry);
+ }
+ }
+ //End IHistoricalDataSet Methods
+
+ protected List<IDataEntry> data;
+ private String[] titles;
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.datasets.rowdataset"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowEntry.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowEntry.java
index c9a5dc6cb7..d46dc868c1 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowEntry.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowEntry.java
@@ -16,79 +16,79 @@ import java.util.Arrays;
import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IDataEntry;
public class RowEntry implements IDataEntry {
- public RowEntry() {
- data = null;
- }
-
- @Override
- public int getRowCount() {
- if(null != data)
- return 1;
- return 0;
- }
-
- @Override
- public int getColCount() {
- return (null == data) ? 0 : data.length;
- }
-
- @Override
- public Object get(String key, int col) {
- return (0 <= col && col < getColCount()) ? data[col] : null;
- }
-
- @Override
- public Object[] getRow(int row) {
- if(0 == row)
- return data;
- return null;
- }
-
- @Override
- public Object[] getRow(String key) {
- return data;
- }
-
- @Override
- public Object[] getColumn(int col) {
- if(0 <= col && getColCount() > col) {
- return new Object[] {get(null, col)};
- }
- return null;
- }
-
- @Override
- public Object[][] getData() {
- return new Object[][] {getRow(null)};
- }
-
- @Override
- public IDataEntry copy() {
- RowEntry entry = new RowEntry();
- if(null != data) {
- entry.data = new Object[data.length];
- System.arraycopy(data, 0, entry.data, 0, data.length);
- }
-
- return entry;
- }
-
- @Override
- public void putRow(int row, Object[] data) {
- if(0 == row && data != null){
- this.data = Arrays.copyOf(data, data.length);
- }
- }
-
- @Override
- public boolean remove(int row) {
- if(row == 0) {
- data = null;
- return true;
- } else {
- return false;
- }
- }
-
- private Object[] data;
+ public RowEntry() {
+ data = null;
+ }
+
+ @Override
+ public int getRowCount() {
+ if(null != data)
+ return 1;
+ return 0;
+ }
+
+ @Override
+ public int getColCount() {
+ return (null == data) ? 0 : data.length;
+ }
+
+ @Override
+ public Object get(String key, int col) {
+ return (0 <= col && col < getColCount()) ? data[col] : null;
+ }
+
+ @Override
+ public Object[] getRow(int row) {
+ if(0 == row)
+ return data;
+ return null;
+ }
+
+ @Override
+ public Object[] getRow(String key) {
+ return data;
+ }
+
+ @Override
+ public Object[] getColumn(int col) {
+ if(0 <= col && getColCount() > col) {
+ return new Object[] {get(null, col)};
+ }
+ return null;
+ }
+
+ @Override
+ public Object[][] getData() {
+ return new Object[][] {getRow(null)};
+ }
+
+ @Override
+ public IDataEntry copy() {
+ RowEntry entry = new RowEntry();
+ if(null != data) {
+ entry.data = new Object[data.length];
+ System.arraycopy(data, 0, entry.data, 0, data.length);
+ }
+
+ return entry;
+ }
+
+ @Override
+ public void putRow(int row, Object[] data) {
+ if(0 == row && data != null){
+ this.data = Arrays.copyOf(data, data.length);
+ }
+ }
+
+ @Override
+ public boolean remove(int row) {
+ if(row == 0) {
+ data = null;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private Object[] data;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowParser.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowParser.java
index 14557feee2..e73e8f9b48 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowParser.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/row/RowParser.java
@@ -21,53 +21,53 @@ import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IDataSetParser;
public class RowParser implements IDataSetParser {
- public RowParser(String[] regEx) {
- this.regEx = Arrays.copyOf(regEx, regEx.length);
- buildPattern();
- }
+ public RowParser(String[] regEx) {
+ this.regEx = Arrays.copyOf(regEx, regEx.length);
+ buildPattern();
+ }
- private void buildPattern() {
- StringBuilder wholeRegExpr = new StringBuilder();
- for(int i=0; i<regEx.length; i++) {
- wholeRegExpr.append('(' + regEx[i] + ')');
- }
- wholePattern = Pattern.compile(wholeRegExpr.toString());
- }
+ private void buildPattern() {
+ StringBuilder wholeRegExpr = new StringBuilder();
+ for(int i=0; i<regEx.length; i++) {
+ wholeRegExpr.append('(' + regEx[i] + ')');
+ }
+ wholePattern = Pattern.compile(wholeRegExpr.toString());
+ }
- @Override
- public IDataEntry parse(StringBuilder s) {
- if(null == s) {
- return null;
- }
+ @Override
+ public IDataEntry parse(StringBuilder s) {
+ if(null == s) {
+ return null;
+ }
- RowEntry e = null;
- Matcher wholeMatcher = wholePattern.matcher(s);
+ RowEntry e = null;
+ Matcher wholeMatcher = wholePattern.matcher(s);
- if(wholeMatcher.find()) {
- e = new RowEntry();
- Object[] data = new Object[regEx.length>>1];
+ if(wholeMatcher.find()) {
+ e = new RowEntry();
+ Object[] data = new Object[regEx.length>>1];
- int group=0, j;
+ int group=0, j;
- for(int i=0; i<regEx.length; i++) {
- group++;
- for(j=0; j<regEx[i].length(); j++) {
- if(regEx[i].charAt(j) == ')') {
- group++;
- }
- }
+ for(int i=0; i<regEx.length; i++) {
+ group++;
+ for(j=0; j<regEx[i].length(); j++) {
+ if(regEx[i].charAt(j) == ')') {
+ group++;
+ }
+ }
- if(0 == (i&1)) {
- data[i>>1] = wholeMatcher.group(group);
- }
- }
- e.putRow(0, data);
- s.delete(0, wholeMatcher.end());
- }
+ if(0 == (i&1)) {
+ data[i>>1] = wholeMatcher.group(group);
+ }
+ }
+ e.putRow(0, data);
+ s.delete(0, wholeMatcher.end());
+ }
- return e;
- }
+ return e;
+ }
- private String[] regEx;
- private Pattern wholePattern;
+ private String[] regEx;
+ private Pattern wholePattern;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/FilteredTableDataSet.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/FilteredTableDataSet.java
index f3f45ff5fd..01390537f2 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/FilteredTableDataSet.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/FilteredTableDataSet.java
@@ -22,159 +22,159 @@ import org.eclipse.linuxtools.systemtap.graphing.core.filters.IDataSetFilter;
public class FilteredTableDataSet extends TableDataSet implements IFilteredDataSet {
- public FilteredTableDataSet(TableDataSet data) {
- super(data.getTitles());
- original = data;
- this.data = data.data;
- filters = new ArrayList<>();
-
- filtersChanged = false;
- historical = false;
- topData = null;
- dataCount = data.getRowCount();
- }
-
- public FilteredTableDataSet(String[] titles) {
- this(new TableDataSet(titles));
- }
-
- //Overwrite methods to insure data is removed from the original DataSet
- @Override
- public void append(IDataEntry entry) {
- original.append(entry);
- }
-
- @Override
- public boolean remove(IDataEntry entry) {
- return original.remove(entry);
- }
-
- @Override
- public boolean remove(int entry) {
- return original.remove(entry);
- }
- //End overwrite methods to insure data is removed from the original DataSet
-
- //Overwrite to ensure the data returned has all the filters applied
- @Override
- public Object[] getColumn(int col, int start, int end) {
- rebuildDataSet();
- return super.getColumn(col, start, end);
- }
-
- @Override
- public Object[] getRow(int row) {
- rebuildDataSet();
- return super.getRow(row);
- }
-
- @Override
- public int getRowCount() {
- rebuildDataSet();
- return super.getRowCount();
- }
-
- @Override
- public Object[] getHistoricalData(String key, int col, int start, int end) {
- return original.getHistoricalData(key, col, start, end);
- }
-
- @Override
- public int getEntryCount() {
- return original.getEntryCount();
- }
-
- @Override
- public IDataEntry getEntry(int entry) {
- return original.getEntry(entry);
- }
-
- @Override
- public Object[][] getData() {
- rebuildDataSet();
- return super.getData();
- }
- //End overwrite to ensure the data returned has all the filters applied
-
- //IFilteredDataSet Methods
- @Override
- public void addFilter(IDataSetFilter filter) {
- filters.add(filter);
- filtersChanged = true;
- }
-
- @Override
- public boolean removeFilter(IDataSetFilter filter) {
- filtersChanged = filters.remove(filter);
- return filtersChanged;
- }
-
- @Override
- public void clearFilters() {
- filters.clear();
- filtersChanged = true;
- }
-
- @Override
- public IDataSetFilter[] getFilters() {
- IDataSetFilter[] f = new IDataSetFilter[filters.size()];
- filters.toArray(f);
- return f;
- }
- //End IFilteredDataSet Methods
-
- private void rebuildDataSet() {
- IDataEntry top = original.getEntry(original.getEntryCount()-1);
-
- if(filtersChanged || dataCount != original.getRowCount() || topData != top || historical) {
- dataCount = original.getRowCount();
- topData = top;
- historical = false;
-
- List<Object>[] filterData = getFilterData();
- for(int i=0; i<filters.size(); i++) {
- filterData = filters.get(i).filter(filterData);
- }
- setFilteredData(filterData);
- }
- }
-
- private ArrayList<Object>[] getFilterData() {
- ArrayList<Object>[] data = GraphingCorePlugin.createArrayList(original.getColCount(), new Object());
- for(int i=0; i<data.length; i++) {
- data[i] = new ArrayList<>();
- }
-
- Object[][] table = original.getData();
- for(int j,i=0; i<original.getRowCount(); i++) {
- for(j=0; j<data.length; j++) {
- data[j].add(table[i][j]);
- }
- }
-
- return data;
- }
-
- private void setFilteredData(List<Object>[] data) {
- this.data = new ArrayList<>();
-
- TableEntry entry = new TableEntry();
- Object[] row;
- for(int j,i=0; i<data[0].size(); i++) {
- row = new Object[data.length];
- for(j=0; j<data.length; j++) {
- row[j] = data[j].get(i);
- }
- entry.add(row);
- }
- this.data.add(entry);
- }
-
- private TableDataSet original;
- private List<IDataSetFilter> filters;
-
- private boolean filtersChanged;
- private int dataCount;
- private Object topData;
- private boolean historical;
+ public FilteredTableDataSet(TableDataSet data) {
+ super(data.getTitles());
+ original = data;
+ this.data = data.data;
+ filters = new ArrayList<>();
+
+ filtersChanged = false;
+ historical = false;
+ topData = null;
+ dataCount = data.getRowCount();
+ }
+
+ public FilteredTableDataSet(String[] titles) {
+ this(new TableDataSet(titles));
+ }
+
+ //Overwrite methods to insure data is removed from the original DataSet
+ @Override
+ public void append(IDataEntry entry) {
+ original.append(entry);
+ }
+
+ @Override
+ public boolean remove(IDataEntry entry) {
+ return original.remove(entry);
+ }
+
+ @Override
+ public boolean remove(int entry) {
+ return original.remove(entry);
+ }
+ //End overwrite methods to insure data is removed from the original DataSet
+
+ //Overwrite to ensure the data returned has all the filters applied
+ @Override
+ public Object[] getColumn(int col, int start, int end) {
+ rebuildDataSet();
+ return super.getColumn(col, start, end);
+ }
+
+ @Override
+ public Object[] getRow(int row) {
+ rebuildDataSet();
+ return super.getRow(row);
+ }
+
+ @Override
+ public int getRowCount() {
+ rebuildDataSet();
+ return super.getRowCount();
+ }
+
+ @Override
+ public Object[] getHistoricalData(String key, int col, int start, int end) {
+ return original.getHistoricalData(key, col, start, end);
+ }
+
+ @Override
+ public int getEntryCount() {
+ return original.getEntryCount();
+ }
+
+ @Override
+ public IDataEntry getEntry(int entry) {
+ return original.getEntry(entry);
+ }
+
+ @Override
+ public Object[][] getData() {
+ rebuildDataSet();
+ return super.getData();
+ }
+ //End overwrite to ensure the data returned has all the filters applied
+
+ //IFilteredDataSet Methods
+ @Override
+ public void addFilter(IDataSetFilter filter) {
+ filters.add(filter);
+ filtersChanged = true;
+ }
+
+ @Override
+ public boolean removeFilter(IDataSetFilter filter) {
+ filtersChanged = filters.remove(filter);
+ return filtersChanged;
+ }
+
+ @Override
+ public void clearFilters() {
+ filters.clear();
+ filtersChanged = true;
+ }
+
+ @Override
+ public IDataSetFilter[] getFilters() {
+ IDataSetFilter[] f = new IDataSetFilter[filters.size()];
+ filters.toArray(f);
+ return f;
+ }
+ //End IFilteredDataSet Methods
+
+ private void rebuildDataSet() {
+ IDataEntry top = original.getEntry(original.getEntryCount()-1);
+
+ if(filtersChanged || dataCount != original.getRowCount() || topData != top || historical) {
+ dataCount = original.getRowCount();
+ topData = top;
+ historical = false;
+
+ List<Object>[] filterData = getFilterData();
+ for(int i=0; i<filters.size(); i++) {
+ filterData = filters.get(i).filter(filterData);
+ }
+ setFilteredData(filterData);
+ }
+ }
+
+ private ArrayList<Object>[] getFilterData() {
+ ArrayList<Object>[] data = GraphingCorePlugin.createArrayList(original.getColCount(), new Object());
+ for(int i=0; i<data.length; i++) {
+ data[i] = new ArrayList<>();
+ }
+
+ Object[][] table = original.getData();
+ for(int j,i=0; i<original.getRowCount(); i++) {
+ for(j=0; j<data.length; j++) {
+ data[j].add(table[i][j]);
+ }
+ }
+
+ return data;
+ }
+
+ private void setFilteredData(List<Object>[] data) {
+ this.data = new ArrayList<>();
+
+ TableEntry entry = new TableEntry();
+ Object[] row;
+ for(int j,i=0; i<data[0].size(); i++) {
+ row = new Object[data.length];
+ for(j=0; j<data.length; j++) {
+ row[j] = data[j].get(i);
+ }
+ entry.add(row);
+ }
+ this.data.add(entry);
+ }
+
+ private TableDataSet original;
+ private List<IDataSetFilter> filters;
+
+ private boolean filtersChanged;
+ private int dataCount;
+ private Object topData;
+ private boolean historical;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableDataSet.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableDataSet.java
index 4156819669..8dfd08868f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableDataSet.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableDataSet.java
@@ -28,207 +28,207 @@ import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IHistoricalDataSe
public class TableDataSet implements IHistoricalDataSet, IBlockDataSet {
- public TableDataSet(String[] labels) {
- if(null == labels){
- this.titles = new String[0];
- } else {
- this.titles = Arrays.copyOf(labels, labels.length);
- }
- data = new ArrayList<>();
- }
-
- //IDataSet Methods
- @Override
- public String[] getTitles() {
- return titles;
- }
-
- @Override
- public String getID() {
- return ID;
- }
-
- @Override
- public boolean readFromFile(File file) {
- try (FileReader fr = new FileReader(file);
- BufferedReader br = new BufferedReader(fr)){
-
- br.readLine(); //Skip the ID
- br.readLine(); //Skip the Titles
- String line;
- TableEntry entry = new TableEntry();
- while(null != (line = br.readLine())) {
- if(line.isEmpty()) {
- append(entry);
- entry = new TableEntry();
- } else {
- entry.add(line.split(", ")); //$NON-NLS-1$
- }
- }
- br.close();
- return true;
- } catch(IOException|ArrayIndexOutOfBoundsException e) {}
- return false;
- }
-
- @Override
- public boolean writeToFile(File file) {
- try {
- file.createNewFile();
- try (FileOutputStream fos = new FileOutputStream(file);
- PrintStream ps = new PrintStream(fos)) {
- StringBuilder b = new StringBuilder();
-
- // ID
- b.append(ID + "\n"); //$NON-NLS-1$
-
- // Labels
- int i, j, k;
- for (i = 0; i < titles.length; i++) {
- b.append(titles[i] + ", "); //$NON-NLS-1$
- }
- b.append("\n"); //$NON-NLS-1$
-
- // Data
- TableEntry e;
- Object[] o;
- for (i = 0; i < data.size(); i++) {
- e = data.get(i);
- for (j = 0; j < e.getRowCount(); j++) {
- o = e.getRow(j);
- for (k = 0; k < o.length; k++) {
- b.append(o[k].toString() + ", "); //$NON-NLS-1$
- }
- b.append("\n"); //$NON-NLS-1$
- }
- b.append("\n"); //$NON-NLS-1$
- }
- ps.print(b.toString());
- }
- return true;
- } catch (IOException e) {
- }
- return false;
- }
-
- @Override
- public int getRowCount() {
- if(data.size() > 0) {
- return data.get(data.size()-1).getRowCount();
- } else {
- return 0;
- }
- }
-
- @Override
- public int getColCount() {
- return titles.length;
- }
-
- @Override
- public Object[] getRow(int row) {
- return data.get(data.size()-1).getRow(row);
- }
-
- @Override
- public Object[] getColumn(int col) {
- return getColumn(col, 0, getRowCount());
- }
-
- @Override
- public Object[] getColumn(int col, int start, int end) {
- if(start > end || start < 0 || end > getEntryCount() || col < COL_ROW_NUM || col >= this.getColCount()) {
- return null;
- }
- if(COL_ROW_NUM == col) {
- Integer[] rows = new Integer[Math.min(end-start, getRowCount())];
- for(int i=0;i<rows.length; i++) {
- rows[i] = Integer.valueOf(start+i+1);
- }
- return rows;
- }
- return data.get(data.size()-1).getColumn(col, start, end);
- }
-
- @Override
- public void setData(IDataEntry data) {
- append(data);
- }
-
- @Override
- public boolean remove(IDataEntry entry) {
- return data.remove(entry);
- }
- //End IDataSet Methods
-
- //IHistoricalDataSet Methods
- @Override
- public void append(IDataEntry data) {
- if(data instanceof TableEntry) {
- this.data.add((TableEntry)data);
- }
- }
-
- @Override
- public Object[] getHistoricalData(String key, int col) {
- return getHistoricalData(key, col, 0, getEntryCount());
- }
-
- @Override
- public Object[] getHistoricalData(String key, int col, int start, int end) {
- if(start > end || start < 0 || end > getEntryCount() || col < COL_ROW_NUM || col >= this.getColCount()) {
- return null;
- }
-
- if(COL_ROW_NUM == col) {
- Integer[] rows = new Integer[Math.min(end-start, data.size())];
- for(int i=0;i<rows.length; i++) {
- rows[i] = Integer.valueOf(start+i+1);
- }
- return rows;
- }
-
- Object[] d = new Object[Math.min(end-start, getEntryCount())];
-
- for(int i=0; i<d.length; i++) {
- d[i] = getEntry(i+start).get(key, col);
- if(null == d[i]) {
- d[i] = Integer.valueOf(0);
- }
- }
- return d;
- }
-
- @Override
- public int getEntryCount() {
- return data.size();
- }
-
- @Override
- public IDataEntry getEntry(int entry) {
- if(entry >=0 && entry < getEntryCount()) {
- return data.get(entry);
- }
- return null;
- }
-
- @Override
- public boolean remove(int entry) {
- if(entry < 0 || entry >= data.size()) {
- return false;
- }
- return (null != data.remove(entry));
- }
- //End IHistoricalDataSet Methods
-
- //IBlockDataSet Methods
- @Override
- public Object[][] getData() {
- return data.get(getEntryCount()-1).getData();
- }
- //End IBlockDataSet Methods
-
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.datasets.tabledataset"; //$NON-NLS-1$
- protected List<TableEntry> data;
- private String[] titles;
+ public TableDataSet(String[] labels) {
+ if(null == labels){
+ this.titles = new String[0];
+ } else {
+ this.titles = Arrays.copyOf(labels, labels.length);
+ }
+ data = new ArrayList<>();
+ }
+
+ //IDataSet Methods
+ @Override
+ public String[] getTitles() {
+ return titles;
+ }
+
+ @Override
+ public String getID() {
+ return ID;
+ }
+
+ @Override
+ public boolean readFromFile(File file) {
+ try (FileReader fr = new FileReader(file);
+ BufferedReader br = new BufferedReader(fr)){
+
+ br.readLine(); //Skip the ID
+ br.readLine(); //Skip the Titles
+ String line;
+ TableEntry entry = new TableEntry();
+ while(null != (line = br.readLine())) {
+ if(line.isEmpty()) {
+ append(entry);
+ entry = new TableEntry();
+ } else {
+ entry.add(line.split(", ")); //$NON-NLS-1$
+ }
+ }
+ br.close();
+ return true;
+ } catch(IOException|ArrayIndexOutOfBoundsException e) {}
+ return false;
+ }
+
+ @Override
+ public boolean writeToFile(File file) {
+ try {
+ file.createNewFile();
+ try (FileOutputStream fos = new FileOutputStream(file);
+ PrintStream ps = new PrintStream(fos)) {
+ StringBuilder b = new StringBuilder();
+
+ // ID
+ b.append(ID + "\n"); //$NON-NLS-1$
+
+ // Labels
+ int i, j, k;
+ for (i = 0; i < titles.length; i++) {
+ b.append(titles[i] + ", "); //$NON-NLS-1$
+ }
+ b.append("\n"); //$NON-NLS-1$
+
+ // Data
+ TableEntry e;
+ Object[] o;
+ for (i = 0; i < data.size(); i++) {
+ e = data.get(i);
+ for (j = 0; j < e.getRowCount(); j++) {
+ o = e.getRow(j);
+ for (k = 0; k < o.length; k++) {
+ b.append(o[k].toString() + ", "); //$NON-NLS-1$
+ }
+ b.append("\n"); //$NON-NLS-1$
+ }
+ b.append("\n"); //$NON-NLS-1$
+ }
+ ps.print(b.toString());
+ }
+ return true;
+ } catch (IOException e) {
+ }
+ return false;
+ }
+
+ @Override
+ public int getRowCount() {
+ if(data.size() > 0) {
+ return data.get(data.size()-1).getRowCount();
+ } else {
+ return 0;
+ }
+ }
+
+ @Override
+ public int getColCount() {
+ return titles.length;
+ }
+
+ @Override
+ public Object[] getRow(int row) {
+ return data.get(data.size()-1).getRow(row);
+ }
+
+ @Override
+ public Object[] getColumn(int col) {
+ return getColumn(col, 0, getRowCount());
+ }
+
+ @Override
+ public Object[] getColumn(int col, int start, int end) {
+ if(start > end || start < 0 || end > getEntryCount() || col < COL_ROW_NUM || col >= this.getColCount()) {
+ return null;
+ }
+ if(COL_ROW_NUM == col) {
+ Integer[] rows = new Integer[Math.min(end-start, getRowCount())];
+ for(int i=0;i<rows.length; i++) {
+ rows[i] = Integer.valueOf(start+i+1);
+ }
+ return rows;
+ }
+ return data.get(data.size()-1).getColumn(col, start, end);
+ }
+
+ @Override
+ public void setData(IDataEntry data) {
+ append(data);
+ }
+
+ @Override
+ public boolean remove(IDataEntry entry) {
+ return data.remove(entry);
+ }
+ //End IDataSet Methods
+
+ //IHistoricalDataSet Methods
+ @Override
+ public void append(IDataEntry data) {
+ if(data instanceof TableEntry) {
+ this.data.add((TableEntry)data);
+ }
+ }
+
+ @Override
+ public Object[] getHistoricalData(String key, int col) {
+ return getHistoricalData(key, col, 0, getEntryCount());
+ }
+
+ @Override
+ public Object[] getHistoricalData(String key, int col, int start, int end) {
+ if(start > end || start < 0 || end > getEntryCount() || col < COL_ROW_NUM || col >= this.getColCount()) {
+ return null;
+ }
+
+ if(COL_ROW_NUM == col) {
+ Integer[] rows = new Integer[Math.min(end-start, data.size())];
+ for(int i=0;i<rows.length; i++) {
+ rows[i] = Integer.valueOf(start+i+1);
+ }
+ return rows;
+ }
+
+ Object[] d = new Object[Math.min(end-start, getEntryCount())];
+
+ for(int i=0; i<d.length; i++) {
+ d[i] = getEntry(i+start).get(key, col);
+ if(null == d[i]) {
+ d[i] = Integer.valueOf(0);
+ }
+ }
+ return d;
+ }
+
+ @Override
+ public int getEntryCount() {
+ return data.size();
+ }
+
+ @Override
+ public IDataEntry getEntry(int entry) {
+ if(entry >=0 && entry < getEntryCount()) {
+ return data.get(entry);
+ }
+ return null;
+ }
+
+ @Override
+ public boolean remove(int entry) {
+ if(entry < 0 || entry >= data.size()) {
+ return false;
+ }
+ return (null != data.remove(entry));
+ }
+ //End IHistoricalDataSet Methods
+
+ //IBlockDataSet Methods
+ @Override
+ public Object[][] getData() {
+ return data.get(getEntryCount()-1).getData();
+ }
+ //End IBlockDataSet Methods
+
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.datasets.tabledataset"; //$NON-NLS-1$
+ protected List<TableEntry> data;
+ private String[] titles;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableEntry.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableEntry.java
index 633ab21e6d..83eeb3ace6 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableEntry.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableEntry.java
@@ -17,103 +17,103 @@ import java.util.List;
import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IDataEntry;
public class TableEntry implements IDataEntry {
- public TableEntry() {
- bodyContent = new ArrayList<>();
- }
-
- @Override
- public int getRowCount() {
- return bodyContent.size();
- }
-
- @Override
- public int getColCount() {
- if(getRowCount() > 0) {
- return bodyContent.get(0).length;
- }
- return 0;
- }
-
- @Override
- public Object get(String key, int col) {
- if(col >= 0 && col < getColCount()) {
- Object[] row = getRow(key);
- if(null != row)
- return row[col];
- }
- return null;
- }
-
- @Override
- public Object[][] getData() {
- Object[][] d = new Object[getRowCount()][getColCount()];
- for(int i=0; i<getRowCount(); i++) {
- d[i] = getRow(i);
- }
- return d;
- }
-
- @Override
- public Object[] getRow(int row) {
- if(row < 0 || row >= getRowCount())
- return null;
- return bodyContent.get(row);
- }
-
- @Override
- public Object[] getRow(String key) {
- Object[] row;
- for(int i=0; i<bodyContent.size(); i++) {
- row = bodyContent.get(i);
- if(row[0].toString().equals(key))
- return row;
- }
- return null;
- }
-
- @Override
- public Object[] getColumn(int col) {
- return getColumn(col, 0, getRowCount());
- }
-
- public Object[] getColumn(int col, int start, int end) {
- if(0 <= col && getColCount() > col && start >=0 && end > start && end <= getRowCount()) {
- Object[] res = new Object[Math.min(end-start, getRowCount())];
- for(int i=0; i<res.length; i++)
- res[i] = bodyContent.get(i+start)[col];
- return res;
- }
- return null;
- }
-
- @Override
- public void putRow(int row, Object[] data) {
- if(row >= bodyContent.size())
- add(data);
- else if(row >= 0) {
- bodyContent.add(row, data);
- bodyContent.remove(row+1);
- }
- }
-
- public void add(Object[] data) {
- if(null != data && (data.length == getColCount() || getRowCount() == 0))
- bodyContent.add(data);
- }
-
- @Override
- public IDataEntry copy() {
- TableEntry entry = new TableEntry();
- for(int i=0; i<bodyContent.size(); i++)
- entry.add(bodyContent.get(i));
-
- return entry;
- }
-
- @Override
- public boolean remove(int row) {
- return (null != bodyContent.remove(row));
- }
-
- private List<Object[]> bodyContent; //ArrayList of arrays
+ public TableEntry() {
+ bodyContent = new ArrayList<>();
+ }
+
+ @Override
+ public int getRowCount() {
+ return bodyContent.size();
+ }
+
+ @Override
+ public int getColCount() {
+ if(getRowCount() > 0) {
+ return bodyContent.get(0).length;
+ }
+ return 0;
+ }
+
+ @Override
+ public Object get(String key, int col) {
+ if(col >= 0 && col < getColCount()) {
+ Object[] row = getRow(key);
+ if(null != row)
+ return row[col];
+ }
+ return null;
+ }
+
+ @Override
+ public Object[][] getData() {
+ Object[][] d = new Object[getRowCount()][getColCount()];
+ for(int i=0; i<getRowCount(); i++) {
+ d[i] = getRow(i);
+ }
+ return d;
+ }
+
+ @Override
+ public Object[] getRow(int row) {
+ if(row < 0 || row >= getRowCount())
+ return null;
+ return bodyContent.get(row);
+ }
+
+ @Override
+ public Object[] getRow(String key) {
+ Object[] row;
+ for(int i=0; i<bodyContent.size(); i++) {
+ row = bodyContent.get(i);
+ if(row[0].toString().equals(key))
+ return row;
+ }
+ return null;
+ }
+
+ @Override
+ public Object[] getColumn(int col) {
+ return getColumn(col, 0, getRowCount());
+ }
+
+ public Object[] getColumn(int col, int start, int end) {
+ if(0 <= col && getColCount() > col && start >=0 && end > start && end <= getRowCount()) {
+ Object[] res = new Object[Math.min(end-start, getRowCount())];
+ for(int i=0; i<res.length; i++)
+ res[i] = bodyContent.get(i+start)[col];
+ return res;
+ }
+ return null;
+ }
+
+ @Override
+ public void putRow(int row, Object[] data) {
+ if(row >= bodyContent.size())
+ add(data);
+ else if(row >= 0) {
+ bodyContent.add(row, data);
+ bodyContent.remove(row+1);
+ }
+ }
+
+ public void add(Object[] data) {
+ if(null != data && (data.length == getColCount() || getRowCount() == 0))
+ bodyContent.add(data);
+ }
+
+ @Override
+ public IDataEntry copy() {
+ TableEntry entry = new TableEntry();
+ for(int i=0; i<bodyContent.size(); i++)
+ entry.add(bodyContent.get(i));
+
+ return entry;
+ }
+
+ @Override
+ public boolean remove(int row) {
+ return (null != bodyContent.remove(row));
+ }
+
+ private List<Object[]> bodyContent; //ArrayList of arrays
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableParser.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableParser.java
index 91a7d25ff0..2883910f8a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableParser.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/datasets/table/TableParser.java
@@ -21,65 +21,65 @@ import org.eclipse.linuxtools.systemtap.graphing.core.datasets.IDataSetParser;
public class TableParser implements IDataSetParser {
- public TableParser(String[] regEx, String delimiter) {
- this.regEx = Arrays.copyOf(regEx, regEx.length);
- this.delimiter = delimiter;
- buildPattern();
- }
-
- private void buildPattern() {
- StringBuilder wholeRegExpr = new StringBuilder();
- for(int i=0; i<regEx.length; i++) {
- wholeRegExpr.append('(' + regEx[i] + ')');
- }
- wholePattern = Pattern.compile(wholeRegExpr.toString());
- delimPattern = Pattern.compile(delimiter);
- }
-
- @Override
- public IDataEntry parse(StringBuilder s) {
- if(null == s) {
- return null;
- }
-
- TableEntry e = null;
-
- Matcher wholeMatcher = wholePattern.matcher(s);
- Matcher delimMatcher = delimPattern.matcher(s);
-
- Object[] data;
- int end = 0;
- if(delimMatcher.find()) {
- e = new TableEntry();
- end = delimMatcher.start();
-
- int group, j;
- while(wholeMatcher.find() && wholeMatcher.end() < end) {
- group = 0;
- data = new Object[regEx.length>>1];
- for(int i=0; i<regEx.length; i++) {
- group++;
- for(j=0; j<regEx[i].length(); j++) {
- if(regEx[i].charAt(j) == ')') {
- group++;
- }
- }
-
- if(0 == (i&1)) {
- data[i>>1] = wholeMatcher.group(group);
- }
- }
- e.add(data);
- }
- s.delete(0, delimMatcher.end());
- }
-
- return e;
- }
-
- private String[] regEx;
- private String delimiter;
-
- private Pattern wholePattern;
- private Pattern delimPattern;
+ public TableParser(String[] regEx, String delimiter) {
+ this.regEx = Arrays.copyOf(regEx, regEx.length);
+ this.delimiter = delimiter;
+ buildPattern();
+ }
+
+ private void buildPattern() {
+ StringBuilder wholeRegExpr = new StringBuilder();
+ for(int i=0; i<regEx.length; i++) {
+ wholeRegExpr.append('(' + regEx[i] + ')');
+ }
+ wholePattern = Pattern.compile(wholeRegExpr.toString());
+ delimPattern = Pattern.compile(delimiter);
+ }
+
+ @Override
+ public IDataEntry parse(StringBuilder s) {
+ if(null == s) {
+ return null;
+ }
+
+ TableEntry e = null;
+
+ Matcher wholeMatcher = wholePattern.matcher(s);
+ Matcher delimMatcher = delimPattern.matcher(s);
+
+ Object[] data;
+ int end = 0;
+ if(delimMatcher.find()) {
+ e = new TableEntry();
+ end = delimMatcher.start();
+
+ int group, j;
+ while(wholeMatcher.find() && wholeMatcher.end() < end) {
+ group = 0;
+ data = new Object[regEx.length>>1];
+ for(int i=0; i<regEx.length; i++) {
+ group++;
+ for(j=0; j<regEx[i].length(); j++) {
+ if(regEx[i].charAt(j) == ')') {
+ group++;
+ }
+ }
+
+ if(0 == (i&1)) {
+ data[i>>1] = wholeMatcher.group(group);
+ }
+ }
+ e.add(data);
+ }
+ s.delete(0, delimMatcher.end());
+ }
+
+ return e;
+ }
+
+ private String[] regEx;
+ private String delimiter;
+
+ private Pattern wholePattern;
+ private Pattern delimPattern;
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/IDataSetFilter.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/IDataSetFilter.java
index f062bd149d..3197470de8 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/IDataSetFilter.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/IDataSetFilter.java
@@ -14,14 +14,14 @@ package org.eclipse.linuxtools.systemtap.graphing.core.filters;
import java.util.List;
public interface IDataSetFilter {
- public List<Object>[] filter(List<Object>[] data);
- public String getID();
- /**
- * @since 2.0
- */
- public String getInfo();
- /**
- * @since 2.0
- */
- public int getColumn();
+ public List<Object>[] filter(List<Object>[] data);
+ public String getID();
+ /**
+ * @since 2.0
+ */
+ public String getInfo();
+ /**
+ * @since 2.0
+ */
+ public int getColumn();
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/MatchFilter.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/MatchFilter.java
index f9cb45e99b..279d9765c2 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/MatchFilter.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/MatchFilter.java
@@ -20,65 +20,65 @@ import org.eclipse.linuxtools.systemtap.structures.Copier;
public class MatchFilter implements IDataSetFilter {
- public MatchFilter(int column, Object value, int style) {
- this.column = column;
- this.value = value;
- this.style = style;
- }
+ public MatchFilter(int column, Object value, int style) {
+ this.column = column;
+ this.value = value;
+ this.style = style;
+ }
- /**
- * Apply the MatchFilter to the passed dataset.
- *
- * @param data The dataset to filter.
- *
- * @return The filtered dataset.
- */
- @Override
- public List<Object>[] filter(List<Object>[] data) {
- if(column < 0 || column >= data.length) {
- return null;
- }
+ /**
+ * Apply the MatchFilter to the passed dataset.
+ *
+ * @param data The dataset to filter.
+ *
+ * @return The filtered dataset.
+ */
+ @Override
+ public List<Object>[] filter(List<Object>[] data) {
+ if(column < 0 || column >= data.length) {
+ return null;
+ }
- List<Object>[] newData = Copier.copy(data);
- boolean equals;
- for(int j, i=newData[column].size()-1; i>=0; i--) {
- equals = newData[column].get(i).toString().equals(value.toString()); //TODO: Find better equivilance method
- if((equals && REMOVE_MATCHING == (style & 1)) || (!equals && KEEP_MATCHING == (style & 1))) {
- for(j=0; j<newData.length; j++) {
- newData[j].remove(i);
- }
- }
- }
- return newData;
- }
+ List<Object>[] newData = Copier.copy(data);
+ boolean equals;
+ for(int j, i=newData[column].size()-1; i>=0; i--) {
+ equals = newData[column].get(i).toString().equals(value.toString()); //TODO: Find better equivilance method
+ if((equals && REMOVE_MATCHING == (style & 1)) || (!equals && KEEP_MATCHING == (style & 1))) {
+ for(j=0; j<newData.length; j++) {
+ newData[j].remove(i);
+ }
+ }
+ }
+ return newData;
+ }
- @Override
- public String getID() {
- return ID;
- }
+ @Override
+ public String getID() {
+ return ID;
+ }
- /**
- * @since 2.0
- */
- @Override
- public String getInfo() {
- return MessageFormat.format(Localization.getString(style == KEEP_MATCHING ? "MatchFilter.Matches" : "MatchFilter.Removes"), value.toString()); //$NON-NLS-1$ //$NON-NLS-2$
- }
+ /**
+ * @since 2.0
+ */
+ @Override
+ public String getInfo() {
+ return MessageFormat.format(Localization.getString(style == KEEP_MATCHING ? "MatchFilter.Matches" : "MatchFilter.Removes"), value.toString()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
- /**
- * @since 2.0
- */
- @Override
- public int getColumn() {
- return column;
- }
+ /**
+ * @since 2.0
+ */
+ @Override
+ public int getColumn() {
+ return column;
+ }
- private int column;
- private Object value;
- private int style;
+ private int column;
+ private Object value;
+ private int style;
- public static final int KEEP_MATCHING = 0;
- public static final int REMOVE_MATCHING = 1;
+ public static final int KEEP_MATCHING = 0;
+ public static final int REMOVE_MATCHING = 1;
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.filters.MatchFilter"; //$NON-NLS-1$
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.filters.MatchFilter"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/RangeFilter.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/RangeFilter.java
index 5e70719edf..2f36520946 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/RangeFilter.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/RangeFilter.java
@@ -21,138 +21,138 @@ import org.eclipse.linuxtools.systemtap.structures.Copier;
public class RangeFilter implements IDataSetFilter {
- /**
- * Create a new Range Filter for a table of data.
- * @param column The index of the table's column to apply the filter to.
- * @param lowerBound The lower bound of the range to apply. Set to <code>null</code> to set a boundless lower limit.
- * @param upperBound The upper bound of the range to apply. Set to <code>null</code> to set a boundless upper limit.
- * @param style Extra properties of this filter, set by <i>bitwise-OR</i>'ing none or more of
- * {@link #INSIDE_BOUNDS}, {@link #OUTSIDE_BOUNDS}, or {@link #INCLUSIVE}.
- */
- public RangeFilter(int column, Number lowerBound, Number upperBound, int style) {
- this.column = column;
- this.lowerBound = lowerBound;
- this.upperBound = upperBound;
- if (lowerBound == null || upperBound == null) {
- this.style = style & INCLUSIVE;
- } else {
- this.style = style;
- }
- }
+ /**
+ * Create a new Range Filter for a table of data.
+ * @param column The index of the table's column to apply the filter to.
+ * @param lowerBound The lower bound of the range to apply. Set to <code>null</code> to set a boundless lower limit.
+ * @param upperBound The upper bound of the range to apply. Set to <code>null</code> to set a boundless upper limit.
+ * @param style Extra properties of this filter, set by <i>bitwise-OR</i>'ing none or more of
+ * {@link #INSIDE_BOUNDS}, {@link #OUTSIDE_BOUNDS}, or {@link #INCLUSIVE}.
+ */
+ public RangeFilter(int column, Number lowerBound, Number upperBound, int style) {
+ this.column = column;
+ this.lowerBound = lowerBound;
+ this.upperBound = upperBound;
+ if (lowerBound == null || upperBound == null) {
+ this.style = style & INCLUSIVE;
+ } else {
+ this.style = style;
+ }
+ }
- /**
- * Apply the RangeFilter to the passed dataset.
- *
- * @param data The dataset to filter.
- *
- * @return The filtered dataset.
- */
- @Override
- public List<Object>[] filter(List<Object>[] data) {
- if(column < 0 || column >= data.length) {
- return null;
- }
+ /**
+ * Apply the RangeFilter to the passed dataset.
+ *
+ * @param data The dataset to filter.
+ *
+ * @return The filtered dataset.
+ */
+ @Override
+ public List<Object>[] filter(List<Object>[] data) {
+ if(column < 0 || column >= data.length) {
+ return null;
+ }
- List<Object>[] newData = Copier.copy(data);
- for(int j,i=newData[column].size()-1; i>=0; i--) {
- if(!inBounds(NumberType.obj2num(newData[column].get(i)))) {
- for(j=0; j<newData.length; j++) {
- newData[j].remove(i);
- }
- }
- }
- return newData;
- }
+ List<Object>[] newData = Copier.copy(data);
+ for(int j,i=newData[column].size()-1; i>=0; i--) {
+ if(!inBounds(NumberType.obj2num(newData[column].get(i)))) {
+ for(j=0; j<newData.length; j++) {
+ newData[j].remove(i);
+ }
+ }
+ }
+ return newData;
+ }
- @Override
- public String getID() {
- return ID;
- }
+ @Override
+ public String getID() {
+ return ID;
+ }
- /**
- * Verify that the number passed is in the bounds of the created filter.
- *
- * @param num The number to verify.
- *
- * @return True if the number is within bounds.
- */
- private boolean inBounds(Number num) {
- if (INSIDE_BOUNDS == (style & 1)) {
- if(INCLUSIVE == (style & 2)) {
- if((upperBound != null && num.doubleValue() > upperBound.doubleValue())
- || (lowerBound != null && num.doubleValue() < lowerBound.doubleValue())) {
- return false;
- }
- } else {
- if((upperBound != null && num.doubleValue() >= upperBound.doubleValue())
- || (lowerBound != null && num.doubleValue() <= lowerBound.doubleValue())) {
- return false;
- }
- }
- } else {
- if(INCLUSIVE == (style & 2)) {
- if((upperBound != null && num.doubleValue() < upperBound.doubleValue())
- && (lowerBound != null && num.doubleValue() > lowerBound.doubleValue())) {
- return false;
- }
- } else {
- if((upperBound != null && num.doubleValue() <= upperBound.doubleValue())
- && (lowerBound != null && num.doubleValue() >= lowerBound.doubleValue())) {
- return false;
- }
- }
- }
- return true;
- }
+ /**
+ * Verify that the number passed is in the bounds of the created filter.
+ *
+ * @param num The number to verify.
+ *
+ * @return True if the number is within bounds.
+ */
+ private boolean inBounds(Number num) {
+ if (INSIDE_BOUNDS == (style & 1)) {
+ if(INCLUSIVE == (style & 2)) {
+ if((upperBound != null && num.doubleValue() > upperBound.doubleValue())
+ || (lowerBound != null && num.doubleValue() < lowerBound.doubleValue())) {
+ return false;
+ }
+ } else {
+ if((upperBound != null && num.doubleValue() >= upperBound.doubleValue())
+ || (lowerBound != null && num.doubleValue() <= lowerBound.doubleValue())) {
+ return false;
+ }
+ }
+ } else {
+ if(INCLUSIVE == (style & 2)) {
+ if((upperBound != null && num.doubleValue() < upperBound.doubleValue())
+ && (lowerBound != null && num.doubleValue() > lowerBound.doubleValue())) {
+ return false;
+ }
+ } else {
+ if((upperBound != null && num.doubleValue() <= upperBound.doubleValue())
+ && (lowerBound != null && num.doubleValue() >= lowerBound.doubleValue())) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
- /**
- * @since 2.0
- */
- @Override
- public String getInfo() {
- boolean insideBounds = INSIDE_BOUNDS == (style & 1);
- boolean inclusive = INCLUSIVE == (style & 2);
- String info;
- if (lowerBound != null && upperBound != null) {
- info = MessageFormat.format(Localization.getString(insideBounds ?
- "RangeFilter.Inside" : "RangeFilter.Outside"), lowerBound.toString(), upperBound.toString()); //$NON-NLS-1$ //$NON-NLS-2$
- return inclusive ? MessageFormat.format(Localization.getString("RangeFilter.Inclusive"), info) : info; //$NON-NLS-1$
- } else {
- boolean lower = lowerBound != null;
- info = (lower ? lowerBound : upperBound).toString();
- return MessageFormat.format(Localization.getString(lower ?
- "RangeFilter.GreaterThan" : "RangeFilter.LessThan"), !inclusive ? //$NON-NLS-1$ //$NON-NLS-2$
- info : MessageFormat.format(Localization.getString("RangeFilter.EqualTo"), info)); //$NON-NLS-1$
- }
- }
+ /**
+ * @since 2.0
+ */
+ @Override
+ public String getInfo() {
+ boolean insideBounds = INSIDE_BOUNDS == (style & 1);
+ boolean inclusive = INCLUSIVE == (style & 2);
+ String info;
+ if (lowerBound != null && upperBound != null) {
+ info = MessageFormat.format(Localization.getString(insideBounds ?
+ "RangeFilter.Inside" : "RangeFilter.Outside"), lowerBound.toString(), upperBound.toString()); //$NON-NLS-1$ //$NON-NLS-2$
+ return inclusive ? MessageFormat.format(Localization.getString("RangeFilter.Inclusive"), info) : info; //$NON-NLS-1$
+ } else {
+ boolean lower = lowerBound != null;
+ info = (lower ? lowerBound : upperBound).toString();
+ return MessageFormat.format(Localization.getString(lower ?
+ "RangeFilter.GreaterThan" : "RangeFilter.LessThan"), !inclusive ? //$NON-NLS-1$ //$NON-NLS-2$
+ info : MessageFormat.format(Localization.getString("RangeFilter.EqualTo"), info)); //$NON-NLS-1$
+ }
+ }
- /**
- * @since 2.0
- */
- @Override
- public int getColumn() {
- return column;
- }
+ /**
+ * @since 2.0
+ */
+ @Override
+ public int getColumn() {
+ return column;
+ }
- private int column;
- private Number upperBound;
- private Number lowerBound;
- private int style;
+ private int column;
+ private Number upperBound;
+ private Number lowerBound;
+ private int style;
- /**
- * Style constant indicating that the filter will only keep values inside the provided bounds.
- * (Not applicable for unbounded ranges.)
- */
- public static final int INSIDE_BOUNDS = 0;
- /**
- * Style constant indicating that the filter will only keep values outside the provided bounds.
- * (Not applicable for unbounded ranges.)
- */
- public static final int OUTSIDE_BOUNDS = 1;
- /**
- * Style constant indicating that the filter will not exclude values that equal either the upper or lower bound.
- */
- public static final int INCLUSIVE = 2;
+ /**
+ * Style constant indicating that the filter will only keep values inside the provided bounds.
+ * (Not applicable for unbounded ranges.)
+ */
+ public static final int INSIDE_BOUNDS = 0;
+ /**
+ * Style constant indicating that the filter will only keep values outside the provided bounds.
+ * (Not applicable for unbounded ranges.)
+ */
+ public static final int OUTSIDE_BOUNDS = 1;
+ /**
+ * Style constant indicating that the filter will not exclude values that equal either the upper or lower bound.
+ */
+ public static final int INCLUSIVE = 2;
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.filters.RangeFilter"; //$NON-NLS-1$
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.filters.RangeFilter"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/SortFilter.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/SortFilter.java
index 2f6e1ca0d2..9d5c7ad035 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/SortFilter.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/SortFilter.java
@@ -22,74 +22,74 @@ import org.eclipse.linuxtools.systemtap.structures.Sort;
public class SortFilter implements IDataSetFilter {
- public SortFilter(int column, int ordering) {
- this.column = column;
- this.style = (ordering==ASCENDING ? ASCENDING : DESCENDING);
- }
-
- /**
- * Apply the RangeFilter to the passed dataset.
- *
- * @param data The dataset to filter.
- *
- * @return The filtered dataset.
- */
- @Override
- public List<Object>[] filter(List<Object>[] data) {
- if(column < 0 || column >= data.length)
- return null;
-
- List<Object>[] newData = Copier.copy(data);
- IndexedObject[] items = new IndexedObject[newData[0].size()];
-
- try {
- for(int i=0; i<newData[column].size(); i++)
- items[i] = new IndexedObject(i, NumberType.cleanObj2Num(newData[column].get(i)));
- } catch(NumberFormatException nfe) {
- for(int i=0; i<newData[column].size(); i++)
- items[i] = new IndexedObject(i, newData[column].get(i));
- }
-
- Sort.quicksort(items, 0, items.length-1);
-
- for(int j, i=0; i<newData.length; i++) {
- for(j=0; j<items.length; j++) {
- if(DESCENDING == style)
- newData[i].add(newData[i].get(items[items.length-j-1].index));
- else
- newData[i].add(newData[i].get(items[j].index));
- }
- for(j=0; j<items.length; j++)
- newData[i].remove(0);
- }
- return newData;
- }
-
- @Override
- public String getID() {
- return ID;
- }
-
- /**
- * @since 2.0
- */
- @Override
- public String getInfo() {
- return Localization.getString(style == ASCENDING ? "SortFilter.Ascending" : "SortFilter.Descending"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * @since 2.0
- */
- @Override
- public int getColumn() {
- return column;
- }
-
- private int column;
- private int style;
-
- public static final int ASCENDING = 0;
- public static final int DESCENDING = 1;
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.filters.SortFilter"; //$NON-NLS-1$
+ public SortFilter(int column, int ordering) {
+ this.column = column;
+ this.style = (ordering==ASCENDING ? ASCENDING : DESCENDING);
+ }
+
+ /**
+ * Apply the RangeFilter to the passed dataset.
+ *
+ * @param data The dataset to filter.
+ *
+ * @return The filtered dataset.
+ */
+ @Override
+ public List<Object>[] filter(List<Object>[] data) {
+ if(column < 0 || column >= data.length)
+ return null;
+
+ List<Object>[] newData = Copier.copy(data);
+ IndexedObject[] items = new IndexedObject[newData[0].size()];
+
+ try {
+ for(int i=0; i<newData[column].size(); i++)
+ items[i] = new IndexedObject(i, NumberType.cleanObj2Num(newData[column].get(i)));
+ } catch(NumberFormatException nfe) {
+ for(int i=0; i<newData[column].size(); i++)
+ items[i] = new IndexedObject(i, newData[column].get(i));
+ }
+
+ Sort.quicksort(items, 0, items.length-1);
+
+ for(int j, i=0; i<newData.length; i++) {
+ for(j=0; j<items.length; j++) {
+ if(DESCENDING == style)
+ newData[i].add(newData[i].get(items[items.length-j-1].index));
+ else
+ newData[i].add(newData[i].get(items[j].index));
+ }
+ for(j=0; j<items.length; j++)
+ newData[i].remove(0);
+ }
+ return newData;
+ }
+
+ @Override
+ public String getID() {
+ return ID;
+ }
+
+ /**
+ * @since 2.0
+ */
+ @Override
+ public String getInfo() {
+ return Localization.getString(style == ASCENDING ? "SortFilter.Ascending" : "SortFilter.Descending"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * @since 2.0
+ */
+ @Override
+ public int getColumn() {
+ return column;
+ }
+
+ private int column;
+ private int style;
+
+ public static final int ASCENDING = 0;
+ public static final int DESCENDING = 1;
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.filters.SortFilter"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/UniqueFilter.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/UniqueFilter.java
index f2c4be9012..79dc032846 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/UniqueFilter.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/filters/UniqueFilter.java
@@ -27,107 +27,107 @@ import org.eclipse.linuxtools.systemtap.structures.Copier;
public class UniqueFilter implements IDataSetFilter {
- public UniqueFilter(int column, IDataAggregate aggregate) {
- this.column = column;
- this.aggregate = aggregate;
- }
+ public UniqueFilter(int column, IDataAggregate aggregate) {
+ this.column = column;
+ this.aggregate = aggregate;
+ }
- /**
- * Verify that the number passed is in the bounds of the created filter.
- *
- * @param data The data to verify.
- *
- * @return True if the number is within bounds.
- */
- @Override
- public List<Object>[] filter(List<Object>[] data) {
- if(column < 0 || column >= data.length) {
- return null;
- }
+ /**
+ * Verify that the number passed is in the bounds of the created filter.
+ *
+ * @param data The data to verify.
+ *
+ * @return True if the number is within bounds.
+ */
+ @Override
+ public List<Object>[] filter(List<Object>[] data) {
+ if(column < 0 || column >= data.length) {
+ return null;
+ }
- List<Object>[] newData = Copier.copy(data);
- ArrayList<Object>[] aggregates = GraphingCorePlugin.createArrayList(newData.length, new Object());
- for(int i=0; i<aggregates.length;i++) {
- aggregates[i] = new ArrayList<>();
- }
+ List<Object>[] newData = Copier.copy(data);
+ ArrayList<Object>[] aggregates = GraphingCorePlugin.createArrayList(newData.length, new Object());
+ for(int i=0; i<aggregates.length;i++) {
+ aggregates[i] = new ArrayList<>();
+ }
- for(int k,j,i=newData[0].size()-1; i>=0; i--) {
- for(j=i-1; j>=0; j--) {
- if(newData[column].get(i).toString().equals(newData[column].get(j).toString())) { //TODO: Find better equivilance method
- i--;
- for(k=0; k<newData.length; k++) {
- aggregates[k].add(newData[k].get(j));
- newData[k].remove(j);
- }
- }
- }
- for(k=0; k<newData.length; k++) {
- aggregates[k].add(newData[k].get(i));
- if(k!=column) {
- newData[k].remove(i);
- try {
- newData[k].add(i, aggregate.aggregate(NumberType.cleanObj2Num(aggregates[k].toArray())));
- } catch(NumberFormatException nfe) {
- newData[k].add(i, columnMerge(aggregates[k].toArray()));
- }
- }
- aggregates[k].clear();
- }
- }
- return newData;
- }
+ for(int k,j,i=newData[0].size()-1; i>=0; i--) {
+ for(j=i-1; j>=0; j--) {
+ if(newData[column].get(i).toString().equals(newData[column].get(j).toString())) { //TODO: Find better equivilance method
+ i--;
+ for(k=0; k<newData.length; k++) {
+ aggregates[k].add(newData[k].get(j));
+ newData[k].remove(j);
+ }
+ }
+ }
+ for(k=0; k<newData.length; k++) {
+ aggregates[k].add(newData[k].get(i));
+ if(k!=column) {
+ newData[k].remove(i);
+ try {
+ newData[k].add(i, aggregate.aggregate(NumberType.cleanObj2Num(aggregates[k].toArray())));
+ } catch(NumberFormatException nfe) {
+ newData[k].add(i, columnMerge(aggregates[k].toArray()));
+ }
+ }
+ aggregates[k].clear();
+ }
+ }
+ return newData;
+ }
- /**
- * Merges two passed columns into a StringBuilder object.
- *
- * @param col The columns to merge.
- *
- * @return The StringBuilder object made as a result of the merge.
- */
- private String columnMerge(Object[] col) {
- StringBuilder sb = new StringBuilder(col[0].toString());
- for(int i=1; i<col.length; i++) {
- if(sb.indexOf(col[i].toString()) < 0) {
- sb.append("/" + col[i].toString()); //$NON-NLS-1$
- }
- }
- return sb.toString();
- }
+ /**
+ * Merges two passed columns into a StringBuilder object.
+ *
+ * @param col The columns to merge.
+ *
+ * @return The StringBuilder object made as a result of the merge.
+ */
+ private String columnMerge(Object[] col) {
+ StringBuilder sb = new StringBuilder(col[0].toString());
+ for(int i=1; i<col.length; i++) {
+ if(sb.indexOf(col[i].toString()) < 0) {
+ sb.append("/" + col[i].toString()); //$NON-NLS-1$
+ }
+ }
+ return sb.toString();
+ }
- @Override
- public String getID() {
- return ID;
- }
+ @Override
+ public String getID() {
+ return ID;
+ }
- /**
- * @since 2.0
- */
- @Override
- public String getInfo() {
- // Return the aggregate name without referencing outside projects.
- if (aggregate.getID().equals(AverageAggregate.ID)) {
- return Localization.getString("UniqueFilter.Average"); //$NON-NLS-1$
- } else if (aggregate.getID().equals(CountAggregate.ID)) {
- return Localization.getString("UniqueFilter.Count"); //$NON-NLS-1$
- } else if (aggregate.getID().equals(MaxAggregate.ID)) {
- return Localization.getString("UniqueFilter.Max"); //$NON-NLS-1$
- } else if (aggregate.getID().equals(MinAggregate.ID)) {
- return Localization.getString("UniqueFilter.Min"); //$NON-NLS-1$
- } else if (aggregate.getID().equals(SumAggregate.ID)) {
- return Localization.getString("UniqueFilter.Sum"); //$NON-NLS-1$
- }
- return Localization.getString("UniqueFilter.Other"); //$NON-NLS-1$
- }
+ /**
+ * @since 2.0
+ */
+ @Override
+ public String getInfo() {
+ // Return the aggregate name without referencing outside projects.
+ if (aggregate.getID().equals(AverageAggregate.ID)) {
+ return Localization.getString("UniqueFilter.Average"); //$NON-NLS-1$
+ } else if (aggregate.getID().equals(CountAggregate.ID)) {
+ return Localization.getString("UniqueFilter.Count"); //$NON-NLS-1$
+ } else if (aggregate.getID().equals(MaxAggregate.ID)) {
+ return Localization.getString("UniqueFilter.Max"); //$NON-NLS-1$
+ } else if (aggregate.getID().equals(MinAggregate.ID)) {
+ return Localization.getString("UniqueFilter.Min"); //$NON-NLS-1$
+ } else if (aggregate.getID().equals(SumAggregate.ID)) {
+ return Localization.getString("UniqueFilter.Sum"); //$NON-NLS-1$
+ }
+ return Localization.getString("UniqueFilter.Other"); //$NON-NLS-1$
+ }
- /**
- * @since 2.0
- */
- @Override
- public int getColumn() {
- return column;
- }
+ /**
+ * @since 2.0
+ */
+ @Override
+ public int getColumn() {
+ return column;
+ }
- private int column;
- private IDataAggregate aggregate;
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.filters.UniqueFilter"; //$NON-NLS-1$
+ private int column;
+ private IDataAggregate aggregate;
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.core.filters.UniqueFilter"; //$NON-NLS-1$
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/ChartStreamDaemon.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/ChartStreamDaemon.java
index 8246588685..f6acd1d19a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/ChartStreamDaemon.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/ChartStreamDaemon.java
@@ -19,48 +19,48 @@ import org.eclipse.linuxtools.systemtap.structures.listeners.IGobblerListener;
public class ChartStreamDaemon implements IGobblerListener {
- public ChartStreamDaemon(IDataSet d, IDataSetParser p) {
- data = d;
- outputData = new StringBuilder(""); //$NON-NLS-1$
- parser = p;
- disposed = false;
- }
+ public ChartStreamDaemon(IDataSet d, IDataSetParser p) {
+ data = d;
+ outputData = new StringBuilder(""); //$NON-NLS-1$
+ parser = p;
+ disposed = false;
+ }
- /**
- * Takes one line from the output data and appends it to data object.
- */
- private void pushData() {
- if(null == data || null == parser)
- return;
+ /**
+ * Takes one line from the output data and appends it to data object.
+ */
+ private void pushData() {
+ if(null == data || null == parser)
+ return;
- IDataEntry e = parser.parse(outputData);
- if(null != e)
- data.setData(e);
- }
+ IDataEntry e = parser.parse(outputData);
+ if(null != e)
+ data.setData(e);
+ }
- @Override
- public void handleDataEvent(String line) {
- outputData.append(line);
- this.pushData();
- }
+ @Override
+ public void handleDataEvent(String line) {
+ outputData.append(line);
+ this.pushData();
+ }
- public boolean isDisposed() {
- return disposed;
- }
+ public boolean isDisposed() {
+ return disposed;
+ }
- public void dispose() {
- if(!disposed) {
- disposed = true;
- data = null;
- if(null != outputData)
- outputData.delete(0, outputData.length());
- outputData = null;
- parser = null;
- }
- }
+ public void dispose() {
+ if(!disposed) {
+ disposed = true;
+ data = null;
+ if(null != outputData)
+ outputData.delete(0, outputData.length());
+ outputData = null;
+ parser = null;
+ }
+ }
- private IDataSet data;
- private StringBuilder outputData;
- private IDataSetParser parser;
- private boolean disposed;
+ private IDataSet data;
+ private StringBuilder outputData;
+ private IDataSetParser parser;
+ private boolean disposed;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/GraphData.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/GraphData.java
index 0ec1f5bc54..e0fcb2c308 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/GraphData.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/GraphData.java
@@ -12,62 +12,62 @@
package org.eclipse.linuxtools.systemtap.graphing.core.structures;
public class GraphData {
- public int xSeries;
- public int[] ySeries;
- public String key;
- public String graphID;
- public String title;
+ public int xSeries;
+ public int[] ySeries;
+ public String key;
+ public String graphID;
+ public String title;
- /**
- * Creates and returns a copy of this GraphData instance.
- * @return A copy of this GraphData.
- * @since 1.1
- */
- public GraphData getCopy() {
- GraphData gd = new GraphData();
- gd.xSeries = this.xSeries;
- gd.ySeries = this.ySeries == null ? null : this.ySeries.clone();
- gd.key = this.key == null ? null : this.key.substring(0);
- gd.graphID = this.graphID == null ? null : this.graphID.substring(0);
- gd.title = this.title == null ? null : this.title.substring(0);
- return gd;
- }
+ /**
+ * Creates and returns a copy of this GraphData instance.
+ * @return A copy of this GraphData.
+ * @since 1.1
+ */
+ public GraphData getCopy() {
+ GraphData gd = new GraphData();
+ gd.xSeries = this.xSeries;
+ gd.ySeries = this.ySeries == null ? null : this.ySeries.clone();
+ gd.key = this.key == null ? null : this.key.substring(0);
+ gd.graphID = this.graphID == null ? null : this.graphID.substring(0);
+ gd.title = this.title == null ? null : this.title.substring(0);
+ return gd;
+ }
- /**
- * Indicates whether all properties of this GraphData are the same as another GraphData.
- * @param gd The GraphData to compare with.
- * @return <code>true</code> if all properties are equal, or <code>false</code> otherwise.
- * @since 1.1
- */
- public boolean equals(GraphData gd) {
- if (gd.ySeries != null && this.ySeries != null) {
- if (gd.ySeries.length != this.ySeries.length) {
- return false;
- }
- for (int i = 0; i < this.ySeries.length; i++) {
- if (gd.ySeries[i] != this.ySeries[i]) {
- return false;
- }
- }
- } else if (gd.ySeries != this.ySeries) {
- return false;
- }
+ /**
+ * Indicates whether all properties of this GraphData are the same as another GraphData.
+ * @param gd The GraphData to compare with.
+ * @return <code>true</code> if all properties are equal, or <code>false</code> otherwise.
+ * @since 1.1
+ */
+ public boolean equals(GraphData gd) {
+ if (gd.ySeries != null && this.ySeries != null) {
+ if (gd.ySeries.length != this.ySeries.length) {
+ return false;
+ }
+ for (int i = 0; i < this.ySeries.length; i++) {
+ if (gd.ySeries[i] != this.ySeries[i]) {
+ return false;
+ }
+ }
+ } else if (gd.ySeries != this.ySeries) {
+ return false;
+ }
- if ((gd.key != this.key)
- && (gd.key != null && this.key != null && !gd.key.equals(this.key))) {
- return false;
- }
+ if ((gd.key != this.key)
+ && (gd.key != null && this.key != null && !gd.key.equals(this.key))) {
+ return false;
+ }
- if ((gd.graphID != this.graphID)
- && (gd.graphID != null && this.graphID != null && !gd.graphID.equals(this.graphID))) {
- return false;
- }
+ if ((gd.graphID != this.graphID)
+ && (gd.graphID != null && this.graphID != null && !gd.graphID.equals(this.graphID))) {
+ return false;
+ }
- if ((gd.title != this.title)
- && (gd.title != null && this.title != null && !gd.title.equals(this.title))) {
- return false;
- }
+ if ((gd.title != this.title)
+ && (gd.title != null && this.title != null && !gd.title.equals(this.title))) {
+ return false;
+ }
- return gd.xSeries == this.xSeries;
- }
+ return gd.xSeries == this.xSeries;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/NumberType.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/NumberType.java
index bd60f8f05a..ad545934c0 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/NumberType.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.core/src/org/eclipse/linuxtools/systemtap/graphing/core/structures/NumberType.java
@@ -13,95 +13,95 @@ package org.eclipse.linuxtools.systemtap.graphing.core.structures;
public final class NumberType {
- /**
- * Returns a new instance of the passed in num of type orig.
- *
- * @param orig The desired datatype.
- * @param num The number to replicate.
- *
- * @return The new cast number.
- */
- public static Number getNumber(Number orig, double num) {
- if(orig instanceof Long) {
- return Long.valueOf((long)num);
- } else if(orig instanceof Double) {
- return Double.valueOf(num);
- } else if(orig instanceof Float) {
- return Float.valueOf((float)num);
- } else if(orig instanceof Byte) {
- return Byte.valueOf((byte)num);
- } else if(orig instanceof Short) {
- return Short.valueOf((short)num);
- }
- return Integer.valueOf((int)num);
- }
+ /**
+ * Returns a new instance of the passed in num of type orig.
+ *
+ * @param orig The desired datatype.
+ * @param num The number to replicate.
+ *
+ * @return The new cast number.
+ */
+ public static Number getNumber(Number orig, double num) {
+ if(orig instanceof Long) {
+ return Long.valueOf((long)num);
+ } else if(orig instanceof Double) {
+ return Double.valueOf(num);
+ } else if(orig instanceof Float) {
+ return Float.valueOf((float)num);
+ } else if(orig instanceof Byte) {
+ return Byte.valueOf((byte)num);
+ } else if(orig instanceof Short) {
+ return Short.valueOf((short)num);
+ }
+ return Integer.valueOf((int)num);
+ }
- /**
- * Takes an array of objects and returns an array of Numbers.
- *
- * @param o The array of objects to convert.
- *
- * @return The array of Numbers from o.
- */
- public static Number[] obj2num(Object[] o) {
- Number[] arr = new Number[o.length];
- for(int i = 0; i < o.length; i++) {
- arr[i] = obj2num(o[i]);
- }
+ /**
+ * Takes an array of objects and returns an array of Numbers.
+ *
+ * @param o The array of objects to convert.
+ *
+ * @return The array of Numbers from o.
+ */
+ public static Number[] obj2num(Object[] o) {
+ Number[] arr = new Number[o.length];
+ for(int i = 0; i < o.length; i++) {
+ arr[i] = obj2num(o[i]);
+ }
- return arr;
- }
+ return arr;
+ }
- /**
- * Takes an array of Numbers and returns an array of objects.
- *
- * @param o The array of Numbers to convert.
- *
- * @return The array of objects from o.
- */
- public static Number obj2num(Object o) {
- Number n = null;
+ /**
+ * Takes an array of Numbers and returns an array of objects.
+ *
+ * @param o The array of Numbers to convert.
+ *
+ * @return The array of objects from o.
+ */
+ public static Number obj2num(Object o) {
+ Number n = null;
- try {
- n = cleanObj2Num(o);
- } catch(NumberFormatException e ) {
- n = Long.valueOf(0);
- }
- return n;
- }
+ try {
+ n = cleanObj2Num(o);
+ } catch(NumberFormatException e ) {
+ n = Long.valueOf(0);
+ }
+ return n;
+ }
- /**
- * Returns an array of Numbers type if they are Numbers, otherwise, returns Doubles and Longs as appropriate
- * based on whether or not it has a '.'
- *
- * @param o The object array to clean.
- *
- * @return The Number array cleaned.
- */
- public static Number[] cleanObj2Num(Object[] o) {
- Number[] arr = new Number[o.length];
- for(int i = 0; i < o.length; i++)
- arr[i] = cleanObj2Num(o[i]);
+ /**
+ * Returns an array of Numbers type if they are Numbers, otherwise, returns Doubles and Longs as appropriate
+ * based on whether or not it has a '.'
+ *
+ * @param o The object array to clean.
+ *
+ * @return The Number array cleaned.
+ */
+ public static Number[] cleanObj2Num(Object[] o) {
+ Number[] arr = new Number[o.length];
+ for(int i = 0; i < o.length; i++)
+ arr[i] = cleanObj2Num(o[i]);
- return arr;
- }
+ return arr;
+ }
- /**
- * Returns a Number type if its a Number, otherwise, returns Doubles and Longs as appropriate
- * based on whether or not it has a '.'
- *
- * @param o The object to clean.
- *
- * @return The Number object cleaned.
- */
- public static Number cleanObj2Num(Object o) {
- if(o instanceof Number)
- return (Number)o;
- else {
- if(o.toString().contains(".")) //$NON-NLS-1$
- return Double.valueOf(o.toString());
- else
- return Long.valueOf(o.toString());
- }
- }
+ /**
+ * Returns a Number type if its a Number, otherwise, returns Doubles and Longs as appropriate
+ * based on whether or not it has a '.'
+ *
+ * @param o The object to clean.
+ *
+ * @return The Number object cleaned.
+ */
+ public static Number cleanObj2Num(Object o) {
+ if(o instanceof Number)
+ return (Number)o;
+ else {
+ if(o.toString().contains(".")) //$NON-NLS-1$
+ return Double.valueOf(o.toString());
+ else
+ return Long.valueOf(o.toString());
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/plugin.xml b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/plugin.xml
index 65a4644217..1d7fec52b2 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/plugin.xml
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/plugin.xml
@@ -1,65 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>
<plugin>
- <extension
- point="org.eclipse.ui.preferencePages">
- <page
- name="%preference.dataTable.name"
- id="org.eclipse.linuxtools.generic.prefs.graphing.datatable"
- class="org.eclipse.linuxtools.internal.systemtap.graphing.ui.preferences.DataTablePreferencePage"
- category="org.eclipse.linuxtools.generic.prefs.graphing"/>
- <page
- name="%preference.graph.name"
- id="org.eclipse.linuxtools.generic.prefs.graphing.graph"
- class="org.eclipse.linuxtools.internal.systemtap.graphing.ui.preferences.GraphPreferencePage"
- category="org.eclipse.linuxtools.generic.prefs.graphing"/>
- <page
- name="%preference.graphing.name"
- class="org.eclipse.linuxtools.internal.systemtap.graphing.ui.preferences.GraphingPreferencePage"
- category="org.eclipse.linuxtools.systemtap.prefs.view"
+ <extension
+ point="org.eclipse.ui.preferencePages">
+ <page
+ name="%preference.dataTable.name"
+ id="org.eclipse.linuxtools.generic.prefs.graphing.datatable"
+ class="org.eclipse.linuxtools.internal.systemtap.graphing.ui.preferences.DataTablePreferencePage"
+ category="org.eclipse.linuxtools.generic.prefs.graphing"/>
+ <page
+ name="%preference.graph.name"
+ id="org.eclipse.linuxtools.generic.prefs.graphing.graph"
+ class="org.eclipse.linuxtools.internal.systemtap.graphing.ui.preferences.GraphPreferencePage"
+ category="org.eclipse.linuxtools.generic.prefs.graphing"/>
+ <page
+ name="%preference.graphing.name"
+ class="org.eclipse.linuxtools.internal.systemtap.graphing.ui.preferences.GraphingPreferencePage"
+ category="org.eclipse.linuxtools.systemtap.prefs.view"
id="org.eclipse.linuxtools.generic.prefs.graphing"/>
- </extension>
+ </extension>
- <extension
- point="org.eclipse.core.runtime.preferences">
- <initializer class="org.eclipse.linuxtools.internal.systemtap.graphing.ui.preferences.PreferenceInitializer"/>
- </extension>
+ <extension
+ point="org.eclipse.core.runtime.preferences">
+ <initializer class="org.eclipse.linuxtools.internal.systemtap.graphing.ui.preferences.PreferenceInitializer"/>
+ </extension>
- <extension
- point="org.eclipse.ui.commands">
- <category
- name="%category.file.name"
- description="%category.file.desc"
- id="org.eclipse.linuxtools.systemtap.graphing.ui.category.file"/>
- <command
- name="%command.save.name"
- description="%command.save.desc"
- categoryId="org.eclipse.linuxtools.systemtap.graphing.ui.category.file"
- id="org.eclipse.linuxtools.systemtap.graphing.ui.commands.SaveGraphImage"
- defaultHandler="org.eclipse.linuxtools.internal.systemtap.graphing.ui.handlers.SaveGraphImageHandler"/>
- </extension>
+ <extension
+ point="org.eclipse.ui.commands">
+ <category
+ name="%category.file.name"
+ description="%category.file.desc"
+ id="org.eclipse.linuxtools.systemtap.graphing.ui.category.file"/>
+ <command
+ name="%command.save.name"
+ description="%command.save.desc"
+ categoryId="org.eclipse.linuxtools.systemtap.graphing.ui.category.file"
+ id="org.eclipse.linuxtools.systemtap.graphing.ui.commands.SaveGraphImage"
+ defaultHandler="org.eclipse.linuxtools.internal.systemtap.graphing.ui.handlers.SaveGraphImageHandler"/>
+ </extension>
- <extension
- point="org.eclipse.ui.menus">
- <menuContribution
- locationURI="toolbar:org.eclipse.linuxtools.systemtap.ui.ide.toolbar?after=chartGroup">
- <command
- commandId="org.eclipse.linuxtools.systemtap.graphing.ui.commands.SaveGraphImage"
- label="%command.save.name"
- icon="icons/actions/chart-save.png">
- <visibleWhen checkEnabled="true"/>
- </command>
- </menuContribution>
- </extension>
+ <extension
+ point="org.eclipse.ui.menus">
+ <menuContribution
+ locationURI="toolbar:org.eclipse.linuxtools.systemtap.ui.ide.toolbar?after=chartGroup">
+ <command
+ commandId="org.eclipse.linuxtools.systemtap.graphing.ui.commands.SaveGraphImage"
+ label="%command.save.name"
+ icon="icons/actions/chart-save.png">
+ <visibleWhen checkEnabled="true"/>
+ </command>
+ </menuContribution>
+ </extension>
- <extension
- point="org.eclipse.ui.editors">
- <editor
- class="org.eclipse.linuxtools.systemtap.graphing.ui.views.GraphSelectorEditor"
- default="false"
- id="org.eclipse.linuxtools.systemtap.graphing.ui.views.GraphSelectorEditor"
- name="Graphs">
- </editor>
- </extension>
+ <extension
+ point="org.eclipse.ui.editors">
+ <editor
+ class="org.eclipse.linuxtools.systemtap.graphing.ui.views.GraphSelectorEditor"
+ default="false"
+ id="org.eclipse.linuxtools.systemtap.graphing.ui.views.GraphSelectorEditor"
+ name="Graphs">
+ </editor>
+ </extension>
</plugin>
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/GraphingUIPlugin.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/GraphingUIPlugin.java
index 77c2f35160..dc065e71fb 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/GraphingUIPlugin.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/GraphingUIPlugin.java
@@ -20,41 +20,41 @@ import org.osgi.framework.BundleContext;
*/
public class GraphingUIPlugin extends AbstractUIPlugin {
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.systemtap.graphing.ui"; //$NON-NLS-1$
- //The shared instance.
- private static GraphingUIPlugin plugin;
-
- /**
- * The constructor.
- */
- public GraphingUIPlugin() {
- plugin = this;
- }
-
- /**
- * This method is called when the plug-in is stopped
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- super.stop(context);
- plugin = null;
- }
-
- /**
- * Returns the shared instance.
- */
- public static GraphingUIPlugin getDefault() {
- return plugin;
- }
-
- /**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path.
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return AbstractUIPlugin.imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.systemtap.graphing.ui"; //$NON-NLS-1$
+ //The shared instance.
+ private static GraphingUIPlugin plugin;
+
+ /**
+ * The constructor.
+ */
+ public GraphingUIPlugin() {
+ plugin = this;
+ }
+
+ /**
+ * This method is called when the plug-in is stopped
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ super.stop(context);
+ plugin = null;
+ }
+
+ /**
+ * Returns the shared instance.
+ */
+ public static GraphingUIPlugin getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns an image descriptor for the image file at the given
+ * plug-in relative path.
+ *
+ * @param path the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ return AbstractUIPlugin.imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/Localization.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/Localization.java
index 185e72b2fb..35f6039145 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/Localization.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/Localization.java
@@ -15,18 +15,18 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Localization {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.graphing.ui.localization"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.graphing.ui.localization"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
- private Localization() {
- }
+ private Localization() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AbstractChartWithAxisBuilder.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AbstractChartWithAxisBuilder.java
index 44d1d7604a..e50c97211e 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AbstractChartWithAxisBuilder.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AbstractChartWithAxisBuilder.java
@@ -35,101 +35,101 @@ import org.swtchart.Range;
*/
public abstract class AbstractChartWithAxisBuilder extends AbstractChartBuilder {
- private PaintListener titleBoundsPaintListener;
- private double defaultMargin = 0.04;
- /**
- * @since 3.0
- */
- protected double getChartMarginXL() {
- return defaultMargin;
- }
- /**
- * @since 3.0
- */
- protected double getChartMarginXU() {
- return defaultMargin;
- }
- /**
- * @since 3.0
- */
- protected double getChartMarginYL() {
- return defaultMargin;
- }
- /**
- * @since 3.0
- */
- protected double getChartMarginYU() {
- return defaultMargin;
- }
+ private PaintListener titleBoundsPaintListener;
+ private double defaultMargin = 0.04;
+ /**
+ * @since 3.0
+ */
+ protected double getChartMarginXL() {
+ return defaultMargin;
+ }
+ /**
+ * @since 3.0
+ */
+ protected double getChartMarginXU() {
+ return defaultMargin;
+ }
+ /**
+ * @since 3.0
+ */
+ protected double getChartMarginYL() {
+ return defaultMargin;
+ }
+ /**
+ * @since 3.0
+ */
+ protected double getChartMarginYU() {
+ return defaultMargin;
+ }
- /**
+ /**
* Title of X axis.
*/
protected String xTitle = null;
- protected boolean xLineGrid, yLineGrid;
- /**
- * @since 3.0
- */
- protected int xSeriesTicks, ySeriesTicks;
+ protected boolean xLineGrid, yLineGrid;
+ /**
+ * @since 3.0
+ */
+ protected int xSeriesTicks, ySeriesTicks;
- /**
- * Create a chart series for that chart.
- */
- protected abstract ISeries createChartISeries(int i);
+ /**
+ * Create a chart series for that chart.
+ */
+ protected abstract ISeries createChartISeries(int i);
- @Override
- protected void updateProperties(PropertyChangeEvent event) {
- super.updateProperties(event);
- String eventName = event.getProperty();
- if (eventName.equals(GraphingPreferenceConstants.P_SHOW_X_GRID_LINES)) {
- xLineGrid = store.getBoolean(GraphingPreferenceConstants.P_SHOW_X_GRID_LINES);
- buildXAxis();
- } else if (eventName.equals(GraphingPreferenceConstants.P_SHOW_Y_GRID_LINES)) {
- yLineGrid = store.getBoolean(GraphingPreferenceConstants.P_SHOW_Y_GRID_LINES);
- buildYAxis();
- } else if (eventName.equals(GraphingPreferenceConstants.P_X_SERIES_TICKS)) {
- xSeriesTicks = store.getInt(GraphingPreferenceConstants.P_X_SERIES_TICKS);
- buildXAxis();
- } else if (eventName.equals(GraphingPreferenceConstants.P_Y_SERIES_TICKS)) {
- ySeriesTicks = store.getInt(GraphingPreferenceConstants.P_Y_SERIES_TICKS);
- buildYAxis();
- }
- }
+ @Override
+ protected void updateProperties(PropertyChangeEvent event) {
+ super.updateProperties(event);
+ String eventName = event.getProperty();
+ if (eventName.equals(GraphingPreferenceConstants.P_SHOW_X_GRID_LINES)) {
+ xLineGrid = store.getBoolean(GraphingPreferenceConstants.P_SHOW_X_GRID_LINES);
+ buildXAxis();
+ } else if (eventName.equals(GraphingPreferenceConstants.P_SHOW_Y_GRID_LINES)) {
+ yLineGrid = store.getBoolean(GraphingPreferenceConstants.P_SHOW_Y_GRID_LINES);
+ buildYAxis();
+ } else if (eventName.equals(GraphingPreferenceConstants.P_X_SERIES_TICKS)) {
+ xSeriesTicks = store.getInt(GraphingPreferenceConstants.P_X_SERIES_TICKS);
+ buildXAxis();
+ } else if (eventName.equals(GraphingPreferenceConstants.P_Y_SERIES_TICKS)) {
+ ySeriesTicks = store.getInt(GraphingPreferenceConstants.P_Y_SERIES_TICKS);
+ buildYAxis();
+ }
+ }
- /**
- * Constructor.
- */
- public AbstractChartWithAxisBuilder(IAdapter adapter, Composite parent, int style, String title) {
- super(adapter, parent, style, title);
- xLineGrid = store.getBoolean(GraphingPreferenceConstants.P_SHOW_X_GRID_LINES);
- yLineGrid = store.getBoolean(GraphingPreferenceConstants.P_SHOW_Y_GRID_LINES);
- xSeriesTicks = store.getInt(GraphingPreferenceConstants.P_X_SERIES_TICKS);
- ySeriesTicks = store.getInt(GraphingPreferenceConstants.P_Y_SERIES_TICKS);
- }
+ /**
+ * Constructor.
+ */
+ public AbstractChartWithAxisBuilder(IAdapter adapter, Composite parent, int style, String title) {
+ super(adapter, parent, style, title);
+ xLineGrid = store.getBoolean(GraphingPreferenceConstants.P_SHOW_X_GRID_LINES);
+ yLineGrid = store.getBoolean(GraphingPreferenceConstants.P_SHOW_Y_GRID_LINES);
+ xSeriesTicks = store.getInt(GraphingPreferenceConstants.P_X_SERIES_TICKS);
+ ySeriesTicks = store.getInt(GraphingPreferenceConstants.P_Y_SERIES_TICKS);
+ }
- @Override
- protected void createChart() {
- super.createChart();
- applyTitleBoundsListener();
- chartMouseMoveListener = new ChartWithAxisMouseMoveListener(chart, chart.getPlotArea());
- }
+ @Override
+ protected void createChart() {
+ super.createChart();
+ applyTitleBoundsListener();
+ chartMouseMoveListener = new ChartWithAxisMouseMoveListener(chart, chart.getPlotArea());
+ }
/**
* After this method is called, the chart's title will (from then on) be centred with the plot area.
- * @since 3.0
- */
+ * @since 3.0
+ */
protected void applyTitleBoundsListener() {
- titleBoundsPaintListener = new PaintListener() {
+ titleBoundsPaintListener = new PaintListener() {
- @Override
- public void paintControl(PaintEvent e) {
- Rectangle bounds = chart.getPlotArea().getBounds();
- Control title = (Control) chart.getTitle();
- Rectangle titleBounds = title.getBounds();
- title.setLocation(new Point(bounds.x + (bounds.width - titleBounds.width) / 2, title.getLocation().y));
- }
- };
- chart.addPaintListener(titleBoundsPaintListener);
+ @Override
+ public void paintControl(PaintEvent e) {
+ Rectangle bounds = chart.getPlotArea().getBounds();
+ Control title = (Control) chart.getTitle();
+ Rectangle titleBounds = title.getBounds();
+ title.setLocation(new Point(bounds.x + (bounds.width - titleBounds.width) / 2, title.getLocation().y));
+ }
+ };
+ chart.addPaintListener(titleBoundsPaintListener);
}
/**
@@ -137,168 +137,168 @@ public abstract class AbstractChartWithAxisBuilder extends AbstractChartBuilder
* @since 3.0
*/
protected void removeTitleBoundsListener() {
- if (titleBoundsPaintListener != null) {
- chart.removePaintListener(titleBoundsPaintListener);
- titleBoundsPaintListener = null;
- }
+ if (titleBoundsPaintListener != null) {
+ chart.removePaintListener(titleBoundsPaintListener);
+ titleBoundsPaintListener = null;
+ }
}
- /**
- * Builds X axis.
- */
- @Override
- protected void buildXAxis() {
- String labels[] = adapter.getLabels();
- IAxis xAxis = this.chart.getAxisSet().getXAxis(0);
- if (xLineGrid) {
- xAxis.getGrid().setStyle(LineStyle.SOLID);
- } else {
- xAxis.getGrid().setStyle(LineStyle.NONE);
- }
- xAxis.getTick().setForeground(BLACK);
- xAxis.getTick().setTickMarkStepHint(xSeriesTicks);
- ITitle xTitle = xAxis.getTitle();
- xTitle.setForeground(BLACK);
+ /**
+ * Builds X axis.
+ */
+ @Override
+ protected void buildXAxis() {
+ String labels[] = adapter.getLabels();
+ IAxis xAxis = this.chart.getAxisSet().getXAxis(0);
+ if (xLineGrid) {
+ xAxis.getGrid().setStyle(LineStyle.SOLID);
+ } else {
+ xAxis.getGrid().setStyle(LineStyle.NONE);
+ }
+ xAxis.getTick().setForeground(BLACK);
+ xAxis.getTick().setTickMarkStepHint(xSeriesTicks);
+ ITitle xTitle = xAxis.getTitle();
+ xTitle.setForeground(BLACK);
- if (labels.length > 0) {
- xTitle.setText(labels[0]);
- }
- else {
- xTitle.setText(""); //$NON-NLS-1$
- }
- }
+ if (labels.length > 0) {
+ xTitle.setText(labels[0]);
+ }
+ else {
+ xTitle.setText(""); //$NON-NLS-1$
+ }
+ }
- /**
- * Builds Y axis.
- */
- @Override
- protected void buildYAxis() {
- IAxis yAxis = this.chart.getAxisSet().getYAxis(0);
- yAxis.getTitle().setText(""); //$NON-NLS-1$
- if (yLineGrid) {
- yAxis.getGrid().setStyle(LineStyle.SOLID);
- } else {
- yAxis.getGrid().setStyle(LineStyle.NONE);
- }
- yAxis.getTick().setForeground(BLACK);
- yAxis.getTick().setTickMarkStepHint(ySeriesTicks);
- }
+ /**
+ * Builds Y axis.
+ */
+ @Override
+ protected void buildYAxis() {
+ IAxis yAxis = this.chart.getAxisSet().getYAxis(0);
+ yAxis.getTitle().setText(""); //$NON-NLS-1$
+ if (yLineGrid) {
+ yAxis.getGrid().setStyle(LineStyle.SOLID);
+ } else {
+ yAxis.getGrid().setStyle(LineStyle.NONE);
+ }
+ yAxis.getTick().setForeground(BLACK);
+ yAxis.getTick().setTickMarkStepHint(ySeriesTicks);
+ }
- /**
- * Builds X series.
- */
- @Override
- protected void buildXSeries() {
- Object data[][] = adapter.getData();
- if (data == null || data.length == 0) {
- return;
- }
+ /**
+ * Builds X series.
+ */
+ @Override
+ protected void buildXSeries() {
+ Object data[][] = adapter.getData();
+ if (data == null || data.length == 0) {
+ return;
+ }
- int start = 0, len = Math.min(this.maxItems, data.length), leny = data[0].length-1;
- if (this.maxItems < data.length) {
- start = data.length - this.maxItems;
- }
+ int start = 0, len = Math.min(this.maxItems, data.length), leny = data[0].length-1;
+ if (this.maxItems < data.length) {
+ start = data.length - this.maxItems;
+ }
- Double[] all_valx = new Double[len];
- Double[][] all_valy = new Double[leny][len];
- // Will want to centre view around points, so be as accurate with max/min as possible.
- double maxX = Double.NEGATIVE_INFINITY;
- double maxY = maxX;
- double minX = Double.POSITIVE_INFINITY;
- double minY = minX;
+ Double[] all_valx = new Double[len];
+ Double[][] all_valy = new Double[leny][len];
+ // Will want to centre view around points, so be as accurate with max/min as possible.
+ double maxX = Double.NEGATIVE_INFINITY;
+ double maxY = maxX;
+ double minX = Double.POSITIVE_INFINITY;
+ double minY = minX;
- // Read in from the data array all x/y points to plot.
- // In the case of an empty (null) value in either axis, ignore both x & y axis data for that point.
- for (int i = 0; i < len; i++) {
- for (int j = 0; j < leny + 1; j++) {
- Double val = getDoubleOrNullValue(data[start + i][j]);
- if (j == 0) {
- if (val != null) {
- all_valx[i] = val;
- maxX = Math.max(val, maxX);
- minX = Math.min(val, minX);
- } else {
- break;
- }
- } else if (val != null) {
- all_valy[j-1][i] = val;
- maxY = Math.max(val, maxY);
- minY = Math.min(val, minY);
- }
- }
- }
+ // Read in from the data array all x/y points to plot.
+ // In the case of an empty (null) value in either axis, ignore both x & y axis data for that point.
+ for (int i = 0; i < len; i++) {
+ for (int j = 0; j < leny + 1; j++) {
+ Double val = getDoubleOrNullValue(data[start + i][j]);
+ if (j == 0) {
+ if (val != null) {
+ all_valx[i] = val;
+ maxX = Math.max(val, maxX);
+ minX = Math.min(val, minX);
+ } else {
+ break;
+ }
+ } else if (val != null) {
+ all_valy[j-1][i] = val;
+ maxY = Math.max(val, maxY);
+ minY = Math.min(val, minY);
+ }
+ }
+ }
- // Now create dense arrays of x/y values that exclude null values,
- // and plot those values to the chart.
+ // Now create dense arrays of x/y values that exclude null values,
+ // and plot those values to the chart.
- ISeries allSeries[] = chart.getSeriesSet().getSeries();
- ISeries series = null;
- for (int i = 0; i < leny; i++) {
- if (i >= allSeries.length) {
- series = createChartISeries(i);
- } else {
- series = chart.getSeriesSet().getSeries()[i];
- }
+ ISeries allSeries[] = chart.getSeriesSet().getSeries();
+ ISeries series = null;
+ for (int i = 0; i < leny; i++) {
+ if (i >= allSeries.length) {
+ series = createChartISeries(i);
+ } else {
+ series = chart.getSeriesSet().getSeries()[i];
+ }
- double[] valx = new double[len];
- double[] valy = new double[len];
- int len_trim = 0;
- for (int j = 0; j < len; j++) {
- if (all_valx[j] != null && all_valy[i][j] != null) {
- valx[len_trim] = all_valx[j].doubleValue();
- valy[len_trim] = all_valy[i][j].doubleValue();
- len_trim++;
- }
- }
- double[] valx_trim = new double[len_trim];
- double[] valy_trim = new double[len_trim];
- for (int j = 0; j < len_trim; j++) {
- valx_trim[j] = valx[j];
- valy_trim[j] = valy[j];
- }
- series.setXSeries(valx_trim);
- series.setYSeries(valy_trim);
- }
+ double[] valx = new double[len];
+ double[] valy = new double[len];
+ int len_trim = 0;
+ for (int j = 0; j < len; j++) {
+ if (all_valx[j] != null && all_valy[i][j] != null) {
+ valx[len_trim] = all_valx[j].doubleValue();
+ valy[len_trim] = all_valy[i][j].doubleValue();
+ len_trim++;
+ }
+ }
+ double[] valx_trim = new double[len_trim];
+ double[] valy_trim = new double[len_trim];
+ for (int j = 0; j < len_trim; j++) {
+ valx_trim[j] = valx[j];
+ valy_trim[j] = valy[j];
+ }
+ series.setXSeries(valx_trim);
+ series.setYSeries(valy_trim);
+ }
- if (series != null && series.getXSeries().length > 0) {
- applyRangeX(minX, maxX);
- applyRangeY(minY, maxY);
- }
- chart.redraw();
- }
+ if (series != null && series.getXSeries().length > 0) {
+ applyRangeX(minX, maxX);
+ applyRangeY(minY, maxY);
+ }
+ chart.redraw();
+ }
- /**
- * This updates the visible range of the chart's x-axis.
- */
- private void applyRangeX(double min, double max) {
- IAxis axis = chart.getAxisSet().getXAxis(0);
- double actualRange = max - min;
- double scaledRange = actualRange * scale;
- double marginL = scaledRange > 0 ? scaledRange * getChartMarginXL() : 1;
- double marginU = scaledRange > 0 ? scaledRange * getChartMarginXU() : 1;
+ /**
+ * This updates the visible range of the chart's x-axis.
+ */
+ private void applyRangeX(double min, double max) {
+ IAxis axis = chart.getAxisSet().getXAxis(0);
+ double actualRange = max - min;
+ double scaledRange = actualRange * scale;
+ double marginL = scaledRange > 0 ? scaledRange * getChartMarginXL() : 1;
+ double marginU = scaledRange > 0 ? scaledRange * getChartMarginXU() : 1;
- double lower = (actualRange - scaledRange) * scroll + min;
- axis.setRange(new Range(lower - marginL, lower + scaledRange + marginU));
- }
+ double lower = (actualRange - scaledRange) * scroll + min;
+ axis.setRange(new Range(lower - marginL, lower + scaledRange + marginU));
+ }
- /**
- * This updates the visible range of the chart's y-axis.
- * @since 3.0
- */
- protected void applyRangeY(double min, double max) {
- IAxis axis = chart.getAxisSet().getYAxis(0);
- double actualRange = max - min;
- double scaledRange = actualRange * scaleY;
- double marginL = scaledRange > 0 ? scaledRange * getChartMarginYL() : 1;
- double marginU = scaledRange > 0 ? scaledRange * getChartMarginYU() : 1;
+ /**
+ * This updates the visible range of the chart's y-axis.
+ * @since 3.0
+ */
+ protected void applyRangeY(double min, double max) {
+ IAxis axis = chart.getAxisSet().getYAxis(0);
+ double actualRange = max - min;
+ double scaledRange = actualRange * scaleY;
+ double marginL = scaledRange > 0 ? scaledRange * getChartMarginYL() : 1;
+ double marginU = scaledRange > 0 ? scaledRange * getChartMarginYU() : 1;
- double lower = (actualRange - scaledRange) * scrollY + min;
- axis.setRange(new Range(lower - marginL, lower + scaledRange + marginU));
- }
+ double lower = (actualRange - scaledRange) * scrollY + min;
+ axis.setRange(new Range(lower - marginL, lower + scaledRange + marginU));
+ }
- @Override
- public void updateDataSet() {
- buildXSeries();
- chartMouseMoveListener.update();
- }
+ @Override
+ public void updateDataSet() {
+ buildXSeries();
+ chartMouseMoveListener.update();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AbstractChartWithoutAxisBuilder.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AbstractChartWithoutAxisBuilder.java
index 9fbdc8f0bc..fbf3368109 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AbstractChartWithoutAxisBuilder.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AbstractChartWithoutAxisBuilder.java
@@ -28,6 +28,6 @@ public abstract class AbstractChartWithoutAxisBuilder extends AbstractChartBuild
*/
public AbstractChartWithoutAxisBuilder(IAdapter adapter, Composite parent, int style, String title) {
- super(adapter, parent, style, title);
- }
+ super(adapter, parent, style, title);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AreaChartBuilder.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AreaChartBuilder.java
index 5db7fb9db2..111e2fa5d6 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AreaChartBuilder.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/AreaChartBuilder.java
@@ -25,16 +25,16 @@ import org.swtchart.ISeries;
public class AreaChartBuilder extends LineChartBuilder {
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.areachartbuilder"; //$NON-NLS-1$
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.areachartbuilder"; //$NON-NLS-1$
public AreaChartBuilder(Composite parent, int style, String title,IAdapter adapter) {
- super(parent, style, title, adapter);
+ super(parent, style, title, adapter);
}
- @Override
- protected ISeries createChartISeries(int i) {
- ILineSeries series = (ILineSeries) super.createChartISeries(i);
- series.enableArea(true);
- return series;
- }
+ @Override
+ protected ISeries createChartISeries(int i) {
+ ILineSeries series = (ILineSeries) super.createChartISeries(i);
+ series.enableArea(true);
+ return series;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/BarChart.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/BarChart.java
index 4d4a6a1191..9fd8336434 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/BarChart.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/BarChart.java
@@ -11,160 +11,160 @@ import org.swtchart.Range;
*/
public class BarChart extends Chart {
- private final static int MIN_LABEL_SIZE = Messages.BarChartBuilder_LabelTrimTag.length();
- private final int fontSize;
-
- private double[][] actualYSeries;
- private String[] fullLabels = null;
- private IAxis xAxis = null;
-
- private boolean updateSuspended = false;
- public void suspendUpdate(boolean suspend) {
- if (updateSuspended == suspend) {
- return;
- }
- updateSuspended = suspend;
-
- // make sure that chart is updated
- if (!suspend) {
- updateLayout();
- }
- }
-
- public BarChart(Composite parent, int style) {
- super(parent, style);
- fontSize = getFont().getFontData()[0].getHeight();
- xAxis = getAxisSet().getXAxis(0);
- xAxis.enableCategory(true);
- xAxis.setCategorySeries(new String[]{""}); //$NON-NLS-1$
- }
-
- /**
- * Sets the BarChart's x-axis category labels such that labels won't get
- * cut off if there isn't enough room to display them fully. Use this
- * instead of accessing the chart's x-axis and setting its category
- * series directly.
- * @param series
- */
- public void setCategorySeries(String[] series) {
- xAxis.setCategorySeries(series);
- fullLabels = xAxis.getCategorySeries();
- }
-
- /**
- * Return the y-value of the specified series' bar. Use this instead of referring directly
- * to the chart's series values with {@link #getSeriesSet()} and {@link ISeries#getYSeries()}.
- * @param series The index of the bar series to get data from.
- * @param barIndex The index of the bar to get the y-value of.
- * @return The y-value of the specified bar.
- */
- public double getBarValue(int series, int barIndex) {
- return actualYSeries[series][barIndex];
- }
-
- /**
- * Returns a list of the full (non-trimmed) label names of each bar.
- * Use this instead of accessing the x-axis' category series, which
- * may contain trimmed label names.
- */
- public String[] getCategorySeries() {
- String[] copiedCategorySeries = null;
-
- if (fullLabels != null) {
- copiedCategorySeries = new String[fullLabels.length];
- System.arraycopy(fullLabels, 0, copiedCategorySeries, 0,
- fullLabels.length);
- }
-
- return copiedCategorySeries;
- }
-
- @Override
- public void updateLayout() {
- if (updateSuspended) {
- return;
- }
-
- // If the x-axis and its labels are set, ensure that their contents fit the width of each label.
- if (fullLabels != null) {
- hideBars();
- String[] labels = xAxis.getCategorySeries();
- if (labels != null && labels.length > 0) {
- String[] trimmedLabels = null;
- trimmedLabels = fitLabels(fullLabels);
-
- // Only update labels if their trimmed contents are different than their current contents.
- for (int i = 0; i < fullLabels.length; i++) {
- if (!trimmedLabels[i].equals(labels[i])) {
- labels = trimmedLabels;
- break;
- }
- }
- if (labels == trimmedLabels) {
- // setCategorySeries triggers an unnecessary call to updateLayout, so prevent it.
- updateSuspended = true;
- xAxis.setCategorySeries(labels);
- updateSuspended = false;
- }
- }
- }
- super.updateLayout();
- }
-
- /**
- * Given an array of label names, return a new set of names that have been trimmed down
- * in order to fit in the chart axis without getting cut off.
- * @param labels An array of label names that may be trimmed.
- * @return A new array containing label names that have been trimmed to fit in the axis display.
- */
- private String[] fitLabels(String[] labels) {
- Range range = xAxis.getRange();
- int maxLabelSize = (int) Math.max(getClientArea().width / (Math.max(range.upper - range.lower, 1) * fontSize), MIN_LABEL_SIZE);
-
- String[] trimlabels = new String[labels.length];
- for (int i = 0; i < labels.length; i++) {
- if (labels[i].length() > maxLabelSize) {
- trimlabels[i] = labels[i].substring(0, maxLabelSize - MIN_LABEL_SIZE)
- .concat(Messages.BarChartBuilder_LabelTrimTag);
- } else {
- trimlabels[i] = labels[i];
- }
- }
- return trimlabels;
- }
-
- /*
- * Workaround for EBZ #427019: out-of-bounds bars appear, so change their values to
- * keep them properly hidden. Save actual bar values elsewhere so they can be retrieved.
- */
- private void hideBars() {
- Range rangeX = xAxis.getRange();
- double bottomY = getAxisSet().getYAxis(0).getRange().lower;
- double nonNegBottomY = Math.max(0, bottomY);
- ISeries[] allSeries = getSeriesSet().getSeries();
- actualYSeries = new double[allSeries.length][];
-
- for (int i = 0, n = allSeries.length; i < n; i++) {
- double[] yseries = allSeries[i].getYSeries();
- if (yseries == null) {
- return;
- }
-
- // Store the true values of the bars into a different array, so they
- // can be displayed later if need be.
- actualYSeries[i] = new double[yseries.length];
- System.arraycopy(yseries, 0, actualYSeries[i], 0, yseries.length);
-
- for (int x = (int) rangeX.lower; x <= (int) rangeX.upper; x++) {
- if (yseries[x] < bottomY) {
- yseries[x] = bottomY;
- }
- }
- if (yseries.length - 1 > rangeX.upper) {
- yseries[(int) rangeX.upper + 1] = nonNegBottomY;
- }
- allSeries[i].setYSeries(yseries);
- }
- }
+ private final static int MIN_LABEL_SIZE = Messages.BarChartBuilder_LabelTrimTag.length();
+ private final int fontSize;
+
+ private double[][] actualYSeries;
+ private String[] fullLabels = null;
+ private IAxis xAxis = null;
+
+ private boolean updateSuspended = false;
+ public void suspendUpdate(boolean suspend) {
+ if (updateSuspended == suspend) {
+ return;
+ }
+ updateSuspended = suspend;
+
+ // make sure that chart is updated
+ if (!suspend) {
+ updateLayout();
+ }
+ }
+
+ public BarChart(Composite parent, int style) {
+ super(parent, style);
+ fontSize = getFont().getFontData()[0].getHeight();
+ xAxis = getAxisSet().getXAxis(0);
+ xAxis.enableCategory(true);
+ xAxis.setCategorySeries(new String[]{""}); //$NON-NLS-1$
+ }
+
+ /**
+ * Sets the BarChart's x-axis category labels such that labels won't get
+ * cut off if there isn't enough room to display them fully. Use this
+ * instead of accessing the chart's x-axis and setting its category
+ * series directly.
+ * @param series
+ */
+ public void setCategorySeries(String[] series) {
+ xAxis.setCategorySeries(series);
+ fullLabels = xAxis.getCategorySeries();
+ }
+
+ /**
+ * Return the y-value of the specified series' bar. Use this instead of referring directly
+ * to the chart's series values with {@link #getSeriesSet()} and {@link ISeries#getYSeries()}.
+ * @param series The index of the bar series to get data from.
+ * @param barIndex The index of the bar to get the y-value of.
+ * @return The y-value of the specified bar.
+ */
+ public double getBarValue(int series, int barIndex) {
+ return actualYSeries[series][barIndex];
+ }
+
+ /**
+ * Returns a list of the full (non-trimmed) label names of each bar.
+ * Use this instead of accessing the x-axis' category series, which
+ * may contain trimmed label names.
+ */
+ public String[] getCategorySeries() {
+ String[] copiedCategorySeries = null;
+
+ if (fullLabels != null) {
+ copiedCategorySeries = new String[fullLabels.length];
+ System.arraycopy(fullLabels, 0, copiedCategorySeries, 0,
+ fullLabels.length);
+ }
+
+ return copiedCategorySeries;
+ }
+
+ @Override
+ public void updateLayout() {
+ if (updateSuspended) {
+ return;
+ }
+
+ // If the x-axis and its labels are set, ensure that their contents fit the width of each label.
+ if (fullLabels != null) {
+ hideBars();
+ String[] labels = xAxis.getCategorySeries();
+ if (labels != null && labels.length > 0) {
+ String[] trimmedLabels = null;
+ trimmedLabels = fitLabels(fullLabels);
+
+ // Only update labels if their trimmed contents are different than their current contents.
+ for (int i = 0; i < fullLabels.length; i++) {
+ if (!trimmedLabels[i].equals(labels[i])) {
+ labels = trimmedLabels;
+ break;
+ }
+ }
+ if (labels == trimmedLabels) {
+ // setCategorySeries triggers an unnecessary call to updateLayout, so prevent it.
+ updateSuspended = true;
+ xAxis.setCategorySeries(labels);
+ updateSuspended = false;
+ }
+ }
+ }
+ super.updateLayout();
+ }
+
+ /**
+ * Given an array of label names, return a new set of names that have been trimmed down
+ * in order to fit in the chart axis without getting cut off.
+ * @param labels An array of label names that may be trimmed.
+ * @return A new array containing label names that have been trimmed to fit in the axis display.
+ */
+ private String[] fitLabels(String[] labels) {
+ Range range = xAxis.getRange();
+ int maxLabelSize = (int) Math.max(getClientArea().width / (Math.max(range.upper - range.lower, 1) * fontSize), MIN_LABEL_SIZE);
+
+ String[] trimlabels = new String[labels.length];
+ for (int i = 0; i < labels.length; i++) {
+ if (labels[i].length() > maxLabelSize) {
+ trimlabels[i] = labels[i].substring(0, maxLabelSize - MIN_LABEL_SIZE)
+ .concat(Messages.BarChartBuilder_LabelTrimTag);
+ } else {
+ trimlabels[i] = labels[i];
+ }
+ }
+ return trimlabels;
+ }
+
+ /*
+ * Workaround for EBZ #427019: out-of-bounds bars appear, so change their values to
+ * keep them properly hidden. Save actual bar values elsewhere so they can be retrieved.
+ */
+ private void hideBars() {
+ Range rangeX = xAxis.getRange();
+ double bottomY = getAxisSet().getYAxis(0).getRange().lower;
+ double nonNegBottomY = Math.max(0, bottomY);
+ ISeries[] allSeries = getSeriesSet().getSeries();
+ actualYSeries = new double[allSeries.length][];
+
+ for (int i = 0, n = allSeries.length; i < n; i++) {
+ double[] yseries = allSeries[i].getYSeries();
+ if (yseries == null) {
+ return;
+ }
+
+ // Store the true values of the bars into a different array, so they
+ // can be displayed later if need be.
+ actualYSeries[i] = new double[yseries.length];
+ System.arraycopy(yseries, 0, actualYSeries[i], 0, yseries.length);
+
+ for (int x = (int) rangeX.lower; x <= (int) rangeX.upper; x++) {
+ if (yseries[x] < bottomY) {
+ yseries[x] = bottomY;
+ }
+ }
+ if (yseries.length - 1 > rangeX.upper) {
+ yseries[(int) rangeX.upper + 1] = nonNegBottomY;
+ }
+ allSeries[i].setYSeries(yseries);
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/BarChartBuilder.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/BarChartBuilder.java
index 9e2c9e91f6..3e9e49f33c 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/BarChartBuilder.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/BarChartBuilder.java
@@ -28,125 +28,125 @@ import org.swtchart.Range;
*/
public class BarChartBuilder extends AbstractChartWithAxisBuilder {
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.barchartbuilder"; //$NON-NLS-1$
-
- public BarChartBuilder(Composite parent, int style, String title, IAdapter adapter) {
- super(adapter, parent, style, title);
- }
-
- @Override
- protected double getChartMarginYL() {
- return 0;
- }
-
- @Override
- protected void createChart() {
- this.chart = new BarChart(this, getStyle());
- applyTitleBoundsListener();
- chartMouseMoveListener = new BarChartMouseMoveListener((BarChart) chart, chart.getPlotArea());
- }
-
- @Override
- protected ISeries createChartISeries(int i) {
- IBarSeries series = (IBarSeries)chart.getSeriesSet().
- createSeries(SeriesType.BAR, adapter.getLabels()[i+1]);
- series.setBarColor(COLORS[i % COLORS.length]);
- return series;
- }
-
- @Override
- protected void buildXSeries() {
- Object data[][] = adapter.getData();
- if (data == null || data.length == 0) {
- return;
- }
-
- int start = 0, len = Math.min(this.maxItems, data.length), leny = data[0].length-1;
- if (this.maxItems < data.length) {
- start = data.length - this.maxItems;
- }
-
- String[] allValx = new String[len];
- Double[][] allValy = new Double[leny][len];
- // Want to show x-axis if possible, so default max/min is 0.
- double maxY = 0;
- double minY = 0;
-
- // Read in from the data array all x/y points to plot.
- // If a y-axis value is empty (null), set it to 0.
- // If an x-axis category is empty, ignore the entire category.
- for (int i = 0; i < len; i++) {
- Object label = data[start + i][0];
- if (label != null) {
- allValx[i] = label.toString();
- for (int j = 1; j < leny + 1; j++) {
- Double val = getDoubleOrNullValue(data[start + i][j]);
- if (val == null) {
- val = 0.0;
- }
- allValy[j-1][i] = val;
- maxY = Math.max(val, maxY);
- minY = Math.min(val, minY);
- }
- }
- }
-
- // Now create dense arrays of x/y values that exclude null values,
- // and plot those values to the chart.
-
- String valx[] = new String[len];
- int lenTrim = 0;
- for (int i = 0; i < len; i++) {
- if (allValx[i] != null) {
- valx[lenTrim] = allValx[i];
- lenTrim++;
- }
- }
- String[] valxTrim = new String[lenTrim];
- System.arraycopy(valx, 0, valxTrim, 0, lenTrim);
-
- ISeries allSeries[] = chart.getSeriesSet().getSeries();
- for (int i = 0; i < leny; i++) {
- ISeries series;
- if (i >= allSeries.length) {
- series = createChartISeries(i);
- } else {
- series = chart.getSeriesSet().getSeries()[i];
- }
-
- double[] valy = new double[len];
- int lenyTrim = 0;
- for (int j = 0; j < len; j++) {
- if (allValy[i][j] != null) {
- valy[lenyTrim] = allValy[i][j].doubleValue();
- lenyTrim++;
- }
- }
- double[] valyTrim = new double[lenyTrim];
- System.arraycopy(valy, 0, valyTrim, 0, lenyTrim);
- series.setYSeries(valyTrim);
- }
-
- ((BarChart) chart).suspendUpdate(true);
- ((BarChart) chart).setCategorySeries(getUniqueNames(valxTrim));
- applyCategoryRange(valxTrim.length);
- applyRangeY(minY, maxY);
- ((BarChart) chart).suspendUpdate(false);
- chart.redraw();
- }
-
- /**
- * This updates the visible range of the chart's x-axis.
- */
- private void applyCategoryRange(int numItems) {
- int itemRange = Math.max(1, (int) Math.ceil(numItems * scale)); // The number of items to display
- int lower = (int) Math.round((numItems - itemRange) * scroll);
- chart.getAxisSet().getXAxis(0).setRange(new Range(lower, lower + itemRange - 1));
- }
-
- @Override
- public void updateDataSet() {
- buildXSeries();
- chartMouseMoveListener.update();
- }
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.barchartbuilder"; //$NON-NLS-1$
+
+ public BarChartBuilder(Composite parent, int style, String title, IAdapter adapter) {
+ super(adapter, parent, style, title);
+ }
+
+ @Override
+ protected double getChartMarginYL() {
+ return 0;
+ }
+
+ @Override
+ protected void createChart() {
+ this.chart = new BarChart(this, getStyle());
+ applyTitleBoundsListener();
+ chartMouseMoveListener = new BarChartMouseMoveListener((BarChart) chart, chart.getPlotArea());
+ }
+
+ @Override
+ protected ISeries createChartISeries(int i) {
+ IBarSeries series = (IBarSeries)chart.getSeriesSet().
+ createSeries(SeriesType.BAR, adapter.getLabels()[i+1]);
+ series.setBarColor(COLORS[i % COLORS.length]);
+ return series;
+ }
+
+ @Override
+ protected void buildXSeries() {
+ Object data[][] = adapter.getData();
+ if (data == null || data.length == 0) {
+ return;
+ }
+
+ int start = 0, len = Math.min(this.maxItems, data.length), leny = data[0].length-1;
+ if (this.maxItems < data.length) {
+ start = data.length - this.maxItems;
+ }
+
+ String[] allValx = new String[len];
+ Double[][] allValy = new Double[leny][len];
+ // Want to show x-axis if possible, so default max/min is 0.
+ double maxY = 0;
+ double minY = 0;
+
+ // Read in from the data array all x/y points to plot.
+ // If a y-axis value is empty (null), set it to 0.
+ // If an x-axis category is empty, ignore the entire category.
+ for (int i = 0; i < len; i++) {
+ Object label = data[start + i][0];
+ if (label != null) {
+ allValx[i] = label.toString();
+ for (int j = 1; j < leny + 1; j++) {
+ Double val = getDoubleOrNullValue(data[start + i][j]);
+ if (val == null) {
+ val = 0.0;
+ }
+ allValy[j-1][i] = val;
+ maxY = Math.max(val, maxY);
+ minY = Math.min(val, minY);
+ }
+ }
+ }
+
+ // Now create dense arrays of x/y values that exclude null values,
+ // and plot those values to the chart.
+
+ String valx[] = new String[len];
+ int lenTrim = 0;
+ for (int i = 0; i < len; i++) {
+ if (allValx[i] != null) {
+ valx[lenTrim] = allValx[i];
+ lenTrim++;
+ }
+ }
+ String[] valxTrim = new String[lenTrim];
+ System.arraycopy(valx, 0, valxTrim, 0, lenTrim);
+
+ ISeries allSeries[] = chart.getSeriesSet().getSeries();
+ for (int i = 0; i < leny; i++) {
+ ISeries series;
+ if (i >= allSeries.length) {
+ series = createChartISeries(i);
+ } else {
+ series = chart.getSeriesSet().getSeries()[i];
+ }
+
+ double[] valy = new double[len];
+ int lenyTrim = 0;
+ for (int j = 0; j < len; j++) {
+ if (allValy[i][j] != null) {
+ valy[lenyTrim] = allValy[i][j].doubleValue();
+ lenyTrim++;
+ }
+ }
+ double[] valyTrim = new double[lenyTrim];
+ System.arraycopy(valy, 0, valyTrim, 0, lenyTrim);
+ series.setYSeries(valyTrim);
+ }
+
+ ((BarChart) chart).suspendUpdate(true);
+ ((BarChart) chart).setCategorySeries(getUniqueNames(valxTrim));
+ applyCategoryRange(valxTrim.length);
+ applyRangeY(minY, maxY);
+ ((BarChart) chart).suspendUpdate(false);
+ chart.redraw();
+ }
+
+ /**
+ * This updates the visible range of the chart's x-axis.
+ */
+ private void applyCategoryRange(int numItems) {
+ int itemRange = Math.max(1, (int) Math.ceil(numItems * scale)); // The number of items to display
+ int lower = (int) Math.round((numItems - itemRange) * scroll);
+ chart.getAxisSet().getXAxis(0).setRange(new Range(lower, lower + itemRange - 1));
+ }
+
+ @Override
+ public void updateDataSet() {
+ buildXSeries();
+ chartMouseMoveListener.update();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/LineChartBuilder.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/LineChartBuilder.java
index 7027c6f0cc..aed22c2e92 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/LineChartBuilder.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/LineChartBuilder.java
@@ -27,19 +27,19 @@ import org.swtchart.LineStyle;
public class LineChartBuilder extends AbstractChartWithAxisBuilder {
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.linechartbuilder"; //$NON-NLS-1$
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.linechartbuilder"; //$NON-NLS-1$
public LineChartBuilder(Composite parent, int style, String title,IAdapter adapter) {
- super(adapter, parent, style, title);
+ super(adapter, parent, style, title);
}
- @Override
- protected ISeries createChartISeries(int i) {
- ILineSeries series = (ILineSeries) chart.getSeriesSet().
- createSeries(SeriesType.LINE, adapter.getLabels()[i+1]);
- series.setSymbolColor(COLORS[i % COLORS.length]);
- series.setLineColor(COLORS[i % COLORS.length]);
- series.setLineStyle(LineStyle.SOLID);
- return series;
- }
+ @Override
+ protected ISeries createChartISeries(int i) {
+ ILineSeries series = (ILineSeries) chart.getSeriesSet().
+ createSeries(SeriesType.LINE, adapter.getLabels()[i+1]);
+ series.setSymbolColor(COLORS[i % COLORS.length]);
+ series.setLineColor(COLORS[i % COLORS.length]);
+ series.setLineStyle(LineStyle.SOLID);
+ return series;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/Messages.java
index b47892c781..fd6409ab85 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/Messages.java
@@ -6,16 +6,16 @@ import org.eclipse.osgi.util.NLS;
* @since 3.0
*/
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.graphing.ui.charts.messages"; //$NON-NLS-1$
- public static String AbstractChartWithAxisBuilder_ToolTipCoords;
- public static String BarChartBuilder_LabelTrimTag;
- public static String BarChartBuilder_ToolTipCoords;
- public static String PieChartBuilder_ToolTipCoords;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.graphing.ui.charts.messages"; //$NON-NLS-1$
+ public static String AbstractChartWithAxisBuilder_ToolTipCoords;
+ public static String BarChartBuilder_LabelTrimTag;
+ public static String BarChartBuilder_ToolTipCoords;
+ public static String PieChartBuilder_ToolTipCoords;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/PieChartBuilder.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/PieChartBuilder.java
index a971263c40..164d95bb32 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/PieChartBuilder.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/PieChartBuilder.java
@@ -23,100 +23,100 @@ import org.swtchart.Range;
* Builds Pie chart.
*/
public class PieChartBuilder extends AbstractChartWithoutAxisBuilder {
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.piechartbuilder"; //$NON-NLS-1$
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.piechartbuilder"; //$NON-NLS-1$
- public PieChartBuilder(Composite parent, int style, String title, IAdapter adapter) {
- super(adapter, parent, style, title);
- }
+ public PieChartBuilder(Composite parent, int style, String title, IAdapter adapter) {
+ super(adapter, parent, style, title);
+ }
- @Override
- protected void createChart() {
- this.chart = new PieChart(this, getStyle());
- ((PieChart) chart).setCustomColors(COLORS);
- chartMouseMoveListener = new PieChartMouseMoveListener((PieChart) chart, chart);
- }
+ @Override
+ protected void createChart() {
+ this.chart = new PieChart(this, getStyle());
+ ((PieChart) chart).setCustomColors(COLORS);
+ chartMouseMoveListener = new PieChartMouseMoveListener((PieChart) chart, chart);
+ }
- @Override
- protected void buildXAxis() {
- String[] labels = adapter.getLabels();
- String[] seriesLabels = new String[labels.length - 1];
- for (int i = 0; i < seriesLabels.length; i++) {
- seriesLabels[i] = labels[i+1];
- }
- IAxis xAxis = this.chart.getAxisSet().getXAxis(0);
- xAxis.getTitle().setText(labels[0]);
- xAxis.setCategorySeries(seriesLabels);
- }
+ @Override
+ protected void buildXAxis() {
+ String[] labels = adapter.getLabels();
+ String[] seriesLabels = new String[labels.length - 1];
+ for (int i = 0; i < seriesLabels.length; i++) {
+ seriesLabels[i] = labels[i+1];
+ }
+ IAxis xAxis = this.chart.getAxisSet().getXAxis(0);
+ xAxis.getTitle().setText(labels[0]);
+ xAxis.setCategorySeries(seriesLabels);
+ }
- @Override
- protected void buildXSeries() {
- Object data[][] = adapter.getData();
- if (data == null || data.length == 0) {
- return;
- }
+ @Override
+ protected void buildXSeries() {
+ Object data[][] = adapter.getData();
+ if (data == null || data.length == 0) {
+ return;
+ }
- int start = 0, len = Math.min(this.maxItems, data.length), leny = data[0].length-1;
- if (this.maxItems < data.length) {
- start = data.length - this.maxItems;
- }
+ int start = 0, len = Math.min(this.maxItems, data.length), leny = data[0].length-1;
+ if (this.maxItems < data.length) {
+ start = data.length - this.maxItems;
+ }
- Double[][] all_values = new Double[len][leny];
- String[] all_labels = new String[len];
+ Double[][] all_values = new Double[len][leny];
+ String[] all_labels = new String[len];
- for (int i = 0; i < all_labels.length; i++) {
- Object label = data[start + i][0];
- if (label != null) {
- all_labels[i] = label.toString();
- for (int j = 1; j < data[start + i].length; j++) {
- // Ignore all null or negative slice values.
- Double val = getDoubleOrNullValue(data[start + i][j]);
- if (val != null && val >= 0) {
- all_values[i][j-1] = val;
- } else {
- all_values[i][j-1] = 0.0;
- }
- }
- }
- }
+ for (int i = 0; i < all_labels.length; i++) {
+ Object label = data[start + i][0];
+ if (label != null) {
+ all_labels[i] = label.toString();
+ for (int j = 1; j < data[start + i].length; j++) {
+ // Ignore all null or negative slice values.
+ Double val = getDoubleOrNullValue(data[start + i][j]);
+ if (val != null && val >= 0) {
+ all_values[i][j-1] = val;
+ } else {
+ all_values[i][j-1] = 0.0;
+ }
+ }
+ }
+ }
- double[][] values = new double[len][leny];
- String[] labels = new String[len];
- int len_trim = 0;
- for (int i = 0; i < len; i++) {
- if (all_labels[i] != null) {
- labels[len_trim] = all_labels[i];
- for (int j = 0; j < leny; j++) {
- values[len_trim][j] = all_values[i][j].doubleValue();
- }
- len_trim++;
- }
- }
- double[][] values_trim = new double[len_trim][leny];
- String[] labels_trim = new String[len_trim];
- for (int i = 0; i < len_trim; i++) {
- labels_trim[i] = labels[i];
- for (int j = 0; j < leny; j++) {
- values_trim[i][j] = values[i][j];
- }
- }
+ double[][] values = new double[len][leny];
+ String[] labels = new String[len];
+ int len_trim = 0;
+ for (int i = 0; i < len; i++) {
+ if (all_labels[i] != null) {
+ labels[len_trim] = all_labels[i];
+ for (int j = 0; j < leny; j++) {
+ values[len_trim][j] = all_values[i][j].doubleValue();
+ }
+ len_trim++;
+ }
+ }
+ double[][] values_trim = new double[len_trim][leny];
+ String[] labels_trim = new String[len_trim];
+ for (int i = 0; i < len_trim; i++) {
+ labels_trim[i] = labels[i];
+ for (int j = 0; j < leny; j++) {
+ values_trim[i][j] = values[i][j];
+ }
+ }
- ((PieChart)this.chart).addPieChartSeries(getUniqueNames(labels_trim), values_trim);
- applyCategoryRange(values_trim[0].length);
- chart.redraw();
- }
+ ((PieChart)this.chart).addPieChartSeries(getUniqueNames(labels_trim), values_trim);
+ applyCategoryRange(values_trim[0].length);
+ chart.redraw();
+ }
- /**
- * This updates the visible range of the chart's x-axis.
- */
- private void applyCategoryRange(int numItems) {
- int itemRange = Math.max(1, (int) Math.ceil(numItems * scale)); // The number of items to display
- int lower = (int) Math.round((numItems - itemRange) * scroll);
- chart.getAxisSet().getXAxis(0).setRange(new Range(lower, lower + itemRange - 1));
- }
+ /**
+ * This updates the visible range of the chart's x-axis.
+ */
+ private void applyCategoryRange(int numItems) {
+ int itemRange = Math.max(1, (int) Math.ceil(numItems * scale)); // The number of items to display
+ int lower = (int) Math.round((numItems - itemRange) * scroll);
+ chart.getAxisSet().getXAxis(0).setRange(new Range(lower, lower + itemRange - 1));
+ }
- @Override
- public void updateDataSet() {
- buildXSeries();
- chartMouseMoveListener.update();
- }
+ @Override
+ public void updateDataSet() {
+ buildXSeries();
+ chartMouseMoveListener.update();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/ScatterChartBuilder.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/ScatterChartBuilder.java
index 2a901d287f..662b4a9e4c 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/ScatterChartBuilder.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/ScatterChartBuilder.java
@@ -25,17 +25,17 @@ import org.swtchart.LineStyle;
*/
public class ScatterChartBuilder extends LineChartBuilder {
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.scatterchartbuilder"; //$NON-NLS-1$
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.scatterchartbuilder"; //$NON-NLS-1$
public ScatterChartBuilder(Composite parent, int style, String title,IAdapter adapter) {
- super(parent, style, title, adapter);
+ super(parent, style, title, adapter);
}
- @Override
- protected ISeries createChartISeries(int i) {
- ILineSeries series = (ILineSeries)super.createChartISeries(i);
- series.setSymbolColor(COLORS[i % COLORS.length]);
- series.setLineStyle(LineStyle.NONE);
- return series;
- }
+ @Override
+ protected ISeries createChartISeries(int i) {
+ ILineSeries series = (ILineSeries)super.createChartISeries(i);
+ series.setSymbolColor(COLORS[i % COLORS.length]);
+ series.setLineStyle(LineStyle.NONE);
+ return series;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/BarChartMouseMoveListener.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/BarChartMouseMoveListener.java
index 5df0ab35d3..81164b964f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/BarChartMouseMoveListener.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/BarChartMouseMoveListener.java
@@ -17,30 +17,30 @@ import org.swtchart.ISeries;
* @since 3.0
*/
public class BarChartMouseMoveListener extends ToolTipChartMouseMoveListener {
- public BarChartMouseMoveListener(BarChart chart, Composite parent) {
- super(chart, parent);
- }
+ public BarChartMouseMoveListener(BarChart chart, Composite parent) {
+ super(chart, parent);
+ }
- @Override
- public void mouseMove(MouseEvent e) {
- super.mouseMove(e);
- ISeries[] allSeries = chart.getSeriesSet().getSeries();
- if (allSeries.length == 0) {
- return;
- }
- IAxis xAxis = chart.getAxisSet().getXAxis(0);
- String[] categorySeries = ((BarChart) chart).getCategorySeries();
- int barIndex = (int) xAxis.getDataCoordinate(e.x);
- if (0 <= barIndex && barIndex < categorySeries.length) {
- String textTip = ""; //$NON-NLS-1$
- for (int i = 0; i < allSeries.length; i++) {
- textTip = textTip.concat((i > 0 ? "\n" : "") + MessageFormat.format(Messages.BarChartBuilder_ToolTipCoords, //$NON-NLS-1$ //$NON-NLS-2$
- allSeries[i].getId(), ((BarChart) chart).getBarValue(i, barIndex)));
- }
- setTextTip(textTip);
- } else {
- tipShell.setVisible(false);
- }
- chart.redraw();
- }
+ @Override
+ public void mouseMove(MouseEvent e) {
+ super.mouseMove(e);
+ ISeries[] allSeries = chart.getSeriesSet().getSeries();
+ if (allSeries.length == 0) {
+ return;
+ }
+ IAxis xAxis = chart.getAxisSet().getXAxis(0);
+ String[] categorySeries = ((BarChart) chart).getCategorySeries();
+ int barIndex = (int) xAxis.getDataCoordinate(e.x);
+ if (0 <= barIndex && barIndex < categorySeries.length) {
+ String textTip = ""; //$NON-NLS-1$
+ for (int i = 0; i < allSeries.length; i++) {
+ textTip = textTip.concat((i > 0 ? "\n" : "") + MessageFormat.format(Messages.BarChartBuilder_ToolTipCoords, //$NON-NLS-1$ //$NON-NLS-2$
+ allSeries[i].getId(), ((BarChart) chart).getBarValue(i, barIndex)));
+ }
+ setTextTip(textTip);
+ } else {
+ tipShell.setVisible(false);
+ }
+ chart.redraw();
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ChartMouseMoveListener.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ChartMouseMoveListener.java
index 640e2e7634..7e0e9baf8b 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ChartMouseMoveListener.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ChartMouseMoveListener.java
@@ -13,56 +13,56 @@ import org.swtchart.Chart;
* @since 3.0
*/
public abstract class ChartMouseMoveListener implements MouseMoveListener {
- protected final Chart chart;
- protected MouseEvent lastMouseEvent = null;
+ protected final Chart chart;
+ protected MouseEvent lastMouseEvent = null;
- /**
- * Constructor.
- * @param chart The chart that this listener is watching.
- * @param hoverArea The plot area of the chart this listener is applied to.
- */
- public ChartMouseMoveListener(Chart chart, final Composite hoverArea) {
- this.chart = chart;
- final MouseMoveListener thisListener = this;
- hoverArea.addMouseTrackListener(new MouseTrackAdapter() {
+ /**
+ * Constructor.
+ * @param chart The chart that this listener is watching.
+ * @param hoverArea The plot area of the chart this listener is applied to.
+ */
+ public ChartMouseMoveListener(Chart chart, final Composite hoverArea) {
+ this.chart = chart;
+ final MouseMoveListener thisListener = this;
+ hoverArea.addMouseTrackListener(new MouseTrackAdapter() {
- @Override
- public void mouseExit(MouseEvent e) {
- hoverArea.removeMouseMoveListener(thisListener);
- exit();
- }
+ @Override
+ public void mouseExit(MouseEvent e) {
+ hoverArea.removeMouseMoveListener(thisListener);
+ exit();
+ }
- @Override
- public void mouseEnter(MouseEvent e) {
- hoverArea.addMouseMoveListener(thisListener);
- }
- });
- }
+ @Override
+ public void mouseEnter(MouseEvent e) {
+ hoverArea.addMouseMoveListener(thisListener);
+ }
+ });
+ }
- /**
- * This method is called whenever the mouse exits the plot area of the chart.
- * It may be overridden to add extra functionality (but always include a super call).
- */
- public void exit() {
- lastMouseEvent = null;
- }
+ /**
+ * This method is called whenever the mouse exits the plot area of the chart.
+ * It may be overridden to add extra functionality (but always include a super call).
+ */
+ public void exit() {
+ lastMouseEvent = null;
+ }
- /**
- * Call this method whenever the chart gets updated, so that another mouse event can be
- * fired with the new chart contents without having to explicitly move the mouse.
- */
- public final void update() {
- if (lastMouseEvent != null) {
- mouseMove(lastMouseEvent);
- }
- }
+ /**
+ * Call this method whenever the chart gets updated, so that another mouse event can be
+ * fired with the new chart contents without having to explicitly move the mouse.
+ */
+ public final void update() {
+ if (lastMouseEvent != null) {
+ mouseMove(lastMouseEvent);
+ }
+ }
- /**
- * Clients must override this method to perform appropriate actions whenever the
- * mouse is moved while inside the chart's plot area (but always include a super call).
- */
- @Override
- public void mouseMove(MouseEvent e) {
- lastMouseEvent = e;
- }
+ /**
+ * Clients must override this method to perform appropriate actions whenever the
+ * mouse is moved while inside the chart's plot area (but always include a super call).
+ */
+ @Override
+ public void mouseMove(MouseEvent e) {
+ lastMouseEvent = e;
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ChartWithAxisMouseMoveListener.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ChartWithAxisMouseMoveListener.java
index 8f256d1aad..806bf5f853 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ChartWithAxisMouseMoveListener.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ChartWithAxisMouseMoveListener.java
@@ -17,38 +17,38 @@ import org.swtchart.ISeries;
* @since 3.0
*/
public class ChartWithAxisMouseMoveListener extends ToolTipChartMouseMoveListener {
- private final double DIST_TOLERANCE = 20.0;
+ private final double DIST_TOLERANCE = 20.0;
- public ChartWithAxisMouseMoveListener(Chart chart, Composite hoverArea) {
- super(chart, hoverArea);
- }
+ public ChartWithAxisMouseMoveListener(Chart chart, Composite hoverArea) {
+ super(chart, hoverArea);
+ }
- @Override
- public void mouseMove(MouseEvent e) {
- super.mouseMove(e);
- double closestDistance = DIST_TOLERANCE;
- int closestIndex = -1;
- ISeries closestSeries = null;
- Point closestPoint = null;
- for (ISeries series : chart.getSeriesSet().getSeries()) {
- for (int i = 0; i < series.getXSeries().length; i++) {
- Point dataPoint = series.getPixelCoordinates(i);
- if (dataPoint.x >= 0 && dataPoint.y >= 0) {
- double dist = Math.sqrt(Math.pow(dataPoint.x - e.x, 2) + Math.pow(dataPoint.y - e.y, 2));
- if (dist < closestDistance) {
- closestDistance = dist;
- closestIndex = i;
- closestSeries = series;
- closestPoint = dataPoint;
- }
- }
- }
- }
- if (closestPoint != null) {
- setTextTip(MessageFormat.format(Messages.AbstractChartWithAxisBuilder_ToolTipCoords,
- closestSeries.getId(), closestSeries.getXSeries()[closestIndex], closestSeries.getYSeries()[closestIndex]));
- } else {
- tipShell.setVisible(false);
- }
- }
+ @Override
+ public void mouseMove(MouseEvent e) {
+ super.mouseMove(e);
+ double closestDistance = DIST_TOLERANCE;
+ int closestIndex = -1;
+ ISeries closestSeries = null;
+ Point closestPoint = null;
+ for (ISeries series : chart.getSeriesSet().getSeries()) {
+ for (int i = 0; i < series.getXSeries().length; i++) {
+ Point dataPoint = series.getPixelCoordinates(i);
+ if (dataPoint.x >= 0 && dataPoint.y >= 0) {
+ double dist = Math.sqrt(Math.pow(dataPoint.x - e.x, 2) + Math.pow(dataPoint.y - e.y, 2));
+ if (dist < closestDistance) {
+ closestDistance = dist;
+ closestIndex = i;
+ closestSeries = series;
+ closestPoint = dataPoint;
+ }
+ }
+ }
+ }
+ if (closestPoint != null) {
+ setTextTip(MessageFormat.format(Messages.AbstractChartWithAxisBuilder_ToolTipCoords,
+ closestSeries.getId(), closestSeries.getXSeries()[closestIndex], closestSeries.getYSeries()[closestIndex]));
+ } else {
+ tipShell.setVisible(false);
+ }
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/PieChartMouseMoveListener.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/PieChartMouseMoveListener.java
index 6f8718bd9b..6a2de4f9c9 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/PieChartMouseMoveListener.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/PieChartMouseMoveListener.java
@@ -12,29 +12,29 @@ import org.swtchart.ISeries;
* @since 3.0
*/
public class PieChartMouseMoveListener extends ToolTipChartMouseMoveListener {
- public PieChartMouseMoveListener(PieChart chart, Composite parent) {
- super(chart, parent);
- }
+ public PieChartMouseMoveListener(PieChart chart, Composite parent) {
+ super(chart, parent);
+ }
- @Override
- public void mouseMove(MouseEvent e) {
- super.mouseMove(e);
- ISeries[] allSeries = chart.getSeriesSet().getSeries();
- int numPies = allSeries.length > 0 ? allSeries[0].getXSeries().length : 0;
- int pieIndex = 0, sliceIndex = -1;
- for (; pieIndex < numPies; pieIndex++) {
- sliceIndex = ((PieChart) chart).getSliceIndexFromPosition(pieIndex, e.x, e.y);
- if (sliceIndex != -1) {
- break;
- }
- }
- if (sliceIndex != -1) {
- setTextTip(MessageFormat.format(Messages.PieChartBuilder_ToolTipCoords,
- chart.getAxisSet().getXAxis(0).getTitle().getText(),
- allSeries[sliceIndex].getId(), allSeries[sliceIndex].getXSeries()[pieIndex],
- Math.round(((PieChart) chart).getSlicePercent(pieIndex, sliceIndex) * 100.0) / 100.0));
- } else {
- tipShell.setVisible(false);
- }
- }
+ @Override
+ public void mouseMove(MouseEvent e) {
+ super.mouseMove(e);
+ ISeries[] allSeries = chart.getSeriesSet().getSeries();
+ int numPies = allSeries.length > 0 ? allSeries[0].getXSeries().length : 0;
+ int pieIndex = 0, sliceIndex = -1;
+ for (; pieIndex < numPies; pieIndex++) {
+ sliceIndex = ((PieChart) chart).getSliceIndexFromPosition(pieIndex, e.x, e.y);
+ if (sliceIndex != -1) {
+ break;
+ }
+ }
+ if (sliceIndex != -1) {
+ setTextTip(MessageFormat.format(Messages.PieChartBuilder_ToolTipCoords,
+ chart.getAxisSet().getXAxis(0).getTitle().getText(),
+ allSeries[sliceIndex].getId(), allSeries[sliceIndex].getXSeries()[pieIndex],
+ Math.round(((PieChart) chart).getSlicePercent(pieIndex, sliceIndex) * 100.0) / 100.0));
+ } else {
+ tipShell.setVisible(false);
+ }
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ToolTipChartMouseMoveListener.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ToolTipChartMouseMoveListener.java
index 316389b8c2..2d7ba2efd9 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ToolTipChartMouseMoveListener.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/charts/listeners/ToolTipChartMouseMoveListener.java
@@ -12,33 +12,33 @@ import org.swtchart.Chart;
* @since 3.0
*/
public class ToolTipChartMouseMoveListener extends ChartMouseMoveListener {
- private final int TIP_OFFSET = 20;
- protected final Shell tipShell;
- protected final Text tipText;
+ private final int TIP_OFFSET = 20;
+ protected final Shell tipShell;
+ protected final Text tipText;
- public ToolTipChartMouseMoveListener(Chart chart, Composite parent) {
- super(chart, parent);
- tipShell = new Shell(Display.getCurrent().getActiveShell(), SWT.TOOL | SWT.ON_TOP);
- tipText = new Text(tipShell, SWT.MULTI | SWT.BOLD);
- tipShell.setVisible(false);
- }
+ public ToolTipChartMouseMoveListener(Chart chart, Composite parent) {
+ super(chart, parent);
+ tipShell = new Shell(Display.getCurrent().getActiveShell(), SWT.TOOL | SWT.ON_TOP);
+ tipText = new Text(tipShell, SWT.MULTI | SWT.BOLD);
+ tipShell.setVisible(false);
+ }
- @Override
- public void exit() {
- super.exit();
- tipShell.setVisible(false);
- }
+ @Override
+ public void exit() {
+ super.exit();
+ tipShell.setVisible(false);
+ }
- protected void setTextTip(String message) {
- Point cursorLocation = Display.getCurrent().getCursorLocation();
- tipShell.setLocation(cursorLocation.x + TIP_OFFSET, cursorLocation.y + TIP_OFFSET);
- if (!message.equals(tipText.getText())) {
- tipText.setText(message);
- tipText.pack();
- tipShell.pack();
- }
- if (!tipShell.isVisible()) {
- tipShell.setVisible(true);
- }
- }
+ protected void setTextTip(String message) {
+ Point cursorLocation = Display.getCurrent().getCursorLocation();
+ tipShell.setLocation(cursorLocation.x + TIP_OFFSET, cursorLocation.y + TIP_OFFSET);
+ if (!message.equals(tipText.getText())) {
+ tipText.setText(message);
+ tipText.pack();
+ tipShell.pack();
+ }
+ if (!tipShell.isVisible()) {
+ tipShell.setVisible(true);
+ }
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/handlers/SaveGraphImageHandler.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/handlers/SaveGraphImageHandler.java
index f22e750565..d2c5ace4d7 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/handlers/SaveGraphImageHandler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/handlers/SaveGraphImageHandler.java
@@ -31,43 +31,43 @@ import org.swtchart.Chart;
*/
public class SaveGraphImageHandler extends AbstractHandler {
- private SaveChartAction saveChartAction = new SaveChartAction();
+ private SaveChartAction saveChartAction = new SaveChartAction();
- /**
- * This is the main method of the action. It handles getting the active graph,
- * prompting the user for a location to save the image to, and then actually doing
- * the save.
- */
- @Override
- public Object execute(ExecutionEvent event) {
- saveChartAction.setChart(getActiveChart());
- saveChartAction.run();
- return null;
- }
+ /**
+ * This is the main method of the action. It handles getting the active graph,
+ * prompting the user for a location to save the image to, and then actually doing
+ * the save.
+ */
+ @Override
+ public Object execute(ExecutionEvent event) {
+ saveChartAction.setChart(getActiveChart());
+ saveChartAction.run();
+ return null;
+ }
- @Override
- public boolean isEnabled() {
- return getActiveGraphEditor() != null;
- }
+ @Override
+ public boolean isEnabled() {
+ return getActiveGraphEditor() != null;
+ }
- private GraphSelectorEditor getActiveGraphEditor() {
- IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().
- getActivePage().getActiveEditor();
- return editor instanceof GraphSelectorEditor ? (GraphSelectorEditor) editor : null;
- }
+ private GraphSelectorEditor getActiveGraphEditor() {
+ IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().
+ getActivePage().getActiveEditor();
+ return editor instanceof GraphSelectorEditor ? (GraphSelectorEditor) editor : null;
+ }
- private AbstractChartBuilder getActiveGraph() {
- GraphSelectorEditor graphEditor = getActiveGraphEditor();
- if (graphEditor == null) {
- return null;
- }
- GraphDisplaySet gds = graphEditor.getActiveDisplaySet();
- return gds == null ? null : gds.getActiveGraph();
- }
+ private AbstractChartBuilder getActiveGraph() {
+ GraphSelectorEditor graphEditor = getActiveGraphEditor();
+ if (graphEditor == null) {
+ return null;
+ }
+ GraphDisplaySet gds = graphEditor.getActiveDisplaySet();
+ return gds == null ? null : gds.getActiveGraph();
+ }
- private Chart getActiveChart() {
- AbstractChartBuilder abs = getActiveGraph();
- return abs == null ? null : abs.getChart();
- }
+ private Chart getActiveChart() {
+ AbstractChartBuilder abs = getActiveGraph();
+ return abs == null ? null : abs.getChart();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/DataTablePreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/DataTablePreferencePage.java
index cc74993867..fb56f5d38f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/DataTablePreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/DataTablePreferencePage.java
@@ -22,33 +22,33 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class DataTablePreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- public DataTablePreferencePage() {
- super(GRID);
- setPreferenceStore(GraphingUIPlugin.getDefault().getPreferenceStore());
- setDescription(Localization.getString("DataTablePreferencePage.GraphDisplayPreferences")); //$NON-NLS-1$
- }
-
- @Override
- public void createFieldEditors() {
- addField(new BooleanFieldEditor(
- GraphingPreferenceConstants.P_JUMP_NEW_TABLE_ENTRY,
- Localization.getString("DataTablePreferencePage.JumpNewestEntry"), //$NON-NLS-1$
- getFieldEditorParent()));
-
- addField(new BooleanFieldEditor(
- GraphingPreferenceConstants.P_AUTO_RESIZE,
- Localization.getString("DataTablePreferencePage.AutoResizeColumns"), //$NON-NLS-1$
- getFieldEditorParent()));
-
- addField(
- new IntegerFieldEditor(
- GraphingPreferenceConstants.P_MAX_DATA_ITEMS,
- Localization.getString("DataTablePreferencePage.MaxDataItems"), //$NON-NLS-1$
- getFieldEditorParent()));
- }
-
- @Override
- public void init(IWorkbench workbench) {}
+ public DataTablePreferencePage() {
+ super(GRID);
+ setPreferenceStore(GraphingUIPlugin.getDefault().getPreferenceStore());
+ setDescription(Localization.getString("DataTablePreferencePage.GraphDisplayPreferences")); //$NON-NLS-1$
+ }
+
+ @Override
+ public void createFieldEditors() {
+ addField(new BooleanFieldEditor(
+ GraphingPreferenceConstants.P_JUMP_NEW_TABLE_ENTRY,
+ Localization.getString("DataTablePreferencePage.JumpNewestEntry"), //$NON-NLS-1$
+ getFieldEditorParent()));
+
+ addField(new BooleanFieldEditor(
+ GraphingPreferenceConstants.P_AUTO_RESIZE,
+ Localization.getString("DataTablePreferencePage.AutoResizeColumns"), //$NON-NLS-1$
+ getFieldEditorParent()));
+
+ addField(
+ new IntegerFieldEditor(
+ GraphingPreferenceConstants.P_MAX_DATA_ITEMS,
+ Localization.getString("DataTablePreferencePage.MaxDataItems"), //$NON-NLS-1$
+ getFieldEditorParent()));
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {}
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphPreferencePage.java
index e9269200f1..059483e09c 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphPreferencePage.java
@@ -22,45 +22,45 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class GraphPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- public GraphPreferencePage() {
- super(GRID);
- setPreferenceStore(GraphingUIPlugin.getDefault().getPreferenceStore());
- setDescription(Localization.getString("GraphPreferencePage.GraphDisplayPreferences")); //$NON-NLS-1$
- }
+ public GraphPreferencePage() {
+ super(GRID);
+ setPreferenceStore(GraphingUIPlugin.getDefault().getPreferenceStore());
+ setDescription(Localization.getString("GraphPreferencePage.GraphDisplayPreferences")); //$NON-NLS-1$
+ }
- @Override
- public void createFieldEditors() {
- addField(new BooleanFieldEditor(
- GraphingPreferenceConstants.P_SHOW_X_GRID_LINES,
- Localization.getString("GraphPreferencePage.ShowXGridLines"), //$NON-NLS-1$
- getFieldEditorParent()));
+ @Override
+ public void createFieldEditors() {
+ addField(new BooleanFieldEditor(
+ GraphingPreferenceConstants.P_SHOW_X_GRID_LINES,
+ Localization.getString("GraphPreferencePage.ShowXGridLines"), //$NON-NLS-1$
+ getFieldEditorParent()));
- addField(new BooleanFieldEditor(
- GraphingPreferenceConstants.P_SHOW_Y_GRID_LINES,
- Localization.getString("GraphPreferencePage.ShowYGridLines"), //$NON-NLS-1$
- getFieldEditorParent()));
+ addField(new BooleanFieldEditor(
+ GraphingPreferenceConstants.P_SHOW_Y_GRID_LINES,
+ Localization.getString("GraphPreferencePage.ShowYGridLines"), //$NON-NLS-1$
+ getFieldEditorParent()));
- addField(
- new IntegerFieldEditor(
- GraphingPreferenceConstants.P_VIEWABLE_DATA_ITEMS,
- Localization.getString("GraphPreferencePage.ViewableDataItems"), //$NON-NLS-1$
- getFieldEditorParent()));
+ addField(
+ new IntegerFieldEditor(
+ GraphingPreferenceConstants.P_VIEWABLE_DATA_ITEMS,
+ Localization.getString("GraphPreferencePage.ViewableDataItems"), //$NON-NLS-1$
+ getFieldEditorParent()));
- addField(
- new IntegerFieldEditor(
- GraphingPreferenceConstants.P_X_SERIES_TICKS,
- Localization.getString("GraphPreferencePage.XSeriesTicks"), //$NON-NLS-1$
- getFieldEditorParent()));
+ addField(
+ new IntegerFieldEditor(
+ GraphingPreferenceConstants.P_X_SERIES_TICKS,
+ Localization.getString("GraphPreferencePage.XSeriesTicks"), //$NON-NLS-1$
+ getFieldEditorParent()));
- addField(
- new IntegerFieldEditor(
- GraphingPreferenceConstants.P_Y_SERIES_TICKS,
- Localization.getString("GraphPreferencePage.YSeriesTicks"), //$NON-NLS-1$
- getFieldEditorParent()));
- }
+ addField(
+ new IntegerFieldEditor(
+ GraphingPreferenceConstants.P_Y_SERIES_TICKS,
+ Localization.getString("GraphPreferencePage.YSeriesTicks"), //$NON-NLS-1$
+ getFieldEditorParent()));
+ }
- @Override
- public void init(IWorkbench workbench) {}
+ @Override
+ public void init(IWorkbench workbench) {}
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphingPreferenceConstants.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphingPreferenceConstants.java
index 8b28286923..a6bb6a7a39 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphingPreferenceConstants.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphingPreferenceConstants.java
@@ -12,18 +12,18 @@
package org.eclipse.linuxtools.internal.systemtap.graphing.ui.preferences;
public class GraphingPreferenceConstants {
- //graphing
- public static final String P_GRAPH_UPDATE_DELAY = "GraphUpdateDelay"; //$NON-NLS-1$
+ //graphing
+ public static final String P_GRAPH_UPDATE_DELAY = "GraphUpdateDelay"; //$NON-NLS-1$
- //graphing.datatable
- public static final String P_JUMP_NEW_TABLE_ENTRY = "JumpNewTableEntry"; //$NON-NLS-1$
- public static final String P_AUTO_RESIZE = "AutoResizeColumns"; //$NON-NLS-1$
- public static final String P_MAX_DATA_ITEMS = "MaxDataItems"; //$NON-NLS-1$
+ //graphing.datatable
+ public static final String P_JUMP_NEW_TABLE_ENTRY = "JumpNewTableEntry"; //$NON-NLS-1$
+ public static final String P_AUTO_RESIZE = "AutoResizeColumns"; //$NON-NLS-1$
+ public static final String P_MAX_DATA_ITEMS = "MaxDataItems"; //$NON-NLS-1$
- //graphing.graph
- public static final String P_SHOW_X_GRID_LINES = "ShowXGridLines"; //$NON-NLS-1$
- public static final String P_SHOW_Y_GRID_LINES = "ShowYGridLines"; //$NON-NLS-1$
- public static final String P_VIEWABLE_DATA_ITEMS = "ViewableDataItems"; //$NON-NLS-1$
- public static final String P_X_SERIES_TICKS = "XSeriesTicks"; //$NON-NLS-1$
- public static final String P_Y_SERIES_TICKS = "YSeriesTicks"; //$NON-NLS-1$
+ //graphing.graph
+ public static final String P_SHOW_X_GRID_LINES = "ShowXGridLines"; //$NON-NLS-1$
+ public static final String P_SHOW_Y_GRID_LINES = "ShowYGridLines"; //$NON-NLS-1$
+ public static final String P_VIEWABLE_DATA_ITEMS = "ViewableDataItems"; //$NON-NLS-1$
+ public static final String P_X_SERIES_TICKS = "XSeriesTicks"; //$NON-NLS-1$
+ public static final String P_Y_SERIES_TICKS = "YSeriesTicks"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphingPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphingPreferencePage.java
index 3b594a703b..31a23699c5 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphingPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/GraphingPreferencePage.java
@@ -21,24 +21,24 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class GraphingPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- public GraphingPreferencePage() {
- super(GRID);
- setPreferenceStore(GraphingUIPlugin.getDefault().getPreferenceStore());
- setDescription(Localization.getString("GraphingPreferencePage.GraphDisplayPreferences")); //$NON-NLS-1$
- }
-
- @Override
- public void createFieldEditors() {
- addField(
- new IntegerFieldEditor(
- GraphingPreferenceConstants.P_GRAPH_UPDATE_DELAY,
- Localization.getString("GraphingPreferencePage.RefreshDelay"), //$NON-NLS-1$
- getFieldEditorParent()));
- }
-
- @Override
- public void init(IWorkbench workbench) {
- // Empty
- }
+ public GraphingPreferencePage() {
+ super(GRID);
+ setPreferenceStore(GraphingUIPlugin.getDefault().getPreferenceStore());
+ setDescription(Localization.getString("GraphingPreferencePage.GraphDisplayPreferences")); //$NON-NLS-1$
+ }
+
+ @Override
+ public void createFieldEditors() {
+ addField(
+ new IntegerFieldEditor(
+ GraphingPreferenceConstants.P_GRAPH_UPDATE_DELAY,
+ Localization.getString("GraphingPreferencePage.RefreshDelay"), //$NON-NLS-1$
+ getFieldEditorParent()));
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ // Empty
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/PreferenceInitializer.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/PreferenceInitializer.java
index f9fd1fca9e..cb7b62580a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/PreferenceInitializer.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/preferences/PreferenceInitializer.java
@@ -18,23 +18,23 @@ import org.eclipse.linuxtools.internal.systemtap.graphing.ui.GraphingUIPlugin;
public class PreferenceInitializer extends AbstractPreferenceInitializer {
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = GraphingUIPlugin.getDefault().getPreferenceStore();
-
- //graphing
- store.setDefault(GraphingPreferenceConstants.P_GRAPH_UPDATE_DELAY, 1000);
-
- //data table
- store.setDefault(GraphingPreferenceConstants.P_AUTO_RESIZE, true);
- store.setDefault(GraphingPreferenceConstants.P_JUMP_NEW_TABLE_ENTRY, false);
- store.setDefault(GraphingPreferenceConstants.P_MAX_DATA_ITEMS, 250);
-
- //graph
- store.setDefault(GraphingPreferenceConstants.P_SHOW_X_GRID_LINES, true);
- store.setDefault(GraphingPreferenceConstants.P_SHOW_Y_GRID_LINES, true);
- store.setDefault(GraphingPreferenceConstants.P_VIEWABLE_DATA_ITEMS, 100);
- store.setDefault(GraphingPreferenceConstants.P_X_SERIES_TICKS, 64);
- store.setDefault(GraphingPreferenceConstants.P_Y_SERIES_TICKS, 64);
- }
+ @Override
+ public void initializeDefaultPreferences() {
+ IPreferenceStore store = GraphingUIPlugin.getDefault().getPreferenceStore();
+
+ //graphing
+ store.setDefault(GraphingPreferenceConstants.P_GRAPH_UPDATE_DELAY, 1000);
+
+ //data table
+ store.setDefault(GraphingPreferenceConstants.P_AUTO_RESIZE, true);
+ store.setDefault(GraphingPreferenceConstants.P_JUMP_NEW_TABLE_ENTRY, false);
+ store.setDefault(GraphingPreferenceConstants.P_MAX_DATA_ITEMS, 250);
+
+ //graph
+ store.setDefault(GraphingPreferenceConstants.P_SHOW_X_GRID_LINES, true);
+ store.setDefault(GraphingPreferenceConstants.P_SHOW_Y_GRID_LINES, true);
+ store.setDefault(GraphingPreferenceConstants.P_VIEWABLE_DATA_ITEMS, 100);
+ store.setDefault(GraphingPreferenceConstants.P_X_SERIES_TICKS, 64);
+ store.setDefault(GraphingPreferenceConstants.P_Y_SERIES_TICKS, 64);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/views/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/views/Messages.java
index ecb5ea22bb..43cea34d7f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/views/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/views/Messages.java
@@ -14,14 +14,14 @@ package org.eclipse.linuxtools.internal.systemtap.graphing.ui.views;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.graphing.ui.views.messages"; //$NON-NLS-1$
- public static String GraphSelectorEditor_graphsEditorTitle;
- public static String GraphSelectorEditor_graphsEditorDefaultTitle;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.graphing.ui.views.messages"; //$NON-NLS-1$
+ public static String GraphSelectorEditor_graphsEditorTitle;
+ public static String GraphSelectorEditor_graphsEditorDefaultTitle;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/AggregateFactory.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/AggregateFactory.java
index fb4bc6b236..6df1c7d8b0 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/AggregateFactory.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/AggregateFactory.java
@@ -26,68 +26,68 @@ public final class AggregateFactory {
private AggregateFactory() {}
- private static final String[] AGGREGATE_NAMES = new String[] {
- Localization.getString("AggregateFactory.AverageAggregate"), //$NON-NLS-1$
- Localization.getString("AggregateFactory.CountAggregate"), //$NON-NLS-1$
- Localization.getString("AggregateFactory.MaxAggregate"), //$NON-NLS-1$
- Localization.getString("AggregateFactory.MinAggregate"), //$NON-NLS-1$
- Localization.getString("AggregateFactory.SumAggregate") //$NON-NLS-1$
- };
+ private static final String[] AGGREGATE_NAMES = new String[] {
+ Localization.getString("AggregateFactory.AverageAggregate"), //$NON-NLS-1$
+ Localization.getString("AggregateFactory.CountAggregate"), //$NON-NLS-1$
+ Localization.getString("AggregateFactory.MaxAggregate"), //$NON-NLS-1$
+ Localization.getString("AggregateFactory.MinAggregate"), //$NON-NLS-1$
+ Localization.getString("AggregateFactory.SumAggregate") //$NON-NLS-1$
+ };
- private static final String[] AGGREGATION_DESCRIPTIONS = new String[] {
- Localization.getString("AggregateFactory.AverageDescription"), //$NON-NLS-1$
- Localization.getString("AggregateFactory.CountDescription"), //$NON-NLS-1$
- Localization.getString("AggregateFactory.MaxDescription"), //$NON-NLS-1$
- Localization.getString("AggregateFactory.MinDescription"), //$NON-NLS-1$
- Localization.getString("AggregateFactory.SumDescription") //$NON-NLS-1$
- };
+ private static final String[] AGGREGATION_DESCRIPTIONS = new String[] {
+ Localization.getString("AggregateFactory.AverageDescription"), //$NON-NLS-1$
+ Localization.getString("AggregateFactory.CountDescription"), //$NON-NLS-1$
+ Localization.getString("AggregateFactory.MaxDescription"), //$NON-NLS-1$
+ Localization.getString("AggregateFactory.MinDescription"), //$NON-NLS-1$
+ Localization.getString("AggregateFactory.SumDescription") //$NON-NLS-1$
+ };
- static final String[] AGGREGATES = new String[] {
- AverageAggregate.ID,
- CountAggregate.ID,
- MaxAggregate.ID,
- MinAggregate.ID,
- SumAggregate.ID
- };
+ static final String[] AGGREGATES = new String[] {
+ AverageAggregate.ID,
+ CountAggregate.ID,
+ MaxAggregate.ID,
+ MinAggregate.ID,
+ SumAggregate.ID
+ };
- public static String getAggregateName(String id) {
- int index = getIndex(id);
- if(index >= 0) {
- return AGGREGATE_NAMES[index];
- }
- return null;
- }
+ public static String getAggregateName(String id) {
+ int index = getIndex(id);
+ if(index >= 0) {
+ return AGGREGATE_NAMES[index];
+ }
+ return null;
+ }
- public static String getAggregateDescription(String id) {
- int index = getIndex(id);
- if(index >= 0) {
- return AGGREGATION_DESCRIPTIONS[index];
- }
- return null;
- }
+ public static String getAggregateDescription(String id) {
+ int index = getIndex(id);
+ if(index >= 0) {
+ return AGGREGATION_DESCRIPTIONS[index];
+ }
+ return null;
+ }
- private static int getIndex(String id) {
- for(int i=0; i< AGGREGATES.length; i++) {
- if(id.equals(AGGREGATES[i])) {
- return i;
- }
- }
- return -1;
- }
+ private static int getIndex(String id) {
+ for(int i=0; i< AGGREGATES.length; i++) {
+ if(id.equals(AGGREGATES[i])) {
+ return i;
+ }
+ }
+ return -1;
+ }
- public static final IDataAggregate createAggregate(String id) {
- switch(getIndex(id)) {
- case 0:
- return new AverageAggregate();
- case 1:
- return new CountAggregate();
- case 2:
- return new MaxAggregate();
- case 3:
- return new MinAggregate();
- case 4:
- return new SumAggregate();
- }
- return null;
- }
+ public static final IDataAggregate createAggregate(String id) {
+ switch(getIndex(id)) {
+ case 0:
+ return new AverageAggregate();
+ case 1:
+ return new CountAggregate();
+ case 2:
+ return new MaxAggregate();
+ case 3:
+ return new MinAggregate();
+ case 4:
+ return new SumAggregate();
+ }
+ return null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/MatchFilterWizardPage.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/MatchFilterWizardPage.java
index 2a3a4d9742..38fe7afff2 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/MatchFilterWizardPage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/MatchFilterWizardPage.java
@@ -59,7 +59,7 @@ public class MatchFilterWizardPage extends FilterWizardPage {
cboColumn.add(serie);
}
- new Label(cmpFilterOpts, SWT.NONE); //Spacer
+ new Label(cmpFilterOpts, SWT.NONE); //Spacer
//String to compare to
Label lblCompare = new Label(cmpFilterOpts, SWT.NONE);
@@ -67,7 +67,7 @@ public class MatchFilterWizardPage extends FilterWizardPage {
txtCompare = new Text(cmpFilterOpts, SWT.BORDER);
txtCompare.addModifyListener(modifyListener);
- new Label(cmpFilterOpts, SWT.NONE); //Spacer
+ new Label(cmpFilterOpts, SWT.NONE); //Spacer
//Style
radKeepMatch = new Button(cmpFilterOpts, SWT.RADIO);
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/RangeFilterWizardPage.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/RangeFilterWizardPage.java
index 2728d34ae5..fe659f5a9f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/RangeFilterWizardPage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/RangeFilterWizardPage.java
@@ -62,7 +62,7 @@ public class RangeFilterWizardPage extends FilterWizardPage {
cboColumn.add(wizard.series[i]);
}
- new Label(cmpFilterOpts, SWT.NONE); //Spacer
+ new Label(cmpFilterOpts, SWT.NONE); //Spacer
//Low
Label lblLow = new Label(cmpFilterOpts, SWT.NONE);
@@ -78,7 +78,7 @@ public class RangeFilterWizardPage extends FilterWizardPage {
txtHigh.addModifyListener(modifyListener);
txtHigh.addKeyListener(numberKeyListener);
- new Label(cmpFilterOpts, SWT.NONE); //Spacer
+ new Label(cmpFilterOpts, SWT.NONE); //Spacer
//Style
radInside = new Button(cmpFilterOpts, SWT.RADIO);
@@ -93,7 +93,7 @@ public class RangeFilterWizardPage extends FilterWizardPage {
chkInclusive.setText(Localization.getString("RangeFilterWizardPage.Inclusive")); //$NON-NLS-1$
chkInclusive.addSelectionListener(selectionListener);
- new Label(cmpFilterOpts, SWT.NONE); //Spacer
+ new Label(cmpFilterOpts, SWT.NONE); //Spacer
cboColumn.select(0);
createFilter();
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/SortFilterWizardPage.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/SortFilterWizardPage.java
index b87f8ec3db..e1cfbe4fc0 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/SortFilterWizardPage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/SortFilterWizardPage.java
@@ -58,7 +58,7 @@ public class SortFilterWizardPage extends FilterWizardPage {
cboColumn.add(wizard.series[i]);
}
- new Label(cmpFilterOpts, SWT.NONE); //Spacer
+ new Label(cmpFilterOpts, SWT.NONE); //Spacer
//Style
radAscending = new Button(cmpFilterOpts, SWT.RADIO);
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/UniqueFilterWizardPage.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/UniqueFilterWizardPage.java
index e661263be1..47777221c3 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/UniqueFilterWizardPage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/internal/systemtap/graphing/ui/wizards/filter/UniqueFilterWizardPage.java
@@ -62,7 +62,7 @@ public class UniqueFilterWizardPage extends FilterWizardPage {
cboColumn.add(series);
}
- new Label(cmpFilterOpts, SWT.NONE); //Spacer
+ new Label(cmpFilterOpts, SWT.NONE); //Spacer
//String to compare to
Label lblAggregate = new Label(cmpFilterOpts, SWT.NONE);
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/GraphDisplaySet.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/GraphDisplaySet.java
index 38df06f4ff..f24244c8d9 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/GraphDisplaySet.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/GraphDisplaySet.java
@@ -61,234 +61,234 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
*/
public class GraphDisplaySet {
- private IPropertyChangeListener propertyChangeListener;
- private IPreferenceStore p;
-
- /**
- * @since 3.0 set must be a IFilteredDataSet.
- */
- public GraphDisplaySet(Composite parent, IFilteredDataSet data) {
- p = GraphingUIPlugin.getDefault().getPreferenceStore();
- int delay = p.getInt(GraphingPreferenceConstants.P_GRAPH_UPDATE_DELAY);
-
- dataSet = data;
- updater = new UpdateManager(delay);
- createPartControl(parent);
-
- propertyChangeListener = new IPropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (updater.isRunning() && event.getProperty().equals(GraphingPreferenceConstants.P_GRAPH_UPDATE_DELAY)) {
- updater.restart((int) event.getNewValue());
- }
- }
- };
- p.addPropertyChangeListener(propertyChangeListener);
-
- builders = new ArrayList<>();
- tabListeners = new ArrayList<>();
- }
-
- /**
- * This method creates the framework for what will be displayed by this dialog box.
- * @param parent The composite that will contain all the elements from this dialog
- */
- private void createPartControl(Composite parent) {
- parent.setLayout(new FormLayout());
- FormData data1 = new FormData();
- Composite cmpCoolBar = new Composite(parent, SWT.NONE);
- data1.left = new FormAttachment(0, 0);
- data1.top = new FormAttachment(0, 0);
- data1.right = new FormAttachment(100, 0);
- data1.bottom = new FormAttachment(0, 10);
- cmpCoolBar.setLayoutData(data1);
-
- FormData data2 = new FormData();
- data2.left = new FormAttachment(0, 0);
- data2.top = new FormAttachment(cmpCoolBar);
- data2.right = new FormAttachment(100, 0);
- data2.bottom = new FormAttachment(100, 0);
- Composite cmpGraph = new Composite(parent, SWT.NONE);
- cmpGraph.setLayoutData(data2);
-
- //This is for the tab view
- cmpGraph.setLayout(new FormLayout());
-
- folder = new CTabFolder(cmpGraph, SWT.NONE);
- FormData data = new FormData();
- data.top = new FormAttachment(0, 0);
- data.left = new FormAttachment(0, 0);
- data.right = new FormAttachment(100, 0);
- data.bottom = new FormAttachment(100, 0);
- folder.setLayoutData(data);
-
- listener = new ButtonClickListener();
- folder.addSelectionListener(listener);
-
- folder.addCTabFolder2Listener(new CTabFolder2Adapter() {
- @Override
- public void close(CTabFolderEvent e) {
- int selected = folder.indexOf((CTabItem)e.item)-2;
- if(null != updater) {
- updater.removeUpdateListener(builders.get(selected));
- }
- builders.remove(selected);
- fireTabCloseEvent();
- }
- });
-
- //This is a tab/button for opening new graphs
- CTabItem newGraph = new CTabItem(folder, SWT.NONE);
- newGraph.setImage(AbstractUIPlugin.imageDescriptorFromPlugin(GraphingUIPlugin.PLUGIN_ID, "icons/actions/new_wiz.gif").createImage()); //$NON-NLS-1$
- newGraph.setToolTipText(Localization.getString("GraphDisplaySet.CreateGraph")); //$NON-NLS-1$
-
- //Tab containing the data table
- CTabItem item = new CTabItem(folder, SWT.NONE);
- item.setText(Localization.getString("GraphDisplaySet.DataView")); //$NON-NLS-1$
- Composite c = new Composite(folder, SWT.NONE);
- GridLayout grid = new GridLayout();
- grid.marginHeight = 0;
- grid.marginWidth = 0;
- c.setLayout(grid);
-
- GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
- DataGrid table = DataSetFactory.getDataGrid(c, dataSet);
- if(null != updater) {
- updater.addUpdateListener(table);
- }
- table.getControl().setLayoutData(gd);
- item.setControl(c);
- folder.setSelection(item);
- lastSelectedTab = 1;
- }
-
- public IDataSet getDataSet() {
- return dataSet;
- }
-
- /**
- * Finds the graph that is open in the current tab
- * @return The graph that is currently visible on the screen
- */
- public AbstractChartBuilder getActiveGraph() {
- if(0 == builders.size() || folder.getSelectionIndex() < 2) {
- return null;
- }
- return builders.get(folder.getSelectionIndex()-2);
- }
-
- /**
- * Removes all internal references in this class. Nothing should make any references
- * to anything in this class after calling the dispose method.
- */
- public void dispose() {
- if(null != updater && updater.isRunning()) {
- updater.dispose();
- }
- updater = null;
-
- p.removePropertyChangeListener(propertyChangeListener);
- propertyChangeListener = null;
-
- dataSet = null;
- if(null != folder && !folder.isDisposed()) {
- folder.removeSelectionListener(listener);
- folder.dispose();
- folder = null;
- }
- listener = null;
-
- for (AbstractChartBuilder builder : builders) {
- builder.dispose();
- }
- builders.clear();
- }
-
- /**
- * This class handles switching between tabs and creating new graphs.
- * When the user selects the first tab a new dialog is displayed for
- * them to select what they want to display for the new graph.
- */
- private class ButtonClickListener extends SelectionAdapter {
- @Override
- public void widgetSelected(SelectionEvent event) {
- CTabFolder folder = (CTabFolder)event.getSource();
-
- if(folder.getSelectionIndex() == 0) {
- folder.setSelection(lastSelectedTab);
- SelectGraphAndSeriesWizard wizard = new SelectGraphAndSeriesWizard(dataSet, null);
- IWorkbench workbench = PlatformUI.getWorkbench();
- wizard.init(workbench, null);
- WizardDialog dialog = new WizardDialog(workbench.getActiveWorkbenchWindow().getShell(), wizard);
- dialog.create();
- dialog.open();
-
- GraphData gd = wizard.getGraphData();
-
- if(null != gd) {
- addGraph(gd);
- }
- wizard.dispose();
- fireTabOpenEvent();
- }
- lastSelectedTab = folder.getSelectionIndex();
- fireTabChangedEvent();
- }
- }
-
- public void addTabListener(ITabListener listener) {
- tabListeners.add(listener);
- }
-
- private void fireTabCloseEvent() {
- for(int i=0; i<tabListeners.size(); i++) {
- (tabListeners.get(i)).tabClosed();
- }
- }
-
- private void fireTabOpenEvent() {
- for(int i=0; i<tabListeners.size(); i++) {
- (tabListeners.get(i)).tabOpened();
- }
- }
-
- private void fireTabChangedEvent() {
- for(int i=0; i<tabListeners.size(); i++) {
- (tabListeners.get(i)).tabChanged();
- }
- }
-
- public void addGraph(GraphData gd) {
- CTabItem item = new CTabItem(folder, SWT.CLOSE);
- item.setText(MessageFormat.format(Localization.getString("GraphDisplaySet.GraphTabTitle"), //$NON-NLS-1$
- gd.title, GraphFactory.getGraphName(gd.graphID)));
- final GraphComposite gc = new GraphComposite(folder, SWT.FILL, gd, dataSet);
- gc.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- gc.addCheckOption("Legend", new SelectionAdapter() { //$NON-NLS-1$
- @Override
- public void widgetSelected(SelectionEvent e) {
- gc.setLegendVisible(((Button)e.getSource()).getSelection());
- }
- });
- folder.setSelection(item);
-
- AbstractChartBuilder g = gc.getCanvas();
- item.setControl(gc);
-
- if(null != g) {
- if(null != updater) {
- updater.addUpdateListener(g);
- }
- builders.add(g);
- }
- }
-
- private int lastSelectedTab;
- private IFilteredDataSet dataSet;
- private CTabFolder folder;
- private ButtonClickListener listener;
- private UpdateManager updater;
- private List<ITabListener> tabListeners;
-
- private List<AbstractChartBuilder> builders;
+ private IPropertyChangeListener propertyChangeListener;
+ private IPreferenceStore p;
+
+ /**
+ * @since 3.0 set must be a IFilteredDataSet.
+ */
+ public GraphDisplaySet(Composite parent, IFilteredDataSet data) {
+ p = GraphingUIPlugin.getDefault().getPreferenceStore();
+ int delay = p.getInt(GraphingPreferenceConstants.P_GRAPH_UPDATE_DELAY);
+
+ dataSet = data;
+ updater = new UpdateManager(delay);
+ createPartControl(parent);
+
+ propertyChangeListener = new IPropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ if (updater.isRunning() && event.getProperty().equals(GraphingPreferenceConstants.P_GRAPH_UPDATE_DELAY)) {
+ updater.restart((int) event.getNewValue());
+ }
+ }
+ };
+ p.addPropertyChangeListener(propertyChangeListener);
+
+ builders = new ArrayList<>();
+ tabListeners = new ArrayList<>();
+ }
+
+ /**
+ * This method creates the framework for what will be displayed by this dialog box.
+ * @param parent The composite that will contain all the elements from this dialog
+ */
+ private void createPartControl(Composite parent) {
+ parent.setLayout(new FormLayout());
+ FormData data1 = new FormData();
+ Composite cmpCoolBar = new Composite(parent, SWT.NONE);
+ data1.left = new FormAttachment(0, 0);
+ data1.top = new FormAttachment(0, 0);
+ data1.right = new FormAttachment(100, 0);
+ data1.bottom = new FormAttachment(0, 10);
+ cmpCoolBar.setLayoutData(data1);
+
+ FormData data2 = new FormData();
+ data2.left = new FormAttachment(0, 0);
+ data2.top = new FormAttachment(cmpCoolBar);
+ data2.right = new FormAttachment(100, 0);
+ data2.bottom = new FormAttachment(100, 0);
+ Composite cmpGraph = new Composite(parent, SWT.NONE);
+ cmpGraph.setLayoutData(data2);
+
+ //This is for the tab view
+ cmpGraph.setLayout(new FormLayout());
+
+ folder = new CTabFolder(cmpGraph, SWT.NONE);
+ FormData data = new FormData();
+ data.top = new FormAttachment(0, 0);
+ data.left = new FormAttachment(0, 0);
+ data.right = new FormAttachment(100, 0);
+ data.bottom = new FormAttachment(100, 0);
+ folder.setLayoutData(data);
+
+ listener = new ButtonClickListener();
+ folder.addSelectionListener(listener);
+
+ folder.addCTabFolder2Listener(new CTabFolder2Adapter() {
+ @Override
+ public void close(CTabFolderEvent e) {
+ int selected = folder.indexOf((CTabItem)e.item)-2;
+ if(null != updater) {
+ updater.removeUpdateListener(builders.get(selected));
+ }
+ builders.remove(selected);
+ fireTabCloseEvent();
+ }
+ });
+
+ //This is a tab/button for opening new graphs
+ CTabItem newGraph = new CTabItem(folder, SWT.NONE);
+ newGraph.setImage(AbstractUIPlugin.imageDescriptorFromPlugin(GraphingUIPlugin.PLUGIN_ID, "icons/actions/new_wiz.gif").createImage()); //$NON-NLS-1$
+ newGraph.setToolTipText(Localization.getString("GraphDisplaySet.CreateGraph")); //$NON-NLS-1$
+
+ //Tab containing the data table
+ CTabItem item = new CTabItem(folder, SWT.NONE);
+ item.setText(Localization.getString("GraphDisplaySet.DataView")); //$NON-NLS-1$
+ Composite c = new Composite(folder, SWT.NONE);
+ GridLayout grid = new GridLayout();
+ grid.marginHeight = 0;
+ grid.marginWidth = 0;
+ c.setLayout(grid);
+
+ GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+ DataGrid table = DataSetFactory.getDataGrid(c, dataSet);
+ if(null != updater) {
+ updater.addUpdateListener(table);
+ }
+ table.getControl().setLayoutData(gd);
+ item.setControl(c);
+ folder.setSelection(item);
+ lastSelectedTab = 1;
+ }
+
+ public IDataSet getDataSet() {
+ return dataSet;
+ }
+
+ /**
+ * Finds the graph that is open in the current tab
+ * @return The graph that is currently visible on the screen
+ */
+ public AbstractChartBuilder getActiveGraph() {
+ if(0 == builders.size() || folder.getSelectionIndex() < 2) {
+ return null;
+ }
+ return builders.get(folder.getSelectionIndex()-2);
+ }
+
+ /**
+ * Removes all internal references in this class. Nothing should make any references
+ * to anything in this class after calling the dispose method.
+ */
+ public void dispose() {
+ if(null != updater && updater.isRunning()) {
+ updater.dispose();
+ }
+ updater = null;
+
+ p.removePropertyChangeListener(propertyChangeListener);
+ propertyChangeListener = null;
+
+ dataSet = null;
+ if(null != folder && !folder.isDisposed()) {
+ folder.removeSelectionListener(listener);
+ folder.dispose();
+ folder = null;
+ }
+ listener = null;
+
+ for (AbstractChartBuilder builder : builders) {
+ builder.dispose();
+ }
+ builders.clear();
+ }
+
+ /**
+ * This class handles switching between tabs and creating new graphs.
+ * When the user selects the first tab a new dialog is displayed for
+ * them to select what they want to display for the new graph.
+ */
+ private class ButtonClickListener extends SelectionAdapter {
+ @Override
+ public void widgetSelected(SelectionEvent event) {
+ CTabFolder folder = (CTabFolder)event.getSource();
+
+ if(folder.getSelectionIndex() == 0) {
+ folder.setSelection(lastSelectedTab);
+ SelectGraphAndSeriesWizard wizard = new SelectGraphAndSeriesWizard(dataSet, null);
+ IWorkbench workbench = PlatformUI.getWorkbench();
+ wizard.init(workbench, null);
+ WizardDialog dialog = new WizardDialog(workbench.getActiveWorkbenchWindow().getShell(), wizard);
+ dialog.create();
+ dialog.open();
+
+ GraphData gd = wizard.getGraphData();
+
+ if(null != gd) {
+ addGraph(gd);
+ }
+ wizard.dispose();
+ fireTabOpenEvent();
+ }
+ lastSelectedTab = folder.getSelectionIndex();
+ fireTabChangedEvent();
+ }
+ }
+
+ public void addTabListener(ITabListener listener) {
+ tabListeners.add(listener);
+ }
+
+ private void fireTabCloseEvent() {
+ for(int i=0; i<tabListeners.size(); i++) {
+ (tabListeners.get(i)).tabClosed();
+ }
+ }
+
+ private void fireTabOpenEvent() {
+ for(int i=0; i<tabListeners.size(); i++) {
+ (tabListeners.get(i)).tabOpened();
+ }
+ }
+
+ private void fireTabChangedEvent() {
+ for(int i=0; i<tabListeners.size(); i++) {
+ (tabListeners.get(i)).tabChanged();
+ }
+ }
+
+ public void addGraph(GraphData gd) {
+ CTabItem item = new CTabItem(folder, SWT.CLOSE);
+ item.setText(MessageFormat.format(Localization.getString("GraphDisplaySet.GraphTabTitle"), //$NON-NLS-1$
+ gd.title, GraphFactory.getGraphName(gd.graphID)));
+ final GraphComposite gc = new GraphComposite(folder, SWT.FILL, gd, dataSet);
+ gc.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ gc.addCheckOption("Legend", new SelectionAdapter() { //$NON-NLS-1$
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ gc.setLegendVisible(((Button)e.getSource()).getSelection());
+ }
+ });
+ folder.setSelection(item);
+
+ AbstractChartBuilder g = gc.getCanvas();
+ item.setControl(gc);
+
+ if(null != g) {
+ if(null != updater) {
+ updater.addUpdateListener(g);
+ }
+ builders.add(g);
+ }
+ }
+
+ private int lastSelectedTab;
+ private IFilteredDataSet dataSet;
+ private CTabFolder folder;
+ private ButtonClickListener listener;
+ private UpdateManager updater;
+ private List<ITabListener> tabListeners;
+
+ private List<AbstractChartBuilder> builders;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/charts/AbstractChartBuilder.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/charts/AbstractChartBuilder.java
index ada3702676..54c848e58d 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/charts/AbstractChartBuilder.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/charts/AbstractChartBuilder.java
@@ -40,354 +40,354 @@ import org.swtchart.ITitle;
*/
public abstract class AbstractChartBuilder extends Composite implements IUpdateListener{
- /**
- * Font name for all titles, labels, and values.
- */
- protected final static String FONT_NAME = "MS Sans Serif"; //$NON-NLS-1$
- protected int maxItems;
- protected double scale = 1.0;
- /**
- * @since 3.0
- */
- protected double scaleY = 1.0;
- /**
- * @since 3.0
- */
- protected double scroll = 1.0;
- /**
- * @since 3.0
- */
- protected double scrollY = 1.0;
-
- /**
- * Provides data for chart.
- */
- protected IAdapter adapter = null;
- protected int xseries;
- protected int[] yseries;
-
- protected static final Color WHITE = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
- protected static final Color BLACK = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
- protected static final Color RED = Display.getDefault().getSystemColor(SWT.COLOR_RED);
-
- protected static final Color[] COLORS = {
- RED,
- Display.getDefault().getSystemColor(SWT.COLOR_GREEN),
- Display.getDefault().getSystemColor(SWT.COLOR_BLUE),
- Display.getDefault().getSystemColor(SWT.COLOR_YELLOW),
- Display.getDefault().getSystemColor(SWT.COLOR_MAGENTA),
- Display.getDefault().getSystemColor(SWT.COLOR_CYAN),
- BLACK,
- new Color(Display.getDefault(), 64, 128, 128),
- new Color(Display.getDefault(), 255, 165, 0),
- new Color(Display.getDefault(), 128, 128, 128),
- };
- /**
- * Chart instance.
- */
- protected Chart chart = null;
-
- /**
- * Chart title.
- */
- protected String title = null;
-
- private List<IUpdateListener> listeners = new ArrayList<>();
-
- /**
- * The mouse listener that watches for MouseMove events over a specified region.
- * It is null by default.
- * @since 3.0
- */
- protected ChartMouseMoveListener chartMouseMoveListener = null;
-
- public abstract void updateDataSet();
-
- /**
- * A reference to the SystemTap Graphing preference store.
- * @since 3.0
- */
- protected IPreferenceStore store;
- /**
- * Updates the chart with properties read from user-set preferences. It is called automatically
- * whenever a change is made to SystemTap Graphing preferences.
- * @param event The update event containing details on the preference that was changed.
- * @since 3.0
- */
- protected void updateProperties(PropertyChangeEvent event) {
- if (event.getProperty().equals(GraphingPreferenceConstants.P_VIEWABLE_DATA_ITEMS)
- || event.getProperty().equals(GraphingPreferenceConstants.P_MAX_DATA_ITEMS)) {
- maxItems = Math.min(store.getInt(GraphingPreferenceConstants.P_VIEWABLE_DATA_ITEMS),
- store.getInt(GraphingPreferenceConstants.P_MAX_DATA_ITEMS));
- updateDataSet();
- }
- }
- private IPropertyChangeListener propertyChangeListener;
-
- /**
- * Constructs one chart builder and associate it to one data set.
- */
- public AbstractChartBuilder(IAdapter adapter, Composite parent, int style, String title) {
- super(parent, style);
- this.adapter = adapter;
- this.title = title;
- this.setLayout(new FillLayout());
-
- store = GraphingUIPlugin.getDefault().getPreferenceStore();
- maxItems = Math.min(store.getInt(GraphingPreferenceConstants.P_VIEWABLE_DATA_ITEMS),
- store.getInt(GraphingPreferenceConstants.P_MAX_DATA_ITEMS));
-
- propertyChangeListener = new IPropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- updateProperties(event);
- }
- };
- store.addPropertyChangeListener(propertyChangeListener);
- }
-
- @Override
- public void dispose() {
- store.removePropertyChangeListener(propertyChangeListener);
- propertyChangeListener = null;
- super.dispose();
- }
-
- /**
- * Builds one chart.
- */
- public void build() {
- createChart();
- buildPlot();
- buildLegend();
- buildTitle();
- buildXAxis();
- buildYAxis();
- buildXSeries();
- buildYSeries();
- updateDataSet();
- }
-
- /**
- * Creates chart instance.
- */
- protected void createChart() {
- this.chart = new Chart(this, getStyle());
- }
-
- /**
- * Builds plot.
- */
- private void buildPlot() {
- this.chart.setBackground(WHITE);
- this.chart.setBackgroundInPlotArea(WHITE);
- }
-
- /**
- * Builds X axis.
- */
- protected void buildXAxis() {}
-
- /**
- * Builds Y axis.
- */
- protected void buildYAxis() {}
-
- /**
- * Builds X series.
- */
- protected void buildXSeries() {}
-
- /**
- * Builds Y series.
- */
- protected void buildYSeries() {}
-
- /**
- * Builds legend.
- *
- */
- private void buildLegend() {
- chart.getLegend().setPosition(SWT.RIGHT);
- }
-
- /**
- * Builds the chart title.
- */
- private void buildTitle() {
- ITitle ctitle = chart.getTitle();
- ctitle.setForeground(BLACK);
- ctitle.setText(this.title);
- }
-
- /**
- * Returns the chart instance.
- *
- * @return the chart instance
- */
- public Chart getChart() {
- return chart;
- }
-
- public void setScale(double scale) {
- if (scale < 0) {
- this.scale = 0;
- } else if (scale > 1) {
- this.scale = 1;
- } else {
- this.scale = scale;
- }
- handleUpdateEvent();
- }
-
- /**
- * @since 3.0
- * @return The current horizontal scale of the chart.
- */
- public double getScale() {
- return this.scale;
- }
-
- /**
- * @since 3.0
- */
- public void setScaleY(double scale) {
- if (scale < 0) {
- this.scaleY = 0;
- } else if (scale > 1) {
- this.scaleY = 1;
- } else {
- this.scaleY = scale;
- }
- handleUpdateEvent();
- }
-
- /**
- * @since 3.0
- * @return The current vertical scale of the chart.
- */
- public double getScaleY() {
- return this.scaleY;
- }
-
- /**
- * @since 3.0
- */
- public void setScroll(double scroll) {
- if (scroll < 0) {
- this.scroll = 0;
- } else if (scroll > 1) {
- this.scroll = 1;
- } else {
- this.scroll = scroll;
- }
- handleUpdateEvent();
- }
-
- /**
- * @since 3.0
- * @return The current horizontal scroll of the chart.
- */
- public double getScroll() {
- return this.scroll;
- }
-
- /**
- * @since 3.0
- */
- public void setScrollY(double scroll) {
- if (scroll < 0) {
- this.scrollY = 0;
- } else if (scroll > 1) {
- this.scrollY = 1;
- } else {
- this.scrollY = scroll;
- }
- handleUpdateEvent();
- }
-
- /**
- * @since 3.0
- * @return The current vertical scroll of the chart.
- */
- public double getScrollY() {
- return this.scrollY;
- }
-
- /**
- * @since 3.0
- */
- protected Double getDoubleOrNullValue(Object o) {
- if (o == null) {
- return null;
- }
- if (o instanceof Integer) {
- return ((Integer)o).doubleValue();
- }
- if (o instanceof Double) {
- return (Double) o;
- }
- try {
- return new Double(o.toString());
- } catch (NumberFormatException e) {
- return null;
- }
- }
-
- @Override
- public void handleUpdateEvent() {
- if (chart != null && !chart.isDisposed()) {
- repaint();
- }
- }
-
- /**
- * @since 3.0
- */
- public void addUpdateListener(IUpdateListener l) {
- listeners.add(l);
- }
-
- /**
- * @since 3.0
- */
- public boolean removeUpdateListener(IUpdateListener l) {
- return listeners.remove(l);
- }
-
- private void repaint() {
- getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- if (!chart.isDisposed()) {
- updateDataSet();
- for (IUpdateListener l : listeners) {
- l.handleUpdateEvent();
- }
- }
+ /**
+ * Font name for all titles, labels, and values.
+ */
+ protected final static String FONT_NAME = "MS Sans Serif"; //$NON-NLS-1$
+ protected int maxItems;
+ protected double scale = 1.0;
+ /**
+ * @since 3.0
+ */
+ protected double scaleY = 1.0;
+ /**
+ * @since 3.0
+ */
+ protected double scroll = 1.0;
+ /**
+ * @since 3.0
+ */
+ protected double scrollY = 1.0;
+
+ /**
+ * Provides data for chart.
+ */
+ protected IAdapter adapter = null;
+ protected int xseries;
+ protected int[] yseries;
+
+ protected static final Color WHITE = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+ protected static final Color BLACK = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
+ protected static final Color RED = Display.getDefault().getSystemColor(SWT.COLOR_RED);
+
+ protected static final Color[] COLORS = {
+ RED,
+ Display.getDefault().getSystemColor(SWT.COLOR_GREEN),
+ Display.getDefault().getSystemColor(SWT.COLOR_BLUE),
+ Display.getDefault().getSystemColor(SWT.COLOR_YELLOW),
+ Display.getDefault().getSystemColor(SWT.COLOR_MAGENTA),
+ Display.getDefault().getSystemColor(SWT.COLOR_CYAN),
+ BLACK,
+ new Color(Display.getDefault(), 64, 128, 128),
+ new Color(Display.getDefault(), 255, 165, 0),
+ new Color(Display.getDefault(), 128, 128, 128),
+ };
+ /**
+ * Chart instance.
+ */
+ protected Chart chart = null;
+
+ /**
+ * Chart title.
+ */
+ protected String title = null;
+
+ private List<IUpdateListener> listeners = new ArrayList<>();
+
+ /**
+ * The mouse listener that watches for MouseMove events over a specified region.
+ * It is null by default.
+ * @since 3.0
+ */
+ protected ChartMouseMoveListener chartMouseMoveListener = null;
+
+ public abstract void updateDataSet();
+
+ /**
+ * A reference to the SystemTap Graphing preference store.
+ * @since 3.0
+ */
+ protected IPreferenceStore store;
+ /**
+ * Updates the chart with properties read from user-set preferences. It is called automatically
+ * whenever a change is made to SystemTap Graphing preferences.
+ * @param event The update event containing details on the preference that was changed.
+ * @since 3.0
+ */
+ protected void updateProperties(PropertyChangeEvent event) {
+ if (event.getProperty().equals(GraphingPreferenceConstants.P_VIEWABLE_DATA_ITEMS)
+ || event.getProperty().equals(GraphingPreferenceConstants.P_MAX_DATA_ITEMS)) {
+ maxItems = Math.min(store.getInt(GraphingPreferenceConstants.P_VIEWABLE_DATA_ITEMS),
+ store.getInt(GraphingPreferenceConstants.P_MAX_DATA_ITEMS));
+ updateDataSet();
+ }
+ }
+ private IPropertyChangeListener propertyChangeListener;
+
+ /**
+ * Constructs one chart builder and associate it to one data set.
+ */
+ public AbstractChartBuilder(IAdapter adapter, Composite parent, int style, String title) {
+ super(parent, style);
+ this.adapter = adapter;
+ this.title = title;
+ this.setLayout(new FillLayout());
+
+ store = GraphingUIPlugin.getDefault().getPreferenceStore();
+ maxItems = Math.min(store.getInt(GraphingPreferenceConstants.P_VIEWABLE_DATA_ITEMS),
+ store.getInt(GraphingPreferenceConstants.P_MAX_DATA_ITEMS));
+
+ propertyChangeListener = new IPropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ updateProperties(event);
}
- });
- }
-
- /**
- * Given an array of label strings, returns a new array in which all duplicate labels
- * have been given unique names.
- * @return A new array containing unique label names.
- * @since 3.0
- */
- protected String[] getUniqueNames(String[] labels) {
- Set<String> labelsUnique = new LinkedHashSet<>();
- for (String label : labels) {
- int count = 1;
- while (!labelsUnique.add(makeCountedLabel(label, count))) {
- count++;
- }
- }
- return labelsUnique.toArray(new String[labels.length]);
- }
-
- private String makeCountedLabel(String original, int count) {
- return count <= 1 ? original : original.concat(String.format(" (%d)", count)); //$NON-NLS-1$
- }
+ };
+ store.addPropertyChangeListener(propertyChangeListener);
+ }
+
+ @Override
+ public void dispose() {
+ store.removePropertyChangeListener(propertyChangeListener);
+ propertyChangeListener = null;
+ super.dispose();
+ }
+
+ /**
+ * Builds one chart.
+ */
+ public void build() {
+ createChart();
+ buildPlot();
+ buildLegend();
+ buildTitle();
+ buildXAxis();
+ buildYAxis();
+ buildXSeries();
+ buildYSeries();
+ updateDataSet();
+ }
+
+ /**
+ * Creates chart instance.
+ */
+ protected void createChart() {
+ this.chart = new Chart(this, getStyle());
+ }
+
+ /**
+ * Builds plot.
+ */
+ private void buildPlot() {
+ this.chart.setBackground(WHITE);
+ this.chart.setBackgroundInPlotArea(WHITE);
+ }
+
+ /**
+ * Builds X axis.
+ */
+ protected void buildXAxis() {}
+
+ /**
+ * Builds Y axis.
+ */
+ protected void buildYAxis() {}
+
+ /**
+ * Builds X series.
+ */
+ protected void buildXSeries() {}
+
+ /**
+ * Builds Y series.
+ */
+ protected void buildYSeries() {}
+
+ /**
+ * Builds legend.
+ *
+ */
+ private void buildLegend() {
+ chart.getLegend().setPosition(SWT.RIGHT);
+ }
+
+ /**
+ * Builds the chart title.
+ */
+ private void buildTitle() {
+ ITitle ctitle = chart.getTitle();
+ ctitle.setForeground(BLACK);
+ ctitle.setText(this.title);
+ }
+
+ /**
+ * Returns the chart instance.
+ *
+ * @return the chart instance
+ */
+ public Chart getChart() {
+ return chart;
+ }
+
+ public void setScale(double scale) {
+ if (scale < 0) {
+ this.scale = 0;
+ } else if (scale > 1) {
+ this.scale = 1;
+ } else {
+ this.scale = scale;
+ }
+ handleUpdateEvent();
+ }
+
+ /**
+ * @since 3.0
+ * @return The current horizontal scale of the chart.
+ */
+ public double getScale() {
+ return this.scale;
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void setScaleY(double scale) {
+ if (scale < 0) {
+ this.scaleY = 0;
+ } else if (scale > 1) {
+ this.scaleY = 1;
+ } else {
+ this.scaleY = scale;
+ }
+ handleUpdateEvent();
+ }
+
+ /**
+ * @since 3.0
+ * @return The current vertical scale of the chart.
+ */
+ public double getScaleY() {
+ return this.scaleY;
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void setScroll(double scroll) {
+ if (scroll < 0) {
+ this.scroll = 0;
+ } else if (scroll > 1) {
+ this.scroll = 1;
+ } else {
+ this.scroll = scroll;
+ }
+ handleUpdateEvent();
+ }
+
+ /**
+ * @since 3.0
+ * @return The current horizontal scroll of the chart.
+ */
+ public double getScroll() {
+ return this.scroll;
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void setScrollY(double scroll) {
+ if (scroll < 0) {
+ this.scrollY = 0;
+ } else if (scroll > 1) {
+ this.scrollY = 1;
+ } else {
+ this.scrollY = scroll;
+ }
+ handleUpdateEvent();
+ }
+
+ /**
+ * @since 3.0
+ * @return The current vertical scroll of the chart.
+ */
+ public double getScrollY() {
+ return this.scrollY;
+ }
+
+ /**
+ * @since 3.0
+ */
+ protected Double getDoubleOrNullValue(Object o) {
+ if (o == null) {
+ return null;
+ }
+ if (o instanceof Integer) {
+ return ((Integer)o).doubleValue();
+ }
+ if (o instanceof Double) {
+ return (Double) o;
+ }
+ try {
+ return new Double(o.toString());
+ } catch (NumberFormatException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public void handleUpdateEvent() {
+ if (chart != null && !chart.isDisposed()) {
+ repaint();
+ }
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void addUpdateListener(IUpdateListener l) {
+ listeners.add(l);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public boolean removeUpdateListener(IUpdateListener l) {
+ return listeners.remove(l);
+ }
+
+ private void repaint() {
+ getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ if (!chart.isDisposed()) {
+ updateDataSet();
+ for (IUpdateListener l : listeners) {
+ l.handleUpdateEvent();
+ }
+ }
+ }
+ });
+ }
+
+ /**
+ * Given an array of label strings, returns a new array in which all duplicate labels
+ * have been given unique names.
+ * @return A new array containing unique label names.
+ * @since 3.0
+ */
+ protected String[] getUniqueNames(String[] labels) {
+ Set<String> labelsUnique = new LinkedHashSet<>();
+ for (String label : labels) {
+ int count = 1;
+ while (!labelsUnique.add(makeCountedLabel(label, count))) {
+ count++;
+ }
+ }
+ return labelsUnique.toArray(new String[labels.length]);
+ }
+
+ private String makeCountedLabel(String original, int count) {
+ return count <= 1 ? original : original.concat(String.format(" (%d)", count)); //$NON-NLS-1$
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/datadisplay/DataGrid.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/datadisplay/DataGrid.java
index 6928884b3a..f452474f3a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/datadisplay/DataGrid.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/datadisplay/DataGrid.java
@@ -50,330 +50,330 @@ import org.eclipse.ui.PlatformUI;
public class DataGrid implements IUpdateListener {
- /**
- * @since 3.0 set must be a IFilteredDataSet.
- */
- public DataGrid(Composite composite, IFilteredDataSet set) {
- prefs = GraphingUIPlugin.getDefault().getPreferenceStore();
- manualResize = !prefs.getBoolean(GraphingPreferenceConstants.P_AUTO_RESIZE);
-
- filteredDataSet = set;
- clickLocation = new Point(-1, -1);
- createPartControl(composite);
-
- propertyChangeListener = new IPropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(GraphingPreferenceConstants.P_MAX_DATA_ITEMS)) {
- handleUpdateEvent();
- }
- }
- };
- prefs.addPropertyChangeListener(propertyChangeListener);
- }
-
- public Control getControl() { return table; }
-
- private void createPartControl(Composite parent) {
- table = new Table(parent, SWT.SINGLE | SWT.FULL_SELECTION);
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
- table.getVerticalBar().setVisible(true);
-
- String[] names = filteredDataSet.getTitles();
- TableColumn column = new TableColumn(table, SWT.LEFT);
- column.setText(Localization.getString("DataGrid.Row")); //$NON-NLS-1$
- column.pack();
- column.setMoveable(false);
- column.setResizable(false);
-
- columnFormat = new IFormattingStyles[names.length];
- for(int i=0; i<names.length; i++) {
- column = new TableColumn(table, SWT.LEFT);
- column.setText(names[i]);
- column.pack();
- column.setMoveable(true);
-
- columnFormat[i] = new StringFormatter();
- }
-
- table.setMenu(this.initMenus());
-
- table.addListener(SWT.MouseDown, new Listener() {
- @Override
- public void handleEvent(Event event) {
- clickLocation.x = event.x;
- clickLocation.y = event.y;
- }
- });
- handleUpdateEvent();
- }
-
- private Menu initMenus() {
- Menu menu = new Menu(table.getShell(), SWT.POP_UP);
- menu.addMenuListener(new MainMenuListener());
-
- Menu formatMenu = new Menu(menu);
- formatMenuItem = new MenuItem(menu, SWT.CASCADE);
- formatMenuItem.setText(Localization.getString("DataGrid.FormatAs")); //$NON-NLS-1$
- formatMenuItem.setMenu(formatMenu);
-
- filterMenu = new Menu(menu);
- MenuItem item = new MenuItem(menu, SWT.CASCADE);
- item.setText(Localization.getString("DataGrid.AddFilter")); //$NON-NLS-1$
- item.addSelectionListener(new AddFilterSelection());
-
- removeFiltersMenuItem = new MenuItem(menu, SWT.CASCADE);
- removeFiltersMenuItem.setText(Localization.getString("DataGrid.RemoveFilter")); //$NON-NLS-1$
- removeFiltersMenuItem.setMenu(filterMenu);
-
- IDataSetFilter[] filters = filteredDataSet.getFilters();
- if(null != filters && filters.length > 0) {
- for(int i=0; i<filters.length; i++) {
- item = new MenuItem(filterMenu, SWT.CASCADE);
- item.setText(AvailableFilterTypes.getFilterName(filters[i].getID()));
- item.setData(filters[i]);
- item.addSelectionListener(new RemoveFilterSelection());
- }
- } else {
- removeFiltersMenuItem.setEnabled(false);
- }
-
- item = new MenuItem(menu, SWT.CHECK);
- item.setText(Localization.getString("DataGrid.ManualyResize")); //$NON-NLS-1$
- item.addSelectionListener(new MenuManualyResizedSelection());
-
- for(int i=0; i<IFormattingStyles.FORMAT_TITLES.length; i++) {
- item = new MenuItem(formatMenu, SWT.RADIO);
- item.setText(IFormattingStyles.FORMAT_TITLES[i]);
- item.addSelectionListener(new MenuFormatSelection());
- }
-
- formatMenuItem.setEnabled(filteredDataSet.getRowCount() > 0);
- formatMenu.addMenuListener(new FormatMenuListener());
- return menu;
- }
-
- private int getSelectedColumn() {
- TableColumn[] cols = table.getColumns();
- int location = 0;
- for(int i=0; i<cols.length; i++) {
- if(clickLocation.x > location && clickLocation.x < (location+=cols[i].getWidth())) {
- return i;
- }
- }
-
- return cols.length-1;
- }
-
- private class MainMenuListener extends MenuAdapter {
- @Override
- public void menuShown(MenuEvent e) {
- MenuItem item = ((Menu)e.widget).getItem(1);
- item.setSelection(manualResize);
- }
- }
-
- private class MenuManualyResizedSelection extends SelectionAdapter {
- @Override
- public void widgetSelected(SelectionEvent e) {
- manualResize = !manualResize;
- }
- }
-
- private class AddFilterSelection extends SelectionAdapter {
- @Override
- public void widgetSelected(SelectionEvent e) {
- SelectFilterWizard wizard = new SelectFilterWizard(filteredDataSet.getTitles());
- IWorkbench workbench = PlatformUI.getWorkbench();
- wizard.init(workbench, null);
- WizardDialog dialog = new WizardDialog(workbench.getActiveWorkbenchWindow().getShell(), wizard);
- dialog.create();
- int result = dialog.open();
-
- if(result != Window.CANCEL) {
- IDataSetFilter filter = wizard.getFilter();
- removeFiltersMenuItem.setEnabled(true);
- filteredDataSet.addFilter(filter);
- table.removeAll();
- handleUpdateEvent();
-
- MenuItem item = new MenuItem(filterMenu, SWT.CASCADE);
- item.setText(MessageFormat.format(Localization.getString("DataGrid.FilterLabel"), //$NON-NLS-1$
- AvailableFilterTypes.getFilterName(filter.getID()), filteredDataSet.getTitles()[filter.getColumn()], filter.getInfo()));
- item.setData(filter);
- item.addSelectionListener(new RemoveFilterSelection());
- }
- wizard.dispose();
- }
- }
-
- private class RemoveFilterSelection implements SelectionListener {
- @Override
- public void widgetSelected(SelectionEvent e) {
- IDataSetFilter idsf = (IDataSetFilter)((MenuItem)e.widget).getData();
- e.widget.dispose();
- if (filterMenu.getItemCount() == 0) {
- removeFiltersMenuItem.setEnabled(false);
- }
-
- if(filteredDataSet.removeFilter(idsf)) {
- table.removeAll();
- handleUpdateEvent();
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {}
- }
-
- private class FormatMenuListener extends MenuAdapter {
- @Override
- public void menuShown(MenuEvent e) {
- MenuItem[] items = ((Menu)e.widget).getItems();
- boolean doubleValid = false, longValid = false;
- String itemText;
-
- int selectedCol = Math.max(1, getSelectedColumn());
-
- for(int i=0; i<items.length; i++) {
- items[i].setSelection(false);
- }
- items[columnFormat[selectedCol-1].getFormat()].setSelection(true);
-
- items[IFormattingStyles.UNFORMATED].setEnabled(true);
- items[IFormattingStyles.STRING].setEnabled(true);
-
- itemText = filteredDataSet.getRow(0)[selectedCol-1].toString();
- try {
- Double.parseDouble(itemText);
- doubleValid = true;
- } catch(NumberFormatException nfe) {}
- try {
- Long.parseLong(itemText);
- longValid = true;
- } catch(NumberFormatException nfe) {}
-
- items[IFormattingStyles.DOUBLE].setEnabled(doubleValid);
- items[IFormattingStyles.HEX].setEnabled(longValid);
- items[IFormattingStyles.OCTAL].setEnabled(longValid);
- items[IFormattingStyles.BINARY].setEnabled(longValid);
- items[IFormattingStyles.DATE].setEnabled(longValid);
- }
- }
-
- private class MenuFormatSelection extends SelectionAdapter {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int format = IFormattingStyles.UNFORMATED;
- int column = Math.max(1, getSelectedColumn());
- int i;
- for(i=0; i<IFormattingStyles.FORMAT_TITLES.length; i++) {
- if(IFormattingStyles.FORMAT_TITLES[i].equals(((MenuItem)e.getSource()).getText())) {
- format = i;
- }
- }
-
- Object[] data = filteredDataSet.getColumn(column-1);
- columnFormat[column-1].setFormat(format);
- for(i=0; i<table.getItemCount(); i++) {
- table.getItem(i).setText(column, columnFormat[column-1].format(data[i].toString()));
- }
- table.redraw();
- }
- }
-
- @Override
- public void handleUpdateEvent() {
- if(table.isDisposed()) {
- return;
- }
-
- table.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- if (table.isDisposed()) {
- return;
- }
- TableItem item;
- int startLocation;
- int endLocation = filteredDataSet.getRowCount();
- int maxItems = prefs.getInt(GraphingPreferenceConstants.P_MAX_DATA_ITEMS);
- int oldSelection = table.getSelectionIndex();
-
- //Remove old items to refresh table, and only read in as many items as will fit.
- //Note that a full refresh is necessary in order for filtered data to appear correctly.
- table.removeAll();
- startLocation = Math.max(endLocation-maxItems, 0);
-
- //Add all the new items to the table
- Object[] os;
- for(int j,i=startLocation; i<endLocation; i++) {
- item = new TableItem(table, SWT.NONE);
- os = filteredDataSet.getRow(i);
-
- //Add 1 to the index/row num since graphs start counting rows at 1, not 0.
- item.setText(0, Integer.toString(i + 1));
- for(j=0; j<os.length; j++) {
- //Ignore null items
- if (os[j] != null) {
- item.setText(j+1, columnFormat[j].format(os[j].toString()));
- }
- }
- }
- //Re-select the old table selection, if there was one
- if (oldSelection != -1) {
- table.select(oldSelection);
- }
-
- //Resize the columns
- TableColumn col = table.getColumn(0);
- col.pack();
- if(!manualResize) {
- TableColumn[] cols = table.getColumns();
- for(int i=1; i<cols.length; i++) {
- cols[i].pack();
- }
- }
-
- //Use if we want to set focus to newly added item.
- //Run async so the table can be fully constructed before jumping to an entry.
- if(prefs.getBoolean(GraphingPreferenceConstants.P_JUMP_NEW_TABLE_ENTRY)
- && table.getItemCount() > 0) {
- table.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- table.showItem(table.getItem(table.getItemCount()-1));
- }
- });
- }
- formatMenuItem.setEnabled(table.getItemCount() > 0);
- }
- });
- }
-
- public void dispose() {
- filteredDataSet = null;
- table.dispose();
- table = null;
- clickLocation = null;
- columnFormat = null;
- prefs.removePropertyChangeListener(propertyChangeListener);
- propertyChangeListener = null;
- }
-
- private IFilteredDataSet filteredDataSet;
- private IFormattingStyles columnFormat[];
- private Table table;
- private Point clickLocation;
- private IPreferenceStore prefs;
- private boolean manualResize;
- private Menu filterMenu;
-
- private MenuItem removeFiltersMenuItem;
- private MenuItem formatMenuItem;
- private IPropertyChangeListener propertyChangeListener;
-
- public static final int NONE = 0;
- public static final int FULL_UPDATE = 1;
+ /**
+ * @since 3.0 set must be a IFilteredDataSet.
+ */
+ public DataGrid(Composite composite, IFilteredDataSet set) {
+ prefs = GraphingUIPlugin.getDefault().getPreferenceStore();
+ manualResize = !prefs.getBoolean(GraphingPreferenceConstants.P_AUTO_RESIZE);
+
+ filteredDataSet = set;
+ clickLocation = new Point(-1, -1);
+ createPartControl(composite);
+
+ propertyChangeListener = new IPropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ if (event.getProperty().equals(GraphingPreferenceConstants.P_MAX_DATA_ITEMS)) {
+ handleUpdateEvent();
+ }
+ }
+ };
+ prefs.addPropertyChangeListener(propertyChangeListener);
+ }
+
+ public Control getControl() { return table; }
+
+ private void createPartControl(Composite parent) {
+ table = new Table(parent, SWT.SINGLE | SWT.FULL_SELECTION);
+ table.setHeaderVisible(true);
+ table.setLinesVisible(true);
+ table.getVerticalBar().setVisible(true);
+
+ String[] names = filteredDataSet.getTitles();
+ TableColumn column = new TableColumn(table, SWT.LEFT);
+ column.setText(Localization.getString("DataGrid.Row")); //$NON-NLS-1$
+ column.pack();
+ column.setMoveable(false);
+ column.setResizable(false);
+
+ columnFormat = new IFormattingStyles[names.length];
+ for(int i=0; i<names.length; i++) {
+ column = new TableColumn(table, SWT.LEFT);
+ column.setText(names[i]);
+ column.pack();
+ column.setMoveable(true);
+
+ columnFormat[i] = new StringFormatter();
+ }
+
+ table.setMenu(this.initMenus());
+
+ table.addListener(SWT.MouseDown, new Listener() {
+ @Override
+ public void handleEvent(Event event) {
+ clickLocation.x = event.x;
+ clickLocation.y = event.y;
+ }
+ });
+ handleUpdateEvent();
+ }
+
+ private Menu initMenus() {
+ Menu menu = new Menu(table.getShell(), SWT.POP_UP);
+ menu.addMenuListener(new MainMenuListener());
+
+ Menu formatMenu = new Menu(menu);
+ formatMenuItem = new MenuItem(menu, SWT.CASCADE);
+ formatMenuItem.setText(Localization.getString("DataGrid.FormatAs")); //$NON-NLS-1$
+ formatMenuItem.setMenu(formatMenu);
+
+ filterMenu = new Menu(menu);
+ MenuItem item = new MenuItem(menu, SWT.CASCADE);
+ item.setText(Localization.getString("DataGrid.AddFilter")); //$NON-NLS-1$
+ item.addSelectionListener(new AddFilterSelection());
+
+ removeFiltersMenuItem = new MenuItem(menu, SWT.CASCADE);
+ removeFiltersMenuItem.setText(Localization.getString("DataGrid.RemoveFilter")); //$NON-NLS-1$
+ removeFiltersMenuItem.setMenu(filterMenu);
+
+ IDataSetFilter[] filters = filteredDataSet.getFilters();
+ if(null != filters && filters.length > 0) {
+ for(int i=0; i<filters.length; i++) {
+ item = new MenuItem(filterMenu, SWT.CASCADE);
+ item.setText(AvailableFilterTypes.getFilterName(filters[i].getID()));
+ item.setData(filters[i]);
+ item.addSelectionListener(new RemoveFilterSelection());
+ }
+ } else {
+ removeFiltersMenuItem.setEnabled(false);
+ }
+
+ item = new MenuItem(menu, SWT.CHECK);
+ item.setText(Localization.getString("DataGrid.ManualyResize")); //$NON-NLS-1$
+ item.addSelectionListener(new MenuManualyResizedSelection());
+
+ for(int i=0; i<IFormattingStyles.FORMAT_TITLES.length; i++) {
+ item = new MenuItem(formatMenu, SWT.RADIO);
+ item.setText(IFormattingStyles.FORMAT_TITLES[i]);
+ item.addSelectionListener(new MenuFormatSelection());
+ }
+
+ formatMenuItem.setEnabled(filteredDataSet.getRowCount() > 0);
+ formatMenu.addMenuListener(new FormatMenuListener());
+ return menu;
+ }
+
+ private int getSelectedColumn() {
+ TableColumn[] cols = table.getColumns();
+ int location = 0;
+ for(int i=0; i<cols.length; i++) {
+ if(clickLocation.x > location && clickLocation.x < (location+=cols[i].getWidth())) {
+ return i;
+ }
+ }
+
+ return cols.length-1;
+ }
+
+ private class MainMenuListener extends MenuAdapter {
+ @Override
+ public void menuShown(MenuEvent e) {
+ MenuItem item = ((Menu)e.widget).getItem(1);
+ item.setSelection(manualResize);
+ }
+ }
+
+ private class MenuManualyResizedSelection extends SelectionAdapter {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ manualResize = !manualResize;
+ }
+ }
+
+ private class AddFilterSelection extends SelectionAdapter {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ SelectFilterWizard wizard = new SelectFilterWizard(filteredDataSet.getTitles());
+ IWorkbench workbench = PlatformUI.getWorkbench();
+ wizard.init(workbench, null);
+ WizardDialog dialog = new WizardDialog(workbench.getActiveWorkbenchWindow().getShell(), wizard);
+ dialog.create();
+ int result = dialog.open();
+
+ if(result != Window.CANCEL) {
+ IDataSetFilter filter = wizard.getFilter();
+ removeFiltersMenuItem.setEnabled(true);
+ filteredDataSet.addFilter(filter);
+ table.removeAll();
+ handleUpdateEvent();
+
+ MenuItem item = new MenuItem(filterMenu, SWT.CASCADE);
+ item.setText(MessageFormat.format(Localization.getString("DataGrid.FilterLabel"), //$NON-NLS-1$
+ AvailableFilterTypes.getFilterName(filter.getID()), filteredDataSet.getTitles()[filter.getColumn()], filter.getInfo()));
+ item.setData(filter);
+ item.addSelectionListener(new RemoveFilterSelection());
+ }
+ wizard.dispose();
+ }
+ }
+
+ private class RemoveFilterSelection implements SelectionListener {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ IDataSetFilter idsf = (IDataSetFilter)((MenuItem)e.widget).getData();
+ e.widget.dispose();
+ if (filterMenu.getItemCount() == 0) {
+ removeFiltersMenuItem.setEnabled(false);
+ }
+
+ if(filteredDataSet.removeFilter(idsf)) {
+ table.removeAll();
+ handleUpdateEvent();
+ }
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {}
+ }
+
+ private class FormatMenuListener extends MenuAdapter {
+ @Override
+ public void menuShown(MenuEvent e) {
+ MenuItem[] items = ((Menu)e.widget).getItems();
+ boolean doubleValid = false, longValid = false;
+ String itemText;
+
+ int selectedCol = Math.max(1, getSelectedColumn());
+
+ for(int i=0; i<items.length; i++) {
+ items[i].setSelection(false);
+ }
+ items[columnFormat[selectedCol-1].getFormat()].setSelection(true);
+
+ items[IFormattingStyles.UNFORMATED].setEnabled(true);
+ items[IFormattingStyles.STRING].setEnabled(true);
+
+ itemText = filteredDataSet.getRow(0)[selectedCol-1].toString();
+ try {
+ Double.parseDouble(itemText);
+ doubleValid = true;
+ } catch(NumberFormatException nfe) {}
+ try {
+ Long.parseLong(itemText);
+ longValid = true;
+ } catch(NumberFormatException nfe) {}
+
+ items[IFormattingStyles.DOUBLE].setEnabled(doubleValid);
+ items[IFormattingStyles.HEX].setEnabled(longValid);
+ items[IFormattingStyles.OCTAL].setEnabled(longValid);
+ items[IFormattingStyles.BINARY].setEnabled(longValid);
+ items[IFormattingStyles.DATE].setEnabled(longValid);
+ }
+ }
+
+ private class MenuFormatSelection extends SelectionAdapter {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ int format = IFormattingStyles.UNFORMATED;
+ int column = Math.max(1, getSelectedColumn());
+ int i;
+ for(i=0; i<IFormattingStyles.FORMAT_TITLES.length; i++) {
+ if(IFormattingStyles.FORMAT_TITLES[i].equals(((MenuItem)e.getSource()).getText())) {
+ format = i;
+ }
+ }
+
+ Object[] data = filteredDataSet.getColumn(column-1);
+ columnFormat[column-1].setFormat(format);
+ for(i=0; i<table.getItemCount(); i++) {
+ table.getItem(i).setText(column, columnFormat[column-1].format(data[i].toString()));
+ }
+ table.redraw();
+ }
+ }
+
+ @Override
+ public void handleUpdateEvent() {
+ if(table.isDisposed()) {
+ return;
+ }
+
+ table.getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ if (table.isDisposed()) {
+ return;
+ }
+ TableItem item;
+ int startLocation;
+ int endLocation = filteredDataSet.getRowCount();
+ int maxItems = prefs.getInt(GraphingPreferenceConstants.P_MAX_DATA_ITEMS);
+ int oldSelection = table.getSelectionIndex();
+
+ //Remove old items to refresh table, and only read in as many items as will fit.
+ //Note that a full refresh is necessary in order for filtered data to appear correctly.
+ table.removeAll();
+ startLocation = Math.max(endLocation-maxItems, 0);
+
+ //Add all the new items to the table
+ Object[] os;
+ for(int j,i=startLocation; i<endLocation; i++) {
+ item = new TableItem(table, SWT.NONE);
+ os = filteredDataSet.getRow(i);
+
+ //Add 1 to the index/row num since graphs start counting rows at 1, not 0.
+ item.setText(0, Integer.toString(i + 1));
+ for(j=0; j<os.length; j++) {
+ //Ignore null items
+ if (os[j] != null) {
+ item.setText(j+1, columnFormat[j].format(os[j].toString()));
+ }
+ }
+ }
+ //Re-select the old table selection, if there was one
+ if (oldSelection != -1) {
+ table.select(oldSelection);
+ }
+
+ //Resize the columns
+ TableColumn col = table.getColumn(0);
+ col.pack();
+ if(!manualResize) {
+ TableColumn[] cols = table.getColumns();
+ for(int i=1; i<cols.length; i++) {
+ cols[i].pack();
+ }
+ }
+
+ //Use if we want to set focus to newly added item.
+ //Run async so the table can be fully constructed before jumping to an entry.
+ if(prefs.getBoolean(GraphingPreferenceConstants.P_JUMP_NEW_TABLE_ENTRY)
+ && table.getItemCount() > 0) {
+ table.getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ table.showItem(table.getItem(table.getItemCount()-1));
+ }
+ });
+ }
+ formatMenuItem.setEnabled(table.getItemCount() > 0);
+ }
+ });
+ }
+
+ public void dispose() {
+ filteredDataSet = null;
+ table.dispose();
+ table = null;
+ clickLocation = null;
+ columnFormat = null;
+ prefs.removePropertyChangeListener(propertyChangeListener);
+ propertyChangeListener = null;
+ }
+
+ private IFilteredDataSet filteredDataSet;
+ private IFormattingStyles columnFormat[];
+ private Table table;
+ private Point clickLocation;
+ private IPreferenceStore prefs;
+ private boolean manualResize;
+ private Menu filterMenu;
+
+ private MenuItem removeFiltersMenuItem;
+ private MenuItem formatMenuItem;
+ private IPropertyChangeListener propertyChangeListener;
+
+ public static final int NONE = 0;
+ public static final int FULL_UPDATE = 1;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/views/GraphSelectorEditor.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/views/GraphSelectorEditor.java
index 6f845f0211..397c085ee5 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/views/GraphSelectorEditor.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/views/GraphSelectorEditor.java
@@ -49,202 +49,202 @@ import org.eclipse.ui.part.EditorPart;
*/
public class GraphSelectorEditor extends EditorPart {
- private CTabFolder scriptFolder;
- private List<GraphDisplaySet> displaySets;
- private List<ITabListener> tabListeners;
- public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.views.GraphSelectorEditor"; //$NON-NLS-1$
-
- public GraphSelectorEditor() {
- super();
- displaySets = new ArrayList<>();
- tabListeners = new ArrayList<>();
- }
-
- /**
- * This method will create a new script set for each of the provided dataSets.
- * Each new script set will be given a new tab item at the end of the list.
- * @param scriptName The full name of the script that is being monitored.
- * @param titles The names to be shown on each new tab
- * @param dataSets The <code>IFilteredDataSet</code>s for each new script set
- * @since 2.2
- */
- public void createScriptSets(String scriptName, List<String> titles, List<IFilteredDataSet> dataSets) {
- CTabItem item = null;
-
- for (int i = 0, n = titles.size(); i < n; i++) {
- item = new CTabItem(scriptFolder, SWT.CLOSE);
- item.setText(titles.get(i));
- Composite parent = new Composite(scriptFolder, SWT.NONE);
- final GraphDisplaySet gds = new GraphDisplaySet(parent, dataSets.get(i));
- displaySets.add(gds);
- item.setControl(parent);
- item.addDisposeListener(new DisposeListener() {
-
- @Override
- public void widgetDisposed(DisposeEvent e) {
- gds.dispose();
- }
- });
- }
-
- scriptFolder.setSelection(item); // Choose the last created item.
- fireTabOpenEvent();
- this.setPartName(NLS.bind(Messages.GraphSelectorEditor_graphsEditorTitle, scriptName.substring(scriptName.lastIndexOf('/')+1)));
- }
-
- /**
- * This method creates the framework for what will be displayed by this dialog box.
- * @param parent The composite that will contain all the elements from this dialog
- */
- @Override
- public void createPartControl(Composite parent) {
- FormData data2 = new FormData();
- data2.left = new FormAttachment(0, 0);
- data2.top = new FormAttachment(0, 0);
- data2.right = new FormAttachment(100, 0);
- data2.bottom = new FormAttachment(100, 0);
- Composite cmpGraph = new Composite(parent, SWT.NONE);
- cmpGraph.setLayoutData(data2);
-
- //This is for the tab view
- cmpGraph.setLayout(new FormLayout());
-
- //Create the folder for all of the script sets, so it takes up all of the parent composite
- scriptFolder = new CTabFolder(cmpGraph, SWT.NONE);
- FormData data = new FormData();
- data.top = new FormAttachment(0, 0);
- data.left = new FormAttachment(0, 0);
- data.right = new FormAttachment(100, 0);
- data.bottom = new FormAttachment(100, 0);
- scriptFolder.setLayoutData(data);
- scriptFolder.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- fireTabChangedEvent();
- }
- });
-
-
- scriptFolder.addCTabFolder2Listener(new CTabFolder2Adapter() {
- @Override
- public void close(CTabFolderEvent e) {
- displaySets.remove(scriptFolder.indexOf((CTabItem)e.item));
- fireTabCloseEvent();
- }
- });
-
- }
-
- /**
- * Finds and returns the active component inside of the active script set
- * @return The <code>GraphDisplaySet</code> that is currently active
- * @since 2.0
- */
- public GraphDisplaySet getActiveDisplaySet() {
- return getDisplaySet(scriptFolder.getSelectionIndex());
- }
-
- /**
- * @return The title of the tab containing the active graph.
- * @since 3.0
- */
- public String getActiveTitle() {
- return scriptFolder.getSelection().getText();
- }
-
- /**
- * Finds and returns the component of the provided index.
- * @param index The index of the GraphDisplaySet to return
- * @return The <code>GraphDisplaySet</code> of the provided
- * index, or null if the index is out of range.
- * @since 2.2
- */
- public GraphDisplaySet getDisplaySet(int index) {
- if(index >= 0 && index < displaySets.size()) {
- return displaySets.get(index);
- } else {
- return null;
- }
- }
-
- @Override
- public void setFocus() {
- // Empty
- }
-
- /**
- * @since 2.0
- */
- public void addTabListener(ITabListener listener) {
- tabListeners.add(listener);
- }
-
- /**
- * @since 2.0
- */
- public void removeTabListener(ITabListener listener) {
- tabListeners.remove(listener);
- }
-
- private void fireTabCloseEvent() {
- for(ITabListener tabListener:tabListeners) {
- tabListener.tabClosed();
- }
- }
-
- private void fireTabOpenEvent() {
- for(ITabListener tabListener:tabListeners) {
- tabListener.tabOpened();
- }
- }
-
- private void fireTabChangedEvent() {
- for(ITabListener tabListener:tabListeners) {
- tabListener.tabChanged();
- }
- }
-
- /**
- * Removes all internal references in this class. Nothing should make any references
- * to anything in this class after calling the dispose method.
- */
- @Override
- public void dispose() {
- super.dispose();
-
- if(null != scriptFolder && !scriptFolder.isDisposed()) {
- scriptFolder.dispose();
- }
- scriptFolder = null;
- if(null != tabListeners) {
- tabListeners.clear();
- }
- tabListeners = null;
- }
-
- @Override
- public void doSave(IProgressMonitor monitor) {
- // TODO
- }
-
- @Override
- public void doSaveAs() {
- // TODO
- }
-
- @Override
- public void init(IEditorSite site, IEditorInput input) {
- setInput(input);
- setSite(site);
- }
-
- @Override
- public boolean isDirty() {
- return false;
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
+ private CTabFolder scriptFolder;
+ private List<GraphDisplaySet> displaySets;
+ private List<ITabListener> tabListeners;
+ public static final String ID = "org.eclipse.linuxtools.systemtap.graphing.ui.views.GraphSelectorEditor"; //$NON-NLS-1$
+
+ public GraphSelectorEditor() {
+ super();
+ displaySets = new ArrayList<>();
+ tabListeners = new ArrayList<>();
+ }
+
+ /**
+ * This method will create a new script set for each of the provided dataSets.
+ * Each new script set will be given a new tab item at the end of the list.
+ * @param scriptName The full name of the script that is being monitored.
+ * @param titles The names to be shown on each new tab
+ * @param dataSets The <code>IFilteredDataSet</code>s for each new script set
+ * @since 2.2
+ */
+ public void createScriptSets(String scriptName, List<String> titles, List<IFilteredDataSet> dataSets) {
+ CTabItem item = null;
+
+ for (int i = 0, n = titles.size(); i < n; i++) {
+ item = new CTabItem(scriptFolder, SWT.CLOSE);
+ item.setText(titles.get(i));
+ Composite parent = new Composite(scriptFolder, SWT.NONE);
+ final GraphDisplaySet gds = new GraphDisplaySet(parent, dataSets.get(i));
+ displaySets.add(gds);
+ item.setControl(parent);
+ item.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(DisposeEvent e) {
+ gds.dispose();
+ }
+ });
+ }
+
+ scriptFolder.setSelection(item); // Choose the last created item.
+ fireTabOpenEvent();
+ this.setPartName(NLS.bind(Messages.GraphSelectorEditor_graphsEditorTitle, scriptName.substring(scriptName.lastIndexOf('/')+1)));
+ }
+
+ /**
+ * This method creates the framework for what will be displayed by this dialog box.
+ * @param parent The composite that will contain all the elements from this dialog
+ */
+ @Override
+ public void createPartControl(Composite parent) {
+ FormData data2 = new FormData();
+ data2.left = new FormAttachment(0, 0);
+ data2.top = new FormAttachment(0, 0);
+ data2.right = new FormAttachment(100, 0);
+ data2.bottom = new FormAttachment(100, 0);
+ Composite cmpGraph = new Composite(parent, SWT.NONE);
+ cmpGraph.setLayoutData(data2);
+
+ //This is for the tab view
+ cmpGraph.setLayout(new FormLayout());
+
+ //Create the folder for all of the script sets, so it takes up all of the parent composite
+ scriptFolder = new CTabFolder(cmpGraph, SWT.NONE);
+ FormData data = new FormData();
+ data.top = new FormAttachment(0, 0);
+ data.left = new FormAttachment(0, 0);
+ data.right = new FormAttachment(100, 0);
+ data.bottom = new FormAttachment(100, 0);
+ scriptFolder.setLayoutData(data);
+ scriptFolder.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ fireTabChangedEvent();
+ }
+ });
+
+
+ scriptFolder.addCTabFolder2Listener(new CTabFolder2Adapter() {
+ @Override
+ public void close(CTabFolderEvent e) {
+ displaySets.remove(scriptFolder.indexOf((CTabItem)e.item));
+ fireTabCloseEvent();
+ }
+ });
+
+ }
+
+ /**
+ * Finds and returns the active component inside of the active script set
+ * @return The <code>GraphDisplaySet</code> that is currently active
+ * @since 2.0
+ */
+ public GraphDisplaySet getActiveDisplaySet() {
+ return getDisplaySet(scriptFolder.getSelectionIndex());
+ }
+
+ /**
+ * @return The title of the tab containing the active graph.
+ * @since 3.0
+ */
+ public String getActiveTitle() {
+ return scriptFolder.getSelection().getText();
+ }
+
+ /**
+ * Finds and returns the component of the provided index.
+ * @param index The index of the GraphDisplaySet to return
+ * @return The <code>GraphDisplaySet</code> of the provided
+ * index, or null if the index is out of range.
+ * @since 2.2
+ */
+ public GraphDisplaySet getDisplaySet(int index) {
+ if(index >= 0 && index < displaySets.size()) {
+ return displaySets.get(index);
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public void setFocus() {
+ // Empty
+ }
+
+ /**
+ * @since 2.0
+ */
+ public void addTabListener(ITabListener listener) {
+ tabListeners.add(listener);
+ }
+
+ /**
+ * @since 2.0
+ */
+ public void removeTabListener(ITabListener listener) {
+ tabListeners.remove(listener);
+ }
+
+ private void fireTabCloseEvent() {
+ for(ITabListener tabListener:tabListeners) {
+ tabListener.tabClosed();
+ }
+ }
+
+ private void fireTabOpenEvent() {
+ for(ITabListener tabListener:tabListeners) {
+ tabListener.tabOpened();
+ }
+ }
+
+ private void fireTabChangedEvent() {
+ for(ITabListener tabListener:tabListeners) {
+ tabListener.tabChanged();
+ }
+ }
+
+ /**
+ * Removes all internal references in this class. Nothing should make any references
+ * to anything in this class after calling the dispose method.
+ */
+ @Override
+ public void dispose() {
+ super.dispose();
+
+ if(null != scriptFolder && !scriptFolder.isDisposed()) {
+ scriptFolder.dispose();
+ }
+ scriptFolder = null;
+ if(null != tabListeners) {
+ tabListeners.clear();
+ }
+ tabListeners = null;
+ }
+
+ @Override
+ public void doSave(IProgressMonitor monitor) {
+ // TODO
+ }
+
+ @Override
+ public void doSaveAs() {
+ // TODO
+ }
+
+ @Override
+ public void init(IEditorSite site, IEditorInput input) {
+ setInput(input);
+ setSite(site);
+ }
+
+ @Override
+ public boolean isDirty() {
+ return false;
+ }
+
+ @Override
+ public boolean isSaveAsAllowed() {
+ return false;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/views/GraphSelectorEditorInput.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/views/GraphSelectorEditorInput.java
index 36c64f201e..9b78c1a4fa 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/views/GraphSelectorEditorInput.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/views/GraphSelectorEditorInput.java
@@ -21,47 +21,47 @@ import org.eclipse.ui.IPersistableElement;
*/
public class GraphSelectorEditorInput implements IEditorInput {
- private String title = null;
+ private String title = null;
- public GraphSelectorEditorInput() {
- title = Messages.GraphSelectorEditor_graphsEditorDefaultTitle;
- }
+ public GraphSelectorEditorInput() {
+ title = Messages.GraphSelectorEditor_graphsEditorDefaultTitle;
+ }
- /**
- * @since 2.2
- */
- public GraphSelectorEditorInput(String scriptTitle) {
- title = NLS.bind(Messages.GraphSelectorEditor_graphsEditorTitle, scriptTitle);
- }
+ /**
+ * @since 2.2
+ */
+ public GraphSelectorEditorInput(String scriptTitle) {
+ title = NLS.bind(Messages.GraphSelectorEditor_graphsEditorTitle, scriptTitle);
+ }
- @Override
- public Object getAdapter(Class adapter) {
- return null;
- }
+ @Override
+ public Object getAdapter(Class adapter) {
+ return null;
+ }
- @Override
- public boolean exists() {
- return false;
- }
+ @Override
+ public boolean exists() {
+ return false;
+ }
- @Override
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
+ @Override
+ public ImageDescriptor getImageDescriptor() {
+ return null;
+ }
- @Override
- public String getName() {
- return null;
- }
+ @Override
+ public String getName() {
+ return null;
+ }
- @Override
- public IPersistableElement getPersistable() {
- return null;
- }
+ @Override
+ public IPersistableElement getPersistable() {
+ return null;
+ }
- @Override
- public String getToolTipText() {
- return title;
- }
+ @Override
+ public String getToolTipText() {
+ return title;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/ExceptionErrorDialog.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/ExceptionErrorDialog.java
index 3002ef3aaf..f17f7c0755 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/ExceptionErrorDialog.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/ExceptionErrorDialog.java
@@ -26,13 +26,13 @@ import org.eclipse.ui.PlatformUI;
*/
public class ExceptionErrorDialog {
- public static int openError(String message, Exception e){
- StringWriter writer = new StringWriter();
- e.printStackTrace(new PrintWriter(writer));
- Status status = new Status(IStatus.ERROR, GraphingUIPlugin.PLUGIN_ID, e.toString(), new Throwable(writer.toString()));
- return ErrorDialog.openError(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getShell(), message,
- message, status);
- }
+ public static int openError(String message, Exception e){
+ StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ Status status = new Status(IStatus.ERROR, GraphingUIPlugin.PLUGIN_ID, e.toString(), new Throwable(writer.toString()));
+ return ErrorDialog.openError(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getShell(), message,
+ message, status);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphComposite.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphComposite.java
index 7c31edc7a1..52cc731849 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphComposite.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphComposite.java
@@ -35,97 +35,97 @@ import org.eclipse.swt.widgets.Composite;
* @author Ryan Morse
*/
public class GraphComposite extends Composite {
- /**
- * The default constructor: creates an internal composite for the Graph to render on, asks GraphFactory
- * to create the graph from the given GraphData and DataSet, then initializes all buttons and listeners.
- */
- public GraphComposite(Composite parent, int style, GraphData gd, IDataSet ds) {
- super(parent, style);
- FormLayout layout = new FormLayout();
- layout.marginWidth = 5;
- layout.marginHeight = 5;
- this.setLayout(layout);
- checkOptions = new ArrayList<>();
-
- checkOptionComp = new Composite(this, style);
- checkOptionComp.setLayout(new RowLayout(SWT.VERTICAL));
- FormData data = new FormData();
- data.bottom = new FormAttachment(100, 0);
- data.right = new FormAttachment(100, 0);
- checkOptionComp.setLayoutData(data);
-
- builder = GraphFactory.createGraph(this, style, gd, ds);
- xControl = GraphFactory.createGraphXControl(this, style);
- yControl = GraphFactory.createGraphYControl(this, style);
-
- if (xControl instanceof IUpdateListener) {
- builder.addUpdateListener((IUpdateListener) xControl);
- }
- if (yControl instanceof IUpdateListener) {
- builder.addUpdateListener((IUpdateListener) yControl);
- }
-
- configure(true);
-
- builder.build();
- }
-
- /**
- * Toggles sidebar visible or not visible.
- * @param withSidebar Enables or disables the sidebar.
- */
- private void configure(boolean withSidebar) {
- sidebarVisible = withSidebar;
-
- for(Button b:checkOptions) {
- b.setVisible(withSidebar);
- }
-
- if (xControl != null) {
- xControl.setVisible(withSidebar);
- }
- if (yControl != null) {
- yControl.setVisible(withSidebar);
- }
-
- FormData data = new FormData();
- data.top = new FormAttachment(0,0);
- data.right = withSidebar ? new FormAttachment(checkOptionComp, 0) : new FormAttachment(100, 0);
- data.bottom = withSidebar && xControl != null ? new FormAttachment(xControl, 0) : new FormAttachment(100, 0);
- data.left = withSidebar && yControl != null ? new FormAttachment(yControl, 0) : new FormAttachment(0, 0);
- builder.setLayoutData(data);
- layout(true, true);
- }
-
- public void addCheckOption(String title, SelectionListener listener) {
- Button b = new Button(checkOptionComp, SWT.CHECK);
- b.setText(title);
- b.addSelectionListener(listener);
- checkOptions.add(b);
- b.setSelection(true);
- configure(sidebarVisible);
- }
-
- /**
- * Returns the graph that is rendering to this composite.
- */
- public AbstractChartBuilder getCanvas() {
- return builder;
- }
-
- /**
- * @since 3.0
- */
- public void setLegendVisible(boolean visible) {
- builder.getChart().getLegend().setVisible(visible);
- builder.handleUpdateEvent();
- }
-
- private final Composite xControl;
- private final Composite yControl;
-
- private boolean sidebarVisible = false;
- private AbstractChartBuilder builder;
- private List<Button> checkOptions;
- private Composite checkOptionComp;
+ /**
+ * The default constructor: creates an internal composite for the Graph to render on, asks GraphFactory
+ * to create the graph from the given GraphData and DataSet, then initializes all buttons and listeners.
+ */
+ public GraphComposite(Composite parent, int style, GraphData gd, IDataSet ds) {
+ super(parent, style);
+ FormLayout layout = new FormLayout();
+ layout.marginWidth = 5;
+ layout.marginHeight = 5;
+ this.setLayout(layout);
+ checkOptions = new ArrayList<>();
+
+ checkOptionComp = new Composite(this, style);
+ checkOptionComp.setLayout(new RowLayout(SWT.VERTICAL));
+ FormData data = new FormData();
+ data.bottom = new FormAttachment(100, 0);
+ data.right = new FormAttachment(100, 0);
+ checkOptionComp.setLayoutData(data);
+
+ builder = GraphFactory.createGraph(this, style, gd, ds);
+ xControl = GraphFactory.createGraphXControl(this, style);
+ yControl = GraphFactory.createGraphYControl(this, style);
+
+ if (xControl instanceof IUpdateListener) {
+ builder.addUpdateListener((IUpdateListener) xControl);
+ }
+ if (yControl instanceof IUpdateListener) {
+ builder.addUpdateListener((IUpdateListener) yControl);
+ }
+
+ configure(true);
+
+ builder.build();
+ }
+
+ /**
+ * Toggles sidebar visible or not visible.
+ * @param withSidebar Enables or disables the sidebar.
+ */
+ private void configure(boolean withSidebar) {
+ sidebarVisible = withSidebar;
+
+ for(Button b:checkOptions) {
+ b.setVisible(withSidebar);
+ }
+
+ if (xControl != null) {
+ xControl.setVisible(withSidebar);
+ }
+ if (yControl != null) {
+ yControl.setVisible(withSidebar);
+ }
+
+ FormData data = new FormData();
+ data.top = new FormAttachment(0,0);
+ data.right = withSidebar ? new FormAttachment(checkOptionComp, 0) : new FormAttachment(100, 0);
+ data.bottom = withSidebar && xControl != null ? new FormAttachment(xControl, 0) : new FormAttachment(100, 0);
+ data.left = withSidebar && yControl != null ? new FormAttachment(yControl, 0) : new FormAttachment(0, 0);
+ builder.setLayoutData(data);
+ layout(true, true);
+ }
+
+ public void addCheckOption(String title, SelectionListener listener) {
+ Button b = new Button(checkOptionComp, SWT.CHECK);
+ b.setText(title);
+ b.addSelectionListener(listener);
+ checkOptions.add(b);
+ b.setSelection(true);
+ configure(sidebarVisible);
+ }
+
+ /**
+ * Returns the graph that is rendering to this composite.
+ */
+ public AbstractChartBuilder getCanvas() {
+ return builder;
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void setLegendVisible(boolean visible) {
+ builder.getChart().getLegend().setVisible(visible);
+ builder.handleUpdateEvent();
+ }
+
+ private final Composite xControl;
+ private final Composite yControl;
+
+ private boolean sidebarVisible = false;
+ private AbstractChartBuilder builder;
+ private List<Button> checkOptions;
+ private Composite checkOptionComp;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphContinuousXControl.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphContinuousXControl.java
index b58d83a725..fa5e1068aa 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphContinuousXControl.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphContinuousXControl.java
@@ -29,115 +29,115 @@ import org.eclipse.swt.widgets.Slider;
*/
public class GraphContinuousXControl extends Composite {
- private static final int CLICK_INCREMENT = 10;
- private static final double TOLERANCE = 0.01;
-
- private AbstractChartBuilder builder;
- private Scale zoomScale;
- private Slider scrollBar;
-
- public GraphContinuousXControl(GraphComposite comp, int style) {
- super(comp, style);
- this.builder = comp.getCanvas();
- this.setLayout(new FormLayout());
- Font font = new Font(comp.getDisplay(), "Arial", 10, SWT.BOLD); //$NON-NLS-1$
-
- FormData thisData = new FormData();
- thisData.bottom = new FormAttachment(100, 0);
- thisData.left = new FormAttachment(builder, 0, SWT.LEFT);
- thisData.right = new FormAttachment(builder, 0, SWT.RIGHT);
- this.setLayoutData(thisData);
-
- Button zoomOutButton = new Button(this, SWT.CENTER);
- zoomOutButton.setText(Messages.GraphContinuousControl_ZoomOutLabel);
- zoomOutButton.setToolTipText(Messages.GraphContinuousXControl_ZoomOutTooltip);
- zoomOutButton.setFont(font);
- FormData data = new FormData();
- data.left = new FormAttachment(0, 0);
- data.bottom = new FormAttachment(100, 0);
- zoomOutButton.setLayoutData(data);
- zoomOutButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- zoomScale.setSelection(zoomScale.getSelection() - CLICK_INCREMENT);
- updateScale();
- }
- });
-
- Button zoomInButton = new Button(this, SWT.CENTER);
- zoomInButton.setText(Messages.GraphContinuousControl_ZoomInLabel);
- zoomInButton.setToolTipText(Messages.GraphContinuousXControl_ZoomInTooltip);
- zoomInButton.setFont(font);
- data = new FormData();
- data.right = new FormAttachment(100, 0);
- data.bottom = ((FormData) zoomOutButton.getLayoutData()).bottom;
- zoomInButton.setLayoutData(data);
- zoomInButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- zoomScale.setSelection(zoomScale.getSelection() + CLICK_INCREMENT);
- updateScale();
- }
- });
-
- zoomScale = new Scale(this,SWT.HORIZONTAL);
- zoomScale.setMinimum(0);
- zoomScale.setMaximum(99);
- zoomScale.setIncrement(1);
- zoomScale.setPageIncrement(CLICK_INCREMENT);
- zoomScale.setSelection(0); // Inverted: high on left, low on right
- zoomScale.setToolTipText(Messages.GraphContinuousXControl_ScaleMessage);
- data = new FormData();
- data.left = new FormAttachment(zoomOutButton, 2);
- data.bottom = ((FormData) zoomInButton.getLayoutData()).bottom;
- data.right = new FormAttachment(zoomInButton, -2);
- zoomScale.setLayoutData(data);
-
- scrollBar = new Slider(this,SWT.HORIZONTAL);
- scrollBar.setMinimum(0);
- scrollBar.setMaximum(101);
- scrollBar.setThumb(100);
- scrollBar.setIncrement(1);
- scrollBar.setPageIncrement(1);
- scrollBar.setSelection(100); // High on right, low on left
- scrollBar.setToolTipText(Messages.GraphContinuousXControl_ScrollMessage);
- data = new FormData();
- data.left = new FormAttachment(zoomOutButton, 0);
- data.bottom = new FormAttachment(zoomScale, 0);
- data.right = new FormAttachment(zoomInButton, 0);
- scrollBar.setLayoutData(data);
-
- zoomScale.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateScale();
- }
- });
- scrollBar.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateScroll();
- }
- });
-
- updateScale();
- updateScroll();
- }
-
- private void updateScale() {
- double newscale = 1.0 - zoomScale.getSelection() / 100.0;
- if (Math.abs(builder.getScale() - newscale) >= TOLERANCE) {
- builder.setScale(newscale);
- scrollBar.setThumb((int) (newscale * 100));
- scrollBar.setSelection((int) (builder.getScroll() * (101 - scrollBar.getThumb())));
- }
- }
-
- private void updateScroll() {
- double newscroll = scrollBar.getSelection() / (101.0 - scrollBar.getThumb());
- if (Math.abs(builder.getScroll() - newscroll) >= TOLERANCE) {
- builder.setScroll(newscroll);
- }
- }
+ private static final int CLICK_INCREMENT = 10;
+ private static final double TOLERANCE = 0.01;
+
+ private AbstractChartBuilder builder;
+ private Scale zoomScale;
+ private Slider scrollBar;
+
+ public GraphContinuousXControl(GraphComposite comp, int style) {
+ super(comp, style);
+ this.builder = comp.getCanvas();
+ this.setLayout(new FormLayout());
+ Font font = new Font(comp.getDisplay(), "Arial", 10, SWT.BOLD); //$NON-NLS-1$
+
+ FormData thisData = new FormData();
+ thisData.bottom = new FormAttachment(100, 0);
+ thisData.left = new FormAttachment(builder, 0, SWT.LEFT);
+ thisData.right = new FormAttachment(builder, 0, SWT.RIGHT);
+ this.setLayoutData(thisData);
+
+ Button zoomOutButton = new Button(this, SWT.CENTER);
+ zoomOutButton.setText(Messages.GraphContinuousControl_ZoomOutLabel);
+ zoomOutButton.setToolTipText(Messages.GraphContinuousXControl_ZoomOutTooltip);
+ zoomOutButton.setFont(font);
+ FormData data = new FormData();
+ data.left = new FormAttachment(0, 0);
+ data.bottom = new FormAttachment(100, 0);
+ zoomOutButton.setLayoutData(data);
+ zoomOutButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ zoomScale.setSelection(zoomScale.getSelection() - CLICK_INCREMENT);
+ updateScale();
+ }
+ });
+
+ Button zoomInButton = new Button(this, SWT.CENTER);
+ zoomInButton.setText(Messages.GraphContinuousControl_ZoomInLabel);
+ zoomInButton.setToolTipText(Messages.GraphContinuousXControl_ZoomInTooltip);
+ zoomInButton.setFont(font);
+ data = new FormData();
+ data.right = new FormAttachment(100, 0);
+ data.bottom = ((FormData) zoomOutButton.getLayoutData()).bottom;
+ zoomInButton.setLayoutData(data);
+ zoomInButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ zoomScale.setSelection(zoomScale.getSelection() + CLICK_INCREMENT);
+ updateScale();
+ }
+ });
+
+ zoomScale = new Scale(this,SWT.HORIZONTAL);
+ zoomScale.setMinimum(0);
+ zoomScale.setMaximum(99);
+ zoomScale.setIncrement(1);
+ zoomScale.setPageIncrement(CLICK_INCREMENT);
+ zoomScale.setSelection(0); // Inverted: high on left, low on right
+ zoomScale.setToolTipText(Messages.GraphContinuousXControl_ScaleMessage);
+ data = new FormData();
+ data.left = new FormAttachment(zoomOutButton, 2);
+ data.bottom = ((FormData) zoomInButton.getLayoutData()).bottom;
+ data.right = new FormAttachment(zoomInButton, -2);
+ zoomScale.setLayoutData(data);
+
+ scrollBar = new Slider(this,SWT.HORIZONTAL);
+ scrollBar.setMinimum(0);
+ scrollBar.setMaximum(101);
+ scrollBar.setThumb(100);
+ scrollBar.setIncrement(1);
+ scrollBar.setPageIncrement(1);
+ scrollBar.setSelection(100); // High on right, low on left
+ scrollBar.setToolTipText(Messages.GraphContinuousXControl_ScrollMessage);
+ data = new FormData();
+ data.left = new FormAttachment(zoomOutButton, 0);
+ data.bottom = new FormAttachment(zoomScale, 0);
+ data.right = new FormAttachment(zoomInButton, 0);
+ scrollBar.setLayoutData(data);
+
+ zoomScale.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateScale();
+ }
+ });
+ scrollBar.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateScroll();
+ }
+ });
+
+ updateScale();
+ updateScroll();
+ }
+
+ private void updateScale() {
+ double newscale = 1.0 - zoomScale.getSelection() / 100.0;
+ if (Math.abs(builder.getScale() - newscale) >= TOLERANCE) {
+ builder.setScale(newscale);
+ scrollBar.setThumb((int) (newscale * 100));
+ scrollBar.setSelection((int) (builder.getScroll() * (101 - scrollBar.getThumb())));
+ }
+ }
+
+ private void updateScroll() {
+ double newscroll = scrollBar.getSelection() / (101.0 - scrollBar.getThumb());
+ if (Math.abs(builder.getScroll() - newscroll) >= TOLERANCE) {
+ builder.setScroll(newscroll);
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphContinuousYControl.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphContinuousYControl.java
index ab132552fa..dda4ababd7 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphContinuousYControl.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphContinuousYControl.java
@@ -29,115 +29,115 @@ import org.eclipse.swt.widgets.Slider;
*/
public class GraphContinuousYControl extends Composite {
- private static final int CLICK_INCREMENT = 10;
- private static final double TOLERANCE = 0.01;
-
- private AbstractChartBuilder builder;
- private Scale zoomScale;
- private Slider scrollBar;
-
- public GraphContinuousYControl(GraphComposite comp, int style) {
- super(comp, style);
- this.builder = comp.getCanvas();
- this.setLayout(new FormLayout());
- Font font = new Font(comp.getDisplay(), "Arial", 10, SWT.BOLD); //$NON-NLS-1$
-
- FormData thisData = new FormData();
- thisData.left = new FormAttachment(0, 0);
- thisData.top = new FormAttachment(builder, 0, SWT.TOP);
- thisData.bottom = new FormAttachment(builder, 0, SWT.BOTTOM);
- this.setLayoutData(thisData);
-
- Button zoomOutButton = new Button(this, SWT.CENTER);
- zoomOutButton.setText(Messages.GraphContinuousControl_ZoomOutLabel);
- zoomOutButton.setToolTipText(Messages.GraphContinuousYControl_ZoomOutTooltip);
- zoomOutButton.setFont(font);
- FormData data = new FormData();
- data.bottom = new FormAttachment(100, 0);
- data.left = new FormAttachment(0, 0);
- zoomOutButton.setLayoutData(data);
- zoomOutButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- zoomScale.setSelection(zoomScale.getSelection() + CLICK_INCREMENT);
- updateScaleY();
- }
- });
-
- Button zoomInButton = new Button(this, SWT.CENTER);
- zoomInButton.setText(Messages.GraphContinuousControl_ZoomInLabel);
- zoomInButton.setToolTipText(Messages.GraphContinuousYControl_ZoomInTooltip);
- zoomInButton.setFont(font);
- data = new FormData();
- data.top = new FormAttachment(0, 0);
- data.left = ((FormData) zoomOutButton.getLayoutData()).left;
- zoomInButton.setLayoutData(data);
- zoomInButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- zoomScale.setSelection(zoomScale.getSelection() - CLICK_INCREMENT);
- updateScaleY();
- }
- });
-
- zoomScale = new Scale(this,SWT.VERTICAL);
- zoomScale.setMinimum(1);
- zoomScale.setMaximum(100);
- zoomScale.setIncrement(1);
- zoomScale.setPageIncrement(CLICK_INCREMENT);
- zoomScale.setSelection(100); // Low on top, high on bottom
- zoomScale.setToolTipText(Messages.GraphContinuousYControl_ScaleMessage);
- data = new FormData();
- data.top = new FormAttachment(zoomInButton, 2);
- data.left = ((FormData) zoomInButton.getLayoutData()).left;
- data.bottom = new FormAttachment(zoomOutButton, -2);
- zoomScale.setLayoutData(data);
-
- scrollBar = new Slider(this,SWT.VERTICAL);
- scrollBar.setMinimum(0);
- scrollBar.setMaximum(101);
- scrollBar.setThumb(100);
- scrollBar.setIncrement(1);
- scrollBar.setPageIncrement(1);
- scrollBar.setSelection(0); // Inverted: high on top, low on bottom
- scrollBar.setToolTipText(Messages.GraphContinuousYControl_ScrollMessage);
- data = new FormData();
- data.top = new FormAttachment(zoomInButton, 0);
- data.left = new FormAttachment(zoomScale, 0);
- data.bottom = new FormAttachment(zoomOutButton, 0);
- scrollBar.setLayoutData(data);
-
- zoomScale.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateScaleY();
- }
- });
- scrollBar.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateScrollY();
- }
- });
-
- updateScaleY();
- updateScrollY();
- }
-
- private void updateScaleY() {
- double newscale = zoomScale.getSelection() / 100.0;
- if (Math.abs(builder.getScaleY() - newscale) >= TOLERANCE) {
- builder.setScaleY(newscale);
- scrollBar.setThumb((int) (newscale * 100));
- scrollBar.setSelection((int) ((1 - builder.getScrollY()) * (101 - scrollBar.getThumb())));
- }
- }
-
- private void updateScrollY() {
- double newscroll = 1.0 - scrollBar.getSelection() / (101.0 - scrollBar.getThumb());
- if (Math.abs(builder.getScrollY() - newscroll) >= TOLERANCE) {
- builder.setScrollY(newscroll);
- }
- }
+ private static final int CLICK_INCREMENT = 10;
+ private static final double TOLERANCE = 0.01;
+
+ private AbstractChartBuilder builder;
+ private Scale zoomScale;
+ private Slider scrollBar;
+
+ public GraphContinuousYControl(GraphComposite comp, int style) {
+ super(comp, style);
+ this.builder = comp.getCanvas();
+ this.setLayout(new FormLayout());
+ Font font = new Font(comp.getDisplay(), "Arial", 10, SWT.BOLD); //$NON-NLS-1$
+
+ FormData thisData = new FormData();
+ thisData.left = new FormAttachment(0, 0);
+ thisData.top = new FormAttachment(builder, 0, SWT.TOP);
+ thisData.bottom = new FormAttachment(builder, 0, SWT.BOTTOM);
+ this.setLayoutData(thisData);
+
+ Button zoomOutButton = new Button(this, SWT.CENTER);
+ zoomOutButton.setText(Messages.GraphContinuousControl_ZoomOutLabel);
+ zoomOutButton.setToolTipText(Messages.GraphContinuousYControl_ZoomOutTooltip);
+ zoomOutButton.setFont(font);
+ FormData data = new FormData();
+ data.bottom = new FormAttachment(100, 0);
+ data.left = new FormAttachment(0, 0);
+ zoomOutButton.setLayoutData(data);
+ zoomOutButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ zoomScale.setSelection(zoomScale.getSelection() + CLICK_INCREMENT);
+ updateScaleY();
+ }
+ });
+
+ Button zoomInButton = new Button(this, SWT.CENTER);
+ zoomInButton.setText(Messages.GraphContinuousControl_ZoomInLabel);
+ zoomInButton.setToolTipText(Messages.GraphContinuousYControl_ZoomInTooltip);
+ zoomInButton.setFont(font);
+ data = new FormData();
+ data.top = new FormAttachment(0, 0);
+ data.left = ((FormData) zoomOutButton.getLayoutData()).left;
+ zoomInButton.setLayoutData(data);
+ zoomInButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ zoomScale.setSelection(zoomScale.getSelection() - CLICK_INCREMENT);
+ updateScaleY();
+ }
+ });
+
+ zoomScale = new Scale(this,SWT.VERTICAL);
+ zoomScale.setMinimum(1);
+ zoomScale.setMaximum(100);
+ zoomScale.setIncrement(1);
+ zoomScale.setPageIncrement(CLICK_INCREMENT);
+ zoomScale.setSelection(100); // Low on top, high on bottom
+ zoomScale.setToolTipText(Messages.GraphContinuousYControl_ScaleMessage);
+ data = new FormData();
+ data.top = new FormAttachment(zoomInButton, 2);
+ data.left = ((FormData) zoomInButton.getLayoutData()).left;
+ data.bottom = new FormAttachment(zoomOutButton, -2);
+ zoomScale.setLayoutData(data);
+
+ scrollBar = new Slider(this,SWT.VERTICAL);
+ scrollBar.setMinimum(0);
+ scrollBar.setMaximum(101);
+ scrollBar.setThumb(100);
+ scrollBar.setIncrement(1);
+ scrollBar.setPageIncrement(1);
+ scrollBar.setSelection(0); // Inverted: high on top, low on bottom
+ scrollBar.setToolTipText(Messages.GraphContinuousYControl_ScrollMessage);
+ data = new FormData();
+ data.top = new FormAttachment(zoomInButton, 0);
+ data.left = new FormAttachment(zoomScale, 0);
+ data.bottom = new FormAttachment(zoomOutButton, 0);
+ scrollBar.setLayoutData(data);
+
+ zoomScale.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateScaleY();
+ }
+ });
+ scrollBar.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateScrollY();
+ }
+ });
+
+ updateScaleY();
+ updateScrollY();
+ }
+
+ private void updateScaleY() {
+ double newscale = zoomScale.getSelection() / 100.0;
+ if (Math.abs(builder.getScaleY() - newscale) >= TOLERANCE) {
+ builder.setScaleY(newscale);
+ scrollBar.setThumb((int) (newscale * 100));
+ scrollBar.setSelection((int) ((1 - builder.getScrollY()) * (101 - scrollBar.getThumb())));
+ }
+ }
+
+ private void updateScrollY() {
+ double newscroll = 1.0 - scrollBar.getSelection() / (101.0 - scrollBar.getThumb());
+ if (Math.abs(builder.getScrollY() - newscroll) >= TOLERANCE) {
+ builder.setScrollY(newscroll);
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphDiscreteXControl.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphDiscreteXControl.java
index e7fdc6af44..d638b75968 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphDiscreteXControl.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/GraphDiscreteXControl.java
@@ -31,140 +31,140 @@ import org.swtchart.Range;
*/
public class GraphDiscreteXControl extends Composite implements IUpdateListener {
- private final static double ZOOM_AMOUNT = 2.0;
-
- private AbstractChartBuilder builder;
- private Button zoomInButton;
- private Button zoomOutButton;
- private Button allButton;
- private Button leftButton;
- private Button rightButton;
- private Button firstButton;
- private Button lastButton;
-
- public GraphDiscreteXControl(GraphComposite comp, int style) {
- super(comp, style);
- this.builder = comp.getCanvas();
- this.setLayout(new RowLayout());
- Font font = new Font(comp.getDisplay(), "Arial", 10, SWT.BOLD); //$NON-NLS-1$
-
- FormData thisData = new FormData();
- thisData.bottom = new FormAttachment(100, 0);
- thisData.left = new FormAttachment(builder, 0, SWT.LEFT);
- this.setLayoutData(thisData);
-
- firstButton = new Button(this, SWT.CENTER);
- firstButton.setText(Messages.GraphDiscreteXControl_First);
- firstButton.setFont(font);
- firstButton.setEnabled(false);
- firstButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- builder.setScroll(0);
- firstButton.setEnabled(false);
- leftButton.setEnabled(false);
- rightButton.setEnabled(true);
- lastButton.setEnabled(true);
- }
- });
-
- leftButton = new Button(this, SWT.CENTER);
- leftButton.setText(Messages.GraphDiscreteXControl_Left);
- leftButton.setFont(font);
- leftButton.setEnabled(false);
- leftButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- stepScroll(-1);
- }
- });
-
- zoomInButton = new Button(this, SWT.CENTER);
- zoomInButton.setText(Messages.GraphDiscreteXControl_ZoomIn);
- zoomInButton.setFont(font);
- zoomInButton.setEnabled(false);
- zoomInButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- builder.setScale(builder.getScale() / ZOOM_AMOUNT);
- }
- });
-
- zoomOutButton = new Button(this, SWT.CENTER);
- zoomOutButton.setText(Messages.GraphDiscreteXControl_ZoomOut);
- zoomOutButton.setFont(font);
- zoomOutButton.setEnabled(false);
- zoomOutButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- builder.setScale(builder.getScale() * ZOOM_AMOUNT);
- }
- });
-
- allButton = new Button(this, SWT.CENTER);
- allButton.setText(Messages.GraphDiscreteXControl_All);
- allButton.setFont(font);
- allButton.setEnabled(false);
- allButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- builder.setScale(1.0);
- }
- });
-
- rightButton = new Button(this, SWT.CENTER);
- rightButton.setText(Messages.GraphDiscreteXControl_Right);
- rightButton.setFont(font);
- rightButton.setEnabled(false);
- rightButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- stepScroll(1);
- }
- });
-
- lastButton = new Button(this, SWT.CENTER);
- lastButton.setText(Messages.GraphDiscreteXControl_Last);
- lastButton.setFont(font);
- lastButton.setEnabled(false);
- lastButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- builder.setScroll(1);
- firstButton.setEnabled(true);
- leftButton.setEnabled(true);
- rightButton.setEnabled(false);
- lastButton.setEnabled(false);
- }
- });
- }
-
- private int getNumItems() {
- ISeries[] series = builder.getChart().getSeriesSet().getSeries();
- return series.length > 0 ? series[0].getXSeries().length : 0;
- }
-
- private void stepScroll(int step) {
- // Note: scroll buttons are disabled when scale is 100%.
- builder.setScroll(builder.getScroll() + step / (double) (getNumItems()) / (1.0 - builder.getScale()));
- }
-
- @Override
- public void handleUpdateEvent() {
- IAxis xAxis = builder.getChart().getAxisSet().getXAxis(0);
- Range range = xAxis.getRange();
- zoomInButton.setEnabled(range.upper - range.lower > 0);
-
- boolean showingAll = builder.getScale() == 1;
- zoomOutButton.setEnabled(!showingAll);
- allButton.setEnabled(!showingAll);
-
- boolean hitLeft = showingAll || range.lower == 0;
- boolean hitRight = showingAll || range.upper == getNumItems() - 1;
- leftButton.setEnabled(!hitLeft);
- rightButton.setEnabled(!hitRight);
- firstButton.setEnabled(!hitLeft);
- lastButton.setEnabled(!hitRight);
- }
+ private final static double ZOOM_AMOUNT = 2.0;
+
+ private AbstractChartBuilder builder;
+ private Button zoomInButton;
+ private Button zoomOutButton;
+ private Button allButton;
+ private Button leftButton;
+ private Button rightButton;
+ private Button firstButton;
+ private Button lastButton;
+
+ public GraphDiscreteXControl(GraphComposite comp, int style) {
+ super(comp, style);
+ this.builder = comp.getCanvas();
+ this.setLayout(new RowLayout());
+ Font font = new Font(comp.getDisplay(), "Arial", 10, SWT.BOLD); //$NON-NLS-1$
+
+ FormData thisData = new FormData();
+ thisData.bottom = new FormAttachment(100, 0);
+ thisData.left = new FormAttachment(builder, 0, SWT.LEFT);
+ this.setLayoutData(thisData);
+
+ firstButton = new Button(this, SWT.CENTER);
+ firstButton.setText(Messages.GraphDiscreteXControl_First);
+ firstButton.setFont(font);
+ firstButton.setEnabled(false);
+ firstButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ builder.setScroll(0);
+ firstButton.setEnabled(false);
+ leftButton.setEnabled(false);
+ rightButton.setEnabled(true);
+ lastButton.setEnabled(true);
+ }
+ });
+
+ leftButton = new Button(this, SWT.CENTER);
+ leftButton.setText(Messages.GraphDiscreteXControl_Left);
+ leftButton.setFont(font);
+ leftButton.setEnabled(false);
+ leftButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ stepScroll(-1);
+ }
+ });
+
+ zoomInButton = new Button(this, SWT.CENTER);
+ zoomInButton.setText(Messages.GraphDiscreteXControl_ZoomIn);
+ zoomInButton.setFont(font);
+ zoomInButton.setEnabled(false);
+ zoomInButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ builder.setScale(builder.getScale() / ZOOM_AMOUNT);
+ }
+ });
+
+ zoomOutButton = new Button(this, SWT.CENTER);
+ zoomOutButton.setText(Messages.GraphDiscreteXControl_ZoomOut);
+ zoomOutButton.setFont(font);
+ zoomOutButton.setEnabled(false);
+ zoomOutButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ builder.setScale(builder.getScale() * ZOOM_AMOUNT);
+ }
+ });
+
+ allButton = new Button(this, SWT.CENTER);
+ allButton.setText(Messages.GraphDiscreteXControl_All);
+ allButton.setFont(font);
+ allButton.setEnabled(false);
+ allButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ builder.setScale(1.0);
+ }
+ });
+
+ rightButton = new Button(this, SWT.CENTER);
+ rightButton.setText(Messages.GraphDiscreteXControl_Right);
+ rightButton.setFont(font);
+ rightButton.setEnabled(false);
+ rightButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ stepScroll(1);
+ }
+ });
+
+ lastButton = new Button(this, SWT.CENTER);
+ lastButton.setText(Messages.GraphDiscreteXControl_Last);
+ lastButton.setFont(font);
+ lastButton.setEnabled(false);
+ lastButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ builder.setScroll(1);
+ firstButton.setEnabled(true);
+ leftButton.setEnabled(true);
+ rightButton.setEnabled(false);
+ lastButton.setEnabled(false);
+ }
+ });
+ }
+
+ private int getNumItems() {
+ ISeries[] series = builder.getChart().getSeriesSet().getSeries();
+ return series.length > 0 ? series[0].getXSeries().length : 0;
+ }
+
+ private void stepScroll(int step) {
+ // Note: scroll buttons are disabled when scale is 100%.
+ builder.setScroll(builder.getScroll() + step / (double) (getNumItems()) / (1.0 - builder.getScale()));
+ }
+
+ @Override
+ public void handleUpdateEvent() {
+ IAxis xAxis = builder.getChart().getAxisSet().getXAxis(0);
+ Range range = xAxis.getRange();
+ zoomInButton.setEnabled(range.upper - range.lower > 0);
+
+ boolean showingAll = builder.getScale() == 1;
+ zoomOutButton.setEnabled(!showingAll);
+ allButton.setEnabled(!showingAll);
+
+ boolean hitLeft = showingAll || range.lower == 0;
+ boolean hitRight = showingAll || range.upper == getNumItems() - 1;
+ leftButton.setEnabled(!hitLeft);
+ rightButton.setEnabled(!hitRight);
+ firstButton.setEnabled(!hitLeft);
+ lastButton.setEnabled(!hitRight);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/Messages.java
index e44578539c..994f0020ca 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/widgets/Messages.java
@@ -17,29 +17,29 @@ import org.eclipse.osgi.util.NLS;
* @since 3.0
*/
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.systemtap.graphing.ui.widgets.messages"; //$NON-NLS-1$
- public static String GraphContinuousControl_ZoomInLabel;
- public static String GraphContinuousXControl_ZoomInTooltip;
- public static String GraphContinuousYControl_ZoomInTooltip;
- public static String GraphContinuousControl_ZoomOutLabel;
- public static String GraphContinuousXControl_ZoomOutTooltip;
- public static String GraphContinuousYControl_ZoomOutTooltip;
- public static String GraphContinuousXControl_ScaleMessage;
- public static String GraphContinuousXControl_ScrollMessage;
- public static String GraphContinuousYControl_ScaleMessage;
- public static String GraphContinuousYControl_ScrollMessage;
- public static String GraphDiscreteXControl_First;
- public static String GraphDiscreteXControl_Left;
- public static String GraphDiscreteXControl_ZoomIn;
- public static String GraphDiscreteXControl_ZoomOut;
- public static String GraphDiscreteXControl_All;
- public static String GraphDiscreteXControl_Right;
- public static String GraphDiscreteXControl_Last;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.systemtap.graphing.ui.widgets.messages"; //$NON-NLS-1$
+ public static String GraphContinuousControl_ZoomInLabel;
+ public static String GraphContinuousXControl_ZoomInTooltip;
+ public static String GraphContinuousYControl_ZoomInTooltip;
+ public static String GraphContinuousControl_ZoomOutLabel;
+ public static String GraphContinuousXControl_ZoomOutTooltip;
+ public static String GraphContinuousYControl_ZoomOutTooltip;
+ public static String GraphContinuousXControl_ScaleMessage;
+ public static String GraphContinuousXControl_ScrollMessage;
+ public static String GraphContinuousYControl_ScaleMessage;
+ public static String GraphContinuousYControl_ScrollMessage;
+ public static String GraphDiscreteXControl_First;
+ public static String GraphDiscreteXControl_Left;
+ public static String GraphDiscreteXControl_ZoomIn;
+ public static String GraphDiscreteXControl_ZoomOut;
+ public static String GraphDiscreteXControl_All;
+ public static String GraphDiscreteXControl_Right;
+ public static String GraphDiscreteXControl_Last;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/dataset/DataSetFactory.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/dataset/DataSetFactory.java
index e64fadecf5..041b8f7264 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/dataset/DataSetFactory.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/dataset/DataSetFactory.java
@@ -21,33 +21,33 @@ import org.eclipse.linuxtools.systemtap.graphing.ui.datadisplay.DataGrid;
import org.eclipse.swt.widgets.Composite;
public final class DataSetFactory {
- public static IDataSet createDataSet(String id, String[] labels) {
- if(id.equals(RowDataSet.ID)) {
- return new RowDataSet(labels);
- } else if(id.equals(TableDataSet.ID)) {
- return new TableDataSet(labels);
- }
- return null;
- }
+ public static IDataSet createDataSet(String id, String[] labels) {
+ if(id.equals(RowDataSet.ID)) {
+ return new RowDataSet(labels);
+ } else if(id.equals(TableDataSet.ID)) {
+ return new TableDataSet(labels);
+ }
+ return null;
+ }
- public static IFilteredDataSet createFilteredDataSet(String id, String[] labels) {
- if(id.equals(RowDataSet.ID)) {
- return new FilteredRowDataSet(labels);
- } else if(id.equals(TableDataSet.ID)) {
- return new FilteredTableDataSet(labels);
- }
- return new FilteredRowDataSet(labels);
- }
+ public static IFilteredDataSet createFilteredDataSet(String id, String[] labels) {
+ if(id.equals(RowDataSet.ID)) {
+ return new FilteredRowDataSet(labels);
+ } else if(id.equals(TableDataSet.ID)) {
+ return new FilteredTableDataSet(labels);
+ }
+ return new FilteredRowDataSet(labels);
+ }
- /**
- * @since 3.0 set must be a IFilteredDataSet.
- */
- public static DataGrid getDataGrid(Composite composite, IFilteredDataSet set) {
- if(set instanceof RowDataSet || set instanceof TableDataSet) {
- return new DataGrid(composite, set);
- }
+ /**
+ * @since 3.0 set must be a IFilteredDataSet.
+ */
+ public static DataGrid getDataGrid(Composite composite, IFilteredDataSet set) {
+ if(set instanceof RowDataSet || set instanceof TableDataSet) {
+ return new DataGrid(composite, set);
+ }
- return null;
- }
+ return null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/GraphFactory.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/GraphFactory.java
index e497aed860..66038b6916 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/GraphFactory.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/GraphFactory.java
@@ -36,157 +36,157 @@ import org.eclipse.swt.widgets.Composite;
public final class GraphFactory {
- private static final String[] graphNames = new String[] {
- Localization.getString("GraphFactory.ScatterGraph"), //$NON-NLS-1$
- Localization.getString("GraphFactory.LineGraph"), //$NON-NLS-1$
- Localization.getString("GraphFactory.BarGraph"), //$NON-NLS-1$
- Localization.getString("GraphFactory.AreaGraph"), //$NON-NLS-1$
- Localization.getString("GraphFactory.PieChart"), //$NON-NLS-1$
- };
-
- private static final String[] graphDescriptions = new String[] {
- Localization.getString("GraphFactory.ScatterDescription"), //$NON-NLS-1$
- Localization.getString("GraphFactory.LineDescription"), //$NON-NLS-1$
- Localization.getString("GraphFactory.BarDescription"), //$NON-NLS-1$
- Localization.getString("GraphFactory.AreaDescription"), //$NON-NLS-1$
- Localization.getString("GraphFactory.PieDescription"), //$NON-NLS-1$
- };
-
- private static final Image[] graphImages = new Image[] {
- GraphingUIPlugin.getImageDescriptor("icons/graphs/ScatterGraph.gif").createImage(), //$NON-NLS-1$
- GraphingUIPlugin.getImageDescriptor("icons/graphs/LineGraph.gif").createImage(), //$NON-NLS-1$
- GraphingUIPlugin.getImageDescriptor("icons/graphs/BarGraph.gif").createImage(), //$NON-NLS-1$
- GraphingUIPlugin.getImageDescriptor("icons/graphs/AreaChart.gif").createImage(), //$NON-NLS-1$
- GraphingUIPlugin.getImageDescriptor("icons/graphs/PieChart.gif").createImage(), //$NON-NLS-1$
- };
-
- private static final String[] graphIDs = new String[] {
- ScatterChartBuilder.ID,
- LineChartBuilder.ID,
- BarChartBuilder.ID,
- AreaChartBuilder.ID,
- PieChartBuilder.ID,
- };
-
- public static String[] getAvailableGraphs(IDataSet data) {
- LinkedList<String> ids = new LinkedList<>();
- if(data instanceof IHistoricalDataSet) {
- ids.add(ScatterChartBuilder.ID);
- ids.add(LineChartBuilder.ID);
- ids.add(AreaChartBuilder.ID);
- ids.add(BarChartBuilder.ID);
- ids.add(PieChartBuilder.ID);
- }
- if(data instanceof IBlockDataSet) {
- if(!ids.contains(BarChartBuilder.ID)) {
- ids.add(BarChartBuilder.ID);
- }
- ids.add(PieChartBuilder.ID);
- }
-
- String[] id = new String[0];
- return ids.toArray(id);
- }
-
- public static String getGraphName(String id) {
- int index = getIndex(id);
- if(index >= 0) {
- return graphNames[index];
- }
- return null;
- }
-
- public static String getGraphDescription(String id) {
- int index = getIndex(id);
- if(index >= 0) {
- return graphDescriptions[index];
- }
- return null;
- }
-
- public static Image getGraphImage(String id) {
- int index = getIndex(id);
- if(index >= 0) {
- return graphImages[index];
- }
- return null;
- }
-
- public static boolean isMultiGraph(String id) {
- return true;
- }
-
- public static final AbstractChartBuilder createGraph(GraphComposite comp,
- int style, GraphData gd, IDataSet data) {
- AbstractChartBuilder builder = null;
-
- switch (getIndex(gd.graphID)) {
- case 0:
- builder = new ScatterChartBuilder(comp, style, gd.title,
- new ScrollAdapter((IHistoricalDataSet) data, gd.xSeries,
- gd.ySeries, gd.key));
- break;
- case 1:
- builder = new LineChartBuilder(comp, style, gd.title,
- new ScrollAdapter((IHistoricalDataSet) data, gd.xSeries,
- gd.ySeries, gd.key));
- break;
- case 2:
- if (!(data instanceof IBlockDataSet) || (null != gd.key)) {
- builder = new BarChartBuilder(comp, style, gd.title,
- new ScrollAdapter((IHistoricalDataSet) data,
- gd.xSeries, gd.ySeries, gd.key));
-
- } else {
- builder = new BarChartBuilder(comp, style, gd.title,
- new BlockAdapter((IBlockDataSet) data, gd.xSeries,
- gd.ySeries));
-
- }
- break;
- case 3:
- builder = new AreaChartBuilder(comp, style, gd.title,
- new ScrollAdapter((IHistoricalDataSet) data, gd.xSeries,
- gd.ySeries, gd.key));
- break;
- case 4:
- builder = new PieChartBuilder(comp, style, gd.title,
- new ScrollAdapter((IHistoricalDataSet) data, gd.xSeries,
- gd.ySeries, gd.key));
-
- break;
- }
- return builder;
- }
-
- /**
- * @since 3.0
- */
- public static final Composite createGraphXControl(GraphComposite comp, int style) {
- AbstractChartBuilder builder = comp.getCanvas();
- if (builder instanceof BarChartBuilder || builder instanceof PieChartBuilder) {
- return new GraphDiscreteXControl(comp, style);
- }
- return new GraphContinuousXControl(comp, style);
- }
-
- /**
- * @since 3.0
- */
- public static final Composite createGraphYControl(GraphComposite comp, int style) {
- AbstractChartBuilder builder = comp.getCanvas();
- if (builder instanceof PieChartBuilder) {
- return null;
- }
- return new GraphContinuousYControl(comp, style);
- }
-
- private static int getIndex(String id) {
- for(int i=0; i<graphIDs.length; i++) {
- if(id.equals(graphIDs[i])) {
- return i;
- }
- }
- return -1;
- }
+ private static final String[] graphNames = new String[] {
+ Localization.getString("GraphFactory.ScatterGraph"), //$NON-NLS-1$
+ Localization.getString("GraphFactory.LineGraph"), //$NON-NLS-1$
+ Localization.getString("GraphFactory.BarGraph"), //$NON-NLS-1$
+ Localization.getString("GraphFactory.AreaGraph"), //$NON-NLS-1$
+ Localization.getString("GraphFactory.PieChart"), //$NON-NLS-1$
+ };
+
+ private static final String[] graphDescriptions = new String[] {
+ Localization.getString("GraphFactory.ScatterDescription"), //$NON-NLS-1$
+ Localization.getString("GraphFactory.LineDescription"), //$NON-NLS-1$
+ Localization.getString("GraphFactory.BarDescription"), //$NON-NLS-1$
+ Localization.getString("GraphFactory.AreaDescription"), //$NON-NLS-1$
+ Localization.getString("GraphFactory.PieDescription"), //$NON-NLS-1$
+ };
+
+ private static final Image[] graphImages = new Image[] {
+ GraphingUIPlugin.getImageDescriptor("icons/graphs/ScatterGraph.gif").createImage(), //$NON-NLS-1$
+ GraphingUIPlugin.getImageDescriptor("icons/graphs/LineGraph.gif").createImage(), //$NON-NLS-1$
+ GraphingUIPlugin.getImageDescriptor("icons/graphs/BarGraph.gif").createImage(), //$NON-NLS-1$
+ GraphingUIPlugin.getImageDescriptor("icons/graphs/AreaChart.gif").createImage(), //$NON-NLS-1$
+ GraphingUIPlugin.getImageDescriptor("icons/graphs/PieChart.gif").createImage(), //$NON-NLS-1$
+ };
+
+ private static final String[] graphIDs = new String[] {
+ ScatterChartBuilder.ID,
+ LineChartBuilder.ID,
+ BarChartBuilder.ID,
+ AreaChartBuilder.ID,
+ PieChartBuilder.ID,
+ };
+
+ public static String[] getAvailableGraphs(IDataSet data) {
+ LinkedList<String> ids = new LinkedList<>();
+ if(data instanceof IHistoricalDataSet) {
+ ids.add(ScatterChartBuilder.ID);
+ ids.add(LineChartBuilder.ID);
+ ids.add(AreaChartBuilder.ID);
+ ids.add(BarChartBuilder.ID);
+ ids.add(PieChartBuilder.ID);
+ }
+ if(data instanceof IBlockDataSet) {
+ if(!ids.contains(BarChartBuilder.ID)) {
+ ids.add(BarChartBuilder.ID);
+ }
+ ids.add(PieChartBuilder.ID);
+ }
+
+ String[] id = new String[0];
+ return ids.toArray(id);
+ }
+
+ public static String getGraphName(String id) {
+ int index = getIndex(id);
+ if(index >= 0) {
+ return graphNames[index];
+ }
+ return null;
+ }
+
+ public static String getGraphDescription(String id) {
+ int index = getIndex(id);
+ if(index >= 0) {
+ return graphDescriptions[index];
+ }
+ return null;
+ }
+
+ public static Image getGraphImage(String id) {
+ int index = getIndex(id);
+ if(index >= 0) {
+ return graphImages[index];
+ }
+ return null;
+ }
+
+ public static boolean isMultiGraph(String id) {
+ return true;
+ }
+
+ public static final AbstractChartBuilder createGraph(GraphComposite comp,
+ int style, GraphData gd, IDataSet data) {
+ AbstractChartBuilder builder = null;
+
+ switch (getIndex(gd.graphID)) {
+ case 0:
+ builder = new ScatterChartBuilder(comp, style, gd.title,
+ new ScrollAdapter((IHistoricalDataSet) data, gd.xSeries,
+ gd.ySeries, gd.key));
+ break;
+ case 1:
+ builder = new LineChartBuilder(comp, style, gd.title,
+ new ScrollAdapter((IHistoricalDataSet) data, gd.xSeries,
+ gd.ySeries, gd.key));
+ break;
+ case 2:
+ if (!(data instanceof IBlockDataSet) || (null != gd.key)) {
+ builder = new BarChartBuilder(comp, style, gd.title,
+ new ScrollAdapter((IHistoricalDataSet) data,
+ gd.xSeries, gd.ySeries, gd.key));
+
+ } else {
+ builder = new BarChartBuilder(comp, style, gd.title,
+ new BlockAdapter((IBlockDataSet) data, gd.xSeries,
+ gd.ySeries));
+
+ }
+ break;
+ case 3:
+ builder = new AreaChartBuilder(comp, style, gd.title,
+ new ScrollAdapter((IHistoricalDataSet) data, gd.xSeries,
+ gd.ySeries, gd.key));
+ break;
+ case 4:
+ builder = new PieChartBuilder(comp, style, gd.title,
+ new ScrollAdapter((IHistoricalDataSet) data, gd.xSeries,
+ gd.ySeries, gd.key));
+
+ break;
+ }
+ return builder;
+ }
+
+ /**
+ * @since 3.0
+ */
+ public static final Composite createGraphXControl(GraphComposite comp, int style) {
+ AbstractChartBuilder builder = comp.getCanvas();
+ if (builder instanceof BarChartBuilder || builder instanceof PieChartBuilder) {
+ return new GraphDiscreteXControl(comp, style);
+ }
+ return new GraphContinuousXControl(comp, style);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public static final Composite createGraphYControl(GraphComposite comp, int style) {
+ AbstractChartBuilder builder = comp.getCanvas();
+ if (builder instanceof PieChartBuilder) {
+ return null;
+ }
+ return new GraphContinuousYControl(comp, style);
+ }
+
+ private static int getIndex(String id) {
+ for(int i=0; i<graphIDs.length; i++) {
+ if(id.equals(graphIDs[i])) {
+ return i;
+ }
+ }
+ return -1;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/SelectGraphAndSeriesWizard.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/SelectGraphAndSeriesWizard.java
index 54b3ad424d..a8b281749c 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/SelectGraphAndSeriesWizard.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/SelectGraphAndSeriesWizard.java
@@ -25,63 +25,63 @@ import org.eclipse.ui.IWorkbench;
* @since 2.1
*/
public class SelectGraphAndSeriesWizard extends Wizard implements INewWizard {
- /**
- * The wizard for creating a new graph.
- * @param data An IDataSet that contains the names of all possible series values (columns).
- * @param gdata A GraphData instance that contains the saved settings of a previously-created graph.
- * If this wizard is for creating a new graph, set this parameter to null.
- */
- public SelectGraphAndSeriesWizard(IDataSet data, GraphData gdata) {
- model = new GraphModel(data);
- edit = (gdata != null);
- if (edit) {
- model.setGraph(gdata.graphID);
- model.setKey(gdata.key);
- model.setTitle(gdata.title);
- model.setXSeries(gdata.xSeries);
- model.setYSeries(gdata.ySeries);
- }
- }
+ /**
+ * The wizard for creating a new graph.
+ * @param data An IDataSet that contains the names of all possible series values (columns).
+ * @param gdata A GraphData instance that contains the saved settings of a previously-created graph.
+ * If this wizard is for creating a new graph, set this parameter to null.
+ */
+ public SelectGraphAndSeriesWizard(IDataSet data, GraphData gdata) {
+ model = new GraphModel(data);
+ edit = (gdata != null);
+ if (edit) {
+ model.setGraph(gdata.graphID);
+ model.setKey(gdata.key);
+ model.setTitle(gdata.title);
+ model.setXSeries(gdata.xSeries);
+ model.setYSeries(gdata.ySeries);
+ }
+ }
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- }
+ @Override
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ }
- @Override
- public void addPages() {
- setWindowTitle(Localization.getString(!edit ? "SelectGraphAndSeriesWizard.CreateGraph" : "SelectGraphAndSeriesWizard.EditGraph")); //$NON-NLS-1$//$NON-NLS-2$
- selectGraphandSeriesPage = new SelectGraphAndSeriesWizardPage();
- addPage(selectGraphandSeriesPage);
- }
+ @Override
+ public void addPages() {
+ setWindowTitle(Localization.getString(!edit ? "SelectGraphAndSeriesWizard.CreateGraph" : "SelectGraphAndSeriesWizard.EditGraph")); //$NON-NLS-1$//$NON-NLS-2$
+ selectGraphandSeriesPage = new SelectGraphAndSeriesWizardPage();
+ addPage(selectGraphandSeriesPage);
+ }
- @Override
- public boolean canFinish() {
- if (selectGraphandSeriesPage.isPageComplete()) {
- return true;
- }
- return false;
- }
+ @Override
+ public boolean canFinish() {
+ if (selectGraphandSeriesPage.isPageComplete()) {
+ return true;
+ }
+ return false;
+ }
- @Override
- public boolean performCancel() {
- model.destroy();
- return true;
- }
+ @Override
+ public boolean performCancel() {
+ model.destroy();
+ return true;
+ }
- @Override
- public boolean performFinish() {
- return true;
- }
+ @Override
+ public boolean performFinish() {
+ return true;
+ }
- public GraphData getGraphData() {
- return model.getGraphData();
- }
+ public GraphData getGraphData() {
+ return model.getGraphData();
+ }
- public boolean isEditing() {
- return edit;
- }
+ public boolean isEditing() {
+ return edit;
+ }
- public SelectGraphAndSeriesWizardPage selectGraphandSeriesPage;
- public GraphModel model;
- private boolean edit;
+ public SelectGraphAndSeriesWizardPage selectGraphandSeriesPage;
+ public GraphModel model;
+ private boolean edit;
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/SelectGraphAndSeriesWizardPage.java b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/SelectGraphAndSeriesWizardPage.java
index 19cbe77c05..0eb1c72d63 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/SelectGraphAndSeriesWizardPage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.graphing.ui/src/org/eclipse/linuxtools/systemtap/graphing/ui/wizards/graph/SelectGraphAndSeriesWizardPage.java
@@ -37,409 +37,409 @@ import org.eclipse.swt.widgets.Text;
* @since 2.1
*/
public class SelectGraphAndSeriesWizardPage extends WizardPage implements Listener {
- public SelectGraphAndSeriesWizardPage() {
- super("selectGraphAndSeries"); //$NON-NLS-1$
- setTitle(Localization.getString("SelectGraphAndSeriesWizardPage.SelectGraphAndSeries")); //$NON-NLS-1$
- }
-
- @Override
- public void createControl(Composite parent) {
- wizard = (SelectGraphAndSeriesWizard)getWizard();
- model = wizard.model;
- edit = wizard.isEditing();
-
- //Set the layout data
- Composite comp = new Composite(parent, SWT.NONE);
- comp.setLayout(new GridLayout());
-
- Group cmpGraphOptsGraph = new Group(comp, SWT.SHADOW_ETCHED_IN);
- cmpGraphOptsGraph.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
- RowLayout rowLayout = new RowLayout();
- rowLayout.type = SWT.HORIZONTAL;
- rowLayout.spacing = 10;
- cmpGraphOptsGraph.setLayout(rowLayout);
- cmpGraphOptsGraph.setText(Localization.getString("SelectGraphAndSeriesWizardPage.Graph")); //$NON-NLS-1$
-
- String[] graphIDs = GraphFactory.getAvailableGraphs(wizard.model.getDataSet());
- int btnGraphSelected = -1;
- btnGraphs = new Button[graphIDs.length];
- for (int i = 0; i < btnGraphs.length; i++) {
- btnGraphs[i] = new Button(cmpGraphOptsGraph, SWT.RADIO);
- btnGraphs[i].setImage(GraphFactory.getGraphImage(graphIDs[i]));
- btnGraphs[i].addListener(SWT.Selection, this);
- btnGraphs[i].setData(graphIDs[i]);
- btnGraphs[i].setToolTipText(GraphFactory.getGraphName(btnGraphs[i].getData().toString()) + "\n\n" + //$NON-NLS-1$
- GraphFactory.getGraphDescription(btnGraphs[i].getData().toString()));
- if (btnGraphSelected == -1 && wizard.isEditing() && graphIDs[i].equals(wizard.model.getGraphID())) {
- btnGraphs[i].setSelection(true);
- btnGraphSelected = i;
- }
- }
-
- ScrolledComposite scrolledComposite = new ScrolledComposite(comp, SWT.V_SCROLL | SWT.BORDER);
- scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- scrolledComposite.setExpandHorizontal(true);
-
- Composite cmpGraphOptsSeries = new Composite(scrolledComposite, SWT.NONE);
- cmpGraphOptsSeries.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- cmpGraphOptsSeries.setLayout(new GridLayout(2, false));
- scrolledComposite.setContent(cmpGraphOptsSeries);
-
- Label lblTitle = new Label(cmpGraphOptsSeries, SWT.NONE);
- lblTitle.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
- lblTitle.setText(Localization.getString("SelectGraphAndSeriesWizardPage.Title")); //$NON-NLS-1$
- txtTitle = new Text(cmpGraphOptsSeries, SWT.BORDER);
- txtTitle.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- if (edit) {
- txtTitle.setText(model.getGraphData().title);
- }
- txtTitle.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- checkErrors(false);
- }
- });
-
- //Add the data series widgets
- String[] labels = model.getSeries();
-
- cboYItems = new Combo[!edit ? labels.length : Math.max(labels.length, model.getYSeries().length)];
- lblYItems = new Label[cboYItems.length];
- deleted = new boolean[cboYItems.length + 1];
-
- Label lblXItem = new Label(cmpGraphOptsSeries, SWT.NONE);
- lblXItem.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
- lblXItem.setText(Localization.getString("SelectGraphAndSeriesWizardPage.XSeries")); //$NON-NLS-1$
- cboXItem = new Combo(cmpGraphOptsSeries, SWT.DROP_DOWN|SWT.READ_ONLY);
- cboXItem.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- cboXItem.addSelectionListener(new ComboSelectionListener());
- cboXItem.add(Localization.getString("SelectGraphAndSeriesWizardPage.RowID")); //$NON-NLS-1$
-
- for (int i = 0; i < cboYItems.length; i++) {
- lblYItems[i] = new Label(cmpGraphOptsSeries, SWT.NONE);
- lblYItems[i].setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
- lblYItems[i].setText(MessageFormat.format(Localization.getString("SelectGraphAndSeriesWizardPage.YSeries"), i)); //$NON-NLS-1$
- cboYItems[i] = new Combo(cmpGraphOptsSeries, SWT.DROP_DOWN|SWT.READ_ONLY);
- cboYItems[i].setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- cboYItems[i].addSelectionListener(new ComboSelectionListener());
-
- if (i > 0) {
- cboYItems[i].add(Localization.getString("SelectGraphAndSeriesWizardPage.NA")); //$NON-NLS-1$
- cboYItems[i].setVisible(false);
- lblYItems[i].setVisible(false);
- }
- }
-
- for (int j, i = 0; i < labels.length; i++) {
- cboXItem.add(labels[i]);
- for (j = 0; j < lblYItems.length; j++) {
- cboYItems[j].add(labels[i]);
- }
- }
-
- int selected;
- if (!edit) {
- cboXItem.select(0);
- cboYItems[0].select(0);
- } else {
- selected = model.getXSeries();
- if (selected < labels.length){
- cboXItem.select(selected + 1);
- } else {
- cboXItem.add(Localization.getString("SelectGraphAndSeriesWizardPage.Deleted"), 0); //$NON-NLS-1$
- cboXItem.select(0);
- deleted[0] = true;
- }
- selected = model.getYSeries()[0];
- if (selected < labels.length) {
- cboYItems[0].select(selected);
- } else {
- cboYItems[0].add(Localization.getString("SelectGraphAndSeriesWizardPage.Deleted"), 0); //$NON-NLS-1$
- cboYItems[0].select(0);
- deleted[1] = true;
- }
- }
- boolean cvisible = true;
- for (int i = 1; i < cboYItems.length; i++) {
- if (!edit || model.getYSeries().length <= i) {
- cboYItems[i].select(selected = 0);
- } else {
- selected = model.getYSeries()[i];
- if (selected < labels.length){
- cboYItems[i].select(selected + 1);
- } else {
- cboYItems[i].add(Localization.getString("SelectGraphAndSeriesWizardPage.Deleted"), 0); //$NON-NLS-1$
- cboYItems[i].select(0);
- deleted[i+1] = true;
- }
- }
- cboYItems[i].setVisible(cvisible);
- lblYItems[i].setVisible(cvisible);
- cvisible = (selected > 0);
- }
-
- //Select one of the graph types by default, rather than blank choice
- if (!edit) {
- btnGraphs[0].setSelection(true);
- saveDataToModelGraph(graphIDs[0]);
- } else if (btnGraphSelected == -1) {
- saveDataToModelGraph(null);
- }
-
- cmpGraphOptsSeries.pack();
- setControl(comp);
- checkErrors(true);
- }
-
- @Override
- public void handleEvent(Event event) {
- if (event.widget instanceof Button) {
- saveDataToModelGraph(((Button)event.widget).getData().toString());
- checkErrors(false);
- wizard.getContainer().updateButtons();
- }
- }
-
- @Override
- public boolean canFlipToNextPage() {
- return false;
- }
-
- @Override
- public boolean isPageComplete() {
- return saveDataToModelSeries();
- }
-
- /**
- * Saves the choice of graph type to the model.
- * @param selected The ID of the selected graph.
- */
- private void saveDataToModelGraph(String selected) {
- model.setGraph(selected);
- }
-
- /**
- * Saves all information pertaining to series data & naming to the model.
- * @return <code>true</code> if there are no conflicts in series data selection,
- * <code>false</code> otherwise. In the case of the latter, no data is saved.
- */
- private boolean saveDataToModelSeries() {
- if (getErrorMessage() == null) {
- model.setTitle(txtTitle.getText());
- model.setXSeries(cboXItem.getSelectionIndex()-1);
-
- int i, count;
- for (i = 1, count = 1; i < cboYItems.length && 0 != cboYItems[i].getSelectionIndex(); i++) {
- count++;
- }
-
- int[] ySeries = new int[count];
- ySeries[0] = cboYItems[0].getSelectionIndex();
- for (i = 1; i < count; i++) {
- ySeries[i] = cboYItems[i].getSelectionIndex()-1;
- }
- model.setYSeries(ySeries);
- return true;
- }
- return false;
- }
-
- private void markAsDuplicate(Combo item, Boolean bad) {
- item.setForeground(item.getDisplay().getSystemColor(bad ? SWT.COLOR_RED : SWT.COLOR_BLACK));
- }
-
- private boolean isSeriesUnique() {
- Combo item = cboXItem;
- int i = 0;
- do {
- if (item.isVisible() &&
- item.getForeground().equals(item.getDisplay().getSystemColor(SWT.COLOR_RED))) {
- return false;
- }
- if (i == cboYItems.length) {
- return true;
- }
- item = cboYItems[i++];
- } while (true);
- }
-
- /**
- * Checks for conflicts in data selection, and marks them. (An example of a conflict
- * is two Y-series fields set to the same output value.)
- * @return <code>true</code> if there is no conflict, <code>false</code> otherwise.
- */
- private boolean findAndMarkDuplicates() {
- boolean foundDuplicate = false;
-
- // Undo duplicate marking, as it is to be updated.
- markAsDuplicate(cboXItem, false);
- for (int i = 0; i < cboYItems.length; i++) {
- markAsDuplicate(cboYItems[i], false);
- }
-
- for (int j, i = 0; i < cboYItems.length; i++) {
- if (cboYItems[i].isVisible() && !deleted[i+1]) {
-
- // Find duplicates by comparing selection indices. Every combo has an
- // extra selection before column names (Row Num or NA), except Y-series 0.
- int offset = (i == 0 ? 1 : 0);
-
- for (j = i+1; j < cboYItems.length; j++) {
- try {
- if (!deleted[j+1] && cboYItems[j].isVisible()
- && cboYItems[i].getSelectionIndex() + offset == cboYItems[j].getSelectionIndex()) {
- markAsDuplicate(cboYItems[i], true);
- markAsDuplicate(cboYItems[j], true);
- foundDuplicate = true;
- }
- } catch (Exception e) {
- // If a cboYItem has no item selected, don't mark any duplicates. Ignore.
- }
- }
-
- if (deleted[0]) {
- continue;
- }
- try {
- int selection = cboYItems[i].getSelectionIndex() + offset;
- if (selection != 0 && selection == cboXItem.getSelectionIndex()) {
- markAsDuplicate(cboYItems[i], true);
- markAsDuplicate(cboXItem, true);
- foundDuplicate = true;
- }
- } catch (Exception e) {
- // Ignore for same reason as above.
- }
- }
- }
- return !foundDuplicate;
- }
-
- /**
- * Checks for deleted/unselected series entries.
- * @return <code>true if some value is not selected, <code>false</code> otherwise.
- */
- private boolean isSeriesDeleted() {
- for (int i = 0; i < deleted.length; i++) {
- if (deleted[i]) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public void dispose() {
- super.dispose();
- if (null != btnGraphs) {
- for (int i = 0; i < btnGraphs.length; i++) {
- btnGraphs[i].dispose();
- }
- }
- btnGraphs = null;
-
- if (null != txtTitle) {
- txtTitle.dispose();
- }
- txtTitle = null;
-
- if (null != cboXItem) {
- cboXItem.dispose();
- }
- cboXItem = null;
- if (null != cboYItems) {
- for (int i = 0; i < cboYItems.length; i++) {
- if (null != cboYItems[i]) {
- cboYItems[i].dispose();
- }
- cboYItems[i] = null;
- if (null != lblYItems[i]) {
- lblYItems[i].dispose();
- }
- lblYItems[i] = null;
- }
- }
- cboYItems = null;
- lblYItems = null;
- model = null;
- }
-
- /**
- * This class is responsible for updating the menu elements whenever
- * the user interacts with them. Namely, it checks for naming errors
- * and invalid series selections, and handles display of Y-series combo boxes.
- */
- private class ComboSelectionListener implements SelectionListener {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {}
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- Combo source = (Combo) e.getSource();
- if (cboXItem.equals(source)) {
- if (deleted[0] && cboXItem.getSelectionIndex() != 0) {
- cboXItem.remove(0);
- deleted[0] = false;
- }
- }
- else {
- for (int i = 0; i < cboYItems.length; i++) {
- if (deleted[i+1] && cboYItems[i].equals(source) && cboYItems[i].getSelectionIndex() != 0) {
- cboYItems[i].remove(0);
- deleted[i+1] = false;
- break;
- }
- }
- boolean setVisible = true;
- if (GraphFactory.isMultiGraph(model.getGraphID())) {
- for (int i = 1; i < cboYItems.length; i++) {
- cboYItems[i].setVisible(setVisible);
- lblYItems[i].setVisible(setVisible);
- if (!setVisible && deleted[i+1]) {
- cboYItems[i].remove(0);
- deleted[i+1] = false;
- cboYItems[i].select(0);
- }
- if (deleted[i+1] || (cboYItems[i].getSelectionIndex() > 0 && cboYItems[i].isVisible())) {
- setVisible = true;
- } else {
- setVisible = false;
- }
- }
- }
- }
- checkErrors(true);
- }
- }
-
- private void checkErrors(boolean markDuplicates) {
- boolean isUnique = markDuplicates ? findAndMarkDuplicates() : isSeriesUnique();
- if (model.getGraphID() == null) {
- setErrorMessage(Localization.getString("SelectGraphAndSeriesWizardPage.NoGraphType")); //$NON-NLS-1$
- }
- else if (!isUnique) {
- setErrorMessage(Localization.getString("SelectGraphAndSeriesWizardPage.SeriesNotUnique")); //$NON-NLS-1$
- }
- else if (isSeriesDeleted()) {
- setErrorMessage(Localization.getString("SelectGraphAndSeriesWizardPage.SeriesDeleted")); //$NON-NLS-1$
- }
- else if (txtTitle.getText().length() == 0) {
- setErrorMessage(Localization.getString("SelectGraphAndSeriesWizardPage.TitleNotSet")); //$NON-NLS-1$
- }
- else {
- setErrorMessage(null);
- }
- getWizard().getContainer().updateButtons();
- }
-
- private Button[] btnGraphs;
- private SelectGraphAndSeriesWizard wizard;
-
- private Text txtTitle; //TODO: Move this to another page once graphs get more detail
- private Combo cboXItem;
- private Combo[] cboYItems;
- private Label[] lblYItems;
- private GraphModel model;
- private boolean[] deleted;
- private boolean edit;
+ public SelectGraphAndSeriesWizardPage() {
+ super("selectGraphAndSeries"); //$NON-NLS-1$
+ setTitle(Localization.getString("SelectGraphAndSeriesWizardPage.SelectGraphAndSeries")); //$NON-NLS-1$
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ wizard = (SelectGraphAndSeriesWizard)getWizard();
+ model = wizard.model;
+ edit = wizard.isEditing();
+
+ //Set the layout data
+ Composite comp = new Composite(parent, SWT.NONE);
+ comp.setLayout(new GridLayout());
+
+ Group cmpGraphOptsGraph = new Group(comp, SWT.SHADOW_ETCHED_IN);
+ cmpGraphOptsGraph.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
+ RowLayout rowLayout = new RowLayout();
+ rowLayout.type = SWT.HORIZONTAL;
+ rowLayout.spacing = 10;
+ cmpGraphOptsGraph.setLayout(rowLayout);
+ cmpGraphOptsGraph.setText(Localization.getString("SelectGraphAndSeriesWizardPage.Graph")); //$NON-NLS-1$
+
+ String[] graphIDs = GraphFactory.getAvailableGraphs(wizard.model.getDataSet());
+ int btnGraphSelected = -1;
+ btnGraphs = new Button[graphIDs.length];
+ for (int i = 0; i < btnGraphs.length; i++) {
+ btnGraphs[i] = new Button(cmpGraphOptsGraph, SWT.RADIO);
+ btnGraphs[i].setImage(GraphFactory.getGraphImage(graphIDs[i]));
+ btnGraphs[i].addListener(SWT.Selection, this);
+ btnGraphs[i].setData(graphIDs[i]);
+ btnGraphs[i].setToolTipText(GraphFactory.getGraphName(btnGraphs[i].getData().toString()) + "\n\n" + //$NON-NLS-1$
+ GraphFactory.getGraphDescription(btnGraphs[i].getData().toString()));
+ if (btnGraphSelected == -1 && wizard.isEditing() && graphIDs[i].equals(wizard.model.getGraphID())) {
+ btnGraphs[i].setSelection(true);
+ btnGraphSelected = i;
+ }
+ }
+
+ ScrolledComposite scrolledComposite = new ScrolledComposite(comp, SWT.V_SCROLL | SWT.BORDER);
+ scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ scrolledComposite.setExpandHorizontal(true);
+
+ Composite cmpGraphOptsSeries = new Composite(scrolledComposite, SWT.NONE);
+ cmpGraphOptsSeries.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ cmpGraphOptsSeries.setLayout(new GridLayout(2, false));
+ scrolledComposite.setContent(cmpGraphOptsSeries);
+
+ Label lblTitle = new Label(cmpGraphOptsSeries, SWT.NONE);
+ lblTitle.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
+ lblTitle.setText(Localization.getString("SelectGraphAndSeriesWizardPage.Title")); //$NON-NLS-1$
+ txtTitle = new Text(cmpGraphOptsSeries, SWT.BORDER);
+ txtTitle.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+ if (edit) {
+ txtTitle.setText(model.getGraphData().title);
+ }
+ txtTitle.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ checkErrors(false);
+ }
+ });
+
+ //Add the data series widgets
+ String[] labels = model.getSeries();
+
+ cboYItems = new Combo[!edit ? labels.length : Math.max(labels.length, model.getYSeries().length)];
+ lblYItems = new Label[cboYItems.length];
+ deleted = new boolean[cboYItems.length + 1];
+
+ Label lblXItem = new Label(cmpGraphOptsSeries, SWT.NONE);
+ lblXItem.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
+ lblXItem.setText(Localization.getString("SelectGraphAndSeriesWizardPage.XSeries")); //$NON-NLS-1$
+ cboXItem = new Combo(cmpGraphOptsSeries, SWT.DROP_DOWN|SWT.READ_ONLY);
+ cboXItem.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+ cboXItem.addSelectionListener(new ComboSelectionListener());
+ cboXItem.add(Localization.getString("SelectGraphAndSeriesWizardPage.RowID")); //$NON-NLS-1$
+
+ for (int i = 0; i < cboYItems.length; i++) {
+ lblYItems[i] = new Label(cmpGraphOptsSeries, SWT.NONE);
+ lblYItems[i].setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
+ lblYItems[i].setText(MessageFormat.format(Localization.getString("SelectGraphAndSeriesWizardPage.YSeries"), i)); //$NON-NLS-1$
+ cboYItems[i] = new Combo(cmpGraphOptsSeries, SWT.DROP_DOWN|SWT.READ_ONLY);
+ cboYItems[i].setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+ cboYItems[i].addSelectionListener(new ComboSelectionListener());
+
+ if (i > 0) {
+ cboYItems[i].add(Localization.getString("SelectGraphAndSeriesWizardPage.NA")); //$NON-NLS-1$
+ cboYItems[i].setVisible(false);
+ lblYItems[i].setVisible(false);
+ }
+ }
+
+ for (int j, i = 0; i < labels.length; i++) {
+ cboXItem.add(labels[i]);
+ for (j = 0; j < lblYItems.length; j++) {
+ cboYItems[j].add(labels[i]);
+ }
+ }
+
+ int selected;
+ if (!edit) {
+ cboXItem.select(0);
+ cboYItems[0].select(0);
+ } else {
+ selected = model.getXSeries();
+ if (selected < labels.length){
+ cboXItem.select(selected + 1);
+ } else {
+ cboXItem.add(Localization.getString("SelectGraphAndSeriesWizardPage.Deleted"), 0); //$NON-NLS-1$
+ cboXItem.select(0);
+ deleted[0] = true;
+ }
+ selected = model.getYSeries()[0];
+ if (selected < labels.length) {
+ cboYItems[0].select(selected);
+ } else {
+ cboYItems[0].add(Localization.getString("SelectGraphAndSeriesWizardPage.Deleted"), 0); //$NON-NLS-1$
+ cboYItems[0].select(0);
+ deleted[1] = true;
+ }
+ }
+ boolean cvisible = true;
+ for (int i = 1; i < cboYItems.length; i++) {
+ if (!edit || model.getYSeries().length <= i) {
+ cboYItems[i].select(selected = 0);
+ } else {
+ selected = model.getYSeries()[i];
+ if (selected < labels.length){
+ cboYItems[i].select(selected + 1);
+ } else {
+ cboYItems[i].add(Localization.getString("SelectGraphAndSeriesWizardPage.Deleted"), 0); //$NON-NLS-1$
+ cboYItems[i].select(0);
+ deleted[i+1] = true;
+ }
+ }
+ cboYItems[i].setVisible(cvisible);
+ lblYItems[i].setVisible(cvisible);
+ cvisible = (selected > 0);
+ }
+
+ //Select one of the graph types by default, rather than blank choice
+ if (!edit) {
+ btnGraphs[0].setSelection(true);
+ saveDataToModelGraph(graphIDs[0]);
+ } else if (btnGraphSelected == -1) {
+ saveDataToModelGraph(null);
+ }
+
+ cmpGraphOptsSeries.pack();
+ setControl(comp);
+ checkErrors(true);
+ }
+
+ @Override
+ public void handleEvent(Event event) {
+ if (event.widget instanceof Button) {
+ saveDataToModelGraph(((Button)event.widget).getData().toString());
+ checkErrors(false);
+ wizard.getContainer().updateButtons();
+ }
+ }
+
+ @Override
+ public boolean canFlipToNextPage() {
+ return false;
+ }
+
+ @Override
+ public boolean isPageComplete() {
+ return saveDataToModelSeries();
+ }
+
+ /**
+ * Saves the choice of graph type to the model.
+ * @param selected The ID of the selected graph.
+ */
+ private void saveDataToModelGraph(String selected) {
+ model.setGraph(selected);
+ }
+
+ /**
+ * Saves all information pertaining to series data & naming to the model.
+ * @return <code>true</code> if there are no conflicts in series data selection,
+ * <code>false</code> otherwise. In the case of the latter, no data is saved.
+ */
+ private boolean saveDataToModelSeries() {
+ if (getErrorMessage() == null) {
+ model.setTitle(txtTitle.getText());
+ model.setXSeries(cboXItem.getSelectionIndex()-1);
+
+ int i, count;
+ for (i = 1, count = 1; i < cboYItems.length && 0 != cboYItems[i].getSelectionIndex(); i++) {
+ count++;
+ }
+
+ int[] ySeries = new int[count];
+ ySeries[0] = cboYItems[0].getSelectionIndex();
+ for (i = 1; i < count; i++) {
+ ySeries[i] = cboYItems[i].getSelectionIndex()-1;
+ }
+ model.setYSeries(ySeries);
+ return true;
+ }
+ return false;
+ }
+
+ private void markAsDuplicate(Combo item, Boolean bad) {
+ item.setForeground(item.getDisplay().getSystemColor(bad ? SWT.COLOR_RED : SWT.COLOR_BLACK));
+ }
+
+ private boolean isSeriesUnique() {
+ Combo item = cboXItem;
+ int i = 0;
+ do {
+ if (item.isVisible() &&
+ item.getForeground().equals(item.getDisplay().getSystemColor(SWT.COLOR_RED))) {
+ return false;
+ }
+ if (i == cboYItems.length) {
+ return true;
+ }
+ item = cboYItems[i++];
+ } while (true);
+ }
+
+ /**
+ * Checks for conflicts in data selection, and marks them. (An example of a conflict
+ * is two Y-series fields set to the same output value.)
+ * @return <code>true</code> if there is no conflict, <code>false</code> otherwise.
+ */
+ private boolean findAndMarkDuplicates() {
+ boolean foundDuplicate = false;
+
+ // Undo duplicate marking, as it is to be updated.
+ markAsDuplicate(cboXItem, false);
+ for (int i = 0; i < cboYItems.length; i++) {
+ markAsDuplicate(cboYItems[i], false);
+ }
+
+ for (int j, i = 0; i < cboYItems.length; i++) {
+ if (cboYItems[i].isVisible() && !deleted[i+1]) {
+
+ // Find duplicates by comparing selection indices. Every combo has an
+ // extra selection before column names (Row Num or NA), except Y-series 0.
+ int offset = (i == 0 ? 1 : 0);
+
+ for (j = i+1; j < cboYItems.length; j++) {
+ try {
+ if (!deleted[j+1] && cboYItems[j].isVisible()
+ && cboYItems[i].getSelectionIndex() + offset == cboYItems[j].getSelectionIndex()) {
+ markAsDuplicate(cboYItems[i], true);
+ markAsDuplicate(cboYItems[j], true);
+ foundDuplicate = true;
+ }
+ } catch (Exception e) {
+ // If a cboYItem has no item selected, don't mark any duplicates. Ignore.
+ }
+ }
+
+ if (deleted[0]) {
+ continue;
+ }
+ try {
+ int selection = cboYItems[i].getSelectionIndex() + offset;
+ if (selection != 0 && selection == cboXItem.getSelectionIndex()) {
+ markAsDuplicate(cboYItems[i], true);
+ markAsDuplicate(cboXItem, true);
+ foundDuplicate = true;
+ }
+ } catch (Exception e) {
+ // Ignore for same reason as above.
+ }
+ }
+ }
+ return !foundDuplicate;
+ }
+
+ /**
+ * Checks for deleted/unselected series entries.
+ * @return <code>true if some value is not selected, <code>false</code> otherwise.
+ */
+ private boolean isSeriesDeleted() {
+ for (int i = 0; i < deleted.length; i++) {
+ if (deleted[i]) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ if (null != btnGraphs) {
+ for (int i = 0; i < btnGraphs.length; i++) {
+ btnGraphs[i].dispose();
+ }
+ }
+ btnGraphs = null;
+
+ if (null != txtTitle) {
+ txtTitle.dispose();
+ }
+ txtTitle = null;
+
+ if (null != cboXItem) {
+ cboXItem.dispose();
+ }
+ cboXItem = null;
+ if (null != cboYItems) {
+ for (int i = 0; i < cboYItems.length; i++) {
+ if (null != cboYItems[i]) {
+ cboYItems[i].dispose();
+ }
+ cboYItems[i] = null;
+ if (null != lblYItems[i]) {
+ lblYItems[i].dispose();
+ }
+ lblYItems[i] = null;
+ }
+ }
+ cboYItems = null;
+ lblYItems = null;
+ model = null;
+ }
+
+ /**
+ * This class is responsible for updating the menu elements whenever
+ * the user interacts with them. Namely, it checks for naming errors
+ * and invalid series selections, and handles display of Y-series combo boxes.
+ */
+ private class ComboSelectionListener implements SelectionListener {
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {}
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ Combo source = (Combo) e.getSource();
+ if (cboXItem.equals(source)) {
+ if (deleted[0] && cboXItem.getSelectionIndex() != 0) {
+ cboXItem.remove(0);
+ deleted[0] = false;
+ }
+ }
+ else {
+ for (int i = 0; i < cboYItems.length; i++) {
+ if (deleted[i+1] && cboYItems[i].equals(source) && cboYItems[i].getSelectionIndex() != 0) {
+ cboYItems[i].remove(0);
+ deleted[i+1] = false;
+ break;
+ }
+ }
+ boolean setVisible = true;
+ if (GraphFactory.isMultiGraph(model.getGraphID())) {
+ for (int i = 1; i < cboYItems.length; i++) {
+ cboYItems[i].setVisible(setVisible);
+ lblYItems[i].setVisible(setVisible);
+ if (!setVisible && deleted[i+1]) {
+ cboYItems[i].remove(0);
+ deleted[i+1] = false;
+ cboYItems[i].select(0);
+ }
+ if (deleted[i+1] || (cboYItems[i].getSelectionIndex() > 0 && cboYItems[i].isVisible())) {
+ setVisible = true;
+ } else {
+ setVisible = false;
+ }
+ }
+ }
+ }
+ checkErrors(true);
+ }
+ }
+
+ private void checkErrors(boolean markDuplicates) {
+ boolean isUnique = markDuplicates ? findAndMarkDuplicates() : isSeriesUnique();
+ if (model.getGraphID() == null) {
+ setErrorMessage(Localization.getString("SelectGraphAndSeriesWizardPage.NoGraphType")); //$NON-NLS-1$
+ }
+ else if (!isUnique) {
+ setErrorMessage(Localization.getString("SelectGraphAndSeriesWizardPage.SeriesNotUnique")); //$NON-NLS-1$
+ }
+ else if (isSeriesDeleted()) {
+ setErrorMessage(Localization.getString("SelectGraphAndSeriesWizardPage.SeriesDeleted")); //$NON-NLS-1$
+ }
+ else if (txtTitle.getText().length() == 0) {
+ setErrorMessage(Localization.getString("SelectGraphAndSeriesWizardPage.TitleNotSet")); //$NON-NLS-1$
+ }
+ else {
+ setErrorMessage(null);
+ }
+ getWizard().getContainer().updateButtons();
+ }
+
+ private Button[] btnGraphs;
+ private SelectGraphAndSeriesWizard wizard;
+
+ private Text txtTitle; //TODO: Move this to another page once graphs get more detail
+ private Combo cboXItem;
+ private Combo[] cboYItems;
+ private Label[] lblYItems;
+ private GraphModel model;
+ private boolean[] deleted;
+ private boolean edit;
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/pom.xml b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/pom.xml
index 642475c6b4..1b277d7996 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/pom.xml
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/pom.xml
@@ -36,7 +36,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.systemtap.structures.tests</testSuite>
<testClass>org.eclipse.linuxtools.systemtap.structures.tests.AllTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.platform.ide</product>
</configuration>
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/AllTests.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/AllTests.java
index 7b8af33d21..f2922c76cd 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/AllTests.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/AllTests.java
@@ -18,9 +18,9 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ CCodeFileFilterTest.class, CommandTest.class,
- CopierTest.class, IndexedObjectTest.class, KernelSourceTreeTest.class,
- LoggingStreamDaemonTest.class, SortTest.class, StreamGobblerTest.class,
- StringFormatterTest.class, TreeDefinitionNodeTest.class,
- TreeNodeTest.class})
+ CopierTest.class, IndexedObjectTest.class, KernelSourceTreeTest.class,
+ LoggingStreamDaemonTest.class, SortTest.class, StreamGobblerTest.class,
+ StringFormatterTest.class, TreeDefinitionNodeTest.class,
+ TreeNodeTest.class})
public class AllTests {
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/CCodeFileFilterTest.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/CCodeFileFilterTest.java
index 93059935ea..0c9fba3f26 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/CCodeFileFilterTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/CCodeFileFilterTest.java
@@ -22,25 +22,25 @@ import org.junit.Test;
public class CCodeFileFilterTest {
- @Before
- public void setUp(){
- filter = new CCodeFileFilter();
- }
-
- @Test
- public void testAccept() {
- assertFalse(filter.accept(null));
- assertFalse(filter.accept(new File("test")));
- assertFalse(filter.accept(new File("test.java")));
- assertTrue(filter.accept(new File("/root/")));
- assertTrue(filter.accept(new File("test.h")));
- assertTrue(filter.accept(new File("test.c")));
- }
-
- @Test
- public void testGetDescription() {
- filter.getDescription();
- }
-
- private CCodeFileFilter filter;
+ @Before
+ public void setUp(){
+ filter = new CCodeFileFilter();
+ }
+
+ @Test
+ public void testAccept() {
+ assertFalse(filter.accept(null));
+ assertFalse(filter.accept(new File("test")));
+ assertFalse(filter.accept(new File("test.java")));
+ assertTrue(filter.accept(new File("/root/")));
+ assertTrue(filter.accept(new File("test.h")));
+ assertTrue(filter.accept(new File("test.c")));
+ }
+
+ @Test
+ public void testGetDescription() {
+ filter.getDescription();
+ }
+
+ private CCodeFileFilter filter;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/CopierTest.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/CopierTest.java
index cc6c6fd0d7..182150c998 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/CopierTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/CopierTest.java
@@ -22,28 +22,28 @@ import org.junit.Test;
public class CopierTest {
- @Test
- public void testCopy() {
- ArrayList<String> list = new ArrayList<>();
- @SuppressWarnings("unchecked")
- ArrayList<Integer>[] lists = new ArrayList[3];
- int listsSize = 3;
-
- for(int i=0; i<listsSize; i++) {
- list.add("" + i);
- for(int j=0; j<5; j++){
- lists[i] = new ArrayList<>();
- lists[i].add(new Integer(j));
- }
- }
-
- List<String> list2 = Copier.copy(list);
- for(int i=0; i<list.size(); i++) {
- assertEquals(list2.get(i), list.get(i));
- }
-
- List<?>[] lists2 = Copier.copy(lists);
- assertArrayEquals(lists, lists2);
- }
+ @Test
+ public void testCopy() {
+ ArrayList<String> list = new ArrayList<>();
+ @SuppressWarnings("unchecked")
+ ArrayList<Integer>[] lists = new ArrayList[3];
+ int listsSize = 3;
+
+ for(int i=0; i<listsSize; i++) {
+ list.add("" + i);
+ for(int j=0; j<5; j++){
+ lists[i] = new ArrayList<>();
+ lists[i].add(new Integer(j));
+ }
+ }
+
+ List<String> list2 = Copier.copy(list);
+ for(int i=0; i<list.size(); i++) {
+ assertEquals(list2.get(i), list.get(i));
+ }
+
+ List<?>[] lists2 = Copier.copy(lists);
+ assertArrayEquals(lists, lists2);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/IndexedObjectTest.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/IndexedObjectTest.java
index c48f83c318..c34cfe6b16 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/IndexedObjectTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/IndexedObjectTest.java
@@ -20,27 +20,27 @@ import org.junit.Test;
public class IndexedObjectTest{
- @Before
- public void setUp() {
- one = new IndexedObject(1, "one");
- two = new IndexedObject(2, "two");
- three = new IndexedObject(3, "three");
- }
-
- @Test
- public void testToString() {
- assertEquals("one", one.toString());
- assertEquals("two", two.toString());
- assertEquals("three", three.toString());
- }
-
- @Test
- public void testCompareTo() {
- assertEquals(0, one.compareTo(one));
- assertTrue(-1 >= one.compareTo(two));
- assertTrue(1 <= three.compareTo(one));
- assertEquals(0, one.compareTo(null));
- }
-
- private IndexedObject one, two, three;
+ @Before
+ public void setUp() {
+ one = new IndexedObject(1, "one");
+ two = new IndexedObject(2, "two");
+ three = new IndexedObject(3, "three");
+ }
+
+ @Test
+ public void testToString() {
+ assertEquals("one", one.toString());
+ assertEquals("two", two.toString());
+ assertEquals("three", three.toString());
+ }
+
+ @Test
+ public void testCompareTo() {
+ assertEquals(0, one.compareTo(one));
+ assertTrue(-1 >= one.compareTo(two));
+ assertTrue(1 <= three.compareTo(one));
+ assertEquals(0, one.compareTo(null));
+ }
+
+ private IndexedObject one, two, three;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/KernelSourceTreeTest.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/KernelSourceTreeTest.java
index c6acc89375..0bf4988415 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/KernelSourceTreeTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/KernelSourceTreeTest.java
@@ -23,52 +23,52 @@ import org.junit.Test;
public class KernelSourceTreeTest {
- @Before
- public void setUp() {
- kst = new KernelSourceTree();
- }
+ @Before
+ public void setUp() {
+ kst = new KernelSourceTree();
+ }
- @Test
- public void testGetTree() {
- assertNull("Inital tree is null", kst.getTree());
- }
+ @Test
+ public void testGetTree() {
+ assertNull("Inital tree is null", kst.getTree());
+ }
- @Test
- public void testBuildKernelTree() {
- TreeNode t;
+ @Test
+ public void testBuildKernelTree() {
+ TreeNode t;
- String direct = null; //Null
- String[] excluded = null;
- kst.buildKernelTree(direct, excluded);
- assertNull("Null directory", kst.getTree());
+ String direct = null; //Null
+ String[] excluded = null;
+ kst.buildKernelTree(direct, excluded);
+ assertNull("Null directory", kst.getTree());
- direct = ""; //Empty string for directory
- kst.buildKernelTree(direct, excluded);
- assertNull("Empty string directory", kst.getTree());
+ direct = ""; //Empty string for directory
+ kst.buildKernelTree(direct, excluded);
+ assertNull("Empty string directory", kst.getTree());
- direct = "/noSuchDirectory/"; //Missing folder
- kst.buildKernelTree(direct, excluded);
- assertEquals("Missing directory", 0, kst.getTree().getChildCount());
+ direct = "/noSuchDirectory/"; //Missing folder
+ kst.buildKernelTree(direct, excluded);
+ assertEquals("Missing directory", 0, kst.getTree().getChildCount());
- direct = "/root/"; //Inaccessible
- kst.buildKernelTree(direct, excluded);
- assertEquals("Inaccessable directory", 0, kst.getTree().getChildCount());
+ direct = "/root/"; //Inaccessible
+ kst.buildKernelTree(direct, excluded);
+ assertEquals("Inaccessable directory", 0, kst.getTree().getChildCount());
- direct = "/bin/"; //No .c or .h files
- kst.buildKernelTree(direct, excluded);
- t = kst.getTree();
- assertEquals("Bin folder item count", 0, t.getChildCount());
- assertTrue("Bin folder name", "bin".equals(t.toString()));
- assertTrue("Bin has file", t.getData() instanceof IFileStore);
+ direct = "/bin/"; //No .c or .h files
+ kst.buildKernelTree(direct, excluded);
+ t = kst.getTree();
+ assertEquals("Bin folder item count", 0, t.getChildCount());
+ assertTrue("Bin folder name", "bin".equals(t.toString()));
+ assertTrue("Bin has file", t.getData() instanceof IFileStore);
- excluded = new String[] {".git"};
- direct = "/tmp/"; //No .c or .h files
- kst.buildKernelTree(direct, excluded);
- }
+ excluded = new String[] {".git"};
+ direct = "/tmp/"; //No .c or .h files
+ kst.buildKernelTree(direct, excluded);
+ }
- public void testDispose() {
- kst.dispose();
- }
+ public void testDispose() {
+ kst.dispose();
+ }
- private KernelSourceTree kst;
+ private KernelSourceTree kst;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/LoggingStreamDaemonTest.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/LoggingStreamDaemonTest.java
index 095526fef3..c459879e5c 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/LoggingStreamDaemonTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/LoggingStreamDaemonTest.java
@@ -26,46 +26,46 @@ import org.junit.Test;
public class LoggingStreamDaemonTest {
- @Before
- public void setUp(){
- StreamGobbler gobbler = new StreamGobbler(System.in);
- gobbler.start();
- daemon = new LoggingStreamDaemon();
- }
+ @Before
+ public void setUp(){
+ StreamGobbler gobbler = new StreamGobbler(System.in);
+ gobbler.start();
+ daemon = new LoggingStreamDaemon();
+ }
- @Test
- public void testHandleDataEvent() {
- daemon.handleDataEvent("test");
- }
+ @Test
+ public void testHandleDataEvent() {
+ daemon.handleDataEvent("test");
+ }
- @Test
- public void testGetOutput() {
- assertTrue(daemon.getOutput().isEmpty());
+ @Test
+ public void testGetOutput() {
+ assertTrue(daemon.getOutput().isEmpty());
- daemon.handleDataEvent("test");
- assertEquals("test", daemon.getOutput());
- }
+ daemon.handleDataEvent("test");
+ assertEquals("test", daemon.getOutput());
+ }
- @Test
- public void testSaveLog() {
- File f = new File("/tmp/loggingstreamdaemon.test");
- assertTrue(daemon.saveLog(f));
- f.delete();
+ @Test
+ public void testSaveLog() {
+ File f = new File("/tmp/loggingstreamdaemon.test");
+ assertTrue(daemon.saveLog(f));
+ f.delete();
- daemon.handleDataEvent("test");
- assertTrue(daemon.saveLog(f));
- f.delete();
+ daemon.handleDataEvent("test");
+ assertTrue(daemon.saveLog(f));
+ f.delete();
- f = new File("/root/");
- assertFalse(daemon.saveLog(f));
- f.delete();
- }
+ f = new File("/root/");
+ assertFalse(daemon.saveLog(f));
+ f.delete();
+ }
- @After
- public void tearDown() {
- daemon.dispose();
- assertNull(daemon.getOutput());
- }
+ @After
+ public void tearDown() {
+ daemon.dispose();
+ assertNull(daemon.getOutput());
+ }
- private LoggingStreamDaemon daemon;
+ private LoggingStreamDaemon daemon;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/SortTest.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/SortTest.java
index 6c0f8835bf..8c93be7049 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/SortTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/SortTest.java
@@ -20,58 +20,58 @@ import org.junit.Test;
public class SortTest {
- @Test
- public void testQuicksort() {
- String blank = "";
- String[] s0 = null;
- String[] s1 = new String[0];
- String[] s2 = new String[] {blank};
- String[] s3 = new String[] {"a"};
- String[] s4 = new String[] {"a", "b", "c", "d"};
- String[] s5 = new String[] {"d", "c", "b", "a"};
- String[] s6 = new String[] {"c", "d", "a", "b"};
- String[] s7 = new String[] {"a", "d", "a", "b"};
+ @Test
+ public void testQuicksort() {
+ String blank = "";
+ String[] s0 = null;
+ String[] s1 = new String[0];
+ String[] s2 = new String[] {blank};
+ String[] s3 = new String[] {"a"};
+ String[] s4 = new String[] {"a", "b", "c", "d"};
+ String[] s5 = new String[] {"d", "c", "b", "a"};
+ String[] s6 = new String[] {"c", "d", "a", "b"};
+ String[] s7 = new String[] {"a", "d", "a", "b"};
- Sort.quicksort(s0, 0, 0);
- assertNull("Sort null list", s0);
+ Sort.quicksort(s0, 0, 0);
+ assertNull("Sort null list", s0);
- Sort.quicksort(s1, 0, 0);
- assertEquals("Sort empty list", 0, s1.length);
+ Sort.quicksort(s1, 0, 0);
+ assertEquals("Sort empty list", 0, s1.length);
- Sort.quicksort(s2, 0, s2.length-1);
- assertEquals("Sort blank list", 1, s2.length);
- assertEquals("Blank item same", blank, s2[0]);
+ Sort.quicksort(s2, 0, s2.length-1);
+ assertEquals("Sort blank list", 1, s2.length);
+ assertEquals("Blank item same", blank, s2[0]);
- Sort.quicksort(s3, 0, s3.length-1);
- assertEquals("Sort single item list", 1, s3.length);
- assertEquals("Single item same", "a", s3[0]);
+ Sort.quicksort(s3, 0, s3.length-1);
+ assertEquals("Sort single item list", 1, s3.length);
+ assertEquals("Single item same", "a", s3[0]);
- Sort.quicksort(s4, 0, s4.length-1);
- assertEquals("Sort ordered list", 4, s4.length);
- assertEquals("Single item same", "a", s4[0]);
- assertEquals("Single item same", "b", s4[1]);
- assertEquals("Single item same", "c", s4[2]);
- assertEquals("Single item same", "d", s4[3]);
+ Sort.quicksort(s4, 0, s4.length-1);
+ assertEquals("Sort ordered list", 4, s4.length);
+ assertEquals("Single item same", "a", s4[0]);
+ assertEquals("Single item same", "b", s4[1]);
+ assertEquals("Single item same", "c", s4[2]);
+ assertEquals("Single item same", "d", s4[3]);
- Sort.quicksort(s5, 0, s5.length-1);
- assertEquals("Sort reversed list", 4, s5.length);
- assertEquals("Single item same", "a", s5[0]);
- assertEquals("Single item same", "b", s5[1]);
- assertEquals("Single item same", "c", s5[2]);
- assertEquals("Single item same", "d", s5[3]);
+ Sort.quicksort(s5, 0, s5.length-1);
+ assertEquals("Sort reversed list", 4, s5.length);
+ assertEquals("Single item same", "a", s5[0]);
+ assertEquals("Single item same", "b", s5[1]);
+ assertEquals("Single item same", "c", s5[2]);
+ assertEquals("Single item same", "d", s5[3]);
- Sort.quicksort(s6, 0, s6.length-1);
- assertEquals("Sort random list", 4, s6.length);
- assertEquals("Single item same", "a", s6[0]);
- assertEquals("Single item same", "b", s6[1]);
- assertEquals("Single item same", "c", s6[2]);
- assertEquals("Single item same", "d", s6[3]);
+ Sort.quicksort(s6, 0, s6.length-1);
+ assertEquals("Sort random list", 4, s6.length);
+ assertEquals("Single item same", "a", s6[0]);
+ assertEquals("Single item same", "b", s6[1]);
+ assertEquals("Single item same", "c", s6[2]);
+ assertEquals("Single item same", "d", s6[3]);
- Sort.quicksort(s7, 0, s7.length-1);
- assertEquals("Sort duplicate item list", 4, s7.length);
- assertEquals("Single item same", "a", s7[0]);
- assertEquals("Single item same", "a", s7[1]);
- assertEquals("Single item same", "b", s7[2]);
- assertEquals("Single item same", "d", s7[3]);
- }
+ Sort.quicksort(s7, 0, s7.length-1);
+ assertEquals("Sort duplicate item list", 4, s7.length);
+ assertEquals("Single item same", "a", s7[0]);
+ assertEquals("Single item same", "a", s7[1]);
+ assertEquals("Single item same", "b", s7[2]);
+ assertEquals("Single item same", "d", s7[3]);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/StringFormatterTest.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/StringFormatterTest.java
index 901c479fb5..37ecbc5ccc 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/StringFormatterTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/StringFormatterTest.java
@@ -21,68 +21,68 @@ import org.junit.Test;
public class StringFormatterTest {
- @Before
- public void setUp(){
- formatter = new StringFormatter();
- }
+ @Before
+ public void setUp(){
+ formatter = new StringFormatter();
+ }
- @Test
- public void testStringFormatter() {
- formatter = new StringFormatter();
- assertNotNull(formatter);
- }
+ @Test
+ public void testStringFormatter() {
+ formatter = new StringFormatter();
+ assertNotNull(formatter);
+ }
- @Test
- public void testGetFormat() {
- formatter.setFormat(IFormattingStyles.UNFORMATED);
- assertEquals(IFormattingStyles.UNFORMATED, formatter.getFormat());
+ @Test
+ public void testGetFormat() {
+ formatter.setFormat(IFormattingStyles.UNFORMATED);
+ assertEquals(IFormattingStyles.UNFORMATED, formatter.getFormat());
- formatter.setFormat(IFormattingStyles.BINARY);
- assertEquals(IFormattingStyles.BINARY, formatter.getFormat());
+ formatter.setFormat(IFormattingStyles.BINARY);
+ assertEquals(IFormattingStyles.BINARY, formatter.getFormat());
- formatter.setFormat(IFormattingStyles.DOUBLE);
- assertEquals(IFormattingStyles.DOUBLE, formatter.getFormat());
+ formatter.setFormat(IFormattingStyles.DOUBLE);
+ assertEquals(IFormattingStyles.DOUBLE, formatter.getFormat());
- formatter.setFormat(IFormattingStyles.HEX);
- assertEquals(IFormattingStyles.HEX, formatter.getFormat());
+ formatter.setFormat(IFormattingStyles.HEX);
+ assertEquals(IFormattingStyles.HEX, formatter.getFormat());
- formatter.setFormat(IFormattingStyles.OCTAL);
- assertEquals(IFormattingStyles.OCTAL, formatter.getFormat());
+ formatter.setFormat(IFormattingStyles.OCTAL);
+ assertEquals(IFormattingStyles.OCTAL, formatter.getFormat());
- formatter.setFormat(IFormattingStyles.STRING);
- assertEquals(IFormattingStyles.STRING, formatter.getFormat());
+ formatter.setFormat(IFormattingStyles.STRING);
+ assertEquals(IFormattingStyles.STRING, formatter.getFormat());
- formatter.setFormat(IFormattingStyles.DATE);
- assertEquals(IFormattingStyles.DATE, formatter.getFormat());
- }
+ formatter.setFormat(IFormattingStyles.DATE);
+ assertEquals(IFormattingStyles.DATE, formatter.getFormat());
+ }
- public void testSetFormat() {
- formatter.setFormat(IFormattingStyles.BINARY);
- assertNotNull(formatter);
- }
+ public void testSetFormat() {
+ formatter.setFormat(IFormattingStyles.BINARY);
+ assertNotNull(formatter);
+ }
- public void testFormat() {
- formatter.setFormat(IFormattingStyles.BINARY);
- assertEquals("0x1000", formatter.format("8"));
+ public void testFormat() {
+ formatter.setFormat(IFormattingStyles.BINARY);
+ assertEquals("0x1000", formatter.format("8"));
- formatter.setFormat(IFormattingStyles.HEX);
- assertEquals("0x8", formatter.format("8"));
+ formatter.setFormat(IFormattingStyles.HEX);
+ assertEquals("0x8", formatter.format("8"));
- formatter.setFormat(IFormattingStyles.OCTAL);
- assertEquals("0x10",formatter.format("8"));
+ formatter.setFormat(IFormattingStyles.OCTAL);
+ assertEquals("0x10",formatter.format("8"));
- formatter.setFormat(IFormattingStyles.STRING);
- assertEquals("8", formatter.format("8"));
+ formatter.setFormat(IFormattingStyles.STRING);
+ assertEquals("8", formatter.format("8"));
- formatter.setFormat(IFormattingStyles.UNFORMATED);
- assertEquals("8", formatter.format("8"));
+ formatter.setFormat(IFormattingStyles.UNFORMATED);
+ assertEquals("8", formatter.format("8"));
- formatter.setFormat(IFormattingStyles.DATE);
- assertEquals("Dec 31, 1969 4:00:00 PM", formatter.format("8"));
+ formatter.setFormat(IFormattingStyles.DATE);
+ assertEquals("Dec 31, 1969 4:00:00 PM", formatter.format("8"));
- formatter.setFormat(IFormattingStyles.DOUBLE);
- assertEquals("8.0", formatter.format("8"));
- }
+ formatter.setFormat(IFormattingStyles.DOUBLE);
+ assertEquals("8.0", formatter.format("8"));
+ }
- private StringFormatter formatter;
+ private StringFormatter formatter;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/TreeDefinitionNodeTest.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/TreeDefinitionNodeTest.java
index a25bdec87f..103ac3f177 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/TreeDefinitionNodeTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/TreeDefinitionNodeTest.java
@@ -23,58 +23,58 @@ import org.junit.Test;
public class TreeDefinitionNodeTest {
- @Before
- public void setUp() {
- data = new StringBuilder("Object");
- data2 = "Data";
- d = "/usr/share";
- d2 = "/usr";
- s = "String";
- s2 = "bah";
+ @Before
+ public void setUp() {
+ data = new StringBuilder("Object");
+ data2 = "Data";
+ d = "/usr/share";
+ d2 = "/usr";
+ s = "String";
+ s2 = "bah";
- t = new TreeDefinitionNode(data, s, d, true);
- child = new TreeDefinitionNode(data2, s2, d2, false);
- t.add(child);
- }
+ t = new TreeDefinitionNode(data, s, d, true);
+ child = new TreeDefinitionNode(data2, s2, d2, false);
+ t.add(child);
+ }
- @Test
- public void testTreeDefinitionNode() {
- String d1 = "One";
- String d2 = "two";
- String s1 = "one";
+ @Test
+ public void testTreeDefinitionNode() {
+ String d1 = "One";
+ String d2 = "two";
+ String s1 = "one";
- TreeDefinitionNode t = new TreeDefinitionNode(d1, s1, d2, false);
- assertEquals("Create child count", 0, t.getChildCount());
- assertEquals("Create child string", s1, t.toString());
- assertEquals("Create child data", d1, t.getData());
- assertEquals("Create child definition", d2, t.getDefinition());
- assertFalse("Create child clickable", t.isClickable());
- }
+ TreeDefinitionNode t = new TreeDefinitionNode(d1, s1, d2, false);
+ assertEquals("Create child count", 0, t.getChildCount());
+ assertEquals("Create child string", s1, t.toString());
+ assertEquals("Create child data", d1, t.getData());
+ assertEquals("Create child definition", d2, t.getDefinition());
+ assertFalse("Create child clickable", t.isClickable());
+ }
- @Test
- public void testGetDefinition() {
- assertNotSame("Correct definition", d2, t.getDefinition());
- assertEquals("Correct definition2", d2, ((TreeDefinitionNode)t.getChildAt(0)).getDefinition());
- }
+ @Test
+ public void testGetDefinition() {
+ assertNotSame("Correct definition", d2, t.getDefinition());
+ assertEquals("Correct definition2", d2, ((TreeDefinitionNode)t.getChildAt(0)).getDefinition());
+ }
- @Test
- public void testSetDefinition() {
- String s1 = "/user/share/systemtap";
- t.setDefinition(s1);
- assertEquals("Replaced definition", s1, t.getDefinition());
- }
+ @Test
+ public void testSetDefinition() {
+ String s1 = "/user/share/systemtap";
+ t.setDefinition(s1);
+ assertEquals("Replaced definition", s1, t.getDefinition());
+ }
- @Test
- public void testDispose() {
- assertNotNull(t.getDefinition());
- t.dispose();
- assertNull(t.getDefinition());
- }
+ @Test
+ public void testDispose() {
+ assertNotNull(t.getDefinition());
+ t.dispose();
+ assertNull(t.getDefinition());
+ }
- private TreeDefinitionNode t;
- private TreeDefinitionNode child;
- private Object data;
- private String data2;
- private String s, s2;
- private String d, d2;
+ private TreeDefinitionNode t;
+ private TreeDefinitionNode child;
+ private Object data;
+ private String data2;
+ private String s, s2;
+ private String d, d2;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/TreeNodeTest.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/TreeNodeTest.java
index 636428b9d2..f8452a4ebb 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/TreeNodeTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/TreeNodeTest.java
@@ -22,221 +22,221 @@ import org.junit.Test;
public class TreeNodeTest {
- @Before
- public void setUp() {
-
- data = new StringBuilder("Object");
- data2 = "Data";
- s = "String";
-
- t = new TreeNode(data, s, false);
- child = new TreeNode(data2, true);
- child2 = new TreeNode(data, s, false);
- t.add(child);
- t.add(child2);
- }
-
- @Test
- public void testTreeNode() {
- String d1 = "One";
- String d2 = "two";
- String s1 = "one";
-
- TreeNode t1 = new TreeNode(d1, s1, false);
- assertEquals("Create child count", 0, t1.getChildCount());
- assertEquals("Create child string", s1, t1.toString());
- assertEquals("Create child data", d1, t1.getData());
- assertFalse("Create child clickable", t1.isClickable());
-
- TreeNode t2 = new TreeNode(d2, true);
- assertEquals("Create child count", 0, t2.getChildCount());
- assertTrue("Create child string", t2.toString().equals(d2));
- assertEquals("Create child data", d2, t2.getData());
- assertTrue("Create child clickable", t2.isClickable());
-
- TreeNode t3 = new TreeNode(null, true);
- assertEquals("Create child count", 0, t3.getChildCount());
- assertEquals("Create child string", null, t3.toString());
- assertEquals("Create child data", null, t3.getData());
- assertTrue("Create child clickable", t3.isClickable());
-
- TreeNode t4 = new TreeNode(d1, s1, false);
- assertEquals("Create child count", 0, t4.getChildCount());
- assertEquals("Create child string", s1, t4.toString());
- assertEquals("Create child data", d1, t4.getData());
- assertFalse("Create child clickable", t4.isClickable());
- }
-
- @Test
- public void testAdd() {
- t.add(new TreeNode("One", "tne", false));
- assertEquals("Add child", 3, t.getChildCount());
-
- t.add(new TreeNode("two", false));
- assertEquals("Add child2", 4, t.getChildCount());
- }
-
- @Test
- public void testAddAt() {
- TreeNode test1 = new TreeNode("one", false);
- t.addAt(test1, 0);
- assertEquals("Child added to front", test1, t.getChildAt(0));
- assertEquals("Child correctly added", 3, t.getChildCount());
-
- TreeNode test2 = new TreeNode("two", false);
- t.addAt(test2, 1);
- assertEquals("Child added to middle", test2, t.getChildAt(1));
- assertEquals("Child correctly added", 4, t.getChildCount());
-
- TreeNode test3 = new TreeNode("three", false);
- t.addAt(test3, 3);
- assertEquals("Child added to end", test3, t.getChildAt(3));
- assertEquals("Child correctly added", 5, t.getChildCount());
-
- TreeNode test4 = new TreeNode("four", false);
- t.addAt(test4, 30);
- assertEquals("Child added to end", test4, t.getChildAt(5));
- assertEquals("Child correctly added", 6, t.getChildCount());
- }
-
- @Test
- public void testGetChildAt() {
- TreeNode child1 = new TreeNode("1", false);
- t.add(child1);
- TreeNode child2 = new TreeNode("2", false);
- t.add(child2);
-
- TreeNode c = t.getChildAt(0);
- assertEquals("Retreive first child from tree", child, c);
-
- c = t.getChildAt(2);
- assertEquals("Retreive middle child from tree", child1, c);
-
- c = t.getChildAt(3);
- assertEquals("Retreive last child from tree", child2, c);
-
- assertNull("No child here", t.getChildAt(10));
- }
-
- @Test
- public void testGetChildCount() {
- assertEquals("Tree child count", 2, t.getChildCount());
- assertEquals("Child child count", 0, t.getChildAt(0).getChildCount());
- }
-
- @Test
- public void testGetData() {
- assertEquals("Correct data", data, t.getData());
- assertEquals("Correct data2", data2, t.getChildAt(0).getData());
- }
-
- @Test
- public void testIsClickable() {
- assertFalse("Nonclickable root", t.isClickable());
- assertTrue("Clickable child", t.getChildAt(0).isClickable());
- }
-
- @Test
- public void testRemove() {
- TreeNode child1 = new TreeNode("1", false);
- t.add(child1);
- TreeNode child2 = new TreeNode("2", false);
- t.add(child2);
- TreeNode child3 = new TreeNode("3", false);
- t.add(child3);
-
- assertEquals("Full tree before remove", 5, t.getChildCount());
-
- assertTrue(t.remove(1));
- assertEquals("Remove middle child from tree", 4, t.getChildCount());
-
- assertTrue(t.remove(0));
- assertEquals("Remove first child from tree", 3, t.getChildCount());
-
- assertTrue(t.remove(1));
- assertEquals("Remove last child from tree", 2, t.getChildCount());
-
- assertFalse(t.remove(10));
- assertEquals("Remove IndexOutOfBounds", 2, t.getChildCount());
- }
-
- @Test
- public void testRemoveAll() {
- t.add(new TreeNode("Child", false));
-
- assertTrue(t.removeAll());
- assertEquals("No children", 0, t.getChildCount());
-
- assertTrue(t.removeAll());
- assertEquals("Still no children", 0, t.getChildCount());
- }
-
- @Test
- public void testSetData() {
- Object o = "asdf";
- t.setData(o);
- assertEquals("Replaced data", o, t.getData());
-
- String o1 = "aaaa";
- t.setData(o1);
- assertEquals("Replaced data with string", o1, t.getData());
- }
-
- @Test
- public void testSetDisplay() {
- String s1 = "aaaa";
- t.setDisplay(s1);
- assertEquals("Replaced display", s1, t.toString());
- }
-
- @Test
- public void testSortTree() {
- TreeNode child1 = new TreeNode("2", false);
- t.add(child1);
- TreeNode child2 = new TreeNode("1", false);
- t.add(child2);
- TreeNode child3 = new TreeNode("3", false);
- t.add(child3);
-
- t.sortTree();
- assertEquals("Same number of children", 5, t.getChildCount());
- assertEquals("Sorted first node correct", child2, t.getChildAt(0));
- assertEquals("Sorted last node correct", child, t.getChildAt(3));
- assertEquals("Sorted middle correct", child1, t.getChildAt(1));
- }
-
- @Test
- public void testSortLevel() {
- TreeNode child1 = new TreeNode("2", false);
- t.add(child1);
- TreeNode child2 = new TreeNode("1", false);
- t.add(child2);
- TreeNode child3 = new TreeNode("3", false);
- t.add(child3);
-
-
- t.sortLevel();
- assertEquals("Same number of children", 5, t.getChildCount());
- assertEquals("Sorted first node correct", child2, t.getChildAt(0));
- assertEquals("Sorted last node correct", child, t.getChildAt(3));
- assertEquals("Sorted middle correct", child1, t.getChildAt(1));
- }
-
- @Test
- public void testToString() {
- assertEquals("Object to string", data2, child.toString());
- assertEquals("Dispaly to string", s, t.toString());
- }
-
- @Test
- public void testDispose() {
- t.dispose();
- }
-
- private TreeNode t;
- private TreeNode child;
- private TreeNode child2;
- private Object data;
- private String data2;
- private String s;
+ @Before
+ public void setUp() {
+
+ data = new StringBuilder("Object");
+ data2 = "Data";
+ s = "String";
+
+ t = new TreeNode(data, s, false);
+ child = new TreeNode(data2, true);
+ child2 = new TreeNode(data, s, false);
+ t.add(child);
+ t.add(child2);
+ }
+
+ @Test
+ public void testTreeNode() {
+ String d1 = "One";
+ String d2 = "two";
+ String s1 = "one";
+
+ TreeNode t1 = new TreeNode(d1, s1, false);
+ assertEquals("Create child count", 0, t1.getChildCount());
+ assertEquals("Create child string", s1, t1.toString());
+ assertEquals("Create child data", d1, t1.getData());
+ assertFalse("Create child clickable", t1.isClickable());
+
+ TreeNode t2 = new TreeNode(d2, true);
+ assertEquals("Create child count", 0, t2.getChildCount());
+ assertTrue("Create child string", t2.toString().equals(d2));
+ assertEquals("Create child data", d2, t2.getData());
+ assertTrue("Create child clickable", t2.isClickable());
+
+ TreeNode t3 = new TreeNode(null, true);
+ assertEquals("Create child count", 0, t3.getChildCount());
+ assertEquals("Create child string", null, t3.toString());
+ assertEquals("Create child data", null, t3.getData());
+ assertTrue("Create child clickable", t3.isClickable());
+
+ TreeNode t4 = new TreeNode(d1, s1, false);
+ assertEquals("Create child count", 0, t4.getChildCount());
+ assertEquals("Create child string", s1, t4.toString());
+ assertEquals("Create child data", d1, t4.getData());
+ assertFalse("Create child clickable", t4.isClickable());
+ }
+
+ @Test
+ public void testAdd() {
+ t.add(new TreeNode("One", "tne", false));
+ assertEquals("Add child", 3, t.getChildCount());
+
+ t.add(new TreeNode("two", false));
+ assertEquals("Add child2", 4, t.getChildCount());
+ }
+
+ @Test
+ public void testAddAt() {
+ TreeNode test1 = new TreeNode("one", false);
+ t.addAt(test1, 0);
+ assertEquals("Child added to front", test1, t.getChildAt(0));
+ assertEquals("Child correctly added", 3, t.getChildCount());
+
+ TreeNode test2 = new TreeNode("two", false);
+ t.addAt(test2, 1);
+ assertEquals("Child added to middle", test2, t.getChildAt(1));
+ assertEquals("Child correctly added", 4, t.getChildCount());
+
+ TreeNode test3 = new TreeNode("three", false);
+ t.addAt(test3, 3);
+ assertEquals("Child added to end", test3, t.getChildAt(3));
+ assertEquals("Child correctly added", 5, t.getChildCount());
+
+ TreeNode test4 = new TreeNode("four", false);
+ t.addAt(test4, 30);
+ assertEquals("Child added to end", test4, t.getChildAt(5));
+ assertEquals("Child correctly added", 6, t.getChildCount());
+ }
+
+ @Test
+ public void testGetChildAt() {
+ TreeNode child1 = new TreeNode("1", false);
+ t.add(child1);
+ TreeNode child2 = new TreeNode("2", false);
+ t.add(child2);
+
+ TreeNode c = t.getChildAt(0);
+ assertEquals("Retreive first child from tree", child, c);
+
+ c = t.getChildAt(2);
+ assertEquals("Retreive middle child from tree", child1, c);
+
+ c = t.getChildAt(3);
+ assertEquals("Retreive last child from tree", child2, c);
+
+ assertNull("No child here", t.getChildAt(10));
+ }
+
+ @Test
+ public void testGetChildCount() {
+ assertEquals("Tree child count", 2, t.getChildCount());
+ assertEquals("Child child count", 0, t.getChildAt(0).getChildCount());
+ }
+
+ @Test
+ public void testGetData() {
+ assertEquals("Correct data", data, t.getData());
+ assertEquals("Correct data2", data2, t.getChildAt(0).getData());
+ }
+
+ @Test
+ public void testIsClickable() {
+ assertFalse("Nonclickable root", t.isClickable());
+ assertTrue("Clickable child", t.getChildAt(0).isClickable());
+ }
+
+ @Test
+ public void testRemove() {
+ TreeNode child1 = new TreeNode("1", false);
+ t.add(child1);
+ TreeNode child2 = new TreeNode("2", false);
+ t.add(child2);
+ TreeNode child3 = new TreeNode("3", false);
+ t.add(child3);
+
+ assertEquals("Full tree before remove", 5, t.getChildCount());
+
+ assertTrue(t.remove(1));
+ assertEquals("Remove middle child from tree", 4, t.getChildCount());
+
+ assertTrue(t.remove(0));
+ assertEquals("Remove first child from tree", 3, t.getChildCount());
+
+ assertTrue(t.remove(1));
+ assertEquals("Remove last child from tree", 2, t.getChildCount());
+
+ assertFalse(t.remove(10));
+ assertEquals("Remove IndexOutOfBounds", 2, t.getChildCount());
+ }
+
+ @Test
+ public void testRemoveAll() {
+ t.add(new TreeNode("Child", false));
+
+ assertTrue(t.removeAll());
+ assertEquals("No children", 0, t.getChildCount());
+
+ assertTrue(t.removeAll());
+ assertEquals("Still no children", 0, t.getChildCount());
+ }
+
+ @Test
+ public void testSetData() {
+ Object o = "asdf";
+ t.setData(o);
+ assertEquals("Replaced data", o, t.getData());
+
+ String o1 = "aaaa";
+ t.setData(o1);
+ assertEquals("Replaced data with string", o1, t.getData());
+ }
+
+ @Test
+ public void testSetDisplay() {
+ String s1 = "aaaa";
+ t.setDisplay(s1);
+ assertEquals("Replaced display", s1, t.toString());
+ }
+
+ @Test
+ public void testSortTree() {
+ TreeNode child1 = new TreeNode("2", false);
+ t.add(child1);
+ TreeNode child2 = new TreeNode("1", false);
+ t.add(child2);
+ TreeNode child3 = new TreeNode("3", false);
+ t.add(child3);
+
+ t.sortTree();
+ assertEquals("Same number of children", 5, t.getChildCount());
+ assertEquals("Sorted first node correct", child2, t.getChildAt(0));
+ assertEquals("Sorted last node correct", child, t.getChildAt(3));
+ assertEquals("Sorted middle correct", child1, t.getChildAt(1));
+ }
+
+ @Test
+ public void testSortLevel() {
+ TreeNode child1 = new TreeNode("2", false);
+ t.add(child1);
+ TreeNode child2 = new TreeNode("1", false);
+ t.add(child2);
+ TreeNode child3 = new TreeNode("3", false);
+ t.add(child3);
+
+
+ t.sortLevel();
+ assertEquals("Same number of children", 5, t.getChildCount());
+ assertEquals("Sorted first node correct", child2, t.getChildAt(0));
+ assertEquals("Sorted last node correct", child, t.getChildAt(3));
+ assertEquals("Sorted middle correct", child1, t.getChildAt(1));
+ }
+
+ @Test
+ public void testToString() {
+ assertEquals("Object to string", data2, child.toString());
+ assertEquals("Dispaly to string", s, t.toString());
+ }
+
+ @Test
+ public void testDispose() {
+ t.dispose();
+ }
+
+ private TreeNode t;
+ private TreeNode child;
+ private TreeNode child2;
+ private Object data;
+ private String data2;
+ private String s;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/runnable/CommandTest.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/runnable/CommandTest.java
index 204c7d0ca0..87322f70c1 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/runnable/CommandTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/runnable/CommandTest.java
@@ -27,95 +27,95 @@ import org.junit.Test;
public class CommandTest extends SystemtapTest{
- @Before
- public void setUp() {
- tc = new Command(new String[] {"ls", "/home/"}, null);
- }
-
- @Test
- public void testCommand() {
- assertNotNull("Command not null", tc);
-
- tc.dispose();
- tc = new Command(null, null);
- assertNotNull("Command not null", tc);
-
- tc.dispose();
- tc = new Command(new String[] {}, null);
- assertNotNull("Command not null", tc);
-
- tc.dispose();
- tc = new Command(new String[] {""}, null);
- assertNotNull("Command not null", tc);
-
- tc.dispose();
- tc = new Command(new String[] {"a"}, null);
- assertNotNull("Command not null", tc);
-
- tc.dispose();
- tc = new Command(new String[] {"ls", "/"}, null);
- assertNotNull("Command not null", tc);
- }
-
- @Test
- public void testIsFinished() {
- assumeTrue(stapInstalled);
- assertTrue("Not finished", tc.isRunning());
- tc.stop();
- assertFalse("Finished", tc.isRunning());
- }
-
- @Test
- public void testGetReturnValue() {
- assertEquals(Integer.MAX_VALUE, tc.getReturnValue());
- }
-
- @Test
- public void testLoggedCommand() throws CoreException {
- assumeTrue(stapInstalled);
- tc.dispose();
-
- tc = new Command(new String[] {"stap", "-v", "-p1", "-e", "probe nosuchfunc{}"}, null);
- tc.start();
- assertTrue(tc.isRunning());
- assertFalse(tc.isDisposed());
- tc.stop();
- assertFalse(tc.isRunning());
- assertFalse(tc.isDisposed());
- tc.dispose();
-
- tc = new Command(new String[] {"stap", "-v", "-p1", "-e", "probe nosuchfunc{}"}, null);
- tc.start();
- assertTrue(tc.isRunning());
- assertFalse(tc.isDisposed());
- tc.stop();
- assertFalse(tc.isRunning());
- assertFalse(tc.isDisposed());
- tc.dispose();
- }
-
- @Test
- public void testStop() throws CoreException {
- assumeTrue(stapInstalled);
- tc.start();
- assertTrue(tc.isRunning());
- tc.stop();
- assertFalse(tc.isRunning());
- }
-
- @Test
- public void testDispose() {
- assertFalse(tc.isDisposed());
- tc.dispose();
- assertTrue(tc.isDisposed());
- }
-
- @After
- public void tearDown() {
- tc.dispose();
- assertTrue(tc.isDisposed());
- }
-
- Command tc;
+ @Before
+ public void setUp() {
+ tc = new Command(new String[] {"ls", "/home/"}, null);
+ }
+
+ @Test
+ public void testCommand() {
+ assertNotNull("Command not null", tc);
+
+ tc.dispose();
+ tc = new Command(null, null);
+ assertNotNull("Command not null", tc);
+
+ tc.dispose();
+ tc = new Command(new String[] {}, null);
+ assertNotNull("Command not null", tc);
+
+ tc.dispose();
+ tc = new Command(new String[] {""}, null);
+ assertNotNull("Command not null", tc);
+
+ tc.dispose();
+ tc = new Command(new String[] {"a"}, null);
+ assertNotNull("Command not null", tc);
+
+ tc.dispose();
+ tc = new Command(new String[] {"ls", "/"}, null);
+ assertNotNull("Command not null", tc);
+ }
+
+ @Test
+ public void testIsFinished() {
+ assumeTrue(stapInstalled);
+ assertTrue("Not finished", tc.isRunning());
+ tc.stop();
+ assertFalse("Finished", tc.isRunning());
+ }
+
+ @Test
+ public void testGetReturnValue() {
+ assertEquals(Integer.MAX_VALUE, tc.getReturnValue());
+ }
+
+ @Test
+ public void testLoggedCommand() throws CoreException {
+ assumeTrue(stapInstalled);
+ tc.dispose();
+
+ tc = new Command(new String[] {"stap", "-v", "-p1", "-e", "probe nosuchfunc{}"}, null);
+ tc.start();
+ assertTrue(tc.isRunning());
+ assertFalse(tc.isDisposed());
+ tc.stop();
+ assertFalse(tc.isRunning());
+ assertFalse(tc.isDisposed());
+ tc.dispose();
+
+ tc = new Command(new String[] {"stap", "-v", "-p1", "-e", "probe nosuchfunc{}"}, null);
+ tc.start();
+ assertTrue(tc.isRunning());
+ assertFalse(tc.isDisposed());
+ tc.stop();
+ assertFalse(tc.isRunning());
+ assertFalse(tc.isDisposed());
+ tc.dispose();
+ }
+
+ @Test
+ public void testStop() throws CoreException {
+ assumeTrue(stapInstalled);
+ tc.start();
+ assertTrue(tc.isRunning());
+ tc.stop();
+ assertFalse(tc.isRunning());
+ }
+
+ @Test
+ public void testDispose() {
+ assertFalse(tc.isDisposed());
+ tc.dispose();
+ assertTrue(tc.isDisposed());
+ }
+
+ @After
+ public void tearDown() {
+ tc.dispose();
+ assertTrue(tc.isDisposed());
+ }
+
+ Command tc;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/runnable/StreamGobblerTest.java b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/runnable/StreamGobblerTest.java
index 57eb76e5cc..80495c56cf 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/runnable/StreamGobblerTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures.tests/src/org/eclipse/linuxtools/systemtap/structures/tests/runnable/StreamGobblerTest.java
@@ -23,53 +23,53 @@ import org.junit.Test;
public class StreamGobblerTest{
- private static class TestStream extends InputStream{
- int i = 10;
- @Override
- public int read() {
- if (i < 0)
- return -1;
+ private static class TestStream extends InputStream{
+ int i = 10;
+ @Override
+ public int read() {
+ if (i < 0)
+ return -1;
- return i--;
- }
- }
+ return i--;
+ }
+ }
- @Before
- public void setUp() {
- sg = new StreamGobbler(new TestStream());
- sg.start();
- }
+ @Before
+ public void setUp() {
+ sg = new StreamGobbler(new TestStream());
+ sg.start();
+ }
- @Test
- public void testStreamGobbler() {
- assertNotNull("StreamGobbler not null", sg);
+ @Test
+ public void testStreamGobbler() {
+ assertNotNull("StreamGobbler not null", sg);
- sg = new StreamGobbler(null);
- assertNotNull("StreamGobbler not null", sg);
+ sg = new StreamGobbler(null);
+ assertNotNull("StreamGobbler not null", sg);
- sg = new StreamGobbler(new TestStream());
- assertNotNull("StreamGobbler not null", sg);
- }
+ sg = new StreamGobbler(new TestStream());
+ assertNotNull("StreamGobbler not null", sg);
+ }
- @Test
- public void testIsRunning() {
- assertTrue("StreamGobbler running", sg.isRunning());
- sg.stop();
- assertFalse("StreamGobbler stopped", sg.isRunning());
- }
-
- @Test
- public void testStop() {
- assertTrue("StreamGobbler running", sg.isRunning());
- sg.stop();
- assertFalse("StreamGobbler stopped", sg.isRunning());
- }
-
- @Test
- public void testDispose() {
- sg.dispose();
- assertFalse(sg.isRunning());
- }
-
- StreamGobbler sg;
+ @Test
+ public void testIsRunning() {
+ assertTrue("StreamGobbler running", sg.isRunning());
+ sg.stop();
+ assertFalse("StreamGobbler stopped", sg.isRunning());
+ }
+
+ @Test
+ public void testStop() {
+ assertTrue("StreamGobbler running", sg.isRunning());
+ sg.stop();
+ assertFalse("StreamGobbler stopped", sg.isRunning());
+ }
+
+ @Test
+ public void testDispose() {
+ sg.dispose();
+ assertFalse(sg.isRunning());
+ }
+
+ StreamGobbler sg;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/internal/systemtap/structures/Localization.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/internal/systemtap/structures/Localization.java
index 06c787ebe8..1486e39399 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/internal/systemtap/structures/Localization.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/internal/systemtap/structures/Localization.java
@@ -15,19 +15,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Localization {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.structures.localization"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.structures.localization"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Localization() {
- }
+ private Localization() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/internal/systemtap/structures/StructuresPlugin.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/internal/systemtap/structures/StructuresPlugin.java
index 03541ec41e..75d9bfe641 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/internal/systemtap/structures/StructuresPlugin.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/internal/systemtap/structures/StructuresPlugin.java
@@ -18,6 +18,6 @@ package org.eclipse.linuxtools.internal.systemtap.structures;
*/
public interface StructuresPlugin {
- String PLUGIN_ID = "org.eclipse.linuxtools.systemtap.structures"; //$NON-NLS-1$
+ String PLUGIN_ID = "org.eclipse.linuxtools.systemtap.structures"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/CCodeFileFilter.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/CCodeFileFilter.java
index 552887cd70..100541dfcf 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/CCodeFileFilter.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/CCodeFileFilter.java
@@ -15,40 +15,40 @@ import java.io.File;
import java.io.FileFilter;
public class CCodeFileFilter implements FileFilter {
- /**
- * Checks a file type and only passes it (returns true) if it is either a directory, a .c, or a .h
- * file type.
- *
- * @param f The file to check.
- *
- * @return A boolean value indicating whether or not to display the file.
- */
- @Override
- public boolean accept(File f) {
- if(null == f)
- return false;
- return accept(f.getName(), f.isDirectory());
- }
+ /**
+ * Checks a file type and only passes it (returns true) if it is either a directory, a .c, or a .h
+ * file type.
+ *
+ * @param f The file to check.
+ *
+ * @return A boolean value indicating whether or not to display the file.
+ */
+ @Override
+ public boolean accept(File f) {
+ if(null == f)
+ return false;
+ return accept(f.getName(), f.isDirectory());
+ }
- /**
- * Checks a file type and only passes it (returns true) if it is either a directory, a .c, or a .h
- * file type.
- *
- * @param name The name of the file
- * @param isDir Is this file a directory?
- *
- * @return A boolean value indicating whether or not to display the file.
- *
- * @since 1.1
- */
- public boolean accept(String name, boolean isDir) {
- String lower = name.toLowerCase();
- return isDir ||
- lower.endsWith(".c") || //$NON-NLS-1$
- lower.endsWith(".h"); //$NON-NLS-1$
- }
+ /**
+ * Checks a file type and only passes it (returns true) if it is either a directory, a .c, or a .h
+ * file type.
+ *
+ * @param name The name of the file
+ * @param isDir Is this file a directory?
+ *
+ * @return A boolean value indicating whether or not to display the file.
+ *
+ * @since 1.1
+ */
+ public boolean accept(String name, boolean isDir) {
+ String lower = name.toLowerCase();
+ return isDir ||
+ lower.endsWith(".c") || //$NON-NLS-1$
+ lower.endsWith(".h"); //$NON-NLS-1$
+ }
- public String getDescription() {
- return ".c, .h files"; //$NON-NLS-1$
- }
+ public String getDescription() {
+ return ".c, .h files"; //$NON-NLS-1$
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/Copier.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/Copier.java
index 9288783e15..61c04fe0b0 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/Copier.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/Copier.java
@@ -16,36 +16,36 @@ import java.util.List;
public final class Copier {
- /**
- * Returns a copy of the passed in ArrayList array object.
- *
- * @param list The ArrayList array object to copy.
- *
- * @return The copy of the ArrayList array.
- * @since 3.0
- */
- public static <T> List<T>[] copy(List<T>[] list) {
- @SuppressWarnings("unchecked")
- List<T>[] list2 = new ArrayList[list.length];
-
- for(int i=0; i<list2.length; i++)
- list2[i] = copy(list[i]);
-
- return list2;
- }
-
- /**
- * Returns a copy of the passed in ArrayList object.
- *
- * @param list The ArrayList object to copy.
- *
- * @return The copy of the ArrayList.
- * @since 3.0
- */
- public static<T> List<T> copy(List<T> list) {
-
- ArrayList<T> list2 = new ArrayList<>();
- list2.addAll(list);
- return list2;
- }
+ /**
+ * Returns a copy of the passed in ArrayList array object.
+ *
+ * @param list The ArrayList array object to copy.
+ *
+ * @return The copy of the ArrayList array.
+ * @since 3.0
+ */
+ public static <T> List<T>[] copy(List<T>[] list) {
+ @SuppressWarnings("unchecked")
+ List<T>[] list2 = new ArrayList[list.length];
+
+ for(int i=0; i<list2.length; i++)
+ list2[i] = copy(list[i]);
+
+ return list2;
+ }
+
+ /**
+ * Returns a copy of the passed in ArrayList object.
+ *
+ * @param list The ArrayList object to copy.
+ *
+ * @return The copy of the ArrayList.
+ * @since 3.0
+ */
+ public static<T> List<T> copy(List<T> list) {
+
+ ArrayList<T> list2 = new ArrayList<>();
+ list2.addAll(list);
+ return list2;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/IFormattingStyles.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/IFormattingStyles.java
index 6e85196794..8dd2663581 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/IFormattingStyles.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/IFormattingStyles.java
@@ -14,17 +14,17 @@ package org.eclipse.linuxtools.systemtap.structures;
import org.eclipse.linuxtools.internal.systemtap.structures.Localization;
public interface IFormattingStyles {
- int UNFORMATED = 0;
- int STRING = 1;
- int DATE = 2;
- int DOUBLE = 3;
- int HEX = 4;
- int OCTAL = 5;
- int BINARY = 6;
+ int UNFORMATED = 0;
+ int STRING = 1;
+ int DATE = 2;
+ int DOUBLE = 3;
+ int HEX = 4;
+ int OCTAL = 5;
+ int BINARY = 6;
- String[] FORMAT_TITLES = {Localization.getString("IFormattingStyles.Unformatted"), Localization.getString("IFormattingStyles.String"), Localization.getString("IFormattingStyles.Date"), Localization.getString("IFormattingStyles.Double"), Localization.getString("IFormattingStyles.Hex"), Localization.getString("IFormattingStyles.Octal"), Localization.getString("IFormattingStyles.Binary")}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ String[] FORMAT_TITLES = {Localization.getString("IFormattingStyles.Unformatted"), Localization.getString("IFormattingStyles.String"), Localization.getString("IFormattingStyles.Date"), Localization.getString("IFormattingStyles.Double"), Localization.getString("IFormattingStyles.Hex"), Localization.getString("IFormattingStyles.Octal"), Localization.getString("IFormattingStyles.Binary")}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- void setFormat(int format);
- String format(String s);
- int getFormat();
+ void setFormat(int format);
+ String format(String s);
+ int getFormat();
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/IndexedObject.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/IndexedObject.java
index 721446809b..daae4081b2 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/IndexedObject.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/IndexedObject.java
@@ -13,26 +13,26 @@ package org.eclipse.linuxtools.systemtap.structures;
public class IndexedObject implements Comparable<IndexedObject>{
- public int index;
- public Object val;
+ public int index;
+ public Object val;
- public IndexedObject(int i, Object v) {
- index = i;
- val = v;
- }
+ public IndexedObject(int i, Object v) {
+ index = i;
+ val = v;
+ }
- @Override
- public String toString() {
- return val.toString();
- }
+ @Override
+ public String toString() {
+ return val.toString();
+ }
- @Override
- public int compareTo(IndexedObject o) {
- if(o != null) {
- Comparable thisVal = (val instanceof Comparable) ? (Comparable)val : val.toString();
- Comparable otherVal = (o.val instanceof Comparable) ? (Comparable)o.val : o.val.toString();
- return thisVal.compareTo(otherVal);
- }
- return 0;
- }
+ @Override
+ public int compareTo(IndexedObject o) {
+ if(o != null) {
+ Comparable thisVal = (val instanceof Comparable) ? (Comparable)val : val.toString();
+ Comparable otherVal = (o.val instanceof Comparable) ? (Comparable)o.val : o.val.toString();
+ return thisVal.compareTo(otherVal);
+ }
+ return 0;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/KernelSourceTree.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/KernelSourceTree.java
index 4ca7c64827..ce26d34327 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/KernelSourceTree.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/KernelSourceTree.java
@@ -25,106 +25,106 @@ import org.eclipse.linuxtools.profiling.launch.IRemoteFileProxy;
import org.eclipse.linuxtools.profiling.launch.RemoteProxyManager;
public class KernelSourceTree {
- public TreeNode getTree() {
- return kernelTree;
- }
+ public TreeNode getTree() {
+ return kernelTree;
+ }
- /**
- * Builds the kernel tree from file parameter direct and stores the excluded string array.
- *
- * @param direct The file to include into the tree.
- * @param excluded The string array to store as excluded.
- */
- public void buildKernelTree(String direct, String[] excluded) {
- if (direct == null || direct.isEmpty()){
- kernelTree = null;
- return;
- }
- try {
- URI locationURI = new URI(direct);
- IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(locationURI);
- this.buildKernelTree(locationURI, excluded, proxy, null);
- } catch (URISyntaxException e) {
- kernelTree = null;
- } catch (CoreException e) {
- kernelTree = null;
- }
- }
+ /**
+ * Builds the kernel tree from file parameter direct and stores the excluded string array.
+ *
+ * @param direct The file to include into the tree.
+ * @param excluded The string array to store as excluded.
+ */
+ public void buildKernelTree(String direct, String[] excluded) {
+ if (direct == null || direct.isEmpty()){
+ kernelTree = null;
+ return;
+ }
+ try {
+ URI locationURI = new URI(direct);
+ IRemoteFileProxy proxy = RemoteProxyManager.getInstance().getFileProxy(locationURI);
+ this.buildKernelTree(locationURI, excluded, proxy, null);
+ } catch (URISyntaxException e) {
+ kernelTree = null;
+ } catch (CoreException e) {
+ kernelTree = null;
+ }
+ }
- /**
- * Builds the kernel tree from file parameter direct and stores the excluded string array.
- *
- * @param locationURI The URI to include into the tree.
- * @param excluded The string array to store as excluded.
- * @param proxy The proxy to be used to get the remote files
- * @param monitor a progress monitor for this operation. Can be null.
- * @throws CoreException
- *
- * @since 1.1
- */
- public void buildKernelTree(URI locationURI, String[] excluded, IRemoteFileProxy proxy, IProgressMonitor monitor) throws CoreException {
- if (excluded != null){
- this.excluded = Arrays.copyOf(excluded, excluded.length);
- }
- IFileStore fs = proxy.getResource(locationURI.getPath());
- if (fs == null) {
- kernelTree = null;
- } else {
- kernelTree = new TreeNode(fs, fs.getName(), false);
- addLevel(kernelTree, monitor);
- }
- }
+ /**
+ * Builds the kernel tree from file parameter direct and stores the excluded string array.
+ *
+ * @param locationURI The URI to include into the tree.
+ * @param excluded The string array to store as excluded.
+ * @param proxy The proxy to be used to get the remote files
+ * @param monitor a progress monitor for this operation. Can be null.
+ * @throws CoreException
+ *
+ * @since 1.1
+ */
+ public void buildKernelTree(URI locationURI, String[] excluded, IRemoteFileProxy proxy, IProgressMonitor monitor) throws CoreException {
+ if (excluded != null){
+ this.excluded = Arrays.copyOf(excluded, excluded.length);
+ }
+ IFileStore fs = proxy.getResource(locationURI.getPath());
+ if (fs == null) {
+ kernelTree = null;
+ } else {
+ kernelTree = new TreeNode(fs, fs.getName(), false);
+ addLevel(kernelTree, monitor);
+ }
+ }
- /**
- * Adds a level to the kernel source tree.
- *
- * @param top The top of the tree to add a level to.
- * @throws CoreException
- */
- private void addLevel(TreeNode top, IProgressMonitor monitor) throws CoreException {
- boolean add;
- TreeNode current;
- IFileStore fs = (IFileStore)top.getData();
- IFileStore[] fsList = null;
- fsList = fs.childStores(EFS.NONE, new NullProgressMonitor());
- if (monitor != null) {
- monitor.beginTask(Localization.getString("ReadingKernelSourceTree"), 100); //$NON-NLS-1$
- }
- CCodeFileFilter filter = new CCodeFileFilter();
- for (IFileStore fsChildren : fsList) {
- add = true;
- boolean isDir = fsChildren.fetchInfo().isDirectory();
- if (!filter.accept(fsChildren.getName(), isDir)) {
- continue;
- }
+ /**
+ * Adds a level to the kernel source tree.
+ *
+ * @param top The top of the tree to add a level to.
+ * @throws CoreException
+ */
+ private void addLevel(TreeNode top, IProgressMonitor monitor) throws CoreException {
+ boolean add;
+ TreeNode current;
+ IFileStore fs = (IFileStore)top.getData();
+ IFileStore[] fsList = null;
+ fsList = fs.childStores(EFS.NONE, new NullProgressMonitor());
+ if (monitor != null) {
+ monitor.beginTask(Localization.getString("ReadingKernelSourceTree"), 100); //$NON-NLS-1$
+ }
+ CCodeFileFilter filter = new CCodeFileFilter();
+ for (IFileStore fsChildren : fsList) {
+ add = true;
+ boolean isDir = fsChildren.fetchInfo().isDirectory();
+ if (!filter.accept(fsChildren.getName(), isDir)) {
+ continue;
+ }
- for(int j=0; j<excluded.length; j++) {
- if(fsChildren.getName().equals(excluded[j].substring(0, excluded[j].length()-1)) && isDir) {
- add = false;
- break;
- }
- }
- if(add) {
- current = new TreeNode(fsChildren, fsChildren.getName(), !isDir);
- top.add(current);
- if(isDir) {
- addLevel(top.getChildAt(top.getChildCount()-1), null);
- if(0 == current.getChildCount()) {
- top.remove(top.getChildCount()-1);
- }
- }
- }
- if (monitor != null) {
- monitor.worked(1);
- }
- }
- top.sortLevel();
- }
+ for(int j=0; j<excluded.length; j++) {
+ if(fsChildren.getName().equals(excluded[j].substring(0, excluded[j].length()-1)) && isDir) {
+ add = false;
+ break;
+ }
+ }
+ if(add) {
+ current = new TreeNode(fsChildren, fsChildren.getName(), !isDir);
+ top.add(current);
+ if(isDir) {
+ addLevel(top.getChildAt(top.getChildCount()-1), null);
+ if(0 == current.getChildCount()) {
+ top.remove(top.getChildCount()-1);
+ }
+ }
+ }
+ if (monitor != null) {
+ monitor.worked(1);
+ }
+ }
+ top.sortLevel();
+ }
- public void dispose() {
- kernelTree = null;
- }
+ public void dispose() {
+ kernelTree = null;
+ }
- private TreeNode kernelTree;
- private String[] excluded = new String[0];
+ private TreeNode kernelTree;
+ private String[] excluded = new String[0];
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/LoggingStreamDaemon.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/LoggingStreamDaemon.java
index 2ca4bdeb6c..6865824537 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/LoggingStreamDaemon.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/LoggingStreamDaemon.java
@@ -22,112 +22,112 @@ import org.eclipse.linuxtools.systemtap.structures.listeners.IGobblerListener;
public class LoggingStreamDaemon implements IGobblerListener {
- /**
- * Sets up an output to log to.
- */
- public LoggingStreamDaemon() {
- output = new StringBuilder();
- try {
- outputFile = File.createTempFile(this.toString(), ".tmp"); //$NON-NLS-1$
- writer = new FileWriter(outputFile, true);
- } catch(IOException ioe) {
- outputFile = null;
- }
- saveLog = false;
- }
+ /**
+ * Sets up an output to log to.
+ */
+ public LoggingStreamDaemon() {
+ output = new StringBuilder();
+ try {
+ outputFile = File.createTempFile(this.toString(), ".tmp"); //$NON-NLS-1$
+ writer = new FileWriter(outputFile, true);
+ } catch(IOException ioe) {
+ outputFile = null;
+ }
+ saveLog = false;
+ }
- /**
- * Pushes output to log.
- */
- private void pushData() {
- if(null != writer) {
- try {
- writer.write(output.toString());
- output.delete(0, output.length());
- writer.flush();
- } catch(IOException ioe) {}
- }
- }
+ /**
+ * Pushes output to log.
+ */
+ private void pushData() {
+ if(null != writer) {
+ try {
+ writer.write(output.toString());
+ output.delete(0, output.length());
+ writer.flush();
+ } catch(IOException ioe) {}
+ }
+ }
- /**
- * Outputs one line.
- */
- @Override
- public void handleDataEvent(String line) {
- output.append(line);
- this.pushData();
- }
+ /**
+ * Outputs one line.
+ */
+ @Override
+ public void handleDataEvent(String line) {
+ output.append(line);
+ this.pushData();
+ }
- /**
- * Reads in and returns the output produced.
- *
- * @return The logged data.
- */
- public String getOutput() {
- if(null == outputFile)
- return null;
- if(output.length() > 0) pushData();
- try (FileReader reader = new FileReader(outputFile)) {
- char[] buffer = new char[BUFFER_SIZE];
- int count;
- StringBuilder builder = new StringBuilder();
- while(-1 != (count = reader.read(buffer))) {
- builder.append(buffer, 0, count);
- }
- return builder.toString();
- } catch(IOException ioe) {}
- return null;
- }
+ /**
+ * Reads in and returns the output produced.
+ *
+ * @return The logged data.
+ */
+ public String getOutput() {
+ if(null == outputFile)
+ return null;
+ if(output.length() > 0) pushData();
+ try (FileReader reader = new FileReader(outputFile)) {
+ char[] buffer = new char[BUFFER_SIZE];
+ int count;
+ StringBuilder builder = new StringBuilder();
+ while(-1 != (count = reader.read(buffer))) {
+ builder.append(buffer, 0, count);
+ }
+ return builder.toString();
+ } catch(IOException ioe) {}
+ return null;
+ }
- /**
- * Saves the logfile.
- *
- * @param file The file to save the log data to.
- *
- * @return True if the save was successful.
- */
- public boolean saveLog(File file) {
- try {
- if(!file.exists()) {
- file.getParentFile().mkdirs();
- file.createNewFile();
- }
- FileWriter w = new FileWriter(file, true);
- try (FileReader r = new FileReader(outputFile)) {
- char[] buffer = new char[BUFFER_SIZE];
- int count;
- while (-1 != (count = r.read(buffer))) {
- w.write(new String(buffer, 0, count));
- }
- }
- w.flush();
- writer.close();
- writer = w;
- outputFile.delete();
- outputFile = file;
- saveLog = true;
- } catch(IOException ioe) {
- return false;
- }
- return true;
- }
+ /**
+ * Saves the logfile.
+ *
+ * @param file The file to save the log data to.
+ *
+ * @return True if the save was successful.
+ */
+ public boolean saveLog(File file) {
+ try {
+ if(!file.exists()) {
+ file.getParentFile().mkdirs();
+ file.createNewFile();
+ }
+ FileWriter w = new FileWriter(file, true);
+ try (FileReader r = new FileReader(outputFile)) {
+ char[] buffer = new char[BUFFER_SIZE];
+ int count;
+ while (-1 != (count = r.read(buffer))) {
+ w.write(new String(buffer, 0, count));
+ }
+ }
+ w.flush();
+ writer.close();
+ writer = w;
+ outputFile.delete();
+ outputFile = file;
+ saveLog = true;
+ } catch(IOException ioe) {
+ return false;
+ }
+ return true;
+ }
- public void dispose() {
- if(null != outputFile && !saveLog)
- outputFile.delete();
- outputFile = null;
- if(null != writer) {
- try {
- writer.close();
- } catch(IOException ioe) {}
- }
- writer = null;
- }
+ public void dispose() {
+ if(null != outputFile && !saveLog)
+ outputFile.delete();
+ outputFile = null;
+ if(null != writer) {
+ try {
+ writer.close();
+ } catch(IOException ioe) {}
+ }
+ writer = null;
+ }
- protected StringBuilder output;
- protected File outputFile;
- protected FileWriter writer;
- private boolean saveLog;
+ protected StringBuilder output;
+ protected File outputFile;
+ protected FileWriter writer;
+ private boolean saveLog;
- private static final int BUFFER_SIZE = 1024;
+ private static final int BUFFER_SIZE = 1024;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/Sort.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/Sort.java
index 8a6a647f81..8d584fe853 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/Sort.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/Sort.java
@@ -12,58 +12,58 @@
package org.eclipse.linuxtools.systemtap.structures;
public final class Sort {
-
- /**
- * Performs quicksort on the supplied list.
- *
- * @param list The list to sort.
- * @param p Recursed value, initially top value.
- * @param r Recursed value, initially bottom value.
- */
- public static void quicksort(Object[] list, int p, int r) {
- if(null == list)
- return;
- else if (p < r) {
- int q = partition(list,p,r);
- if (q == r)
- q--;
- quicksort(list,p,q);
- quicksort(list,q+1,r);
- }
- }
+ /**
+ * Performs quicksort on the supplied list.
+ *
+ * @param list The list to sort.
+ * @param p Recursed value, initially top value.
+ * @param r Recursed value, initially bottom value.
+ */
+ public static void quicksort(Object[] list, int p, int r) {
+ if(null == list)
+ return;
+ else if (p < r) {
+ int q = partition(list,p,r);
+ if (q == r)
+ q--;
- /**
- * Partitions the input list, used by Quiksort.
- *
- * @param list The list to partition.
- * @param p Recursed value, initially top value.
- * @param r Recursed value, initially bottom value.
- */
- private static int partition (Object[] list, int p, int r) {
- Comparable pivot = (list[p] instanceof Comparable ? (Comparable)list[p] : list[p].toString());
- int lo = p;
- int hi = r;
+ quicksort(list,p,q);
+ quicksort(list,q+1,r);
+ }
+ }
- while (true) {
- while (getComparable(list[hi]).compareTo(pivot) >= 0 && lo < hi)
- hi--;
+ /**
+ * Partitions the input list, used by Quiksort.
+ *
+ * @param list The list to partition.
+ * @param p Recursed value, initially top value.
+ * @param r Recursed value, initially bottom value.
+ */
+ private static int partition (Object[] list, int p, int r) {
+ Comparable pivot = (list[p] instanceof Comparable ? (Comparable)list[p] : list[p].toString());
+ int lo = p;
+ int hi = r;
- while (getComparable(list[lo]).compareTo(pivot) < 0 && lo < hi)
- lo++;
-
- if (lo < hi) {
- Object T = list[lo];
- list[lo] = list[hi];
- list[hi] = T;
- } else
- return hi;
- }
- }
-
- private static Comparable getComparable(Object o) {
- return (o instanceof Comparable
- ? (Comparable)o
- : o.toString());
- }
+ while (true) {
+ while (getComparable(list[hi]).compareTo(pivot) >= 0 && lo < hi)
+ hi--;
+
+ while (getComparable(list[lo]).compareTo(pivot) < 0 && lo < hi)
+ lo++;
+
+ if (lo < hi) {
+ Object T = list[lo];
+ list[lo] = list[hi];
+ list[hi] = T;
+ } else
+ return hi;
+ }
+ }
+
+ private static Comparable getComparable(Object o) {
+ return (o instanceof Comparable
+ ? (Comparable)o
+ : o.toString());
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/StringFormatter.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/StringFormatter.java
index 45b20a1e64..0b8617435b 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/StringFormatter.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/StringFormatter.java
@@ -16,46 +16,46 @@ import java.util.Date;
public class StringFormatter implements IFormattingStyles {
- public StringFormatter() {
- format = IFormattingStyles.UNFORMATED;
- }
-
- @Override
- public int getFormat() {
- return format;
- }
-
- @Override
- public void setFormat(int format) {
- this.format = format;
- }
-
- /**
- * Potentially modifies a string value according to a certain format based on the current value
- * of format.
- *
- * @param s The string to potential modify.
- *
- * @return The modified string.
- */
- @Override
- public String format(String s) {
- switch (format) {
- case STRING:
- return s;
- case DATE:
- return DateFormat.getDateTimeInstance().format(new Date(Long.parseLong(s)));
- case HEX:
- return "0x"+Long.toHexString(Long.parseLong(s)); //$NON-NLS-1$
- case OCTAL:
- return "0x"+Long.toOctalString(Long.parseLong(s)); //$NON-NLS-1$
- case BINARY:
- return "0x" + Long.toBinaryString(Long.parseLong(s)); //$NON-NLS-1$
- case DOUBLE:
- return "" + Double.parseDouble(s); //$NON-NLS-1$
- }
- return s;
- }
-
- private int format;
+ public StringFormatter() {
+ format = IFormattingStyles.UNFORMATED;
+ }
+
+ @Override
+ public int getFormat() {
+ return format;
+ }
+
+ @Override
+ public void setFormat(int format) {
+ this.format = format;
+ }
+
+ /**
+ * Potentially modifies a string value according to a certain format based on the current value
+ * of format.
+ *
+ * @param s The string to potential modify.
+ *
+ * @return The modified string.
+ */
+ @Override
+ public String format(String s) {
+ switch (format) {
+ case STRING:
+ return s;
+ case DATE:
+ return DateFormat.getDateTimeInstance().format(new Date(Long.parseLong(s)));
+ case HEX:
+ return "0x"+Long.toHexString(Long.parseLong(s)); //$NON-NLS-1$
+ case OCTAL:
+ return "0x"+Long.toOctalString(Long.parseLong(s)); //$NON-NLS-1$
+ case BINARY:
+ return "0x" + Long.toBinaryString(Long.parseLong(s)); //$NON-NLS-1$
+ case DOUBLE:
+ return "" + Double.parseDouble(s); //$NON-NLS-1$
+ }
+ return s;
+ }
+
+ private int format;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/TreeDefinitionNode.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/TreeDefinitionNode.java
index 6a808539b4..a3a421a031 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/TreeDefinitionNode.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/TreeDefinitionNode.java
@@ -13,24 +13,24 @@ package org.eclipse.linuxtools.systemtap.structures;
public class TreeDefinitionNode extends TreeNode {
- public TreeDefinitionNode(Object d, String disp, String def, boolean c) {
- super(d, disp, c);
- definition = def;
- }
+ public TreeDefinitionNode(Object d, String disp, String def, boolean c) {
+ super(d, disp, c);
+ definition = def;
+ }
- public String getDefinition() {
- return definition;
- }
+ public String getDefinition() {
+ return definition;
+ }
- public void setDefinition(String d) {
- definition = d;
- }
+ public void setDefinition(String d) {
+ definition = d;
+ }
- @Override
- public void dispose() {
- super.dispose();
- definition = null;
- }
+ @Override
+ public void dispose() {
+ super.dispose();
+ definition = null;
+ }
- private String definition;
+ private String definition;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/TreeNode.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/TreeNode.java
index 9aa5e89c2b..639be9f36e 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/TreeNode.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/TreeNode.java
@@ -15,131 +15,131 @@ import java.util.ArrayList;
import java.util.List;
public class TreeNode {
- public TreeNode(Object d, boolean c) {
- children = new ArrayList<>();
- data = d;
- clickable = c;
-
- if(null == data) {
- display = null;
- } else {
- display = d.toString();
- }
- }
-
- public TreeNode(Object d, String disp, boolean c) {
- children = new ArrayList<>();
- data = d;
- display = disp;
- clickable = c;
- }
-
- public void add(TreeNode item) {
- children.add(item);
- }
-
- public void addAt(TreeNode item, int location) {
- children.add(Math.min(children.size(), location), item);
- }
-
- public int getChildCount() {
- return children.size();
- }
-
- public TreeNode getChildAt(int i){
- if(children.size() > i) {
- return children.get(i);
- } else {
- return null;
- }
- }
-
- public Object getData() {
- return data;
- }
-
- public boolean isClickable() {
- return clickable;
- }
-
- public boolean remove(int i) {
- if(children.size() > i) {
- return(null != children.remove(i));
- } else {
- return false;
- }
- }
-
- public boolean removeAll() {
- for(int i=children.size()-1; i>=0; i--) {
- remove(i);
- }
- return true;
- }
-
- public void setData(Object d) {
- data = d;
- }
-
- public void setDisplay(String disp) {
- display = disp;
- }
-
- /**
- * Restructures the tree so that probes are grouped by type and
- * functions are sorted alphabetically.
- */
- public void sortTree() {
- sortLevel();
- for (TreeNode temp : children) {
- temp.sortTree();
- }
- }
-
- /**
- * Performs quicksort on the level.
- */
- public void sortLevel() {
- TreeNode[] children = this.children.toArray(new TreeNode[0]);
- removeAll();
- Sort.quicksort(children, 0, children.length - 1);
-
- for (TreeNode child : children) {
- add(child);
- }
- }
-
- @Override
- public String toString() {
- return display;
- }
-
- public void dispose() {
- if (null != children) {
- for (TreeNode child : children) {
- child.dispose();
- }
- }
- children = null;
- data = null;
- display = null;
- }
-
- /**
- * @since 2.0
- */
- public TreeNode getChildByName(String name){
- for (TreeNode child : children) {
- if (child.toString().equals(name)) {
- return child;
- }
- }
-
- return null;
- }
-
- private List<TreeNode> children;
- private Object data;
- private String display;
- private boolean clickable;
+ public TreeNode(Object d, boolean c) {
+ children = new ArrayList<>();
+ data = d;
+ clickable = c;
+
+ if(null == data) {
+ display = null;
+ } else {
+ display = d.toString();
+ }
+ }
+
+ public TreeNode(Object d, String disp, boolean c) {
+ children = new ArrayList<>();
+ data = d;
+ display = disp;
+ clickable = c;
+ }
+
+ public void add(TreeNode item) {
+ children.add(item);
+ }
+
+ public void addAt(TreeNode item, int location) {
+ children.add(Math.min(children.size(), location), item);
+ }
+
+ public int getChildCount() {
+ return children.size();
+ }
+
+ public TreeNode getChildAt(int i){
+ if(children.size() > i) {
+ return children.get(i);
+ } else {
+ return null;
+ }
+ }
+
+ public Object getData() {
+ return data;
+ }
+
+ public boolean isClickable() {
+ return clickable;
+ }
+
+ public boolean remove(int i) {
+ if(children.size() > i) {
+ return(null != children.remove(i));
+ } else {
+ return false;
+ }
+ }
+
+ public boolean removeAll() {
+ for(int i=children.size()-1; i>=0; i--) {
+ remove(i);
+ }
+ return true;
+ }
+
+ public void setData(Object d) {
+ data = d;
+ }
+
+ public void setDisplay(String disp) {
+ display = disp;
+ }
+
+ /**
+ * Restructures the tree so that probes are grouped by type and
+ * functions are sorted alphabetically.
+ */
+ public void sortTree() {
+ sortLevel();
+ for (TreeNode temp : children) {
+ temp.sortTree();
+ }
+ }
+
+ /**
+ * Performs quicksort on the level.
+ */
+ public void sortLevel() {
+ TreeNode[] children = this.children.toArray(new TreeNode[0]);
+ removeAll();
+ Sort.quicksort(children, 0, children.length - 1);
+
+ for (TreeNode child : children) {
+ add(child);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return display;
+ }
+
+ public void dispose() {
+ if (null != children) {
+ for (TreeNode child : children) {
+ child.dispose();
+ }
+ }
+ children = null;
+ data = null;
+ display = null;
+ }
+
+ /**
+ * @since 2.0
+ */
+ public TreeNode getChildByName(String name){
+ for (TreeNode child : children) {
+ if (child.toString().equals(name)) {
+ return child;
+ }
+ }
+
+ return null;
+ }
+
+ private List<TreeNode> children;
+ private Object data;
+ private String display;
+ private boolean clickable;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/UpdateManager.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/UpdateManager.java
index d8f9523604..00b58e01e2 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/UpdateManager.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/UpdateManager.java
@@ -21,81 +21,81 @@ import org.eclipse.linuxtools.systemtap.structures.listeners.IUpdateListener;
public class UpdateManager {
- public UpdateManager(int delay) {
- updateListeners = new ArrayList<>();
- stopped = false;
- disposed = false;
- restart(delay);
- }
+ public UpdateManager(int delay) {
+ updateListeners = new ArrayList<>();
+ stopped = false;
+ disposed = false;
+ restart(delay);
+ }
- /**
- * @since 3.0
- */
- public void restart(int delay) {
- if (timer != null) {
- timer.cancel();
- }
- timer = new Timer("Update Manager", true); //$NON-NLS-1$
- timer.scheduleAtFixedRate(new Notify(), delay, delay);
- }
+ /**
+ * @since 3.0
+ */
+ public void restart(int delay) {
+ if (timer != null) {
+ timer.cancel();
+ }
+ timer = new Timer("Update Manager", true); //$NON-NLS-1$
+ timer.scheduleAtFixedRate(new Notify(), delay, delay);
+ }
- /**
- * Terminates the timer and removes all update listeners.
- */
- public void stop() {
- if(!stopped) {
- stopped = true;
- timer.cancel();
- synchronized (updateListeners) {
- for(int i=0; i<updateListeners.size(); i++) {
- removeUpdateListener(updateListeners.get(i));
- }
- }
- }
- }
+ /**
+ * Terminates the timer and removes all update listeners.
+ */
+ public void stop() {
+ if(!stopped) {
+ stopped = true;
+ timer.cancel();
+ synchronized (updateListeners) {
+ for(int i=0; i<updateListeners.size(); i++) {
+ removeUpdateListener(updateListeners.get(i));
+ }
+ }
+ }
+ }
- public void addUpdateListener(IUpdateListener l) {
- if(!updateListeners.contains(l)) {
- updateListeners.add(l);
- }
- }
- public void removeUpdateListener(IUpdateListener l) {
- if(updateListeners.contains(l)) {
- updateListeners.remove(l);
- }
- }
+ public void addUpdateListener(IUpdateListener l) {
+ if(!updateListeners.contains(l)) {
+ updateListeners.add(l);
+ }
+ }
+ public void removeUpdateListener(IUpdateListener l) {
+ if(updateListeners.contains(l)) {
+ updateListeners.remove(l);
+ }
+ }
- public boolean isRunning() {
- return !stopped;
- }
+ public boolean isRunning() {
+ return !stopped;
+ }
- public void dispose() {
- if(!disposed) {
- disposed = true;
- stop();
- timer = null;
- updateListeners = null;
- }
- }
+ public void dispose() {
+ if(!disposed) {
+ disposed = true;
+ stop();
+ timer = null;
+ updateListeners = null;
+ }
+ }
- /**
- * Handle any events that are timed to occur.
- */
- private class Notify extends TimerTask {
- @Override
- public void run() {
- if(!stopped) {
- synchronized (updateListeners) {
- for(int i = 0; i < updateListeners.size(); i++) {
- (updateListeners.get(i)).handleUpdateEvent();
- }
- }
- }
- }
- }
+ /**
+ * Handle any events that are timed to occur.
+ */
+ private class Notify extends TimerTask {
+ @Override
+ public void run() {
+ if(!stopped) {
+ synchronized (updateListeners) {
+ for(int i = 0; i < updateListeners.size(); i++) {
+ (updateListeners.get(i)).handleUpdateEvent();
+ }
+ }
+ }
+ }
+ }
- private Timer timer;
- private List<IUpdateListener> updateListeners;
- private boolean stopped;
- private boolean disposed;
+ private Timer timer;
+ private List<IUpdateListener> updateListeners;
+ private boolean stopped;
+ private boolean disposed;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/IGobblerListener.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/IGobblerListener.java
index fd3921f0fa..8f9aff1c54 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/IGobblerListener.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/IGobblerListener.java
@@ -13,9 +13,9 @@ package org.eclipse.linuxtools.systemtap.structures.listeners;
public interface IGobblerListener {
- /**
- * called by streamgobbler when new data is present
- *
- */
- void handleDataEvent(String line);
+ /**
+ * called by streamgobbler when new data is present
+ *
+ */
+ void handleDataEvent(String line);
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/ITabListener.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/ITabListener.java
index 899a099e72..71dd09e356 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/ITabListener.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/ITabListener.java
@@ -12,7 +12,7 @@
package org.eclipse.linuxtools.systemtap.structures.listeners;
public interface ITabListener {
- void tabOpened();
- void tabClosed();
- void tabChanged();
+ void tabOpened();
+ void tabClosed();
+ void tabChanged();
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/IUpdateListener.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/IUpdateListener.java
index c29c33b3a1..b380b33382 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/IUpdateListener.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/listeners/IUpdateListener.java
@@ -12,5 +12,5 @@
package org.eclipse.linuxtools.systemtap.structures.listeners;
public interface IUpdateListener {
- void handleUpdateEvent();
+ void handleUpdateEvent();
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/process/SystemTapRuntimeProcessFactory.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/process/SystemTapRuntimeProcessFactory.java
index 4f4b61acd6..8410968d96 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/process/SystemTapRuntimeProcessFactory.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/process/SystemTapRuntimeProcessFactory.java
@@ -13,37 +13,37 @@ import org.eclipse.debug.core.model.RuntimeProcess;
*/
public class SystemTapRuntimeProcessFactory implements IProcessFactory {
- public static final String PROCESS_FACTORY_ID = "org.eclipse.linuxtools.systemtap.ui.ide.SystemTapRuntimeProcessFactory"; //$NON-NLS-1$
-
- public static class SystemTapRuntimeProcess extends RuntimeProcess {
-
- private Process originalProcess = null;
-
- public SystemTapRuntimeProcess(ILaunch launch, Process process,
- String name, Map<String, String> attributes) {
- super(launch, process, name, attributes);
- originalProcess = process;
- }
-
- public boolean matchesProcess(Process process) {
- return originalProcess.equals(process);
- }
-
- /**
- * SystemTap scripts use a ScriptConsole instance as their output stream,
- * so don't use the default stream.
- */
- @Override
- protected IStreamsProxy createStreamsProxy() {
- return null;
- }
-
- }
-
- @Override
- public IProcess newProcess(ILaunch launch, Process process, String label,
- Map<String, String> attributes) {
- return new SystemTapRuntimeProcess(launch, process, label, attributes);
- }
+ public static final String PROCESS_FACTORY_ID = "org.eclipse.linuxtools.systemtap.ui.ide.SystemTapRuntimeProcessFactory"; //$NON-NLS-1$
+
+ public static class SystemTapRuntimeProcess extends RuntimeProcess {
+
+ private Process originalProcess = null;
+
+ public SystemTapRuntimeProcess(ILaunch launch, Process process,
+ String name, Map<String, String> attributes) {
+ super(launch, process, name, attributes);
+ originalProcess = process;
+ }
+
+ public boolean matchesProcess(Process process) {
+ return originalProcess.equals(process);
+ }
+
+ /**
+ * SystemTap scripts use a ScriptConsole instance as their output stream,
+ * so don't use the default stream.
+ */
+ @Override
+ protected IStreamsProxy createStreamsProxy() {
+ return null;
+ }
+
+ }
+
+ @Override
+ public IProcess newProcess(ILaunch launch, Process process, String label,
+ Map<String, String> attributes) {
+ return new SystemTapRuntimeProcess(launch, process, label, attributes);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/process/SystemtapProcessFactory.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/process/SystemtapProcessFactory.java
index a73aeee010..ddbbcab069 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/process/SystemtapProcessFactory.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/process/SystemtapProcessFactory.java
@@ -27,76 +27,76 @@ import com.jcraft.jsch.Session;
*/
public class SystemtapProcessFactory {
- /**
- * Runs stap with the given arguments on the given host using the given
- * credentials.
- *
- * @param user
- * the user name to use on the remote machine.
- * @param host
- * the host where the systemtap process will be run.
- * @param password
- * password for authenticating with the given host.
- * @return a {@link Channel} connected to the remotely running process.
- * @throws JSchException
- * thrown if there are problems connecting to the remote
- * machine.
- */
- public static Channel execRemote(String[] args,
- OutputStream out, OutputStream err, String user, String host,
- String password) throws JSchException {
- JSch jsch = new JSch();
- Session session = jsch.getSession(user, host, 22);
- session.setPassword(password);
- java.util.Properties config = new java.util.Properties();
- config.put("StrictHostKeyChecking", "no"); //$NON-NLS-1$//$NON-NLS-2$
- session.setConfig(config);
- session.connect();
+ /**
+ * Runs stap with the given arguments on the given host using the given
+ * credentials.
+ *
+ * @param user
+ * the user name to use on the remote machine.
+ * @param host
+ * the host where the systemtap process will be run.
+ * @param password
+ * password for authenticating with the given host.
+ * @return a {@link Channel} connected to the remotely running process.
+ * @throws JSchException
+ * thrown if there are problems connecting to the remote
+ * machine.
+ */
+ public static Channel execRemote(String[] args,
+ OutputStream out, OutputStream err, String user, String host,
+ String password) throws JSchException {
+ JSch jsch = new JSch();
+ Session session = jsch.getSession(user, host, 22);
+ session.setPassword(password);
+ java.util.Properties config = new java.util.Properties();
+ config.put("StrictHostKeyChecking", "no"); //$NON-NLS-1$//$NON-NLS-2$
+ session.setConfig(config);
+ session.connect();
- StringBuilder command = new StringBuilder();
- for (int i = 0; i < args.length; i++) {
- command.append(args[i]);
- }
+ StringBuilder command = new StringBuilder();
+ for (int i = 0; i < args.length; i++) {
+ command.append(args[i]);
+ }
- Channel channel = session.openChannel("exec"); //$NON-NLS-1$
- ((ChannelExec) channel).setCommand(command.toString());
+ Channel channel = session.openChannel("exec"); //$NON-NLS-1$
+ ((ChannelExec) channel).setCommand(command.toString());
- channel.setInputStream(null, true);
- channel.setOutputStream(out, true);
- channel.setExtOutputStream(err, true);
+ channel.setInputStream(null, true);
+ channel.setOutputStream(out, true);
+ channel.setExtOutputStream(err, true);
- return channel;
- }
+ return channel;
+ }
- /**
- * Runs stap with the given arguments on the given host using the given
- * credentials and waits for the process to finish executing.
- *
- * @param user
- * the user name to use on the remote machine.
- * @param host
- * the host where the systemtap process will be run.
- * @param password
- * password for authenticating with the given host.
- * @return a {@link Channel} connected to the remotely running process.
- * @throws JSchException
- * thrown if there are problems connecting to the remote
- * machine.
- */
- public static Channel execRemoteAndWait(String[] args,
- OutputStream out, OutputStream err, String user, String host,
- String password) throws JSchException {
- Channel channel = execRemote(args, out, err, user, host, password);
+ /**
+ * Runs stap with the given arguments on the given host using the given
+ * credentials and waits for the process to finish executing.
+ *
+ * @param user
+ * the user name to use on the remote machine.
+ * @param host
+ * the host where the systemtap process will be run.
+ * @param password
+ * password for authenticating with the given host.
+ * @return a {@link Channel} connected to the remotely running process.
+ * @throws JSchException
+ * thrown if there are problems connecting to the remote
+ * machine.
+ */
+ public static Channel execRemoteAndWait(String[] args,
+ OutputStream out, OutputStream err, String user, String host,
+ String password) throws JSchException {
+ Channel channel = execRemote(args, out, err, user, host, password);
- while (!channel.isClosed()){
- try {
- Thread.sleep(250);
- } catch (InterruptedException e) {
- // Thread was interrupted just return.
- return channel;
- }
- }
+ while (!channel.isClosed()){
+ try {
+ Thread.sleep(250);
+ } catch (InterruptedException e) {
+ // Thread was interrupted just return.
+ return channel;
+ }
+ }
- return channel;
- }
+ return channel;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/Command.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/Command.java
index 8fa9bc2386..84422f4a69 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/Command.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/Command.java
@@ -33,308 +33,308 @@ import org.eclipse.linuxtools.tools.launch.core.factory.RuntimeProcessFactory;
* @since 2.0
*/
public class Command implements Runnable {
- /*
- * Bug in the exec command prevents using a single string. Forced
- * to use a workaround in order to run commands with spaces.
- *
- * http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4365120
- * http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4109888
- */
-
- /**
- * @since 2.0
- */
- protected boolean stopped = false;
- private boolean started = false;
- /**
- * @since 2.0
- */
- protected StreamGobbler inputGobbler = null;
- /**
- * @since 2.0
- */
- protected StreamGobbler errorGobbler = null;
-
- private boolean disposed = false;
- private List<IGobblerListener> inputListeners = new ArrayList<>(); //Only used to allow adding listeners before creating the StreamGobbler
- private List<IGobblerListener> errorListeners = new ArrayList<>(); //Only used to allow adding listeners before creating the StreamGobbler
- private int returnVal = Integer.MAX_VALUE;
-
- private String[] cmd;
- private String[] envVars;
- protected Process process;
- /**
- * @since 2.1
- */
- protected IProject project = null;
- private final LoggingStreamDaemon logger;
-
- public static final int ERROR_STREAM = 0;
- public static final int INPUT_STREAM = 1;
-
- /**
- * Spawns the new thread that this class will run in. From the Runnable
- * interface spawning the new thread automatically calls the run() method.
- * This must be called by the implementing class in order to start the
- * StreamGobbler.
- * @param cmd The entire command to run
- * @param envVars List of all environment variables to use
- * @since 2.0
- */
- public Command(String[] cmd, String[] envVars) {
- this(cmd, envVars, null);
- }
-
- /**
- * Spawns the new thread that this class will run in. From the Runnable
- * interface spawning the new thread automatically calls the run() method.
- * This must be called by the implementing class in order to start the
- * StreamGobbler.
- * @param cmd The entire command to run
- * @param envVars List of all environment variables to use
- * @param project The project this script belongs to or null
- * @since 2.1
- */
- public Command(String[] cmd, String[] envVars, IProject project) {
- if (cmd != null) {
- this.cmd = Arrays.copyOf(cmd, cmd.length);
- }
-
- if (envVars != null) {
- this.envVars = Arrays.copyOf(envVars, envVars.length);
- }
- this.project = project;
- logger = new LoggingStreamDaemon();
- addInputStreamListener(logger);
- }
-
- /**
- * Starts the <code>Thread</code> that the new <code>Process</code> will run in.
- * This must be called in order to get the process to start running.
- * @throws CoreException
- */
- public void start() throws CoreException {
- IStatus status = init();
- if(status.isOK()) {
- Thread t = new Thread(this, cmd[0]);
- t.start();
- started = true;
- } else {
- stop();
- returnVal = Integer.MIN_VALUE;
- throw new CoreException(status);
- }
- }
-
- /**
- * Starts up the process that will execute the provided command and registers
- * the <code>StreamGobblers</code> with their respective streams.
- * @since 2.0
- */
- protected IStatus init() {
- try {
- process = RuntimeProcessFactory.getFactory().exec(cmd, envVars, project);
-
- if (process == null){
- return new Status(IStatus.ERROR, StructuresPlugin.PLUGIN_ID, Messages.Command_failedToRunSystemtap);
- }
-
- errorGobbler = new StreamGobbler(process.getErrorStream());
- inputGobbler = new StreamGobbler(process.getInputStream());
-
- this.transferListeners();
- return Status.OK_STATUS;
- } catch (IOException e) {
- return new Status(IStatus.ERROR, StructuresPlugin.PLUGIN_ID, e.getMessage(), e);
- }
- }
-
- /**
- * This transfers any listeners which may have been added
- * to the command before the process has been constructed
- * properly to the process itself.
- * @since 2.0
- */
- protected void transferListeners(){
- for(IGobblerListener listener :inputListeners) {
- inputGobbler.addDataListener(listener);
- }
- for(IGobblerListener listener: errorListeners) {
- errorGobbler.addDataListener(listener);
- }
- }
-
- /**
- * This method handles checking the status of the running <code>Process</code>. It
- * is called when the new Thread is created, and thus should never be called by
- * any implementing program. To run call the <code>start</code> method.
- */
- @Override
- public void run() {
- errorGobbler.start();
- inputGobbler.start();
- try {
- process.waitFor();
- } catch (InterruptedException e) {}
- stop();
- }
-
- /**
- * Stops the process from running and stops the <code>StreamGobblers</code> from monitering
- * the dead process and unregisters the StreamListener. Also wakes up any threads waiting
- * on this command.
- */
- public synchronized void stop() {
- if(!stopped) {
- if(null != errorGobbler) {
- errorGobbler.stop();
- }
- if(null != inputGobbler) {
- inputGobbler.stop();
- }
- try {
- if(process != null){
- process.waitFor();
- }
- } catch (InterruptedException e) {
- // This thread was interrupted while waiting for
- // the process to exit. Destroy the process just
- // to make sure it exits.
- process.destroy();
- }
- removeInputStreamListener(logger);
- stopped = true;
- notifyAll(); // Wake up threads waiting for this command to stop.
- }
- }
-
- /**
- * Method to check whether or not the process is running.
- * @return The execution status.
- */
- public boolean isRunning() {
- return !stopped;
- }
-
- /**
- * Method to check whether or not the process has began to run.
- * @return <code>false</code> before the process begins to run or
- * if initialization of the process has failed; <code>true</code> otherwise.
- * @since 3.0
- */
- public boolean hasStarted() {
- return started;
- }
-
- /**
- * Method to check if this class has already been disposed.
- * @return Status of the class.
- */
- public boolean isDisposed() {
- return disposed;
- }
-
- /**
- * The return value of the process.
- * 2^231-1 if the process is still running.
- * -2^231 if there was an error creating the process
- * @return The return value generated from running the provided command.
- */
- public int getReturnValue() {
- return returnVal;
- }
-
- /**
- * Registers the provided <code>IGobblerListener</code> with the InputStream
- * @param listener A listener to monitor the InputStream from the Process
- */
- public void addInputStreamListener(IGobblerListener listener) {
- if(null != inputGobbler) {
- inputGobbler.addDataListener(listener);
- } else {
- inputListeners.add(listener);
- }
- }
-
- /**
- * Registers the provided <code>IGobblerListener</code> with the ErrorStream
- * @param listener A listener to monitor the ErrorStream from the Process
- */
- public void addErrorStreamListener(IGobblerListener listener) {
- if(null != errorGobbler) {
- errorGobbler.addDataListener(listener);
- } else {
- errorListeners.add(listener);
- }
- }
-
- /**
- * Removes the provided listener from those monitoring the InputStream.
- * @param listener An </code>IGobblerListener</code> that is monitoring the stream.
- */
- public void removeInputStreamListener(IGobblerListener listener) {
- if(null != inputGobbler) {
- inputGobbler.removeDataListener(listener);
- } else {
- inputListeners.remove(listener);
- }
- }
-
- /**
- * Removes the provided listener from those monitoring the ErrorStream.
- * @param listener An </code>IGobblerListener</code> that is monitoring the stream.
- */
- public void removeErrorStreamListener(IGobblerListener listener) {
- if(null != errorGobbler) {
- errorGobbler.removeDataListener(listener);
- } else {
- errorListeners.remove(listener);
- }
- }
-
- /**
- * Saves the input stream data to a permanent file. Any new data on the
- * stream will automatically be saved to the file.
- * @param file The file to save the InputStream to.
- */
- public boolean saveLog(File file) {
- return logger.saveLog(file);
- }
-
- /**
- * Disposes of all internal components of this class. Nothing in the class should be
- * referenced after this is called.
- */
- public void dispose() {
- if(!disposed) {
- stop();
- disposed = true;
-
- inputListeners.clear();
- errorListeners.clear();
-
- inputListeners = null;
- errorListeners = null;
-
- if(null != inputGobbler) {
- inputGobbler.dispose();
- }
- inputGobbler = null;
-
- if(null != errorGobbler) {
- errorGobbler.dispose();
- }
- errorGobbler = null;
- logger.dispose();
- }
- }
-
- /**
- * @return The process of this command.
- * @since 3.0
- */
- public Process getProcess() {
- return process;
- }
+ /*
+ * Bug in the exec command prevents using a single string. Forced
+ * to use a workaround in order to run commands with spaces.
+ *
+ * http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4365120
+ * http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4109888
+ */
+
+ /**
+ * @since 2.0
+ */
+ protected boolean stopped = false;
+ private boolean started = false;
+ /**
+ * @since 2.0
+ */
+ protected StreamGobbler inputGobbler = null;
+ /**
+ * @since 2.0
+ */
+ protected StreamGobbler errorGobbler = null;
+
+ private boolean disposed = false;
+ private List<IGobblerListener> inputListeners = new ArrayList<>(); //Only used to allow adding listeners before creating the StreamGobbler
+ private List<IGobblerListener> errorListeners = new ArrayList<>(); //Only used to allow adding listeners before creating the StreamGobbler
+ private int returnVal = Integer.MAX_VALUE;
+
+ private String[] cmd;
+ private String[] envVars;
+ protected Process process;
+ /**
+ * @since 2.1
+ */
+ protected IProject project = null;
+ private final LoggingStreamDaemon logger;
+
+ public static final int ERROR_STREAM = 0;
+ public static final int INPUT_STREAM = 1;
+
+ /**
+ * Spawns the new thread that this class will run in. From the Runnable
+ * interface spawning the new thread automatically calls the run() method.
+ * This must be called by the implementing class in order to start the
+ * StreamGobbler.
+ * @param cmd The entire command to run
+ * @param envVars List of all environment variables to use
+ * @since 2.0
+ */
+ public Command(String[] cmd, String[] envVars) {
+ this(cmd, envVars, null);
+ }
+
+ /**
+ * Spawns the new thread that this class will run in. From the Runnable
+ * interface spawning the new thread automatically calls the run() method.
+ * This must be called by the implementing class in order to start the
+ * StreamGobbler.
+ * @param cmd The entire command to run
+ * @param envVars List of all environment variables to use
+ * @param project The project this script belongs to or null
+ * @since 2.1
+ */
+ public Command(String[] cmd, String[] envVars, IProject project) {
+ if (cmd != null) {
+ this.cmd = Arrays.copyOf(cmd, cmd.length);
+ }
+
+ if (envVars != null) {
+ this.envVars = Arrays.copyOf(envVars, envVars.length);
+ }
+ this.project = project;
+ logger = new LoggingStreamDaemon();
+ addInputStreamListener(logger);
+ }
+
+ /**
+ * Starts the <code>Thread</code> that the new <code>Process</code> will run in.
+ * This must be called in order to get the process to start running.
+ * @throws CoreException
+ */
+ public void start() throws CoreException {
+ IStatus status = init();
+ if(status.isOK()) {
+ Thread t = new Thread(this, cmd[0]);
+ t.start();
+ started = true;
+ } else {
+ stop();
+ returnVal = Integer.MIN_VALUE;
+ throw new CoreException(status);
+ }
+ }
+
+ /**
+ * Starts up the process that will execute the provided command and registers
+ * the <code>StreamGobblers</code> with their respective streams.
+ * @since 2.0
+ */
+ protected IStatus init() {
+ try {
+ process = RuntimeProcessFactory.getFactory().exec(cmd, envVars, project);
+
+ if (process == null){
+ return new Status(IStatus.ERROR, StructuresPlugin.PLUGIN_ID, Messages.Command_failedToRunSystemtap);
+ }
+
+ errorGobbler = new StreamGobbler(process.getErrorStream());
+ inputGobbler = new StreamGobbler(process.getInputStream());
+
+ this.transferListeners();
+ return Status.OK_STATUS;
+ } catch (IOException e) {
+ return new Status(IStatus.ERROR, StructuresPlugin.PLUGIN_ID, e.getMessage(), e);
+ }
+ }
+
+ /**
+ * This transfers any listeners which may have been added
+ * to the command before the process has been constructed
+ * properly to the process itself.
+ * @since 2.0
+ */
+ protected void transferListeners(){
+ for(IGobblerListener listener :inputListeners) {
+ inputGobbler.addDataListener(listener);
+ }
+ for(IGobblerListener listener: errorListeners) {
+ errorGobbler.addDataListener(listener);
+ }
+ }
+
+ /**
+ * This method handles checking the status of the running <code>Process</code>. It
+ * is called when the new Thread is created, and thus should never be called by
+ * any implementing program. To run call the <code>start</code> method.
+ */
+ @Override
+ public void run() {
+ errorGobbler.start();
+ inputGobbler.start();
+ try {
+ process.waitFor();
+ } catch (InterruptedException e) {}
+ stop();
+ }
+
+ /**
+ * Stops the process from running and stops the <code>StreamGobblers</code> from monitering
+ * the dead process and unregisters the StreamListener. Also wakes up any threads waiting
+ * on this command.
+ */
+ public synchronized void stop() {
+ if(!stopped) {
+ if(null != errorGobbler) {
+ errorGobbler.stop();
+ }
+ if(null != inputGobbler) {
+ inputGobbler.stop();
+ }
+ try {
+ if(process != null){
+ process.waitFor();
+ }
+ } catch (InterruptedException e) {
+ // This thread was interrupted while waiting for
+ // the process to exit. Destroy the process just
+ // to make sure it exits.
+ process.destroy();
+ }
+ removeInputStreamListener(logger);
+ stopped = true;
+ notifyAll(); // Wake up threads waiting for this command to stop.
+ }
+ }
+
+ /**
+ * Method to check whether or not the process is running.
+ * @return The execution status.
+ */
+ public boolean isRunning() {
+ return !stopped;
+ }
+
+ /**
+ * Method to check whether or not the process has began to run.
+ * @return <code>false</code> before the process begins to run or
+ * if initialization of the process has failed; <code>true</code> otherwise.
+ * @since 3.0
+ */
+ public boolean hasStarted() {
+ return started;
+ }
+
+ /**
+ * Method to check if this class has already been disposed.
+ * @return Status of the class.
+ */
+ public boolean isDisposed() {
+ return disposed;
+ }
+
+ /**
+ * The return value of the process.
+ * 2^231-1 if the process is still running.
+ * -2^231 if there was an error creating the process
+ * @return The return value generated from running the provided command.
+ */
+ public int getReturnValue() {
+ return returnVal;
+ }
+
+ /**
+ * Registers the provided <code>IGobblerListener</code> with the InputStream
+ * @param listener A listener to monitor the InputStream from the Process
+ */
+ public void addInputStreamListener(IGobblerListener listener) {
+ if(null != inputGobbler) {
+ inputGobbler.addDataListener(listener);
+ } else {
+ inputListeners.add(listener);
+ }
+ }
+
+ /**
+ * Registers the provided <code>IGobblerListener</code> with the ErrorStream
+ * @param listener A listener to monitor the ErrorStream from the Process
+ */
+ public void addErrorStreamListener(IGobblerListener listener) {
+ if(null != errorGobbler) {
+ errorGobbler.addDataListener(listener);
+ } else {
+ errorListeners.add(listener);
+ }
+ }
+
+ /**
+ * Removes the provided listener from those monitoring the InputStream.
+ * @param listener An </code>IGobblerListener</code> that is monitoring the stream.
+ */
+ public void removeInputStreamListener(IGobblerListener listener) {
+ if(null != inputGobbler) {
+ inputGobbler.removeDataListener(listener);
+ } else {
+ inputListeners.remove(listener);
+ }
+ }
+
+ /**
+ * Removes the provided listener from those monitoring the ErrorStream.
+ * @param listener An </code>IGobblerListener</code> that is monitoring the stream.
+ */
+ public void removeErrorStreamListener(IGobblerListener listener) {
+ if(null != errorGobbler) {
+ errorGobbler.removeDataListener(listener);
+ } else {
+ errorListeners.remove(listener);
+ }
+ }
+
+ /**
+ * Saves the input stream data to a permanent file. Any new data on the
+ * stream will automatically be saved to the file.
+ * @param file The file to save the InputStream to.
+ */
+ public boolean saveLog(File file) {
+ return logger.saveLog(file);
+ }
+
+ /**
+ * Disposes of all internal components of this class. Nothing in the class should be
+ * referenced after this is called.
+ */
+ public void dispose() {
+ if(!disposed) {
+ stop();
+ disposed = true;
+
+ inputListeners.clear();
+ errorListeners.clear();
+
+ inputListeners = null;
+ errorListeners = null;
+
+ if(null != inputGobbler) {
+ inputGobbler.dispose();
+ }
+ inputGobbler = null;
+
+ if(null != errorGobbler) {
+ errorGobbler.dispose();
+ }
+ errorGobbler = null;
+ logger.dispose();
+ }
+ }
+
+ /**
+ * @return The process of this command.
+ * @since 3.0
+ */
+ public Process getProcess() {
+ return process;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/Messages.java
index dfeb01470a..52ca8aaba8 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/Messages.java
@@ -14,13 +14,13 @@ package org.eclipse.linuxtools.systemtap.structures.runnable;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.systemtap.structures.runnable.messages"; //$NON-NLS-1$
- public static String Command_failedToRunSystemtap;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.systemtap.structures.runnable.messages"; //$NON-NLS-1$
+ public static String Command_failedToRunSystemtap;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/StreamGobbler.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/StreamGobbler.java
index 2b1ad45db5..d23ff9e52a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/StreamGobbler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/StreamGobbler.java
@@ -26,131 +26,131 @@ import org.eclipse.linuxtools.systemtap.structures.listeners.IGobblerListener;
*/
public class StreamGobbler implements Runnable {
- public StreamGobbler(InputStream is) {
- if(null != is) {
- this.is = is;
- line = new StringBuilder();
- listeners = new ArrayList<>();
- }
- }
-
- /**
- * Spawns the new thread that this class will run in. From the Runnable
- * interface spawning the new thread automatically calls the run() method.
- * This must be called by the implementing class in order to start the
- * StreamGobbler.
- */
- //Make sure to call this method to start the StreamGobbler
- public void start() {
- reader = new Thread(this, "StreamGobbler"); //$NON-NLS-1$
- reader.start();
- }
-
- /**
- * Checks to see if the gobbler is still running.
- * @return boolean representing whether or not it is sill running
- */
- public boolean isRunning() {
- return (null != reader);
- }
-
- /**
- * The main method of this class. It monitors the provided thread to see
- * when new data is available and then appends it to its current list of
- * data. When a new line is read it will fire a DataEvent for listeners
- * to get a hold of the data.
- */
- @Override
- public void run() {
- if (reader != Thread.currentThread())
- return;
-
- try {
- int val = is.read();
- while(val != -1) {
- line.append((char)val);
-
- if ('\n' == val)
- this.fireNewDataEvent();
-
- val = is.read();
- }
- } catch (IOException ioe) {} // If stream closed before thread shuts down
- }
-
- /**
- * Stops the gobbler from monitoring the stream, and fires one last data event
- * to make sure that listeners have the entire contents of what was read in
- * from the stream.
- */
- public synchronized void stop() {
- if (reader != null){
- try {
- // Wait for the reader thread to finish.
- reader.join();
- } catch (InterruptedException e) {
- // The thread was interrupted; nothing to do; finish stopping.
- }
- reader = null;
- }
- notify();
- // Fire one last time to ensure listeners have gotten everything.
- this.fireNewDataEvent();
- }
-
- /**
- * Gets rid of all internal references to objects.
- */
- public void dispose() {
- if(isRunning())
- stop();
- line = null;
- reader = null;
- is = null;
- }
-
- /**
- * Fires new events to everything that is monitoring this stream. Then clears
- * the current line of data.
- */
- private void fireNewDataEvent() {
- this.fireNewDataEvent(line.toString());
- line.delete(0, line.length());
- }
-
- public void fireNewDataEvent(String l) {
- synchronized (listeners) {
- for(int i = 0; i < listeners.size(); i++){
- listeners.get(i).handleDataEvent(l);
- }
- }
- }
-
- /**
- * Registers the provided listener to get data events.
- * @param l A listener that needs to monitor the stream.
- */
- public void addDataListener(IGobblerListener l) {
- synchronized (listeners) {
- if(l != null && !listeners.contains(l)){
- listeners.add(l);
- }
- }
- }
-
- /**
- * Unregisters the provided listener from getting new data events.
- * @param l A listener that is monitoring the stream and should be removed
- */
- public void removeDataListener(IGobblerListener l) {
- synchronized (listeners) {
- if(listeners.contains(l))
- listeners.remove(l);
- }
- }
-
- private List<IGobblerListener> listeners;
- private StringBuilder line;
- private Thread reader;
- private InputStream is;
+ public StreamGobbler(InputStream is) {
+ if(null != is) {
+ this.is = is;
+ line = new StringBuilder();
+ listeners = new ArrayList<>();
+ }
+ }
+
+ /**
+ * Spawns the new thread that this class will run in. From the Runnable
+ * interface spawning the new thread automatically calls the run() method.
+ * This must be called by the implementing class in order to start the
+ * StreamGobbler.
+ */
+ //Make sure to call this method to start the StreamGobbler
+ public void start() {
+ reader = new Thread(this, "StreamGobbler"); //$NON-NLS-1$
+ reader.start();
+ }
+
+ /**
+ * Checks to see if the gobbler is still running.
+ * @return boolean representing whether or not it is sill running
+ */
+ public boolean isRunning() {
+ return (null != reader);
+ }
+
+ /**
+ * The main method of this class. It monitors the provided thread to see
+ * when new data is available and then appends it to its current list of
+ * data. When a new line is read it will fire a DataEvent for listeners
+ * to get a hold of the data.
+ */
+ @Override
+ public void run() {
+ if (reader != Thread.currentThread())
+ return;
+
+ try {
+ int val = is.read();
+ while(val != -1) {
+ line.append((char)val);
+
+ if ('\n' == val)
+ this.fireNewDataEvent();
+
+ val = is.read();
+ }
+ } catch (IOException ioe) {} // If stream closed before thread shuts down
+ }
+
+ /**
+ * Stops the gobbler from monitoring the stream, and fires one last data event
+ * to make sure that listeners have the entire contents of what was read in
+ * from the stream.
+ */
+ public synchronized void stop() {
+ if (reader != null){
+ try {
+ // Wait for the reader thread to finish.
+ reader.join();
+ } catch (InterruptedException e) {
+ // The thread was interrupted; nothing to do; finish stopping.
+ }
+ reader = null;
+ }
+ notify();
+ // Fire one last time to ensure listeners have gotten everything.
+ this.fireNewDataEvent();
+ }
+
+ /**
+ * Gets rid of all internal references to objects.
+ */
+ public void dispose() {
+ if(isRunning())
+ stop();
+ line = null;
+ reader = null;
+ is = null;
+ }
+
+ /**
+ * Fires new events to everything that is monitoring this stream. Then clears
+ * the current line of data.
+ */
+ private void fireNewDataEvent() {
+ this.fireNewDataEvent(line.toString());
+ line.delete(0, line.length());
+ }
+
+ public void fireNewDataEvent(String l) {
+ synchronized (listeners) {
+ for(int i = 0; i < listeners.size(); i++){
+ listeners.get(i).handleDataEvent(l);
+ }
+ }
+ }
+
+ /**
+ * Registers the provided listener to get data events.
+ * @param l A listener that needs to monitor the stream.
+ */
+ public void addDataListener(IGobblerListener l) {
+ synchronized (listeners) {
+ if(l != null && !listeners.contains(l)){
+ listeners.add(l);
+ }
+ }
+ }
+
+ /**
+ * Unregisters the provided listener from getting new data events.
+ * @param l A listener that is monitoring the stream and should be removed
+ */
+ public void removeDataListener(IGobblerListener l) {
+ synchronized (listeners) {
+ if(listeners.contains(l))
+ listeners.remove(l);
+ }
+ }
+
+ private List<IGobblerListener> listeners;
+ private StringBuilder line;
+ private Thread reader;
+ private InputStream is;
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/StringStreamGobbler.java b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/StringStreamGobbler.java
index 0d54f2d233..fce17e2b35 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/StringStreamGobbler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.structures/src/org/eclipse/linuxtools/systemtap/structures/runnable/StringStreamGobbler.java
@@ -19,19 +19,19 @@ import java.io.InputStream;
*
*/
public class StringStreamGobbler extends StreamGobbler {
- StringBuilder output;
+ StringBuilder output;
- public StringStreamGobbler(InputStream is) {
- super(is);
- this.output = new StringBuilder();
- }
+ public StringStreamGobbler(InputStream is) {
+ super(is);
+ this.output = new StringBuilder();
+ }
- @Override
- public void fireNewDataEvent(String line) {
- output.append(line);
- }
+ @Override
+ public void fireNewDataEvent(String line) {
+ output.append(line);
+ }
- public StringBuilder getOutput() {
- return output;
- }
+ public StringBuilder getOutput() {
+ return output;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/pom.xml b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/pom.xml
index fdd9192736..ae348b9a78 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/pom.xml
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/pom.xml
@@ -35,7 +35,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.systemtap.ui.consolelog.tests</testSuite>
<testClass>org.eclipse.linuxtools.systemtap.ui.consolelog.test.AllTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.platform.ide</product>
</configuration>
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/AllTests.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/AllTests.java
index 2650a745e0..d1425c8543 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/AllTests.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/AllTests.java
@@ -19,6 +19,6 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ ConsoleStreamDaemonTest.class,
- ErrorStreamDaemonTest.class, ScriptConsoleTest.class })
+ ErrorStreamDaemonTest.class, ScriptConsoleTest.class })
public class AllTests {
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ConsoleStreamDaemonTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ConsoleStreamDaemonTest.java
index 59cb5f3b55..dd4dac008f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ConsoleStreamDaemonTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ConsoleStreamDaemonTest.java
@@ -23,39 +23,39 @@ import org.junit.Test;
public class ConsoleStreamDaemonTest {
- @Before
- public void setUp() {
- StreamGobbler gobbler = new StreamGobbler(System.in);
- gobbler.start();
- daemon = new ConsoleStreamDaemon(null);
- }
- @Test
- public void testConsoleStreamDaemon() {
- assertNotNull(daemon);
-
- ConsoleStreamDaemon csd = new ConsoleStreamDaemon(null);
- assertNotNull(csd);
-
- csd = new ConsoleStreamDaemon(ScriptConsole.getInstance("test"));
- assertNotNull(csd);
- }
- @Test
- public void testHandleDataEvent() {
- daemon.handleDataEvent("");
- assertNotNull(daemon);
- }
- @Test
- public void testIsDisposed() {
- ConsoleStreamDaemon csd = new ConsoleStreamDaemon(null);
- assertFalse(csd.isDisposed());
- csd.dispose();
- assertTrue(csd.isDisposed());
- }
- @Test
- public void testDispose() {
- daemon.dispose();
- assertNotNull(daemon);
- }
-
- private ConsoleStreamDaemon daemon;
+ @Before
+ public void setUp() {
+ StreamGobbler gobbler = new StreamGobbler(System.in);
+ gobbler.start();
+ daemon = new ConsoleStreamDaemon(null);
+ }
+ @Test
+ public void testConsoleStreamDaemon() {
+ assertNotNull(daemon);
+
+ ConsoleStreamDaemon csd = new ConsoleStreamDaemon(null);
+ assertNotNull(csd);
+
+ csd = new ConsoleStreamDaemon(ScriptConsole.getInstance("test"));
+ assertNotNull(csd);
+ }
+ @Test
+ public void testHandleDataEvent() {
+ daemon.handleDataEvent("");
+ assertNotNull(daemon);
+ }
+ @Test
+ public void testIsDisposed() {
+ ConsoleStreamDaemon csd = new ConsoleStreamDaemon(null);
+ assertFalse(csd.isDisposed());
+ csd.dispose();
+ assertTrue(csd.isDisposed());
+ }
+ @Test
+ public void testDispose() {
+ daemon.dispose();
+ assertNotNull(daemon);
+ }
+
+ private ConsoleStreamDaemon daemon;
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ErrorStreamDaemonTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ErrorStreamDaemonTest.java
index 7998d31ac8..be7be1fe81 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ErrorStreamDaemonTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ErrorStreamDaemonTest.java
@@ -24,41 +24,41 @@ import org.junit.Test;
public class ErrorStreamDaemonTest {
- @Before
- public void setUp() {
- StreamGobbler gobbler = new StreamGobbler(System.in);
- gobbler.start();
- daemon = new ErrorStreamDaemon(null, null, null);
- }
-
- @Test
- public void testConsoleStreamDaemon() {
- assertNotNull(daemon);
+ @Before
+ public void setUp() {
+ StreamGobbler gobbler = new StreamGobbler(System.in);
+ gobbler.start();
+ daemon = new ErrorStreamDaemon(null, null, null);
+ }
- ConsoleStreamDaemon csd = new ConsoleStreamDaemon(null);
- assertNotNull(csd);
-
- csd = new ConsoleStreamDaemon(ScriptConsole.getInstance("test"));
- assertNotNull(csd);
- }
-
- @Test
- public void testHandleDataEvent() {
- daemon.handleDataEvent("");
- assertNotNull(daemon);
- }
- @Test
- public void testIsDisposed() {
- ConsoleStreamDaemon csd = new ConsoleStreamDaemon(null);
- assertFalse(csd.isDisposed());
- csd.dispose();
- assertTrue(csd.isDisposed());
- }
- @Test
- public void testDispose() {
- daemon.dispose();
- assertNotNull(daemon);
- }
-
- private ErrorStreamDaemon daemon;
+ @Test
+ public void testConsoleStreamDaemon() {
+ assertNotNull(daemon);
+
+ ConsoleStreamDaemon csd = new ConsoleStreamDaemon(null);
+ assertNotNull(csd);
+
+ csd = new ConsoleStreamDaemon(ScriptConsole.getInstance("test"));
+ assertNotNull(csd);
+ }
+
+ @Test
+ public void testHandleDataEvent() {
+ daemon.handleDataEvent("");
+ assertNotNull(daemon);
+ }
+ @Test
+ public void testIsDisposed() {
+ ConsoleStreamDaemon csd = new ConsoleStreamDaemon(null);
+ assertFalse(csd.isDisposed());
+ csd.dispose();
+ assertTrue(csd.isDisposed());
+ }
+ @Test
+ public void testDispose() {
+ daemon.dispose();
+ assertNotNull(daemon);
+ }
+
+ private ErrorStreamDaemon daemon;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ScriptConsoleTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ScriptConsoleTest.java
index 5a06f2a46b..86c3261885 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ScriptConsoleTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog.tests/src/org/eclipse/linuxtools/systemtap/ui/consolelog/test/structures/ScriptConsoleTest.java
@@ -21,18 +21,18 @@ import org.junit.Test;
public class ScriptConsoleTest {
- @Before
- public void setUp() {
- console = ScriptConsole.getInstance("test");
- }
- @Test
- public void testGetInstance() {
- assertNotNull(console);
- assertSame(console, ScriptConsole.getInstance("test"));
- ScriptConsole console2 = ScriptConsole.getInstance("a");
- assertNotNull(console2);
- assertNotSame(console, console2);
- }
+ @Before
+ public void setUp() {
+ console = ScriptConsole.getInstance("test");
+ }
+ @Test
+ public void testGetInstance() {
+ assertNotNull(console);
+ assertSame(console, ScriptConsole.getInstance("test"));
+ ScriptConsole console2 = ScriptConsole.getInstance("a");
+ assertNotNull(console2);
+ assertNotSame(console, console2);
+ }
- private ScriptConsole console;
+ private ScriptConsole console;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/plugin.xml b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/plugin.xml
index f06dae426d..dc9a80b0f7 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/plugin.xml
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/plugin.xml
@@ -1,32 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>
<plugin>
- <extension
- point="org.eclipse.ui.views">
- <view
+ <extension
+ point="org.eclipse.ui.views">
+ <view
allowMultiple="false"
category="org.eclipse.linuxtools.systemtap.ui"
class="org.eclipse.linuxtools.systemtap.ui.consolelog.views.ErrorView"
icon="icons/views/error_obj.gif"
id="org.eclipse.linuxtools.systemtap.ui.consolelog.views.ErrorView"
name="%view.error.name"/>
- </extension>
-
-
-
- <extension
- point="org.eclipse.core.runtime.preferences">
- <initializer class="org.eclipse.linuxtools.systemtap.ui.consolelog.preferences.PreferenceInitializer"/>
- </extension>
-
- <extension
- point="org.eclipse.ui.preferencePages">
- <page
- name="%preference.consoleLog.name"
- id="org.eclipse.linuxtools.systemtap.prefs.consoleLog"
- class="org.eclipse.linuxtools.systemtap.ui.consolelog.preferences.ConsoleLogPreferencePage"
- category="org.eclipse.linuxtools.systemtap.prefs.view"/>
- </extension>
+ </extension>
+
+
+
+ <extension
+ point="org.eclipse.core.runtime.preferences">
+ <initializer class="org.eclipse.linuxtools.systemtap.ui.consolelog.preferences.PreferenceInitializer"/>
+ </extension>
+
+ <extension
+ point="org.eclipse.ui.preferencePages">
+ <page
+ name="%preference.consoleLog.name"
+ id="org.eclipse.linuxtools.systemtap.prefs.consoleLog"
+ class="org.eclipse.linuxtools.systemtap.ui.consolelog.preferences.ConsoleLogPreferencePage"
+ category="org.eclipse.linuxtools.systemtap.prefs.view"/>
+ </extension>
<extension
point="org.eclipse.ui.console.consolePageParticipants">
<consolePageParticipant
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/CloseStapConsoleAction.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/CloseStapConsoleAction.java
index 0ead485c6f..428f670311 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/CloseStapConsoleAction.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/CloseStapConsoleAction.java
@@ -21,30 +21,30 @@ import org.eclipse.ui.console.IConsole;
public class CloseStapConsoleAction extends ConsoleAction implements ScriptConsoleObserver {
- @Override
- public void run() {
- PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
- @Override
- public void run() {
- if(null != console){
- ConsolePlugin.getDefault().getConsoleManager().removeConsoles(new IConsole[]{console});
- }
- }
- });
- }
+ @Override
+ public void run() {
+ PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ if(null != console){
+ ConsolePlugin.getDefault().getConsoleManager().removeConsoles(new IConsole[]{console});
+ }
+ }
+ });
+ }
- public CloseStapConsoleAction(ScriptConsole fConsole) {
- super(fConsole,
- ConsoleLogPlugin.getDefault().getBundle().getEntry("icons/actions/progress_rem.gif"), //$NON-NLS-1$
- Localization.getString("action.closeConsole.name"), //$NON-NLS-1$
- Localization.getString("action.closeConsole.desc")); //$NON-NLS-1$
- setEnabled(false);
- console.addScriptConsoleObserver(this);
- }
+ public CloseStapConsoleAction(ScriptConsole fConsole) {
+ super(fConsole,
+ ConsoleLogPlugin.getDefault().getBundle().getEntry("icons/actions/progress_rem.gif"), //$NON-NLS-1$
+ Localization.getString("action.closeConsole.name"), //$NON-NLS-1$
+ Localization.getString("action.closeConsole.desc")); //$NON-NLS-1$
+ setEnabled(false);
+ console.addScriptConsoleObserver(this);
+ }
- @Override
- public void runningStateChanged(boolean started, boolean stopped) {
- setEnabled(stopped);
- }
+ @Override
+ public void runningStateChanged(boolean started, boolean stopped) {
+ setEnabled(stopped);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/ConsoleAction.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/ConsoleAction.java
index 162ef4709d..c26fc3af6f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/ConsoleAction.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/ConsoleAction.java
@@ -24,16 +24,16 @@ import org.eclipse.linuxtools.systemtap.ui.consolelog.structures.ScriptConsole;
*/
public abstract class ConsoleAction extends Action {
- protected ScriptConsole console;
+ protected ScriptConsole console;
- protected ConsoleAction(ScriptConsole fConsole,
- URL imagePath,
- String text,
- String toolTip){
- this.console = fConsole;
+ protected ConsoleAction(ScriptConsole fConsole,
+ URL imagePath,
+ String text,
+ String toolTip){
+ this.console = fConsole;
- setImageDescriptor(ImageDescriptor.createFromURL(imagePath));
- setToolTipText(text);
- setText(toolTip);
- }
+ setImageDescriptor(ImageDescriptor.createFromURL(imagePath));
+ setToolTipText(text);
+ setText(toolTip);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/SaveLogAction.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/SaveLogAction.java
index 7eb10eda7c..d4bd8c2664 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/SaveLogAction.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/SaveLogAction.java
@@ -26,45 +26,45 @@ import org.eclipse.ui.PlatformUI;
*/
public class SaveLogAction extends ConsoleAction {
- /**
- * @since 2.0
- */
- public SaveLogAction(ScriptConsole fConsole) {
- super(fConsole,
- ConsoleLogPlugin.getDefault().getBundle().getEntry("icons/actions/save_log.gif"), //$NON-NLS-1$
- Localization.getString("action.saveLog.name"), //$NON-NLS-1$
- Localization.getString("action.saveLog.desc")); //$NON-NLS-1$
- }
+ /**
+ * @since 2.0
+ */
+ public SaveLogAction(ScriptConsole fConsole) {
+ super(fConsole,
+ ConsoleLogPlugin.getDefault().getBundle().getEntry("icons/actions/save_log.gif"), //$NON-NLS-1$
+ Localization.getString("action.saveLog.name"), //$NON-NLS-1$
+ Localization.getString("action.saveLog.desc")); //$NON-NLS-1$
+ }
- /**
- * The main method of this class. Handles getting the current <code>ScriptConsole</code>
- * and telling it to save the output to the selected file.
- */
- @Override
- public void run() {
- if(null != console) {
- File file = getFile();
- if(null != file){
- console.saveStream(file);
- }
- }
- }
+ /**
+ * The main method of this class. Handles getting the current <code>ScriptConsole</code>
+ * and telling it to save the output to the selected file.
+ */
+ @Override
+ public void run() {
+ if(null != console) {
+ File file = getFile();
+ if(null != file){
+ console.saveStream(file);
+ }
+ }
+ }
- /**
- * Brings up a dialog box for the user to select a place to save the log output.
- * @return File representing the desired destination for the log.
- */
- private File getFile() {
- String path = null;
- FileDialog dialog= new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
- dialog.setText(Localization.getString("SaveLogAction.OutputFile")); //$NON-NLS-1$
+ /**
+ * Brings up a dialog box for the user to select a place to save the log output.
+ * @return File representing the desired destination for the log.
+ */
+ private File getFile() {
+ String path = null;
+ FileDialog dialog= new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
+ dialog.setText(Localization.getString("SaveLogAction.OutputFile")); //$NON-NLS-1$
- path = dialog.open();
+ path = dialog.open();
- if(null == path){
- return null;
- }
+ if(null == path){
+ return null;
+ }
- return new File(path);
- }
+ return new File(path);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/StopScriptAction.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/StopScriptAction.java
index fff9f52de2..4472905ef8 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/StopScriptAction.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/actions/StopScriptAction.java
@@ -26,39 +26,39 @@ import org.eclipse.ui.PlatformUI;
*/
public class StopScriptAction extends ConsoleAction implements ScriptConsoleObserver {
- /**
- * This is the main method of the class. It handles stopping the
- * currently active <code>ScriptConsole</code>.
- */
- @Override
- public void run() {
- PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
- @Override
- public void run() {
- if(null != console){
- console.stop();
- }
- }
- });
- }
+ /**
+ * This is the main method of the class. It handles stopping the
+ * currently active <code>ScriptConsole</code>.
+ */
+ @Override
+ public void run() {
+ PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ if(null != console){
+ console.stop();
+ }
+ }
+ });
+ }
- /**
- * @since 2.0
- */
- public StopScriptAction(ScriptConsole fConsole) {
- super(fConsole,
- ConsoleLogPlugin.getDefault().getBundle().getEntry("icons/actions/stop_script.gif"), //$NON-NLS-1$
- Localization.getString("action.stopScript.name"), //$NON-NLS-1$
- Localization.getString("action.stopScript.desc")); //$NON-NLS-1$
- console.addScriptConsoleObserver(this);
- }
+ /**
+ * @since 2.0
+ */
+ public StopScriptAction(ScriptConsole fConsole) {
+ super(fConsole,
+ ConsoleLogPlugin.getDefault().getBundle().getEntry("icons/actions/stop_script.gif"), //$NON-NLS-1$
+ Localization.getString("action.stopScript.name"), //$NON-NLS-1$
+ Localization.getString("action.stopScript.desc")); //$NON-NLS-1$
+ console.addScriptConsoleObserver(this);
+ }
- /**
- * @since 2.0
- */
- @Override
- public void runningStateChanged(boolean started, boolean stopped) {
- setEnabled(!stopped);
- }
+ /**
+ * @since 2.0
+ */
+ @Override
+ public void runningStateChanged(boolean started, boolean stopped) {
+ setEnabled(!stopped);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/preferences/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/preferences/Messages.java
index 50d0f8f2e2..54c2fe5168 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/preferences/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/preferences/Messages.java
@@ -12,19 +12,19 @@ package org.eclipse.linuxtools.internal.systemtap.ui.consolelog.preferences;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.consolelog.preferences.messages"; //$NON-NLS-1$
- public static String ConsoleLogPreferencePage_AlwaysConnectToHost;
- public static String ConsoleLogPreferencePage_Host;
- public static String ConsoleLogPreferencePage_Password;
- public static String ConsoleLogPreferencePage_Port;
- public static String ConsoleLogPreferencePage_PreferencesTitle;
- public static String ConsoleLogPreferencePage_SecondsToSaveData;
- public static String ConsoleLogPreferencePage_User;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.consolelog.preferences.messages"; //$NON-NLS-1$
+ public static String ConsoleLogPreferencePage_AlwaysConnectToHost;
+ public static String ConsoleLogPreferencePage_Host;
+ public static String ConsoleLogPreferencePage_Password;
+ public static String ConsoleLogPreferencePage_Port;
+ public static String ConsoleLogPreferencePage_PreferencesTitle;
+ public static String ConsoleLogPreferencePage_SecondsToSaveData;
+ public static String ConsoleLogPreferencePage_User;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/structures/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/structures/Messages.java
index d6e84c965f..438bc08abd 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/structures/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/internal/systemtap/ui/consolelog/structures/Messages.java
@@ -14,14 +14,14 @@ package org.eclipse.linuxtools.internal.systemtap.ui.consolelog.structures;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- public static String ConsoleStreamDaemon_errorWritingToConsole;
- public static String RemoteScriptOptions_invalidArguments;
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.consolelog.structures.messages"; //$NON-NLS-1$
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ public static String ConsoleStreamDaemon_errorWritingToConsole;
+ public static String RemoteScriptOptions_invalidArguments;
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.consolelog.structures.messages"; //$NON-NLS-1$
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/Messages.java
index 8a71232bfe..c85d79a6e0 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/Messages.java
@@ -16,16 +16,16 @@ import org.eclipse.osgi.util.NLS;
* @since 2.0
*/
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.systemtap.ui.consolelog.messages"; //$NON-NLS-1$
- public static String ScpExec_errorConnectingToServer;
- public static String ScpExec_ConnTimedOut;
- public static String ScpExec_Error;
- public static String ScpExec_FileTransferFailed;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.systemtap.ui.consolelog.messages"; //$NON-NLS-1$
+ public static String ScpExec_errorConnectingToServer;
+ public static String ScpExec_ConnTimedOut;
+ public static String ScpExec_Error;
+ public static String ScpExec_FileTransferFailed;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScpClient.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScpClient.java
index 176df4ffc6..a9d730feff 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScpClient.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScpClient.java
@@ -27,12 +27,12 @@ import com.jcraft.jsch.Session;
public class ScpClient {
- private Session session;
+ private Session session;
- /**
- * @since 3.0
- */
- public ScpClient(RemoteScriptOptions remoteOptions) throws JSchException {
+ /**
+ * @since 3.0
+ */
+ public ScpClient(RemoteScriptOptions remoteOptions) throws JSchException {
JSch jsch=new JSch();
@@ -45,89 +45,89 @@ public class ScpClient {
session.connect();
}
- public void transfer(String fromFile, String toFile) throws IOException,
- JSchException {
- String rfile = toFile;
- String lfile = fromFile;
- String command = "scp -t " + rfile; //$NON-NLS-1$
- Channel channel = session.openChannel("exec"); //$NON-NLS-1$
- ((ChannelExec) channel).setCommand(command);
-
- // get I/O streams for remote scp
- try (OutputStream out = channel.getOutputStream();
- InputStream in = channel.getInputStream()) {
-
- channel.connect();
-
- if (checkAck(in) != 0) {
- System.out.println("err"); //$NON-NLS-1$
- }
-
- // send "C0644 filesize filename", where filename should not include
- // '/'
- long filesize = (new File(lfile)).length();
- command = "C0644 " + filesize + " "; //$NON-NLS-1$ //$NON-NLS-2$
- if (lfile.lastIndexOf('/') > 0) {
- command += lfile.substring(lfile.lastIndexOf('/') + 1);
- } else {
- command += lfile;
- }
- command += "\n"; //$NON-NLS-1$
-
- out.write(command.getBytes());
- out.flush();
- if (checkAck(in) != 0) {
- System.out.println("err"); //$NON-NLS-1$
- }
-
- // send a content of lfile
- byte[] buf = new byte[1024];
- try (FileInputStream fis = new FileInputStream(lfile)) {
- while (true) {
- int len = fis.read(buf, 0, buf.length);
- if (len <= 0) {
- break;
- }
- out.write(buf, 0, len);
-
- }
- }
- // send '\0'
- buf[0] = 0;
- out.write(buf, 0, 1);
- out.flush();
- if (checkAck(in) != 0) {
- System.out.println("err"); //$NON-NLS-1$
- }
- }
-
- channel.disconnect();
- session.disconnect();
-
- }
-
- private static int checkAck(InputStream in) throws IOException {
- int b = in.read();
- // b may be 0 for success,
- // 1 for error,
- // 2 for fatal error,
- // -1
- if (b == 0) {
- return b;
- }
- if (b == -1) {
- return b;
- }
-
- if (b == 1 || b == 2) {
- StringBuilder sb = new StringBuilder();
- int c;
- do {
- c = in.read();
- sb.append((char) c);
- } while (c != '\n');
- }
- return b;
- }
+ public void transfer(String fromFile, String toFile) throws IOException,
+ JSchException {
+ String rfile = toFile;
+ String lfile = fromFile;
+ String command = "scp -t " + rfile; //$NON-NLS-1$
+ Channel channel = session.openChannel("exec"); //$NON-NLS-1$
+ ((ChannelExec) channel).setCommand(command);
+
+ // get I/O streams for remote scp
+ try (OutputStream out = channel.getOutputStream();
+ InputStream in = channel.getInputStream()) {
+
+ channel.connect();
+
+ if (checkAck(in) != 0) {
+ System.out.println("err"); //$NON-NLS-1$
+ }
+
+ // send "C0644 filesize filename", where filename should not include
+ // '/'
+ long filesize = (new File(lfile)).length();
+ command = "C0644 " + filesize + " "; //$NON-NLS-1$ //$NON-NLS-2$
+ if (lfile.lastIndexOf('/') > 0) {
+ command += lfile.substring(lfile.lastIndexOf('/') + 1);
+ } else {
+ command += lfile;
+ }
+ command += "\n"; //$NON-NLS-1$
+
+ out.write(command.getBytes());
+ out.flush();
+ if (checkAck(in) != 0) {
+ System.out.println("err"); //$NON-NLS-1$
+ }
+
+ // send a content of lfile
+ byte[] buf = new byte[1024];
+ try (FileInputStream fis = new FileInputStream(lfile)) {
+ while (true) {
+ int len = fis.read(buf, 0, buf.length);
+ if (len <= 0) {
+ break;
+ }
+ out.write(buf, 0, len);
+
+ }
+ }
+ // send '\0'
+ buf[0] = 0;
+ out.write(buf, 0, 1);
+ out.flush();
+ if (checkAck(in) != 0) {
+ System.out.println("err"); //$NON-NLS-1$
+ }
+ }
+
+ channel.disconnect();
+ session.disconnect();
+
+ }
+
+ private static int checkAck(InputStream in) throws IOException {
+ int b = in.read();
+ // b may be 0 for success,
+ // 1 for error,
+ // 2 for fatal error,
+ // -1
+ if (b == 0) {
+ return b;
+ }
+ if (b == -1) {
+ return b;
+ }
+
+ if (b == 1 || b == 2) {
+ StringBuilder sb = new StringBuilder();
+ int c;
+ do {
+ c = in.read();
+ sb.append((char) c);
+ } while (c != '\n');
+ }
+ return b;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScpExec.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScpExec.java
index 23cee15f27..399ddeb913 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScpExec.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScpExec.java
@@ -30,83 +30,83 @@ import com.jcraft.jsch.JSchException;
public class ScpExec extends Command {
- private Channel channel;
- private RemoteScriptOptions remoteOptions;
-
- /**
- * @since 3.0
- */
- public ScpExec(String cmds[], RemoteScriptOptions remoteOptions) {
- super(cmds, null);
- this.command = ""; //$NON-NLS-1$
- for (String cmd:cmds) {
- this.command = this.command + " " + cmd; //$NON-NLS-1$
- }
- this.remoteOptions = remoteOptions;
- }
-
- @Override
- protected IStatus init() {
- try {
- channel = SystemtapProcessFactory.execRemote(
- new String[] { command }, System.out, System.err, remoteOptions.getUserName(), remoteOptions.getHostName(), remoteOptions.getPassword());
-
- errorGobbler = new StreamGobbler(channel.getExtInputStream());
- inputGobbler = new StreamGobbler(channel.getInputStream());
-
- this.transferListeners();
- return Status.OK_STATUS;
- } catch (final JSchException|IOException e) {
- final IStatus status = new Status(IStatus.ERROR, ConsoleLogPlugin.PLUGIN_ID, Messages.ScpExec_FileTransferFailed, e);
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Messages.ScpExec_Error, e.getMessage(), status);
- }
- });
- return status;
- }
- }
-
- @Override
- public void run() {
- try {
- channel.connect();
-
- errorGobbler.start();
- inputGobbler.start();
-
- while (!stopped) {
- if (channel.isClosed() || (channel.getExitStatus() != -1)) {
- stop();
- break;
- }
- }
-
- } catch (JSchException e) {
- ExceptionErrorDialog.openError(Messages.ScpExec_errorConnectingToServer, e);
- }
- }
+ private Channel channel;
+ private RemoteScriptOptions remoteOptions;
+
+ /**
+ * @since 3.0
+ */
+ public ScpExec(String cmds[], RemoteScriptOptions remoteOptions) {
+ super(cmds, null);
+ this.command = ""; //$NON-NLS-1$
+ for (String cmd:cmds) {
+ this.command = this.command + " " + cmd; //$NON-NLS-1$
+ }
+ this.remoteOptions = remoteOptions;
+ }
+
+ @Override
+ protected IStatus init() {
+ try {
+ channel = SystemtapProcessFactory.execRemote(
+ new String[] { command }, System.out, System.err, remoteOptions.getUserName(), remoteOptions.getHostName(), remoteOptions.getPassword());
+
+ errorGobbler = new StreamGobbler(channel.getExtInputStream());
+ inputGobbler = new StreamGobbler(channel.getInputStream());
+
+ this.transferListeners();
+ return Status.OK_STATUS;
+ } catch (final JSchException|IOException e) {
+ final IStatus status = new Status(IStatus.ERROR, ConsoleLogPlugin.PLUGIN_ID, Messages.ScpExec_FileTransferFailed, e);
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Messages.ScpExec_Error, e.getMessage(), status);
+ }
+ });
+ return status;
+ }
+ }
+
+ @Override
+ public void run() {
+ try {
+ channel.connect();
+
+ errorGobbler.start();
+ inputGobbler.start();
+
+ while (!stopped) {
+ if (channel.isClosed() || (channel.getExitStatus() != -1)) {
+ stop();
+ break;
+ }
+ }
+
+ } catch (JSchException e) {
+ ExceptionErrorDialog.openError(Messages.ScpExec_errorConnectingToServer, e);
+ }
+ }
/* Stops the process from running and stops the <code>StreamGobblers</code> from monitoring
- * the dead process.
- */
- @Override
- public synchronized void stop() {
- if(!stopped) {
- if(null != errorGobbler) {
- errorGobbler.stop();
- }
- if(null != inputGobbler) {
- inputGobbler.stop();
- }
- if (channel != null) {
- channel.disconnect();
- }
+ * the dead process.
+ */
+ @Override
+ public synchronized void stop() {
+ if(!stopped) {
+ if(null != errorGobbler) {
+ errorGobbler.stop();
+ }
+ if(null != inputGobbler) {
+ inputGobbler.stop();
+ }
+ if (channel != null) {
+ channel.disconnect();
+ }
stopped = true;
notifyAll();
- }
- }
+ }
+ }
private String command;
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScriptConsolePageParticipant.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScriptConsolePageParticipant.java
index 35915de113..2e29f88fc0 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScriptConsolePageParticipant.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/ScriptConsolePageParticipant.java
@@ -31,71 +31,71 @@ import org.eclipse.ui.part.IPageBookViewPage;
*/
public class ScriptConsolePageParticipant implements IConsolePageParticipant, IDebugContextListener {
- private IPageBookViewPage fPage;
- private IConsoleView fView;
- private ScriptConsole fConsole;
-
- @Override
- @SuppressWarnings("rawtypes")
- public Object getAdapter(Class adapter) {
- return null;
- }
-
- @Override
- public void init(IPageBookViewPage page, IConsole iConsole) {
- if (!(iConsole instanceof ScriptConsole)){
- return;
- }
-
- fPage = page;
- fConsole = (ScriptConsole) iConsole;
- fView = (IConsoleView) fPage.getSite().getPage().findView(IConsoleConstants.ID_CONSOLE_VIEW);
-
- StopScriptAction stopScriptAction = new StopScriptAction(fConsole);
- CloseStapConsoleAction closeConsoleAction = new CloseStapConsoleAction(fConsole);
- SaveLogAction saveLogAction = new SaveLogAction(fConsole);
-
- // contribute to toolbar
- IToolBarManager manager = fPage.getSite().getActionBars().getToolBarManager();
- manager.appendToGroup(IConsoleConstants.LAUNCH_GROUP, stopScriptAction);
- manager.appendToGroup(IConsoleConstants.LAUNCH_GROUP, closeConsoleAction);
- manager.appendToGroup(IConsoleConstants.OUTPUT_GROUP, saveLogAction);
-
- //TODO if {@link ModifyParsingAction} is restored, it is to be used here,
- //in the same way stopScriptAction and saveLogAction are used.
-
- DebugUITools.getDebugContextManager().getContextService(fPage.getSite().getWorkbenchWindow()).addDebugContextListener(this);
- }
-
- @Override
- public void dispose() {
- DebugUITools.getDebugContextManager().getContextService(fPage.getSite().getWorkbenchWindow()).removeDebugContextListener(this);
- fConsole = null;
- }
-
- @Override
- public void activated() {
- }
-
- @Override
- public void deactivated() {
- }
-
- /**
- * @since 3.0
- */
- @Override
- public void debugContextChanged(DebugContextEvent event) {
- if ((event.getFlags() & DebugContextEvent.ACTIVATED) > 0) {
- if (fView != null && fConsole != null) {
- IProcess process = DebugUITools.getCurrentProcess();
- if (process instanceof SystemTapRuntimeProcessFactory.SystemTapRuntimeProcess
- && ((SystemTapRuntimeProcessFactory.SystemTapRuntimeProcess) process)
- .matchesProcess(fConsole.getProcess())) {
- fView.display(fConsole);
- }
- }
- }
- }
+ private IPageBookViewPage fPage;
+ private IConsoleView fView;
+ private ScriptConsole fConsole;
+
+ @Override
+ @SuppressWarnings("rawtypes")
+ public Object getAdapter(Class adapter) {
+ return null;
+ }
+
+ @Override
+ public void init(IPageBookViewPage page, IConsole iConsole) {
+ if (!(iConsole instanceof ScriptConsole)){
+ return;
+ }
+
+ fPage = page;
+ fConsole = (ScriptConsole) iConsole;
+ fView = (IConsoleView) fPage.getSite().getPage().findView(IConsoleConstants.ID_CONSOLE_VIEW);
+
+ StopScriptAction stopScriptAction = new StopScriptAction(fConsole);
+ CloseStapConsoleAction closeConsoleAction = new CloseStapConsoleAction(fConsole);
+ SaveLogAction saveLogAction = new SaveLogAction(fConsole);
+
+ // contribute to toolbar
+ IToolBarManager manager = fPage.getSite().getActionBars().getToolBarManager();
+ manager.appendToGroup(IConsoleConstants.LAUNCH_GROUP, stopScriptAction);
+ manager.appendToGroup(IConsoleConstants.LAUNCH_GROUP, closeConsoleAction);
+ manager.appendToGroup(IConsoleConstants.OUTPUT_GROUP, saveLogAction);
+
+ //TODO if {@link ModifyParsingAction} is restored, it is to be used here,
+ //in the same way stopScriptAction and saveLogAction are used.
+
+ DebugUITools.getDebugContextManager().getContextService(fPage.getSite().getWorkbenchWindow()).addDebugContextListener(this);
+ }
+
+ @Override
+ public void dispose() {
+ DebugUITools.getDebugContextManager().getContextService(fPage.getSite().getWorkbenchWindow()).removeDebugContextListener(this);
+ fConsole = null;
+ }
+
+ @Override
+ public void activated() {
+ }
+
+ @Override
+ public void deactivated() {
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public void debugContextChanged(DebugContextEvent event) {
+ if ((event.getFlags() & DebugContextEvent.ACTIVATED) > 0) {
+ if (fView != null && fConsole != null) {
+ IProcess process = DebugUITools.getCurrentProcess();
+ if (process instanceof SystemTapRuntimeProcessFactory.SystemTapRuntimeProcess
+ && ((SystemTapRuntimeProcessFactory.SystemTapRuntimeProcess) process)
+ .matchesProcess(fConsole.getProcess())) {
+ fView.display(fConsole);
+ }
+ }
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/dialogs/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/dialogs/Messages.java
index 68152e3c09..c1ab2fb538 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/dialogs/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/dialogs/Messages.java
@@ -16,20 +16,20 @@ import org.eclipse.osgi.util.NLS;
* @since 2.0
*/
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.systemtap.ui.consolelog.dialogs.messages"; //$NON-NLS-1$
- public static String SelectServerDialog_RemoteServerDetails;
- public static String SelectServerDialog_Host;
- public static String SelectServerDialog_User;
- public static String SelectServerDialog_Password;
- public static String SelectServerDialog_AlwaysConnectToHost;
- public static String SelectServerDialog_Cancel;
- public static String SelectServerDialog_Connect;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.systemtap.ui.consolelog.dialogs.messages"; //$NON-NLS-1$
+ public static String SelectServerDialog_RemoteServerDetails;
+ public static String SelectServerDialog_Host;
+ public static String SelectServerDialog_User;
+ public static String SelectServerDialog_Password;
+ public static String SelectServerDialog_AlwaysConnectToHost;
+ public static String SelectServerDialog_Cancel;
+ public static String SelectServerDialog_Connect;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/dialogs/SelectServerDialog.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/dialogs/SelectServerDialog.java
index cf7fc9d404..86ab23206a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/dialogs/SelectServerDialog.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/dialogs/SelectServerDialog.java
@@ -28,119 +28,119 @@ import org.eclipse.swt.widgets.Text;
public class SelectServerDialog extends Dialog {
- private Text hostText;
- private Text userText;
- private Text passwordText;
- private Button rememberButton;
- private Button connectButton;
- private Button cancelButton;
- private boolean result;
-
- public SelectServerDialog(Shell parent) {
- super(parent);
- }
-
- public boolean open() {
- if (ConsoleLogPlugin.getDefault().getPreferenceStore().getBoolean(ConsoleLogPreferenceConstants.REMEMBER_SERVER)) {
- return true;
- }
- result = false;
-
- Shell parent = getParent();
- final Shell shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
- shell.setText(Messages.SelectServerDialog_RemoteServerDetails);
- shell.pack();
-
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- layout.makeColumnsEqualWidth = false;
- shell.setLayout(layout);
-
- GridData dataLeft = new GridData();
- dataLeft.grabExcessHorizontalSpace = false;
- dataLeft.horizontalAlignment = SWT.LEFT;
- Label hostLabel = new Label(shell, SWT.NONE);
- hostLabel.setText(Messages.SelectServerDialog_Host);
- hostLabel.setLayoutData(dataLeft);
-
- GridData dataFill = new GridData();
- dataFill.grabExcessHorizontalSpace = true;
- dataFill.horizontalAlignment = SWT.FILL;
- hostText = new Text(shell, SWT.SINGLE | SWT.BORDER);
- hostText.setLayoutData(dataFill);
- hostText.setText(ConsoleLogPlugin.getDefault().getPreferenceStore().getString(ConsoleLogPreferenceConstants.HOST_NAME));
-
- Label userLabel = new Label(shell, SWT.NONE);
- userLabel.setText(Messages.SelectServerDialog_User);
- userLabel.setLayoutData(dataLeft);
-
- userText = new Text(shell, SWT.SINGLE | SWT.BORDER);
- userText.setLayoutData(dataFill);
- userText.setText(ConsoleLogPlugin.getDefault().getPreferenceStore().getString(ConsoleLogPreferenceConstants.SCP_USER));
-
- Label passwordLabel = new Label(shell, SWT.NONE);
- passwordLabel.setText(Messages.SelectServerDialog_Password);
- passwordLabel.setLayoutData(dataLeft);
-
- passwordText = new Text(shell, SWT.SINGLE | SWT.BORDER);
- passwordText.setEchoChar('*');
- passwordText.setLayoutData(dataFill);
- passwordText.setText(ConsoleLogPlugin.getDefault().getPreferenceStore().getString(ConsoleLogPreferenceConstants.SCP_PASSWORD));
-
-
- GridData data = new GridData();
- data.horizontalAlignment = SWT.LEFT;
- data.horizontalSpan = 2;
- rememberButton = new Button(shell, SWT.CHECK);
- rememberButton.setLayoutData(data);
- rememberButton.setText(Messages.SelectServerDialog_AlwaysConnectToHost);
-
- data = new GridData();
- data.horizontalAlignment = SWT.RIGHT;
- cancelButton = new Button(shell, SWT.PUSH);
- cancelButton.setLayoutData(data);
- cancelButton.setSize(50, 100);
- cancelButton.setText(Messages.SelectServerDialog_Cancel);
- cancelButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- result = false;
- shell.dispose();
- }
- });
-
- data = new GridData();
- data.horizontalAlignment = SWT.RIGHT;
- connectButton = new Button(shell, SWT.PUSH);
- connectButton.setLayoutData(data);
- connectButton.setSize(50, 100);
- connectButton.setText(Messages.SelectServerDialog_Connect);
- connectButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- // FIXME: no error handling is done, should probably be
- // pushed down to the connection level
- // Set the preferences to this new info.
- ConsoleLogPlugin.getDefault().getPreferenceStore().setValue(ConsoleLogPreferenceConstants.HOST_NAME, hostText.getText());
- ConsoleLogPlugin.getDefault().getPreferenceStore().setValue(ConsoleLogPreferenceConstants.REMEMBER_SERVER, rememberButton.getSelection());
- ConsoleLogPlugin.getDefault().getPreferenceStore().setValue(ConsoleLogPreferenceConstants.SCP_PASSWORD, passwordText.getText());
- ConsoleLogPlugin.getDefault().getPreferenceStore().setValue(ConsoleLogPreferenceConstants.SCP_USER, userText.getText());
- result = true;
-
- shell.close();
- }
- });
-
- shell.pack();
- shell.open();
-
- Display display = parent.getDisplay();
- while (!shell.isDisposed()) {
- if (!display.readAndDispatch()) {
- display.sleep();
- }
- }
-
- return result;
- }
+ private Text hostText;
+ private Text userText;
+ private Text passwordText;
+ private Button rememberButton;
+ private Button connectButton;
+ private Button cancelButton;
+ private boolean result;
+
+ public SelectServerDialog(Shell parent) {
+ super(parent);
+ }
+
+ public boolean open() {
+ if (ConsoleLogPlugin.getDefault().getPreferenceStore().getBoolean(ConsoleLogPreferenceConstants.REMEMBER_SERVER)) {
+ return true;
+ }
+ result = false;
+
+ Shell parent = getParent();
+ final Shell shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
+ shell.setText(Messages.SelectServerDialog_RemoteServerDetails);
+ shell.pack();
+
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ layout.makeColumnsEqualWidth = false;
+ shell.setLayout(layout);
+
+ GridData dataLeft = new GridData();
+ dataLeft.grabExcessHorizontalSpace = false;
+ dataLeft.horizontalAlignment = SWT.LEFT;
+ Label hostLabel = new Label(shell, SWT.NONE);
+ hostLabel.setText(Messages.SelectServerDialog_Host);
+ hostLabel.setLayoutData(dataLeft);
+
+ GridData dataFill = new GridData();
+ dataFill.grabExcessHorizontalSpace = true;
+ dataFill.horizontalAlignment = SWT.FILL;
+ hostText = new Text(shell, SWT.SINGLE | SWT.BORDER);
+ hostText.setLayoutData(dataFill);
+ hostText.setText(ConsoleLogPlugin.getDefault().getPreferenceStore().getString(ConsoleLogPreferenceConstants.HOST_NAME));
+
+ Label userLabel = new Label(shell, SWT.NONE);
+ userLabel.setText(Messages.SelectServerDialog_User);
+ userLabel.setLayoutData(dataLeft);
+
+ userText = new Text(shell, SWT.SINGLE | SWT.BORDER);
+ userText.setLayoutData(dataFill);
+ userText.setText(ConsoleLogPlugin.getDefault().getPreferenceStore().getString(ConsoleLogPreferenceConstants.SCP_USER));
+
+ Label passwordLabel = new Label(shell, SWT.NONE);
+ passwordLabel.setText(Messages.SelectServerDialog_Password);
+ passwordLabel.setLayoutData(dataLeft);
+
+ passwordText = new Text(shell, SWT.SINGLE | SWT.BORDER);
+ passwordText.setEchoChar('*');
+ passwordText.setLayoutData(dataFill);
+ passwordText.setText(ConsoleLogPlugin.getDefault().getPreferenceStore().getString(ConsoleLogPreferenceConstants.SCP_PASSWORD));
+
+
+ GridData data = new GridData();
+ data.horizontalAlignment = SWT.LEFT;
+ data.horizontalSpan = 2;
+ rememberButton = new Button(shell, SWT.CHECK);
+ rememberButton.setLayoutData(data);
+ rememberButton.setText(Messages.SelectServerDialog_AlwaysConnectToHost);
+
+ data = new GridData();
+ data.horizontalAlignment = SWT.RIGHT;
+ cancelButton = new Button(shell, SWT.PUSH);
+ cancelButton.setLayoutData(data);
+ cancelButton.setSize(50, 100);
+ cancelButton.setText(Messages.SelectServerDialog_Cancel);
+ cancelButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ result = false;
+ shell.dispose();
+ }
+ });
+
+ data = new GridData();
+ data.horizontalAlignment = SWT.RIGHT;
+ connectButton = new Button(shell, SWT.PUSH);
+ connectButton.setLayoutData(data);
+ connectButton.setSize(50, 100);
+ connectButton.setText(Messages.SelectServerDialog_Connect);
+ connectButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ // FIXME: no error handling is done, should probably be
+ // pushed down to the connection level
+ // Set the preferences to this new info.
+ ConsoleLogPlugin.getDefault().getPreferenceStore().setValue(ConsoleLogPreferenceConstants.HOST_NAME, hostText.getText());
+ ConsoleLogPlugin.getDefault().getPreferenceStore().setValue(ConsoleLogPreferenceConstants.REMEMBER_SERVER, rememberButton.getSelection());
+ ConsoleLogPlugin.getDefault().getPreferenceStore().setValue(ConsoleLogPreferenceConstants.SCP_PASSWORD, passwordText.getText());
+ ConsoleLogPlugin.getDefault().getPreferenceStore().setValue(ConsoleLogPreferenceConstants.SCP_USER, userText.getText());
+ result = true;
+
+ shell.close();
+ }
+ });
+
+ shell.pack();
+ shell.open();
+
+ Display display = parent.getDisplay();
+ while (!shell.isDisposed()) {
+ if (!display.readAndDispatch()) {
+ display.sleep();
+ }
+ }
+
+ return result;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/internal/ConsoleLogPlugin.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/internal/ConsoleLogPlugin.java
index 6956a6bfea..04a976839e 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/internal/ConsoleLogPlugin.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/internal/ConsoleLogPlugin.java
@@ -19,35 +19,35 @@ import org.osgi.framework.BundleContext;
*/
public class ConsoleLogPlugin extends AbstractUIPlugin {
- /**
- * @since 2.0
- */
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.systemtap.ui.consolelog"; //$NON-NLS-1$
-
- //The shared instance.
- private static ConsoleLogPlugin plugin;
-
- /**
- * The constructor.
- */
- public ConsoleLogPlugin() {
- plugin = this;
- }
-
- /**
- * This method is called when the plug-in is stopped
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- super.stop(context);
- plugin = null;
- }
-
- /**
- * Returns the shared instance.
- */
- public static ConsoleLogPlugin getDefault() {
- return plugin;
- }
+ /**
+ * @since 2.0
+ */
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.systemtap.ui.consolelog"; //$NON-NLS-1$
+
+ //The shared instance.
+ private static ConsoleLogPlugin plugin;
+
+ /**
+ * The constructor.
+ */
+ public ConsoleLogPlugin() {
+ plugin = this;
+ }
+
+ /**
+ * This method is called when the plug-in is stopped
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ super.stop(context);
+ plugin = null;
+ }
+
+ /**
+ * Returns the shared instance.
+ */
+ public static ConsoleLogPlugin getDefault() {
+ return plugin;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/internal/Localization.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/internal/Localization.java
index 0deb77e8b2..18c2f43e78 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/internal/Localization.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/internal/Localization.java
@@ -15,19 +15,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Localization {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.systemtap.ui.consolelog.internal.localization"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.systemtap.ui.consolelog.internal.localization"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Localization() {
- }
+ private Localization() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/ConsoleLogPreferenceConstants.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/ConsoleLogPreferenceConstants.java
index f36ab92690..48c71656ec 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/ConsoleLogPreferenceConstants.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/ConsoleLogPreferenceConstants.java
@@ -12,13 +12,13 @@
package org.eclipse.linuxtools.systemtap.ui.consolelog.preferences;
public interface ConsoleLogPreferenceConstants {
- //ide
- String HOST_NAME = "host"; //$NON-NLS-1$
- String PORT_NUMBER = "port"; //$NON-NLS-1$
- String DB_COMMIT = "commit"; //$NON-NLS-1$
- String SAVE_LENGTH = "saveLength"; //$NON-NLS-1$
- String REMEMBER_SERVER = "rememberServer"; //$NON-NLS-1$
- String SCP_USER = "scpuser"; //$NON-NLS-1$
- String SCP_PASSWORD = "scppassword"; //$NON-NLS-1$
- String REMEMBER_SCPUSER = "rememberscpuser"; //$NON-NLS-1$
+ //ide
+ String HOST_NAME = "host"; //$NON-NLS-1$
+ String PORT_NUMBER = "port"; //$NON-NLS-1$
+ String DB_COMMIT = "commit"; //$NON-NLS-1$
+ String SAVE_LENGTH = "saveLength"; //$NON-NLS-1$
+ String REMEMBER_SERVER = "rememberServer"; //$NON-NLS-1$
+ String SCP_USER = "scpuser"; //$NON-NLS-1$
+ String SCP_PASSWORD = "scppassword"; //$NON-NLS-1$
+ String REMEMBER_SCPUSER = "rememberscpuser"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/ConsoleLogPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/ConsoleLogPreferencePage.java
index a29056c846..2215c5fc69 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/ConsoleLogPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/ConsoleLogPreferencePage.java
@@ -21,38 +21,38 @@ import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
public class ConsoleLogPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- public ConsoleLogPreferencePage() {
- super(GRID);
- setPreferenceStore(ConsoleLogPlugin.getDefault().getPreferenceStore());
- setDescription(Messages.ConsoleLogPreferencePage_PreferencesTitle);
- }
+ public ConsoleLogPreferencePage() {
+ super(GRID);
+ setPreferenceStore(ConsoleLogPlugin.getDefault().getPreferenceStore());
+ setDescription(Messages.ConsoleLogPreferencePage_PreferencesTitle);
+ }
- @Override
- public void createFieldEditors() {
+ @Override
+ public void createFieldEditors() {
- addField(new StringFieldEditor(ConsoleLogPreferenceConstants.HOST_NAME,
- Messages.ConsoleLogPreferencePage_Host, getFieldEditorParent()));
+ addField(new StringFieldEditor(ConsoleLogPreferenceConstants.HOST_NAME,
+ Messages.ConsoleLogPreferencePage_Host, getFieldEditorParent()));
- addField(new IntegerFieldEditor(ConsoleLogPreferenceConstants.PORT_NUMBER,
- Messages.ConsoleLogPreferencePage_Port, getFieldEditorParent()));
+ addField(new IntegerFieldEditor(ConsoleLogPreferenceConstants.PORT_NUMBER,
+ Messages.ConsoleLogPreferencePage_Port, getFieldEditorParent()));
- addField(new StringFieldEditor(ConsoleLogPreferenceConstants.SCP_USER,
- Messages.ConsoleLogPreferencePage_User, getFieldEditorParent()));
+ addField(new StringFieldEditor(ConsoleLogPreferenceConstants.SCP_USER,
+ Messages.ConsoleLogPreferencePage_User, getFieldEditorParent()));
- StringFieldEditor passwordField = new StringFieldEditor(
- ConsoleLogPreferenceConstants.SCP_PASSWORD, Messages.ConsoleLogPreferencePage_Password,
+ StringFieldEditor passwordField = new StringFieldEditor(
+ ConsoleLogPreferenceConstants.SCP_PASSWORD, Messages.ConsoleLogPreferencePage_Password,
getFieldEditorParent());
passwordField.getTextControl(getFieldEditorParent()).setEchoChar('*');
addField(passwordField);
- addField(new BooleanFieldEditor(ConsoleLogPreferenceConstants.REMEMBER_SERVER,
- Messages.ConsoleLogPreferencePage_AlwaysConnectToHost, getFieldEditorParent()));
+ addField(new BooleanFieldEditor(ConsoleLogPreferenceConstants.REMEMBER_SERVER,
+ Messages.ConsoleLogPreferencePage_AlwaysConnectToHost, getFieldEditorParent()));
- addField(new IntegerFieldEditor(ConsoleLogPreferenceConstants.SAVE_LENGTH,
- Messages.ConsoleLogPreferencePage_SecondsToSaveData, getFieldEditorParent()));
+ addField(new IntegerFieldEditor(ConsoleLogPreferenceConstants.SAVE_LENGTH,
+ Messages.ConsoleLogPreferencePage_SecondsToSaveData, getFieldEditorParent()));
- }
+ }
- @Override
- public void init(IWorkbench workbench) {}
+ @Override
+ public void init(IWorkbench workbench) {}
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/PreferenceInitializer.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/PreferenceInitializer.java
index 31df1aeb18..d6d2a29237 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/PreferenceInitializer.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/preferences/PreferenceInitializer.java
@@ -19,20 +19,20 @@ import org.eclipse.linuxtools.systemtap.ui.consolelog.internal.ConsoleLogPlugin;
public class PreferenceInitializer extends AbstractPreferenceInitializer {
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = ConsoleLogPlugin.getDefault().getPreferenceStore();
-
- //ide
- store.setDefault(ConsoleLogPreferenceConstants.HOST_NAME, "localhost"); //$NON-NLS-1$
- store.setDefault(ConsoleLogPreferenceConstants.PORT_NUMBER, 22462);
- store.setDefault(ConsoleLogPreferenceConstants.DB_COMMIT, false);
- store.setDefault(ConsoleLogPreferenceConstants.SAVE_LENGTH, 5);
- store.setDefault(ConsoleLogPreferenceConstants.REMEMBER_SERVER, false);
- store.setDefault(ConsoleLogPreferenceConstants.SCP_USER, "guest"); //$NON-NLS-1$
- store.setDefault(ConsoleLogPreferenceConstants.SCP_PASSWORD, "welcome"); //$NON-NLS-1$
- store.setDefault(ConsoleLogPreferenceConstants.REMEMBER_SCPUSER, false);
-
-
- }
+ @Override
+ public void initializeDefaultPreferences() {
+ IPreferenceStore store = ConsoleLogPlugin.getDefault().getPreferenceStore();
+
+ //ide
+ store.setDefault(ConsoleLogPreferenceConstants.HOST_NAME, "localhost"); //$NON-NLS-1$
+ store.setDefault(ConsoleLogPreferenceConstants.PORT_NUMBER, 22462);
+ store.setDefault(ConsoleLogPreferenceConstants.DB_COMMIT, false);
+ store.setDefault(ConsoleLogPreferenceConstants.SAVE_LENGTH, 5);
+ store.setDefault(ConsoleLogPreferenceConstants.REMEMBER_SERVER, false);
+ store.setDefault(ConsoleLogPreferenceConstants.SCP_USER, "guest"); //$NON-NLS-1$
+ store.setDefault(ConsoleLogPreferenceConstants.SCP_PASSWORD, "welcome"); //$NON-NLS-1$
+ store.setDefault(ConsoleLogPreferenceConstants.REMEMBER_SCPUSER, false);
+
+
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ConsoleStreamDaemon.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ConsoleStreamDaemon.java
index 7d6f22554a..2ddd4f98fa 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ConsoleStreamDaemon.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ConsoleStreamDaemon.java
@@ -24,58 +24,58 @@ import org.eclipse.ui.console.IOConsoleOutputStream;
* @author Ryan Morse
*/
public class ConsoleStreamDaemon implements IGobblerListener {
- public ConsoleStreamDaemon(ScriptConsole console) {
- this.console = console;
- if(null != console) {
- ioConsole = console.newOutputStream();
- }
- disposed = false;
- }
+ public ConsoleStreamDaemon(ScriptConsole console) {
+ this.console = console;
+ if(null != console) {
+ ioConsole = console.newOutputStream();
+ }
+ disposed = false;
+ }
- /**
- * Prints out the new output data to the console
- */
- protected void pushData() {
- if(null != ioConsole) {
- try {
- ioConsole.write(output);
- } catch (IOException e) {
- ExceptionErrorDialog.openError(Messages.ConsoleStreamDaemon_errorWritingToConsole, e);
- }
- }
- }
+ /**
+ * Prints out the new output data to the console
+ */
+ protected void pushData() {
+ if(null != ioConsole) {
+ try {
+ ioConsole.write(output);
+ } catch (IOException e) {
+ ExceptionErrorDialog.openError(Messages.ConsoleStreamDaemon_errorWritingToConsole, e);
+ }
+ }
+ }
- /**
- * Captures data events and pushes the data to the console
- */
- @Override
- public void handleDataEvent(String line) {
- output = line;
- this.pushData();
- }
+ /**
+ * Captures data events and pushes the data to the console
+ */
+ @Override
+ public void handleDataEvent(String line) {
+ output = line;
+ this.pushData();
+ }
- /**
- * Checks to see if the class has been disposed already
- * @return boolean representing whether or not the class has been disposed
- */
- public boolean isDisposed() {
- return disposed;
- }
+ /**
+ * Checks to see if the class has been disposed already
+ * @return boolean representing whether or not the class has been disposed
+ */
+ public boolean isDisposed() {
+ return disposed;
+ }
- /**
- * Disposes of all internal references in the class. No method should be called after this.
- */
- public void dispose() {
- if(!disposed) {
- disposed = true;
- output = null;
- console = null;
- ioConsole = null;
- }
- }
+ /**
+ * Disposes of all internal references in the class. No method should be called after this.
+ */
+ public void dispose() {
+ if(!disposed) {
+ disposed = true;
+ output = null;
+ console = null;
+ ioConsole = null;
+ }
+ }
- protected String output;
- protected ScriptConsole console;
- protected IOConsoleOutputStream ioConsole;
- private boolean disposed;
+ protected String output;
+ protected ScriptConsole console;
+ protected IOConsoleOutputStream ioConsole;
+ private boolean disposed;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ErrorStreamDaemon.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ErrorStreamDaemon.java
index 57b12245c0..da9ebc5a34 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ErrorStreamDaemon.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ErrorStreamDaemon.java
@@ -19,63 +19,63 @@ import org.eclipse.linuxtools.systemtap.ui.consolelog.views.ErrorView;
* @author Ryan Morse
*/
public class ErrorStreamDaemon extends ConsoleStreamDaemon {
- public ErrorStreamDaemon(ScriptConsole console, ErrorView errorWindow, IErrorParser parser) {
- super(console);
+ public ErrorStreamDaemon(ScriptConsole console, ErrorView errorWindow, IErrorParser parser) {
+ super(console);
- outputData = new StringBuilder();
- this.parser = parser;
- if (null != errorWindow) {
- errorView = errorWindow;
- errorView.clear();
- }
- }
+ outputData = new StringBuilder();
+ this.parser = parser;
+ if (null != errorWindow) {
+ errorView = errorWindow;
+ errorView.clear();
+ }
+ }
- /**
- * Prints out the new output data to the console and parses it and sends it to the
- * ErrorView.
- */
- @Override
- protected void pushData() {
- if(output.startsWith(Localization.getString("ErrorStreamDaemon.Password"))) { //$NON-NLS-1$
- output = output.substring(Localization.getString("ErrorStreamDaemon.Password").length()); //$NON-NLS-1$
- }
+ /**
+ * Prints out the new output data to the console and parses it and sends it to the
+ * ErrorView.
+ */
+ @Override
+ protected void pushData() {
+ if(output.startsWith(Localization.getString("ErrorStreamDaemon.Password"))) { //$NON-NLS-1$
+ output = output.substring(Localization.getString("ErrorStreamDaemon.Password").length()); //$NON-NLS-1$
+ }
- super.pushData();
+ super.pushData();
- outputData.append(output);
+ outputData.append(output);
- /* Since we never know when the last set of data is comming we don't clear the
- * errorStream in the hope of getting a more complete error message. As a result
- * the parser will always return what we already had. Clear removes anything
- * that was added before.
- */
- if(null != errorView) {
- String[][] errors = parser.parseOutput(outputData.toString());
+ /* Since we never know when the last set of data is comming we don't clear the
+ * errorStream in the hope of getting a more complete error message. As a result
+ * the parser will always return what we already had. Clear removes anything
+ * that was added before.
+ */
+ if(null != errorView) {
+ String[][] errors = parser.parseOutput(outputData.toString());
- if(null != errors) {
- errorView.clear();
- for(String[] error :errors) {
- errorView.add(error);
- }
- }
- }
- }
+ if(null != errors) {
+ errorView.clear();
+ for(String[] error :errors) {
+ errorView.add(error);
+ }
+ }
+ }
+ }
- /**
- * Disposes of all internal references in the class. No method should be called after this.
- */
- @Override
- public void dispose() {
- if(!isDisposed()) {
- super.dispose();
- errorView = null;
- outputData.delete(0, outputData.length());
- outputData = null;
- parser = null;
- }
- }
+ /**
+ * Disposes of all internal references in the class. No method should be called after this.
+ */
+ @Override
+ public void dispose() {
+ if(!isDisposed()) {
+ super.dispose();
+ errorView = null;
+ outputData.delete(0, outputData.length());
+ outputData = null;
+ parser = null;
+ }
+ }
- private ErrorView errorView;
- private StringBuilder outputData;
- private IErrorParser parser;
+ private ErrorView errorView;
+ private StringBuilder outputData;
+ private IErrorParser parser;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ErrorTableDisplay.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ErrorTableDisplay.java
index c179de1691..54cf4b61d5 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ErrorTableDisplay.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ErrorTableDisplay.java
@@ -37,142 +37,142 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
* @author Ryan Morse
*/
public class ErrorTableDisplay {
- public ErrorTableDisplay(Composite parent, String[] titles) {
- this.titles = Arrays.copyOf(titles, titles.length);
- createControl(parent);
- }
-
- /**
- * Creates the table for displaying error messages in.
- * @param parent The container for the new error table.
- */
- private void createControl(Composite parent) {
- table = new Table(parent, SWT.SINGLE);
- table.setHeaderVisible(true);
- table.getVerticalBar().setVisible(true);
- table.setLinesVisible(true);
- table.addMouseListener(mouseListener);
-
- TableColumn column;
- for(String title: titles) {
- column = new TableColumn(table, SWT.NONE);
- column.setText(title);
- }
-
- updateColumns();
- }
-
- /**
- * Clears all items from the table.
- */
- public void clear() {
- table.getDisplay().syncExec(new Runnable() {
- @Override
- public void run() {
- table.removeAll();
- }
- });
- }
-
- /**
- * Adds a new row to the table with an error icon.
- * @param row The pre-divied sections of the error message.
- */
- public void addRow(final String[] row) {
- addRow(row, AbstractUIPlugin.imageDescriptorFromPlugin(ConsoleLogPlugin.PLUGIN_ID, "icons/views/error_st_obj.gif").createImage()); //$NON-NLS-1$
- }
-
- /**
- * Adds a new row to the table.
- * @param row The pre-divied sections of the error message.
- * @param img The image to display with the error.
- */
- private void addRow(final String[] row, final Image img) {
- table.getDisplay().syncExec(new Runnable() {
- @Override
- public void run() {
- item = new TableItem(table, SWT.NULL);
- for(int i=0; i<row.length; i++) {
- item.setText(i+1, row[i]);
- }
- item.setImage(img);
- updateColumns();
- }
-
- });
- }
-
- /**
- * Updates each of the columns in the table to ensure that the entries all fit
- * as well as possible.
- */
- private void updateColumns() {
- TableColumn[] columns = table.getColumns();
- for (TableColumn column: columns) {
- column.pack();
- column.setMoveable(true);
- }
- }
-
- public Control getControl() {
- return table;
- }
-
- /**
- * Disposes of all internal references in the class. No method should be called after this.
- */
- public void dispose() {
- if(null != table && !table.isDisposed()) {
- table.removeMouseListener(mouseListener);
- table.dispose();
- table = null;
- }
-
- if(titles != null) {
- for(int i=0; i<titles.length; i++) {
- titles[i] = null;
- }
- }
- titles = null;
-
- if(null != item) {
- item.dispose();
- }
- item = null;
- }
-
- /**
- * MouseListener that is used to detect when the user clicks on a row in the table.
- * When clicked it will find the line number the error occured on and then set the
- * cursor location to that location in the active editor.
- */
- private final MouseListener mouseListener = new MouseAdapter() {
- @Override
- public void mouseDoubleClick(MouseEvent me) {
- String location = table.getSelection()[0].getText(4);
-
- if(location.length() > 0) {
- int line = 0;
- if(location.indexOf(':') > 0) {
- String[] pos = location.split(":"); //$NON-NLS-1$
- line = Integer.parseInt(pos[0]);
- } else {
- line = Integer.parseInt(location);
- }
-
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- IEditorPart ed = page.getActiveEditor();
-
- if(ed instanceof SimpleEditor) {
- SimpleEditor editor = ((SimpleEditor)ed);
- editor.selectLine(line);
- editor.setFocus();
- }
- }
- }
- };
-
- private Table table;
- private String[] titles;
- private TableItem item;
+ public ErrorTableDisplay(Composite parent, String[] titles) {
+ this.titles = Arrays.copyOf(titles, titles.length);
+ createControl(parent);
+ }
+
+ /**
+ * Creates the table for displaying error messages in.
+ * @param parent The container for the new error table.
+ */
+ private void createControl(Composite parent) {
+ table = new Table(parent, SWT.SINGLE);
+ table.setHeaderVisible(true);
+ table.getVerticalBar().setVisible(true);
+ table.setLinesVisible(true);
+ table.addMouseListener(mouseListener);
+
+ TableColumn column;
+ for(String title: titles) {
+ column = new TableColumn(table, SWT.NONE);
+ column.setText(title);
+ }
+
+ updateColumns();
+ }
+
+ /**
+ * Clears all items from the table.
+ */
+ public void clear() {
+ table.getDisplay().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ table.removeAll();
+ }
+ });
+ }
+
+ /**
+ * Adds a new row to the table with an error icon.
+ * @param row The pre-divied sections of the error message.
+ */
+ public void addRow(final String[] row) {
+ addRow(row, AbstractUIPlugin.imageDescriptorFromPlugin(ConsoleLogPlugin.PLUGIN_ID, "icons/views/error_st_obj.gif").createImage()); //$NON-NLS-1$
+ }
+
+ /**
+ * Adds a new row to the table.
+ * @param row The pre-divied sections of the error message.
+ * @param img The image to display with the error.
+ */
+ private void addRow(final String[] row, final Image img) {
+ table.getDisplay().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ item = new TableItem(table, SWT.NULL);
+ for(int i=0; i<row.length; i++) {
+ item.setText(i+1, row[i]);
+ }
+ item.setImage(img);
+ updateColumns();
+ }
+
+ });
+ }
+
+ /**
+ * Updates each of the columns in the table to ensure that the entries all fit
+ * as well as possible.
+ */
+ private void updateColumns() {
+ TableColumn[] columns = table.getColumns();
+ for (TableColumn column: columns) {
+ column.pack();
+ column.setMoveable(true);
+ }
+ }
+
+ public Control getControl() {
+ return table;
+ }
+
+ /**
+ * Disposes of all internal references in the class. No method should be called after this.
+ */
+ public void dispose() {
+ if(null != table && !table.isDisposed()) {
+ table.removeMouseListener(mouseListener);
+ table.dispose();
+ table = null;
+ }
+
+ if(titles != null) {
+ for(int i=0; i<titles.length; i++) {
+ titles[i] = null;
+ }
+ }
+ titles = null;
+
+ if(null != item) {
+ item.dispose();
+ }
+ item = null;
+ }
+
+ /**
+ * MouseListener that is used to detect when the user clicks on a row in the table.
+ * When clicked it will find the line number the error occured on and then set the
+ * cursor location to that location in the active editor.
+ */
+ private final MouseListener mouseListener = new MouseAdapter() {
+ @Override
+ public void mouseDoubleClick(MouseEvent me) {
+ String location = table.getSelection()[0].getText(4);
+
+ if(location.length() > 0) {
+ int line = 0;
+ if(location.indexOf(':') > 0) {
+ String[] pos = location.split(":"); //$NON-NLS-1$
+ line = Integer.parseInt(pos[0]);
+ } else {
+ line = Integer.parseInt(location);
+ }
+
+ IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
+ IEditorPart ed = page.getActiveEditor();
+
+ if(ed instanceof SimpleEditor) {
+ SimpleEditor editor = ((SimpleEditor)ed);
+ editor.selectLine(line);
+ editor.setFocus();
+ }
+ }
+ }
+ };
+
+ private Table table;
+ private String[] titles;
+ private TableItem item;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/IErrorParser.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/IErrorParser.java
index e4991ead20..36869edba8 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/IErrorParser.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/IErrorParser.java
@@ -12,5 +12,5 @@
package org.eclipse.linuxtools.systemtap.ui.consolelog.structures;
public interface IErrorParser {
- String[][] parseOutput(String data);
+ String[][] parseOutput(String data);
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/RemoteScriptOptions.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/RemoteScriptOptions.java
index d6f3cddbf9..1191b6205c 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/RemoteScriptOptions.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/RemoteScriptOptions.java
@@ -20,44 +20,44 @@ import org.eclipse.linuxtools.internal.systemtap.ui.consolelog.structures.Messag
*/
public class RemoteScriptOptions {
- private String userName = null;
- private String password = null;
- private String hostName = null;
-
- public String getUserName() {
- return userName;
- }
-
- public String getPassword() {
- return password;
- }
-
- public String getHostName() {
- return hostName;
- }
-
- public RemoteScriptOptions(String userName, String password, String hostName) {
- if (userName == null || password == null || hostName == null) {
- throw new IllegalArgumentException(Messages.RemoteScriptOptions_invalidArguments);
- }
- this.userName = userName;
- this.password = password;
- this.hostName = hostName;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof RemoteScriptOptions) {
- return false;
- }
- RemoteScriptOptions other = (RemoteScriptOptions) obj;
- return this.userName.equals(other.userName)
- && this.password.equals(other.password)
- && this.hostName.equals(other.hostName);
- }
-
- @Override
- public int hashCode() {
- return super.hashCode();
- }
+ private String userName = null;
+ private String password = null;
+ private String hostName = null;
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public String getHostName() {
+ return hostName;
+ }
+
+ public RemoteScriptOptions(String userName, String password, String hostName) {
+ if (userName == null || password == null || hostName == null) {
+ throw new IllegalArgumentException(Messages.RemoteScriptOptions_invalidArguments);
+ }
+ this.userName = userName;
+ this.password = password;
+ this.hostName = hostName;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj instanceof RemoteScriptOptions) {
+ return false;
+ }
+ RemoteScriptOptions other = (RemoteScriptOptions) obj;
+ return this.userName.equals(other.userName)
+ && this.password.equals(other.password)
+ && this.hostName.equals(other.hostName);
+ }
+
+ @Override
+ public int hashCode() {
+ return super.hashCode();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ScriptConsole.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ScriptConsole.java
index 7b616d932d..638feb3a90 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ScriptConsole.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/structures/ScriptConsole.java
@@ -43,500 +43,500 @@ import org.eclipse.ui.console.IOConsole;
* @author Ryan Morse
*/
public class ScriptConsole extends IOConsole {
- private static final long RETRY_STOP_TIME = 500;
- private static final long JOIN_WAIT_TIME = 500;
-
- /**
- * The command that will run in this console.
- */
- private Command cmd;
-
- /**
- * A protocol for sending "stop" signals to cmd when it is forcably
- * stopped by a user action.
- */
- private Runnable stopCommand;
-
- /**
- * A thread in which to asynchronously run stopCommand.
- */
- private Thread stopCommandThread;
-
- /**
- * A thread used for notifying the console when cmd has successfully stopped.
- */
- private Thread onCmdStopThread;
-
- /**
- * A thread used for starting a new run of cmd. It starts a new run only
- * once a previous run of cmd has successfully stopped.
- */
- private Thread onCmdStartThread;
-
- private String moduleName;
-
- private ErrorStreamDaemon errorDaemon;
- private ConsoleStreamDaemon consoleDaemon;
-
- /**
- * @since 2.0
- */
- public static interface ScriptConsoleObserver {
- /**
- * @since 3.0
- */
- public void runningStateChanged(boolean started, boolean stopped);
- }
-
- private final List<ScriptConsoleObserver> activeConsoleObservers = new LinkedList<>();
- private List<ScriptConsoleObserver> inactiveConsoleObservers = new LinkedList<>();
-
- /**
- * Returns whether or not a ScriptConsole of the specified name exists and is running.
- * @param name The name of the console (likely a script name) to check.
- * @return <code>true</code> if a ScriptConsole of the given name both exists and is running,
- * or <code>false</code> otherwise.
- * @since 3.0
- */
- public static boolean instanceIsRunning(String name) {
- IConsole ic[] = ConsolePlugin.getDefault().getConsoleManager().getConsoles();
- if (null != ic) {
- for (IConsole consoleIterator: ic) {
- if (consoleIterator instanceof ScriptConsole){
- ScriptConsole activeConsole = (ScriptConsole) consoleIterator;
- if(activeConsole.getName().endsWith(name) && activeConsole.isRunning()) {
- return true;
- }
- }
- }
- }
- return false;
- }
-
- /**
- * This method is used to create a reference to a new <code>ScriptConsole</code>. If there
- * is already an console that has the same name as that provided it will be stopped,
- * cleared and returned to the caller to use. If there is no console matching the
- * provided name then a new <code>ScriptConsole</code> will be created for use.
- * @param name The name of the console that should be created & returned.
- * @return A console of the specified name, or <code>null</code> if there is an error.
- */
- public synchronized static ScriptConsole getInstance(String name) {
- ScriptConsole console = null;
- try {
- IConsole ic[] = ConsolePlugin.getDefault().getConsoleManager().getConsoles();
-
- //Prevent running the same script twice
- if(null != ic) {
- ScriptConsole activeConsole;
- for (IConsole consoleIterator: ic) {
- if (consoleIterator instanceof ScriptConsole){
- activeConsole = (ScriptConsole) consoleIterator;
- if(activeConsole.getName().endsWith(name)) {
- //Stop any script currently running, and terminate stream listeners.
- if (activeConsole.isRunning()) {
- activeConsole.stop();
- if (activeConsole.errorDaemon != null) {
- activeConsole.cmd.removeErrorStreamListener(activeConsole.errorDaemon);
- }
- if (activeConsole.consoleDaemon != null) {
- activeConsole.cmd.removeInputStreamListener(activeConsole.consoleDaemon);
- }
- }
- if (activeConsole.onCmdStopThread != null && activeConsole.onCmdStopThread.isAlive()) {
- activeConsole.onCmdStopThread.interrupt();
- try {
- activeConsole.onCmdStopThread.join(JOIN_WAIT_TIME);
- } catch (InterruptedException e) {}
- }
- //Remove output from last run
- activeConsole.clearConsole();
- activeConsole.setName(name);
- console = activeConsole;
- break;
- }
- }
- }
- }
-
- if(null == console) {
- console = new ScriptConsole(name, null);
- ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] {console});
- }
- } catch(NullPointerException npe) {
- console = null;
- }
- return console;
- }
-
- /**
- * This method will check to see if any scripts are currently running.
- * @return - boolean indicating whether any scripts are running
- * @since 2.0
- */
- public static boolean anyRunning() {
- IConsole ic[] = ConsolePlugin.getDefault().getConsoleManager().getConsoles();
- ScriptConsole console;
-
- for(IConsole con : ic) {
- if (con instanceof ScriptConsole){
- console = (ScriptConsole)con;
- if(console.isRunning()){
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * This method will stop all consoles that are running.
- * @since 2.0
- */
- public static void stopAll() {
- IConsole ic[] = ConsolePlugin.getDefault().getConsoleManager().getConsoles();
- ScriptConsole console;
-
- for(IConsole con : ic) {
- if (con instanceof ScriptConsole){
- console = (ScriptConsole)con;
- console.stop();
- }
- }
- }
-
- ScriptConsole(String name, ImageDescriptor imageDescriptor) {
- super(name, imageDescriptor);
- cmd = null;
- }
-
- /**
- * Creates the <code>ConsoleStreamDaemon</code> for passing data from the
- * <code>LoggedCommand</code>'s InputStream to the Console.
- */
- private void createConsoleDaemon() {
- consoleDaemon = new ConsoleStreamDaemon(this);
- }
-
- /**
- * Creates the <code>ErrorStreamDaemon</code> for passing data from the
- * <code>LoggedCommand</code>'s ErrorStream to the Console and ErrorView.
- */
- private void createErrorDaemon(IErrorParser parser) {
- ErrorView errorView = null;
- IViewPart ivp = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(ErrorView.ID);
- if(ivp instanceof ErrorView) {
- errorView = ((ErrorView)ivp);
- }
- errorDaemon = new ErrorStreamDaemon(this, errorView, parser);
- }
-
- private boolean waitingToStart() {
- return onCmdStartThread != null && onCmdStartThread.isAlive();
- }
-
- /**
- * Runs the provided command in this ScriptConsole instance.
- * @param command The command and arguments to run.
- * @param envVars The environment variables to use while running
- * @param remoteOptions The remote options (such as username and password) to run the script with.
- * @param errorParser The parser to handle error messages generated by the command
- * @since 3.0
- */
- public void run(String[] command, String[] envVars, final RemoteScriptOptions remoteOptions, IErrorParser errorParser) {
- // Don't start a new command if one is already waiting to be started.
- if (waitingToStart()) {
- return;
- }
- cmd = new ScpExec(command, remoteOptions);
-
- this.stopCommand = new Runnable() {
- private final Command stopcmd = cmd;
- private final String stopString = getStopString();
-
- @Override
- public void run() {
- ScpExec stop = new ScpExec(new String[]{stopString}, remoteOptions);
- try {
- synchronized (stopcmd) {
- while (stopcmd.isRunning()) {
- stop.start();
- stopcmd.wait(RETRY_STOP_TIME);
- }
- }
- } catch (CoreException e) {
- // Failed to start the 'stop' process. Ignore.
- } catch (InterruptedException e) {
- // Wait was interrupted. Exit.
- }
- }
- };
- this.run(cmd, errorParser);
- }
-
- /**
- * Runs the provided command in this ScriptConsole instance on the current
- * host.
- * @param command The command and arguments to run.
- * @param envVars The environment variables to use while running
- * @param errorParser The parser to handle error messages generated by the command
- * @param project The project that command belongs to or null
- * @since 2.1
- */
- public void runLocally(String[] command, String[] envVars, IErrorParser errorParser, IProject project) {
- // Don't start a new command if one is already waiting to be started.
- if (waitingToStart()) {
- return;
- }
- cmd = new Command(command, envVars, project);
- final IProject proj = project;
-
- this.stopCommand = new Runnable() {
- private final Command stopcmd = cmd;
- String stopString = getStopString();
-
- @Override
- public void run() {
- try {
- synchronized (stopcmd) {
- while (stopcmd.isRunning()) {
- RuntimeProcessFactory.getFactory().exec(stopString, null, proj);
- stopcmd.wait(RETRY_STOP_TIME);
- }
- }
- } catch (IOException e) {
- ExceptionErrorDialog.openError(Localization.getString("ScriptConsole.ErrorKillingStap"), e); //$NON-NLS-1$
- } catch (InterruptedException e) {
- //Wait was interrupted. Exit.
- }
- }
- };
- this.run(cmd, errorParser);
- }
-
- private void run(final Command cmd, IErrorParser errorParser){
- final Runnable onCmdStop = new Runnable() {
- @Override
- public void run() {
- try {
- synchronized (cmd) {
- while (cmd.isRunning()) {
- cmd.wait();
- }
- onCmdStopActions();
- }
- } catch (InterruptedException e) {
- return;
- }
- }
- };
- Runnable onCmdStart = new Runnable() {
- @Override
- public void run() {
- if (stopCommandThread != null && stopCommandThread.isAlive()) {
- try {
- stopCommandThread.join();
- } catch (InterruptedException e) {
- return;
- }
- }
- createConsoleDaemon();
- if (errorDaemon != null) {
- cmd.addErrorStreamListener(errorDaemon);
- }
- cmd.addInputStreamListener(consoleDaemon);
- onCmdStopThread = new Thread(onCmdStop);
- onCmdStopThread.start();
- try {
- cmd.start();
- } catch (final CoreException e) {
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- ExceptionErrorDialog.openError(e.getMessage(), e);
- }
- });
- cmd.dispose();
- return;
- }
- notifyConsoleObservers();
- }
- };
-
- if (errorParser != null) {
- createErrorDaemon(errorParser);
- }
- activate();
- ConsolePlugin.getDefault().getConsoleManager().showConsoleView(this);
-
- onCmdStartThread = new Thread(onCmdStart);
+ private static final long RETRY_STOP_TIME = 500;
+ private static final long JOIN_WAIT_TIME = 500;
+
+ /**
+ * The command that will run in this console.
+ */
+ private Command cmd;
+
+ /**
+ * A protocol for sending "stop" signals to cmd when it is forcably
+ * stopped by a user action.
+ */
+ private Runnable stopCommand;
+
+ /**
+ * A thread in which to asynchronously run stopCommand.
+ */
+ private Thread stopCommandThread;
+
+ /**
+ * A thread used for notifying the console when cmd has successfully stopped.
+ */
+ private Thread onCmdStopThread;
+
+ /**
+ * A thread used for starting a new run of cmd. It starts a new run only
+ * once a previous run of cmd has successfully stopped.
+ */
+ private Thread onCmdStartThread;
+
+ private String moduleName;
+
+ private ErrorStreamDaemon errorDaemon;
+ private ConsoleStreamDaemon consoleDaemon;
+
+ /**
+ * @since 2.0
+ */
+ public static interface ScriptConsoleObserver {
+ /**
+ * @since 3.0
+ */
+ public void runningStateChanged(boolean started, boolean stopped);
+ }
+
+ private final List<ScriptConsoleObserver> activeConsoleObservers = new LinkedList<>();
+ private List<ScriptConsoleObserver> inactiveConsoleObservers = new LinkedList<>();
+
+ /**
+ * Returns whether or not a ScriptConsole of the specified name exists and is running.
+ * @param name The name of the console (likely a script name) to check.
+ * @return <code>true</code> if a ScriptConsole of the given name both exists and is running,
+ * or <code>false</code> otherwise.
+ * @since 3.0
+ */
+ public static boolean instanceIsRunning(String name) {
+ IConsole ic[] = ConsolePlugin.getDefault().getConsoleManager().getConsoles();
+ if (null != ic) {
+ for (IConsole consoleIterator: ic) {
+ if (consoleIterator instanceof ScriptConsole){
+ ScriptConsole activeConsole = (ScriptConsole) consoleIterator;
+ if(activeConsole.getName().endsWith(name) && activeConsole.isRunning()) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * This method is used to create a reference to a new <code>ScriptConsole</code>. If there
+ * is already an console that has the same name as that provided it will be stopped,
+ * cleared and returned to the caller to use. If there is no console matching the
+ * provided name then a new <code>ScriptConsole</code> will be created for use.
+ * @param name The name of the console that should be created & returned.
+ * @return A console of the specified name, or <code>null</code> if there is an error.
+ */
+ public synchronized static ScriptConsole getInstance(String name) {
+ ScriptConsole console = null;
+ try {
+ IConsole ic[] = ConsolePlugin.getDefault().getConsoleManager().getConsoles();
+
+ //Prevent running the same script twice
+ if(null != ic) {
+ ScriptConsole activeConsole;
+ for (IConsole consoleIterator: ic) {
+ if (consoleIterator instanceof ScriptConsole){
+ activeConsole = (ScriptConsole) consoleIterator;
+ if(activeConsole.getName().endsWith(name)) {
+ //Stop any script currently running, and terminate stream listeners.
+ if (activeConsole.isRunning()) {
+ activeConsole.stop();
+ if (activeConsole.errorDaemon != null) {
+ activeConsole.cmd.removeErrorStreamListener(activeConsole.errorDaemon);
+ }
+ if (activeConsole.consoleDaemon != null) {
+ activeConsole.cmd.removeInputStreamListener(activeConsole.consoleDaemon);
+ }
+ }
+ if (activeConsole.onCmdStopThread != null && activeConsole.onCmdStopThread.isAlive()) {
+ activeConsole.onCmdStopThread.interrupt();
+ try {
+ activeConsole.onCmdStopThread.join(JOIN_WAIT_TIME);
+ } catch (InterruptedException e) {}
+ }
+ //Remove output from last run
+ activeConsole.clearConsole();
+ activeConsole.setName(name);
+ console = activeConsole;
+ break;
+ }
+ }
+ }
+ }
+
+ if(null == console) {
+ console = new ScriptConsole(name, null);
+ ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] {console});
+ }
+ } catch(NullPointerException npe) {
+ console = null;
+ }
+ return console;
+ }
+
+ /**
+ * This method will check to see if any scripts are currently running.
+ * @return - boolean indicating whether any scripts are running
+ * @since 2.0
+ */
+ public static boolean anyRunning() {
+ IConsole ic[] = ConsolePlugin.getDefault().getConsoleManager().getConsoles();
+ ScriptConsole console;
+
+ for(IConsole con : ic) {
+ if (con instanceof ScriptConsole){
+ console = (ScriptConsole)con;
+ if(console.isRunning()){
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * This method will stop all consoles that are running.
+ * @since 2.0
+ */
+ public static void stopAll() {
+ IConsole ic[] = ConsolePlugin.getDefault().getConsoleManager().getConsoles();
+ ScriptConsole console;
+
+ for(IConsole con : ic) {
+ if (con instanceof ScriptConsole){
+ console = (ScriptConsole)con;
+ console.stop();
+ }
+ }
+ }
+
+ ScriptConsole(String name, ImageDescriptor imageDescriptor) {
+ super(name, imageDescriptor);
+ cmd = null;
+ }
+
+ /**
+ * Creates the <code>ConsoleStreamDaemon</code> for passing data from the
+ * <code>LoggedCommand</code>'s InputStream to the Console.
+ */
+ private void createConsoleDaemon() {
+ consoleDaemon = new ConsoleStreamDaemon(this);
+ }
+
+ /**
+ * Creates the <code>ErrorStreamDaemon</code> for passing data from the
+ * <code>LoggedCommand</code>'s ErrorStream to the Console and ErrorView.
+ */
+ private void createErrorDaemon(IErrorParser parser) {
+ ErrorView errorView = null;
+ IViewPart ivp = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(ErrorView.ID);
+ if(ivp instanceof ErrorView) {
+ errorView = ((ErrorView)ivp);
+ }
+ errorDaemon = new ErrorStreamDaemon(this, errorView, parser);
+ }
+
+ private boolean waitingToStart() {
+ return onCmdStartThread != null && onCmdStartThread.isAlive();
+ }
+
+ /**
+ * Runs the provided command in this ScriptConsole instance.
+ * @param command The command and arguments to run.
+ * @param envVars The environment variables to use while running
+ * @param remoteOptions The remote options (such as username and password) to run the script with.
+ * @param errorParser The parser to handle error messages generated by the command
+ * @since 3.0
+ */
+ public void run(String[] command, String[] envVars, final RemoteScriptOptions remoteOptions, IErrorParser errorParser) {
+ // Don't start a new command if one is already waiting to be started.
+ if (waitingToStart()) {
+ return;
+ }
+ cmd = new ScpExec(command, remoteOptions);
+
+ this.stopCommand = new Runnable() {
+ private final Command stopcmd = cmd;
+ private final String stopString = getStopString();
+
+ @Override
+ public void run() {
+ ScpExec stop = new ScpExec(new String[]{stopString}, remoteOptions);
+ try {
+ synchronized (stopcmd) {
+ while (stopcmd.isRunning()) {
+ stop.start();
+ stopcmd.wait(RETRY_STOP_TIME);
+ }
+ }
+ } catch (CoreException e) {
+ // Failed to start the 'stop' process. Ignore.
+ } catch (InterruptedException e) {
+ // Wait was interrupted. Exit.
+ }
+ }
+ };
+ this.run(cmd, errorParser);
+ }
+
+ /**
+ * Runs the provided command in this ScriptConsole instance on the current
+ * host.
+ * @param command The command and arguments to run.
+ * @param envVars The environment variables to use while running
+ * @param errorParser The parser to handle error messages generated by the command
+ * @param project The project that command belongs to or null
+ * @since 2.1
+ */
+ public void runLocally(String[] command, String[] envVars, IErrorParser errorParser, IProject project) {
+ // Don't start a new command if one is already waiting to be started.
+ if (waitingToStart()) {
+ return;
+ }
+ cmd = new Command(command, envVars, project);
+ final IProject proj = project;
+
+ this.stopCommand = new Runnable() {
+ private final Command stopcmd = cmd;
+ String stopString = getStopString();
+
+ @Override
+ public void run() {
+ try {
+ synchronized (stopcmd) {
+ while (stopcmd.isRunning()) {
+ RuntimeProcessFactory.getFactory().exec(stopString, null, proj);
+ stopcmd.wait(RETRY_STOP_TIME);
+ }
+ }
+ } catch (IOException e) {
+ ExceptionErrorDialog.openError(Localization.getString("ScriptConsole.ErrorKillingStap"), e); //$NON-NLS-1$
+ } catch (InterruptedException e) {
+ //Wait was interrupted. Exit.
+ }
+ }
+ };
+ this.run(cmd, errorParser);
+ }
+
+ private void run(final Command cmd, IErrorParser errorParser){
+ final Runnable onCmdStop = new Runnable() {
+ @Override
+ public void run() {
+ try {
+ synchronized (cmd) {
+ while (cmd.isRunning()) {
+ cmd.wait();
+ }
+ onCmdStopActions();
+ }
+ } catch (InterruptedException e) {
+ return;
+ }
+ }
+ };
+ Runnable onCmdStart = new Runnable() {
+ @Override
+ public void run() {
+ if (stopCommandThread != null && stopCommandThread.isAlive()) {
+ try {
+ stopCommandThread.join();
+ } catch (InterruptedException e) {
+ return;
+ }
+ }
+ createConsoleDaemon();
+ if (errorDaemon != null) {
+ cmd.addErrorStreamListener(errorDaemon);
+ }
+ cmd.addInputStreamListener(consoleDaemon);
+ onCmdStopThread = new Thread(onCmdStop);
+ onCmdStopThread.start();
+ try {
+ cmd.start();
+ } catch (final CoreException e) {
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ ExceptionErrorDialog.openError(e.getMessage(), e);
+ }
+ });
+ cmd.dispose();
+ return;
+ }
+ notifyConsoleObservers();
+ }
+ };
+
+ if (errorParser != null) {
+ createErrorDaemon(errorParser);
+ }
+ activate();
+ ConsolePlugin.getDefault().getConsoleManager().showConsoleView(this);
+
+ onCmdStartThread = new Thread(onCmdStart);
onCmdStartThread.start();
- }
-
- private void onCmdStopActions() {
- notifyConsoleObservers();
- final String name = super.getName();
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- setName(Localization.getString("ScriptConsole.Terminated") + name); //$NON-NLS-1$
- }
- });
- }
-
- private synchronized void notifyConsoleObservers(){
- boolean started = hasStarted();
- boolean running = isRunning();
- for (ScriptConsoleObserver observer : inactiveConsoleObservers) {
- activeConsoleObservers.remove(observer);
- }
- inactiveConsoleObservers = new LinkedList<>();
- for (ScriptConsoleObserver observer : activeConsoleObservers) {
- observer.runningStateChanged(started, !running);
- }
- }
-
- /**
- * @since 2.0
- */
- public synchronized void addScriptConsoleObserver(ScriptConsoleObserver observer){
- activeConsoleObservers.add(observer);
- observer.runningStateChanged(hasStarted(), !isRunning());
- }
-
- /**
- * @since 3.0
- */
- public synchronized void removeScriptConsoleObserver(ScriptConsoleObserver observer){
- if (activeConsoleObservers.contains(observer)) {
- inactiveConsoleObservers.add(observer);
- }
- }
-
- /**
- * Check to see if the Command has been set up
- * @return boolean representing if the command has started
- * @since 3.0
- */
- private boolean hasStarted() {
- return cmd == null ? false : cmd.hasStarted();
- }
-
- /**
- * Check to see if the Command is still running
- * @return boolean representing if the command is running
- */
- public boolean isRunning() {
- return cmd == null ? false : cmd.isRunning();
- }
-
- /**
- * Check to see if this class has already been disposed.
- * @return boolean representing whether or not the class has been disposed.
- */
- public boolean isDisposed() {
- // If there is no command it can be considered disposed
- if (null == cmd) {
- return true;
- }
- return cmd.isDisposed();
- }
-
- /**
- * Method to allow the user to save the Commands output to a file for use latter.
- * @param file The new file to save the output to.
- */
- public void saveStream(File file) {
- if (isRunning()) {
- if (!cmd.saveLog(file)) {
- MessageDialog
- .openWarning(
- PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getShell(),
- Localization.getString("ScriptConsole.Problem"), Localization.getString("ScriptConsole.ErrorSavingLog")); //$NON-NLS-1$//$NON-NLS-2$
-
- }
- }
- }
-
- /**
- * Gets the command that is running in this console, or null if there is no running command.
- * @return The <code>LoggedCommand</code> that is running in this console.
- * @since 2.0
- */
- public Command getCommand() {
- return cmd;
- }
-
- /**
- * @return The process associated with this console's script when it is run.
- * A <code>null</code> process indicates that the script has not yet started
- * (if {@link #isRunning} returns true) or failed to start (if {@link #isRunning} is false).
- * @since 3.0
- */
- public Process getProcess() {
- return cmd != null ? cmd.getProcess() : null;
- }
-
- /**
- * Stops the running command and the associated listeners.
- */
- public synchronized void stop() {
- if (isRunning() && (stopCommandThread == null || !stopCommandThread.isAlive())) {
- // Stop the underlying stap process
- stopCommandThread = new Thread(this.stopCommand);
- stopCommandThread.start();
- }
- }
-
- private String getModuleName(){
- if(this.moduleName == null){
- moduleName = this.getName();
- int lastSlash = moduleName.lastIndexOf('/')+1;
- if (lastSlash < 0) {
- lastSlash = 0;
- }
- int lastDot = moduleName.indexOf(".stp"); //$NON-NLS-1$
- if (lastDot > 0) {
- moduleName = moduleName.substring(lastSlash, lastDot);
- }
- }
- return this.moduleName;
- }
-
- private String getStopString(){
- return "pkill -SIGINT -f stapio.*"+ getModuleName(); //$NON-NLS-1$
- }
- /**
- * Disposes of all internal references in the class. No method should be called after this.
- */
- @Override
- public void dispose() {
- if(!isDisposed()) {
- if(null != cmd) {
- cmd.dispose();
- }
- cmd = null;
- if(null != errorDaemon) {
- errorDaemon.dispose();
- }
- errorDaemon = null;
- if(null != consoleDaemon) {
- consoleDaemon.dispose();
- }
- consoleDaemon = null;
- }
- }
-
- /**
- * Changes the name displayed on this console.
- * @param name The new name to display on the console.
- */
- @Override
- public void setName(String name) {
- super.setName(name);
- if(null != ConsolePlugin.getDefault()) {
- ConsolePlugin.getDefault().getConsoleManager().refresh(this);
- }
- }
+ }
+
+ private void onCmdStopActions() {
+ notifyConsoleObservers();
+ final String name = super.getName();
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ setName(Localization.getString("ScriptConsole.Terminated") + name); //$NON-NLS-1$
+ }
+ });
+ }
+
+ private synchronized void notifyConsoleObservers(){
+ boolean started = hasStarted();
+ boolean running = isRunning();
+ for (ScriptConsoleObserver observer : inactiveConsoleObservers) {
+ activeConsoleObservers.remove(observer);
+ }
+ inactiveConsoleObservers = new LinkedList<>();
+ for (ScriptConsoleObserver observer : activeConsoleObservers) {
+ observer.runningStateChanged(started, !running);
+ }
+ }
+
+ /**
+ * @since 2.0
+ */
+ public synchronized void addScriptConsoleObserver(ScriptConsoleObserver observer){
+ activeConsoleObservers.add(observer);
+ observer.runningStateChanged(hasStarted(), !isRunning());
+ }
+
+ /**
+ * @since 3.0
+ */
+ public synchronized void removeScriptConsoleObserver(ScriptConsoleObserver observer){
+ if (activeConsoleObservers.contains(observer)) {
+ inactiveConsoleObservers.add(observer);
+ }
+ }
+
+ /**
+ * Check to see if the Command has been set up
+ * @return boolean representing if the command has started
+ * @since 3.0
+ */
+ private boolean hasStarted() {
+ return cmd == null ? false : cmd.hasStarted();
+ }
+
+ /**
+ * Check to see if the Command is still running
+ * @return boolean representing if the command is running
+ */
+ public boolean isRunning() {
+ return cmd == null ? false : cmd.isRunning();
+ }
+
+ /**
+ * Check to see if this class has already been disposed.
+ * @return boolean representing whether or not the class has been disposed.
+ */
+ public boolean isDisposed() {
+ // If there is no command it can be considered disposed
+ if (null == cmd) {
+ return true;
+ }
+ return cmd.isDisposed();
+ }
+
+ /**
+ * Method to allow the user to save the Commands output to a file for use latter.
+ * @param file The new file to save the output to.
+ */
+ public void saveStream(File file) {
+ if (isRunning()) {
+ if (!cmd.saveLog(file)) {
+ MessageDialog
+ .openWarning(
+ PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getShell(),
+ Localization.getString("ScriptConsole.Problem"), Localization.getString("ScriptConsole.ErrorSavingLog")); //$NON-NLS-1$//$NON-NLS-2$
+
+ }
+ }
+ }
+
+ /**
+ * Gets the command that is running in this console, or null if there is no running command.
+ * @return The <code>LoggedCommand</code> that is running in this console.
+ * @since 2.0
+ */
+ public Command getCommand() {
+ return cmd;
+ }
+
+ /**
+ * @return The process associated with this console's script when it is run.
+ * A <code>null</code> process indicates that the script has not yet started
+ * (if {@link #isRunning} returns true) or failed to start (if {@link #isRunning} is false).
+ * @since 3.0
+ */
+ public Process getProcess() {
+ return cmd != null ? cmd.getProcess() : null;
+ }
+
+ /**
+ * Stops the running command and the associated listeners.
+ */
+ public synchronized void stop() {
+ if (isRunning() && (stopCommandThread == null || !stopCommandThread.isAlive())) {
+ // Stop the underlying stap process
+ stopCommandThread = new Thread(this.stopCommand);
+ stopCommandThread.start();
+ }
+ }
+
+ private String getModuleName(){
+ if(this.moduleName == null){
+ moduleName = this.getName();
+ int lastSlash = moduleName.lastIndexOf('/')+1;
+ if (lastSlash < 0) {
+ lastSlash = 0;
+ }
+ int lastDot = moduleName.indexOf(".stp"); //$NON-NLS-1$
+ if (lastDot > 0) {
+ moduleName = moduleName.substring(lastSlash, lastDot);
+ }
+ }
+ return this.moduleName;
+ }
+
+ private String getStopString(){
+ return "pkill -SIGINT -f stapio.*"+ getModuleName(); //$NON-NLS-1$
+ }
+ /**
+ * Disposes of all internal references in the class. No method should be called after this.
+ */
+ @Override
+ public void dispose() {
+ if(!isDisposed()) {
+ if(null != cmd) {
+ cmd.dispose();
+ }
+ cmd = null;
+ if(null != errorDaemon) {
+ errorDaemon.dispose();
+ }
+ errorDaemon = null;
+ if(null != consoleDaemon) {
+ consoleDaemon.dispose();
+ }
+ consoleDaemon = null;
+ }
+ }
+
+ /**
+ * Changes the name displayed on this console.
+ * @param name The new name to display on the console.
+ */
+ @Override
+ public void setName(String name) {
+ super.setName(name);
+ if(null != ConsolePlugin.getDefault()) {
+ ConsolePlugin.getDefault().getConsoleManager().refresh(this);
+ }
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/views/ErrorView.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/views/ErrorView.java
index 39603b01dc..ff6cdcd2b4 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/views/ErrorView.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.consolelog/src/org/eclipse/linuxtools/systemtap/ui/consolelog/views/ErrorView.java
@@ -28,66 +28,66 @@ import org.eclipse.ui.part.ViewPart;
* @author Ryan Morse
*/
public class ErrorView extends ViewPart {
- public ErrorView() {
- super();
- }
-
- /**
- * Creates a new table to contain all of the error messages.
- * @param parent The composite to draw all content to.
- */
- @Override
- public void createPartControl(Composite parent) {
- Composite c = new Composite(parent, SWT.NONE);
+ public ErrorView() {
+ super();
+ }
- GridLayout grid = new GridLayout();
- c.setLayout(grid);
+ /**
+ * Creates a new table to contain all of the error messages.
+ * @param parent The composite to draw all content to.
+ */
+ @Override
+ public void createPartControl(Composite parent) {
+ Composite c = new Composite(parent, SWT.NONE);
- GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
- table = new ErrorTableDisplay(c, new String[] {"", Localization.getString("ErrorView.Type"), Localization.getString("ErrorView.Description"), Localization.getString("ErrorView.Saw"), Localization.getString("ErrorView.Line")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- table.getControl().setLayoutData(gd);
- }
+ GridLayout grid = new GridLayout();
+ c.setLayout(grid);
- /**
- * Adds the log details to the table of errors.
- * @param log The details for an error message to display in the table.
- */
- public void add(final String[] log) {
- table.getControl().getDisplay().syncExec(new Runnable() {
- @Override
- public void run() {
- table.addRow(log);
+ GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
+ table = new ErrorTableDisplay(c, new String[] {"", Localization.getString("ErrorView.Type"), Localization.getString("ErrorView.Description"), Localization.getString("ErrorView.Saw"), Localization.getString("ErrorView.Line")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ table.getControl().setLayoutData(gd);
+ }
- try {
- PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().showView(ID);
- } catch(PartInitException pie) {
- }
- }
- });
- }
-
- /**
- * Clears the entire table of error messages.
- */
- public void clear() {
- if(null != table)
- table.clear();
- }
-
- @Override
- public void setFocus() {}
+ /**
+ * Adds the log details to the table of errors.
+ * @param log The details for an error message to display in the table.
+ */
+ public void add(final String[] log) {
+ table.getControl().getDisplay().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ table.addRow(log);
- /**
- * Disposes of everything in this class.
- */
- @Override
- public void dispose() {
- if(null != table)
- table.dispose();
- table = null;
- super.dispose();
- }
-
- private volatile ErrorTableDisplay table;
- public static final String ID = "org.eclipse.linuxtools.systemtap.ui.consolelog.views.ErrorView"; //$NON-NLS-1$
+ try {
+ PlatformUI.getWorkbench().getWorkbenchWindows()[0].getActivePage().showView(ID);
+ } catch(PartInitException pie) {
+ }
+ }
+ });
+ }
+
+ /**
+ * Clears the entire table of error messages.
+ */
+ public void clear() {
+ if(null != table)
+ table.clear();
+ }
+
+ @Override
+ public void setFocus() {}
+
+ /**
+ * Disposes of everything in this class.
+ */
+ @Override
+ public void dispose() {
+ if(null != table)
+ table.dispose();
+ table = null;
+ super.dispose();
+ }
+
+ private volatile ErrorTableDisplay table;
+ public static final String ID = "org.eclipse.linuxtools.systemtap.ui.consolelog.views.ErrorView"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/build-helper.xml b/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/build-helper.xml
index 1a445364a0..8f165e5267 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/build-helper.xml
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/build-helper.xml
@@ -1,60 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="org.eclipse.linuxtools.systemtap.ui.doc" default="all">
- <description>
+ <description>
Generate Eclipse help content for the Linux Tools SystemTap user guide
</description>
- <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
+ <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
- <path id="wikitext.tasks.classpath">
- <!-- Replace dir with the dir you have wikitext installed into.-->
- <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
- <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
- </fileset>
- </path>
+ <path id="wikitext.tasks.classpath">
+ <!-- Replace dir with the dir you have wikitext installed into.-->
+ <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
+ <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
+ </fileset>
+ </path>
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
- <target name="all" description="Generate Eclipse help content for the Linux Tools SystemTap user guide">
- <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="SystemTap User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*, Infobox">
+ <target name="all" description="Generate Eclipse help content for the Linux Tools SystemTap user guide">
+ <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="SystemTap User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*, Infobox">
- <path name="Linux_Tools_Project/Systemtap/User_Guide" title="SystemTap User Guide" generateToc="false" />
- <stylesheet url="book.css" />
- <pageAppendum>
- = Updating This Document =
+ <path name="Linux_Tools_Project/Systemtap/User_Guide" title="SystemTap User Guide" generateToc="false" />
+ <stylesheet url="book.css" />
+ <pageAppendum>
+ = Updating This Document =
- This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
- http://wiki.eclipse.org/Linux_Tools_Project/SystemTap/User_Guide .
- </pageAppendum>
- </mediawiki-to-eclipse-help>
- <antcall target="test" />
- </target>
+ This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
+ http://wiki.eclipse.org/Linux_Tools_Project/SystemTap/User_Guide .
+ </pageAppendum>
+ </mediawiki-to-eclipse-help>
+ <antcall target="test" />
+ </target>
- <target name="test" description="verify that all of the HTML files are well-formed XML">
- <echo level="info">
+ <target name="test" description="verify that all of the HTML files are well-formed XML">
+ <echo level="info">
Validating help content XML and HTML files: The Eclipse help system expects well-formed XML
-
+
If validation fails it is because either:
-
+
* the userguide source code is poorly formed, or
* the WikiText MediaWiki parser has a bug
-
+
Problems with userguide source are usually caused by improper use of HTML markup in the MediaWiki source,
or inadvertently starting a line with a space character (in MediaWiki this starts a preformatted block)
- </echo>
-
- <!--
- Don't bother with DTD validation: we only care if the files are well-formed.
- We therefore provide an empty DTD
- -->
- <echo file="tmp/__empty.dtd" message="" />
- <xmlvalidate lenient="true">
- <fileset dir="Linux_Tools_Project">
- <include name="**/*.html" />
- </fileset>
- <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
- </xmlvalidate>
- <delete dir="tmp" />
- </target>
+ </echo>
+
+ <!--
+ Don't bother with DTD validation: we only care if the files are well-formed.
+ We therefore provide an empty DTD
+ -->
+ <echo file="tmp/__empty.dtd" message="" />
+ <xmlvalidate lenient="true">
+ <fileset dir="Linux_Tools_Project">
+ <include name="**/*.html" />
+ </fileset>
+ <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
+ </xmlvalidate>
+ <delete dir="tmp" />
+ </target>
</project>
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/toc-doc.xml b/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/toc-doc.xml
index 056cf38595..ddb77fc556 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/toc-doc.xml
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/toc-doc.xml
@@ -1,4 +1,4 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html" label="SystemTap User Guide">
-<link toc="toc.xml" />
+<link toc="toc.xml" />
</toc>
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/toc.xml b/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/toc.xml
index a6e31947e5..d2283153a3 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/toc.xml
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.doc/toc.xml
@@ -1,87 +1,87 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html" label="SystemTap User Guide">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html" label="SystemTap User Guide">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html" label="Overview">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#The_SystemTap_Plugin" label="The SystemTap Plugin"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Systemtap" label="Systemtap"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Installing" label="Installing">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Requirements" label="Requirements"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Kernel_Source_Location" label="Kernel Source Location"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Tutorials" label="Tutorials"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Preferences_.28Optional.29" label="Preferences (Optional)"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Links_to_SystemTap_Resources" label="Links to SystemTap Resources"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html" label="SystemTap IDE">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Getting_Started" label="Getting Started">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#IDE_Tutorial" label="IDE Tutorial">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Lesson_1:_Getting_Started" label="Lesson 1: Getting Started"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Lesson_2:_Writing_Your_First_Script" label="Lesson 2: Writing Your First Script"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Lesson_3:_Running_Your_Script" label="Lesson 3: Running Your Script"></topic>
- </topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Concepts" label="Concepts">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#SystemTap_IDE_Perspective" label="SystemTap IDE Perspective"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#STP_Editor" label="STP Editor"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Function_Browser" label="Function Browser"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Kernel_Browser" label="Kernel Browser"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Probe_Alias_Browser" label="Probe Alias Browser"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Tasks" label="Tasks">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Creating_SystemTap_Scripts" label="Creating SystemTap Scripts"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Using_the_STP_Editor" label="Using the STP Editor"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Viewing_Data_Charts" label="Viewing Data Charts"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Reference" label="Reference">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Views_and_Editors" label="Views and Editors">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Views" label="Views"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Editors" label="Editors"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Menus" label="Menus">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Edit" label="Edit"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Navigate" label="Navigate"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Run" label="Run"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Window" label="Window"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Toolbars" label="Toolbars">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Action_Bar" label="Action Bar"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Preferences" label="Preferences"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Frequently_Asked_Questions" label="Frequently Asked Questions"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Example_SystemTap_Scripts" label="Example SystemTap Scripts">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#top.stp_-_Prints_the_top_20_system_calls_.28http:.2F.2Fsourceware.org.2Fsystemtap.2Fexamples.2Ftop.stp.29" label="top.stp - Prints the top 20 system calls (http://sourceware.org/systemtap/examples/top.stp)"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#prof.stp_-_Simple_profiling_.28http:.2F.2Fsourceware.org.2Fsystemtap.2Fexamples.2Fprof.stp.29" label="prof.stp - Simple profiling (http://sourceware.org/systemtap/examples/prof.stp)"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#keyhack.stp_-_Modifying_variables_in_the_kernel._.28http:.2F.2Fsourceware.org.2Fsystemtap.2Fexamples.2Fkeyhack.stp.29" label="keyhack.stp - Modifying variables in the kernel. (http://sourceware.org/systemtap/examples/keyhack.stp)"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#kmalloc.stp_-_Statistics_example._.28http:.2F.2Fsourceware.org.2Fsystemtap.2Fexamples.2Fkmalloc.stp.29" label="kmalloc.stp - Statistics example. (http://sourceware.org/systemtap/examples/kmalloc.stp)"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#kmalloc2.stp_-_Example_using_arrays_of_statistics._.28http:.2F.2Fsourceware.org.2Fsystemtap.2Fexamples.2Fkmalloc2.stp.29" label="kmalloc2.stp - Example using arrays of statistics. (http://sourceware.org/systemtap/examples/kmalloc2.stp)"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Guide_to_Regular_Expressions" label="Guide to Regular Expressions"></topic>
- </topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html" label="SystemTap Graphing">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Getting_Started_2" label="Getting Started">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Introduction" label="Introduction"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Graphing_Tutorial" label="Graphing Tutorial">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Create_Graph_Wizard" label="Create Graph Wizard"></topic>
- </topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Concepts_2" label="Concepts">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Data_Table" label="Data Table"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Data_Graph_Types" label="Data Graph Types">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Scatter_Graph" label="Scatter Graph"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Line_Graph" label="Line Graph"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Area_Graph" label="Area Graph"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Bar_Graph" label="Bar Graph"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Pie_Graph" label="Pie Graph"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Filters" label="Filters"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Graph_Interaction" label="Graph Interaction"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Reference_2" label="Reference">
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Frequently_Asked_Questions_2" label="Frequently Asked Questions"></topic>
- </topic>
- </topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/Copyright-Information.html" label="Copyright Information"></topic>
- <topic href="Linux_Tools_Project/Systemtap/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
- </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html" label="SystemTap User Guide">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html" label="Overview">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#The_SystemTap_Plugin" label="The SystemTap Plugin"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Systemtap" label="Systemtap"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Installing" label="Installing">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Requirements" label="Requirements"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Kernel_Source_Location" label="Kernel Source Location"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Tutorials" label="Tutorials"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Preferences_.28Optional.29" label="Preferences (Optional)"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/User-Guide.html#Links_to_SystemTap_Resources" label="Links to SystemTap Resources"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html" label="SystemTap IDE">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Getting_Started" label="Getting Started">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#IDE_Tutorial" label="IDE Tutorial">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Lesson_1:_Getting_Started" label="Lesson 1: Getting Started"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Lesson_2:_Writing_Your_First_Script" label="Lesson 2: Writing Your First Script"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Lesson_3:_Running_Your_Script" label="Lesson 3: Running Your Script"></topic>
+ </topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Concepts" label="Concepts">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#SystemTap_IDE_Perspective" label="SystemTap IDE Perspective"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#STP_Editor" label="STP Editor"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Function_Browser" label="Function Browser"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Kernel_Browser" label="Kernel Browser"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Probe_Alias_Browser" label="Probe Alias Browser"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Tasks" label="Tasks">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Creating_SystemTap_Scripts" label="Creating SystemTap Scripts"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Using_the_STP_Editor" label="Using the STP Editor"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Viewing_Data_Charts" label="Viewing Data Charts"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Reference" label="Reference">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Views_and_Editors" label="Views and Editors">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Views" label="Views"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Editors" label="Editors"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Menus" label="Menus">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Edit" label="Edit"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Navigate" label="Navigate"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Run" label="Run"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Window" label="Window"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Toolbars" label="Toolbars">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Action_Bar" label="Action Bar"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Preferences" label="Preferences"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Frequently_Asked_Questions" label="Frequently Asked Questions"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Example_SystemTap_Scripts" label="Example SystemTap Scripts">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#top.stp_-_Prints_the_top_20_system_calls_.28http:.2F.2Fsourceware.org.2Fsystemtap.2Fexamples.2Ftop.stp.29" label="top.stp - Prints the top 20 system calls (http://sourceware.org/systemtap/examples/top.stp)"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#prof.stp_-_Simple_profiling_.28http:.2F.2Fsourceware.org.2Fsystemtap.2Fexamples.2Fprof.stp.29" label="prof.stp - Simple profiling (http://sourceware.org/systemtap/examples/prof.stp)"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#keyhack.stp_-_Modifying_variables_in_the_kernel._.28http:.2F.2Fsourceware.org.2Fsystemtap.2Fexamples.2Fkeyhack.stp.29" label="keyhack.stp - Modifying variables in the kernel. (http://sourceware.org/systemtap/examples/keyhack.stp)"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#kmalloc.stp_-_Statistics_example._.28http:.2F.2Fsourceware.org.2Fsystemtap.2Fexamples.2Fkmalloc.stp.29" label="kmalloc.stp - Statistics example. (http://sourceware.org/systemtap/examples/kmalloc.stp)"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#kmalloc2.stp_-_Example_using_arrays_of_statistics._.28http:.2F.2Fsourceware.org.2Fsystemtap.2Fexamples.2Fkmalloc2.stp.29" label="kmalloc2.stp - Example using arrays of statistics. (http://sourceware.org/systemtap/examples/kmalloc2.stp)"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-IDE.html#Guide_to_Regular_Expressions" label="Guide to Regular Expressions"></topic>
+ </topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html" label="SystemTap Graphing">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Getting_Started_2" label="Getting Started">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Introduction" label="Introduction"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Graphing_Tutorial" label="Graphing Tutorial">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Create_Graph_Wizard" label="Create Graph Wizard"></topic>
+ </topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Concepts_2" label="Concepts">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Data_Table" label="Data Table"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Data_Graph_Types" label="Data Graph Types">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Scatter_Graph" label="Scatter Graph"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Line_Graph" label="Line Graph"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Area_Graph" label="Area Graph"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Bar_Graph" label="Bar Graph"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Pie_Graph" label="Pie Graph"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Filters" label="Filters"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Graph_Interaction" label="Graph Interaction"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Reference_2" label="Reference">
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/SystemTap-Graphing.html#Frequently_Asked_Questions_2" label="Frequently Asked Questions"></topic>
+ </topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/Copyright-Information.html" label="Copyright Information"></topic>
+ <topic href="Linux_Tools_Project/Systemtap/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
+ </topic>
</toc> \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/plugin.xml b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/plugin.xml
index 08e3a719cd..0140117902 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/plugin.xml
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/plugin.xml
@@ -1,42 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.0"?>
<plugin>
- <extension
- point="org.eclipse.ui.commands">
- <command
- name="%action.open.name"
- description="%action.open.desc"
- categoryId="org.eclipse.linuxtools.systemtap.ui.editor.category.file"
- id="org.eclipse.linuxtools.systemtap.ui.editor.commands.file.OpenFileCommand"/>
- <category
- name="%category.file.name"
- description="%category.file.desc"
- id="org.eclipse.linuxtools.systemtap.ui.editor.category.file"/>
- </extension>
-
- <extension
- point="org.eclipse.ui.actionSets">
- <actionSet
- label="%actionset.file.name"
- visible="false"
- id="org.eclipse.linuxtools.systemtap.ui.editor.FileActionSet">
- <action
- label="%action.open.name"
- id="org.eclipse.linuxtools.systemtap.ui.editor.actions.file.OpenFileAction"
- icon="icons/actions/file/open_wiz.gif"
- toolbarPath="org.eclipse.ui.workbench.file/new.ext"
- class="org.eclipse.linuxtools.systemtap.ui.editor.actions.file.OpenFileAction"
- definitionId="org.eclipse.linuxtools.systemtap.ui.editor.commands.file.OpenFileCommand"
- style="push"
- state="false"/>
- </actionSet>
- </extension>
+ <extension
+ point="org.eclipse.ui.commands">
+ <command
+ name="%action.open.name"
+ description="%action.open.desc"
+ categoryId="org.eclipse.linuxtools.systemtap.ui.editor.category.file"
+ id="org.eclipse.linuxtools.systemtap.ui.editor.commands.file.OpenFileCommand"/>
+ <category
+ name="%category.file.name"
+ description="%category.file.desc"
+ id="org.eclipse.linuxtools.systemtap.ui.editor.category.file"/>
+ </extension>
- <extension
- point="org.eclipse.ui.perspectiveExtensions">
- <perspectiveExtension
- targetID="org.eclipse.linuxtools.systemtap.ui.ide.IDEPerspective">
- <actionSet id="org.eclipse.linuxtools.systemtap.ui.editor.FileActionSet"/>
- </perspectiveExtension>
- </extension>
+ <extension
+ point="org.eclipse.ui.actionSets">
+ <actionSet
+ label="%actionset.file.name"
+ visible="false"
+ id="org.eclipse.linuxtools.systemtap.ui.editor.FileActionSet">
+ <action
+ label="%action.open.name"
+ id="org.eclipse.linuxtools.systemtap.ui.editor.actions.file.OpenFileAction"
+ icon="icons/actions/file/open_wiz.gif"
+ toolbarPath="org.eclipse.ui.workbench.file/new.ext"
+ class="org.eclipse.linuxtools.systemtap.ui.editor.actions.file.OpenFileAction"
+ definitionId="org.eclipse.linuxtools.systemtap.ui.editor.commands.file.OpenFileCommand"
+ style="push"
+ state="false"/>
+ </actionSet>
+ </extension>
+
+ <extension
+ point="org.eclipse.ui.perspectiveExtensions">
+ <perspectiveExtension
+ targetID="org.eclipse.linuxtools.systemtap.ui.ide.IDEPerspective">
+ <actionSet id="org.eclipse.linuxtools.systemtap.ui.editor.FileActionSet"/>
+ </perspectiveExtension>
+ </extension>
</plugin>
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/internal/systemtap/ui/editor/EditorPlugin.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/internal/systemtap/ui/editor/EditorPlugin.java
index 0ff8355cc7..0833d6195f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/internal/systemtap/ui/editor/EditorPlugin.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/internal/systemtap/ui/editor/EditorPlugin.java
@@ -16,5 +16,5 @@ package org.eclipse.linuxtools.internal.systemtap.ui.editor;
*/
public interface EditorPlugin {
- String ID = "org.eclipse.linuxtools.systemtap.ui.editor"; //$NON-NLS-1$
+ String ID = "org.eclipse.linuxtools.systemtap.ui.editor"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/internal/systemtap/ui/editor/Localization.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/internal/systemtap/ui/editor/Localization.java
index 03f1be3da4..04ab0bcc59 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/internal/systemtap/ui/editor/Localization.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/internal/systemtap/ui/editor/Localization.java
@@ -15,19 +15,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Localization {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.editor.localization"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.editor.localization"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Localization() {
- }
+ private Localization() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/ColorManager.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/ColorManager.java
index 8937b4364e..4f50f547f5 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/ColorManager.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/ColorManager.java
@@ -22,20 +22,20 @@ import org.eclipse.swt.widgets.Display;
public class ColorManager {
- private Map<RGB, Color> colorTable = new HashMap<>(10);
+ private Map<RGB, Color> colorTable = new HashMap<>(10);
- public void dispose() {
- Iterator<Color> e = colorTable.values().iterator();
- while (e.hasNext())
- e.next().dispose();
- }
+ public void dispose() {
+ Iterator<Color> e = colorTable.values().iterator();
+ while (e.hasNext())
+ e.next().dispose();
+ }
- public Color getColor(RGB rgb) {
- Color color = colorTable.get(rgb);
- if (color == null) {
- color = new Color(Display.getCurrent(), rgb);
- colorTable.put(rgb, color);
- }
- return color;
- }
+ public Color getColor(RGB rgb) {
+ Color color = colorTable.get(rgb);
+ if (color == null) {
+ color = new Color(Display.getCurrent(), rgb);
+ colorTable.put(rgb, color);
+ }
+ return color;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/DoubleClickStrategy.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/DoubleClickStrategy.java
index 8c8996ad2b..0f2089dacf 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/DoubleClickStrategy.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/DoubleClickStrategy.java
@@ -17,131 +17,131 @@ import org.eclipse.jface.text.ITextDoubleClickStrategy;
import org.eclipse.jface.text.ITextViewer;
public class DoubleClickStrategy implements ITextDoubleClickStrategy {
- private ITextViewer fText;
-
- @Override
- public void doubleClicked(ITextViewer part) {
- int pos = part.getSelectedRange().x;
-
- if (pos < 0) {
- return;
- }
-
- fText = part;
-
- if (!selectComment(pos)) {
- selectWord(pos);
- }
- }
-
- /**
- * Method handles the selection of comments in the editor.
- *
- * @param caretPos postition of the caret
- */
- private boolean selectComment(int caretPos) {
- IDocument doc = fText.getDocument();
- int startPos, endPos;
-
- try {
- int pos = caretPos;
- char c = ' ';
-
- while (pos >= 0) {
- c = doc.getChar(pos);
- if (c == '\\') {
- pos -= 2;
- continue;
- }
- if (c == Character.LINE_SEPARATOR || c == '\"') {
- break;
- }
- --pos;
- }
-
- if (c != '\"') {
- return false;
- }
-
- startPos = pos;
-
- pos = caretPos;
- int length = doc.getLength();
- c = ' ';
-
- while (pos < length) {
- c = doc.getChar(pos);
- if (c == Character.LINE_SEPARATOR || c == '\"') {
- break;
- }
- ++pos;
- }
- if (c != '\"') {
- return false;
- }
-
- endPos = pos;
-
- int offset = startPos + 1;
- int len = endPos - offset;
- fText.setSelectedRange(offset, len);
-
- return true;
- } catch (BadLocationException x) {
- // Pass
- }
-
- return false;
- }
-
- /**
- * Method handles the selection of words in the editor.
- *
- * @param caretPos postition of the caret
- */
- private boolean selectWord(int caretPos) {
- IDocument doc = fText.getDocument();
- int startPos, endPos;
-
- try {
- int pos = caretPos;
- char c;
-
- while (pos >= 0) {
- c = doc.getChar(pos);
- if (!Character.isJavaIdentifierPart(c)) {
- break;
- }
- --pos;
- }
-
- startPos = pos;
-
- pos = caretPos;
- int length = doc.getLength();
-
- while (pos < length) {
- c = doc.getChar(pos);
- if (!Character.isJavaIdentifierPart(c)) {
- break;
- }
- ++pos;
- }
-
- endPos = pos;
- selectRange(startPos, endPos);
-
- return true;
- } catch (BadLocationException x) {
- // Pass
- }
-
- return false;
- }
-
- private void selectRange(int startPos, int stopPos) {
- int offset = startPos + 1;
- int length = stopPos - offset;
- fText.setSelectedRange(offset, length);
- }
+ private ITextViewer fText;
+
+ @Override
+ public void doubleClicked(ITextViewer part) {
+ int pos = part.getSelectedRange().x;
+
+ if (pos < 0) {
+ return;
+ }
+
+ fText = part;
+
+ if (!selectComment(pos)) {
+ selectWord(pos);
+ }
+ }
+
+ /**
+ * Method handles the selection of comments in the editor.
+ *
+ * @param caretPos postition of the caret
+ */
+ private boolean selectComment(int caretPos) {
+ IDocument doc = fText.getDocument();
+ int startPos, endPos;
+
+ try {
+ int pos = caretPos;
+ char c = ' ';
+
+ while (pos >= 0) {
+ c = doc.getChar(pos);
+ if (c == '\\') {
+ pos -= 2;
+ continue;
+ }
+ if (c == Character.LINE_SEPARATOR || c == '\"') {
+ break;
+ }
+ --pos;
+ }
+
+ if (c != '\"') {
+ return false;
+ }
+
+ startPos = pos;
+
+ pos = caretPos;
+ int length = doc.getLength();
+ c = ' ';
+
+ while (pos < length) {
+ c = doc.getChar(pos);
+ if (c == Character.LINE_SEPARATOR || c == '\"') {
+ break;
+ }
+ ++pos;
+ }
+ if (c != '\"') {
+ return false;
+ }
+
+ endPos = pos;
+
+ int offset = startPos + 1;
+ int len = endPos - offset;
+ fText.setSelectedRange(offset, len);
+
+ return true;
+ } catch (BadLocationException x) {
+ // Pass
+ }
+
+ return false;
+ }
+
+ /**
+ * Method handles the selection of words in the editor.
+ *
+ * @param caretPos postition of the caret
+ */
+ private boolean selectWord(int caretPos) {
+ IDocument doc = fText.getDocument();
+ int startPos, endPos;
+
+ try {
+ int pos = caretPos;
+ char c;
+
+ while (pos >= 0) {
+ c = doc.getChar(pos);
+ if (!Character.isJavaIdentifierPart(c)) {
+ break;
+ }
+ --pos;
+ }
+
+ startPos = pos;
+
+ pos = caretPos;
+ int length = doc.getLength();
+
+ while (pos < length) {
+ c = doc.getChar(pos);
+ if (!Character.isJavaIdentifierPart(c)) {
+ break;
+ }
+ ++pos;
+ }
+
+ endPos = pos;
+ selectRange(startPos, endPos);
+
+ return true;
+ } catch (BadLocationException x) {
+ // Pass
+ }
+
+ return false;
+ }
+
+ private void selectRange(int startPos, int stopPos) {
+ int offset = startPos + 1;
+ int length = stopPos - offset;
+ fText.setSelectedRange(offset, length);
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/PathEditorInput.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/PathEditorInput.java
index b2ac795831..18e26ffc14 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/PathEditorInput.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/PathEditorInput.java
@@ -21,62 +21,62 @@ import org.eclipse.ui.ide.FileStoreEditorInput;
public class PathEditorInput extends FileStoreEditorInput implements IPathEditorInput, ILocationProvider {
- private IPath fPath;
+ private IPath fPath;
- public PathEditorInput(IPath path) {
- super(EFS.getLocalFileSystem().getStore(path));
- if (path == null) {
- throw new IllegalArgumentException();
- }
- this.fPath = path;
- }
+ public PathEditorInput(IPath path) {
+ super(EFS.getLocalFileSystem().getStore(path));
+ if (path == null) {
+ throw new IllegalArgumentException();
+ }
+ this.fPath = path;
+ }
- @Override
- public int hashCode() {
- return fPath.hashCode();
- }
+ @Override
+ public int hashCode() {
+ return fPath.hashCode();
+ }
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj instanceof PathEditorInput) {
- PathEditorInput other = (PathEditorInput) obj;
- return fPath.equals(other.fPath);
- } else if (obj instanceof FileStoreEditorInput) {
- return super.equals(obj);
- }
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj instanceof PathEditorInput) {
+ PathEditorInput other = (PathEditorInput) obj;
+ return fPath.equals(other.fPath);
+ } else if (obj instanceof FileStoreEditorInput) {
+ return super.equals(obj);
+ }
- return false;
- }
+ return false;
+ }
- @Override
- public String getName() {
- String[] substr = fPath.segments();
- return substr[substr.length -1];
- }
+ @Override
+ public String getName() {
+ String[] substr = fPath.segments();
+ return substr[substr.length -1];
+ }
- @Override
- public IPath getPath() {
- return fPath;
- }
+ @Override
+ public IPath getPath() {
+ return fPath;
+ }
- @Override
- public IPath getPath(Object element) {
- if(element instanceof PathEditorInput) {
- return ((PathEditorInput)element).getPath();
- }
- return null;
- }
+ @Override
+ public IPath getPath(Object element) {
+ if(element instanceof PathEditorInput) {
+ return ((PathEditorInput)element).getPath();
+ }
+ return null;
+ }
- @Override
- public Object getAdapter(Class adapter) {
- if (PathEditorInput.class.equals(adapter)
- || IPathEditorInput.class.equals(adapter)
- || ILocationProvider.class.equals(adapter)) {
- return this;
- }
- return Platform.getAdapterManager().getAdapter(this, adapter);
- }
+ @Override
+ public Object getAdapter(Class adapter) {
+ if (PathEditorInput.class.equals(adapter)
+ || IPathEditorInput.class.equals(adapter)
+ || ILocationProvider.class.equals(adapter)) {
+ return this;
+ }
+ return Platform.getAdapterManager().getAdapter(this, adapter);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/SimpleDocumentProvider.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/SimpleDocumentProvider.java
index d0d3724b75..5a10e96aae 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/SimpleDocumentProvider.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/SimpleDocumentProvider.java
@@ -41,160 +41,160 @@ import org.eclipse.ui.texteditor.AbstractDocumentProvider;
public class SimpleDocumentProvider extends AbstractDocumentProvider {
- @Override
- protected IDocument createDocument(Object element) throws CoreException {
- if (element instanceof IEditorInput) {
- IDocument document= new Document();
- setDocumentContent(document, (IEditorInput) element);
- return document;
- }
-
- return null;
- }
-
- /**
- * Tries to read the file pointed at by <code>input</code> if it is an
- * <code>IPathEditorInput</code>. If the file does not exist, <code>true</code>
- * is returned.
- *
- * @param document the document to fill with the contents of <code>input</code>
- * @param input the editor input
- * @throws CoreException if reading the file fails
- */
- private static void setDocumentContent(IDocument document, IEditorInput input) throws CoreException {
- Reader reader = null;
- try {
- if (input instanceof FileStoreEditorInput){
- reader = new InputStreamReader(((FileStoreEditorInput)input).getURI().toURL().openStream());
- } else if (input instanceof IPathEditorInput){
- reader= new FileReader(((IPathEditorInput)input).getPath().toFile());
- } else {
- return;
- }
- } catch (FileNotFoundException e) {
- // return empty document and save later
- return;
- } catch (MalformedURLException e) {
- throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID ,Localization.getString("SimpleDocumentProvider.incorrectURL"), e)); //$NON-NLS-1$
- } catch (IOException e) {
- throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID, Localization.getString("SimpleDocumentProvider.errorCreatingFile"), e)); //$NON-NLS-1$
- }
-
- try {
- setDocumentContent(document, reader);
- return;
- } catch (IOException e) {
- throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID, IStatus.OK, Localization.getString("SimpleDocumentProvider.errorCreatingFile"), e)); //$NON-NLS-1$
- }
- }
-
- /**
- * Reads in document content from a reader and fills <code>document</code>
- *
- * @param document the document to fill
- * @param reader the source
- * @throws IOException if reading fails
- */
- private static void setDocumentContent(IDocument document, Reader reader) throws IOException {
- try (Reader in= new BufferedReader(reader)) {
-
- StringBuffer buffer= new StringBuffer(512);
- char[] readBuffer= new char[512];
- int n= in.read(readBuffer);
- while (n > 0) {
- buffer.append(readBuffer, 0, n);
- n= in.read(readBuffer);
- }
-
- document.set(buffer.toString());
- }
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#createAnnotationModel(java.lang.Object)
- */
- @Override
- protected IAnnotationModel createAnnotationModel(Object element) {
- return null;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doSaveDocument(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
- */
- @Override
- protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
- if (element instanceof IPathEditorInput) {
- IPathEditorInput pei= (IPathEditorInput) element;
- IPath path= pei.getPath();
- File file= path.toFile();
-
- try {
- file.createNewFile();
-
- if (file.exists()) {
- if (file.canWrite()) {
- Writer writer= new FileWriter(file);
- writeDocumentContent(document, writer, monitor);
- } else {
- throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID, IStatus.OK, "file is read-only", null)); //$NON-NLS-1$
- }
- } else {
- throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID, IStatus.OK, "error creating file", null)); //$NON-NLS-1$
- }
- } catch (IOException e) {
- throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID, IStatus.OK, Localization.getString("errorCreatingFile"), e)); //$NON-NLS-1$
- }
- }
- }
-
- /**
- * Saves the document contents to a stream.
- *
- * @param document the document to save
- * @param writer the stream to save it to
- * @param monitor a progress monitor to report progress
- * @throws IOException if writing fails
- */
- private static void writeDocumentContent(IDocument document, Writer writer, IProgressMonitor monitor) throws IOException {
- try (Writer out= new BufferedWriter(writer)) {
- out.write(document.get());
- }
- }
-
- /*
- * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#getOperationRunner(org.eclipse.core.runtime.IProgressMonitor)
- */
- @Override
- protected IRunnableContext getOperationRunner(IProgressMonitor monitor) {
- return null;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#isModifiable(java.lang.Object)
- */
- @Override
- public boolean isModifiable(Object element) {
- if (element instanceof IPathEditorInput) {
- IPathEditorInput pei= (IPathEditorInput) element;
- File file= pei.getPath().toFile();
- return file.canWrite() || !file.exists(); // Allow to edit new files
- }
- return false;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#isReadOnly(java.lang.Object)
- */
- @Override
- public boolean isReadOnly(Object element) {
- return !isModifiable(element);
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#isStateValidated(java.lang.Object)
- */
- @Override
- public boolean isStateValidated(Object element) {
- return true;
- }
+ @Override
+ protected IDocument createDocument(Object element) throws CoreException {
+ if (element instanceof IEditorInput) {
+ IDocument document= new Document();
+ setDocumentContent(document, (IEditorInput) element);
+ return document;
+ }
+
+ return null;
+ }
+
+ /**
+ * Tries to read the file pointed at by <code>input</code> if it is an
+ * <code>IPathEditorInput</code>. If the file does not exist, <code>true</code>
+ * is returned.
+ *
+ * @param document the document to fill with the contents of <code>input</code>
+ * @param input the editor input
+ * @throws CoreException if reading the file fails
+ */
+ private static void setDocumentContent(IDocument document, IEditorInput input) throws CoreException {
+ Reader reader = null;
+ try {
+ if (input instanceof FileStoreEditorInput){
+ reader = new InputStreamReader(((FileStoreEditorInput)input).getURI().toURL().openStream());
+ } else if (input instanceof IPathEditorInput){
+ reader= new FileReader(((IPathEditorInput)input).getPath().toFile());
+ } else {
+ return;
+ }
+ } catch (FileNotFoundException e) {
+ // return empty document and save later
+ return;
+ } catch (MalformedURLException e) {
+ throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID ,Localization.getString("SimpleDocumentProvider.incorrectURL"), e)); //$NON-NLS-1$
+ } catch (IOException e) {
+ throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID, Localization.getString("SimpleDocumentProvider.errorCreatingFile"), e)); //$NON-NLS-1$
+ }
+
+ try {
+ setDocumentContent(document, reader);
+ return;
+ } catch (IOException e) {
+ throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID, IStatus.OK, Localization.getString("SimpleDocumentProvider.errorCreatingFile"), e)); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Reads in document content from a reader and fills <code>document</code>
+ *
+ * @param document the document to fill
+ * @param reader the source
+ * @throws IOException if reading fails
+ */
+ private static void setDocumentContent(IDocument document, Reader reader) throws IOException {
+ try (Reader in= new BufferedReader(reader)) {
+
+ StringBuffer buffer= new StringBuffer(512);
+ char[] readBuffer= new char[512];
+ int n= in.read(readBuffer);
+ while (n > 0) {
+ buffer.append(readBuffer, 0, n);
+ n= in.read(readBuffer);
+ }
+
+ document.set(buffer.toString());
+ }
+ }
+
+ /*
+ * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#createAnnotationModel(java.lang.Object)
+ */
+ @Override
+ protected IAnnotationModel createAnnotationModel(Object element) {
+ return null;
+ }
+
+ /*
+ * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doSaveDocument(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
+ */
+ @Override
+ protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
+ if (element instanceof IPathEditorInput) {
+ IPathEditorInput pei= (IPathEditorInput) element;
+ IPath path= pei.getPath();
+ File file= path.toFile();
+
+ try {
+ file.createNewFile();
+
+ if (file.exists()) {
+ if (file.canWrite()) {
+ Writer writer= new FileWriter(file);
+ writeDocumentContent(document, writer, monitor);
+ } else {
+ throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID, IStatus.OK, "file is read-only", null)); //$NON-NLS-1$
+ }
+ } else {
+ throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID, IStatus.OK, "error creating file", null)); //$NON-NLS-1$
+ }
+ } catch (IOException e) {
+ throw new CoreException(new Status(IStatus.ERROR, EditorPlugin.ID, IStatus.OK, Localization.getString("errorCreatingFile"), e)); //$NON-NLS-1$
+ }
+ }
+ }
+
+ /**
+ * Saves the document contents to a stream.
+ *
+ * @param document the document to save
+ * @param writer the stream to save it to
+ * @param monitor a progress monitor to report progress
+ * @throws IOException if writing fails
+ */
+ private static void writeDocumentContent(IDocument document, Writer writer, IProgressMonitor monitor) throws IOException {
+ try (Writer out= new BufferedWriter(writer)) {
+ out.write(document.get());
+ }
+ }
+
+ /*
+ * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#getOperationRunner(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ @Override
+ protected IRunnableContext getOperationRunner(IProgressMonitor monitor) {
+ return null;
+ }
+
+ /*
+ * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#isModifiable(java.lang.Object)
+ */
+ @Override
+ public boolean isModifiable(Object element) {
+ if (element instanceof IPathEditorInput) {
+ IPathEditorInput pei= (IPathEditorInput) element;
+ File file= pei.getPath().toFile();
+ return file.canWrite() || !file.exists(); // Allow to edit new files
+ }
+ return false;
+ }
+
+ /*
+ * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#isReadOnly(java.lang.Object)
+ */
+ @Override
+ public boolean isReadOnly(Object element) {
+ return !isModifiable(element);
+ }
+
+ /*
+ * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#isStateValidated(java.lang.Object)
+ */
+ @Override
+ public boolean isStateValidated(Object element) {
+ return true;
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/SimpleEditor.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/SimpleEditor.java
index ae55177f6f..031a2ddfba 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/SimpleEditor.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/SimpleEditor.java
@@ -33,178 +33,178 @@ import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.editors.text.TextEditor;
public class SimpleEditor extends TextEditor {
- public SimpleEditor() {
- super();
- // make sure we inherit all the text editing commands (delete line etc).
- setKeyBindingScopes(new String[] { "org.eclipse.linuxtools.systemtap.ui.ide.context" }); //$NON-NLS-1$
- internalInit();
- }
-
- /**
- * @since 3.0
- */
- protected void internalInit() {
- configureInsertMode(SMART_INSERT, false);
- setDocumentProvider(new SimpleDocumentProvider());
- }
-
- /**
- * Searches the IDocument for the specified string.
- *
- * @param search string to find, case-sensitive
- * @return the integer line number of the string
- */
- public int find(String search) {
- return findWithOptions(search, false);
- }
-
- /**
- * Searches the IDocument for the specified regex.
- * @param regex string regex to find
- * @return the integer line number of the string
- * @since 3.0
- */
- public int findRegex(String regex) {
- return findWithOptions(regex, true);
- }
-
- private int findWithOptions(String search, boolean regExSearch) {
- IDocument doc = getSourceViewer().getDocument();
- FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter(doc);
-
- int line = 0;
-
- jumpToLocation(0, 0);
- try {
- IRegion reg = finder.find(0, search, true, !regExSearch, false, regExSearch);
- int offset = reg.getOffset();
- line = doc.getLineOfOffset(offset);
- } catch (BadLocationException ble) {
- // Pass
- } catch (NullPointerException npe) {
- line = -1;
- }
-
- return line;
- }
-
- /**
- * Jumps to the location in the IDocument.
- * @param line The line you wish to jump to.
- * @param character The character you wish to jump to.
- */
- public void jumpToLocation(int line, int character) {
- IDocument doc = getSourceViewer().getDocument();
-
- try {
- int offset = doc.getLineOffset(line-1) + character;
- this.getSelectionProvider().setSelection(new TextSelection(doc, offset, 0));
- } catch (BadLocationException boe) {
- // Pass
- }
- }
-
- /**
- * Selects a line in the IDocument.
- * @param line the line you wish to select
- */
- public void selectLine(int line) {
- IDocument doc = getSourceViewer().getDocument();
-
- try {
- this.getSelectionProvider().setSelection(new TextSelection(doc, doc.getLineOffset(line-1), doc.getLineLength(line-1)-1));
- } catch (BadLocationException boe) {
- // Pass
- }
- }
-
- /**
- * Performs a SaveAs on the IDocument.
- */
- @Override
- public void doSaveAs() {
- File file = queryFile();
- if (file == null) {
- return;
- }
-
- IEditorInput inputFile = createEditorInput(file);
-
- IDocument doc = getSourceViewer().getDocument();
- String s = doc.get();
-
- try (FileOutputStream fos = new FileOutputStream(file);
- PrintStream ps = new PrintStream(fos)){
- ps.print(s);
- ps.close();
- } catch (IOException fnfe) {
- // Pass
- }
-
- setInput(inputFile);
- setPartName(inputFile.getName());
- }
-
- /**
- * Sets up an editor input based on the specified file.
- * @param file the location of the file you wish to set.
- * @return input object created.
- */
- private static IEditorInput createEditorInput(File file) {
- IPath location= new Path(file.getAbsolutePath());
- PathEditorInput input= new PathEditorInput(location);
- return input;
- }
-
- /**
- * Inserts text into the IDocument.
- * @param text string to insert
- */
- public void insertText(String text) {
- IDocument doc = getSourceViewer().getDocument();
- String s = doc.get();
- int offset = s.length();
- s += text;
- doc.set(s);
- this.setHighlightRange(offset, 0, true);
- }
-
- /**
- * Inserts text at the current location.
- * @param text string to insert
- */
- public void insertTextAtCurrent(String text) {
- ISelection selection = this.getSelectionProvider().getSelection();
- IDocument doc = getSourceViewer().getDocument();
-
- if (selection instanceof ITextSelection) {
- ITextSelection s = (ITextSelection) selection;
- StringBuffer sb = new StringBuffer(doc.get().substring(0, s.getOffset()));
- sb.append(text.trim());
- sb.append(doc.get().substring(s.getOffset() + s.getLength(), doc.get().length()));
- doc.set(sb.toString());
- this.setHighlightRange(s.getOffset() + text.trim().length(), 0, true);
- }
- }
-
- private static File queryFile() {
- FileDialog dialog= new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
- dialog.setText(Localization.getString("NewFileAction.NewFile")); //$NON-NLS-1$
- String path= dialog.open();
- if (path != null && path.length() > 0) {
- return new File(path);
- }
- return null;
- }
-
- /**
- * Determines whether saving is allowed currently.
- * @return boolean value indicating whether or not saving is allowed
- */
- @Override
- public boolean isSaveAsAllowed() {
- return true;
- }
-
- public static final String ID = "org.eclipse.linuxtools.systemtap.ui.editor.SimpleEditor"; //$NON-NLS-1$
+ public SimpleEditor() {
+ super();
+ // make sure we inherit all the text editing commands (delete line etc).
+ setKeyBindingScopes(new String[] { "org.eclipse.linuxtools.systemtap.ui.ide.context" }); //$NON-NLS-1$
+ internalInit();
+ }
+
+ /**
+ * @since 3.0
+ */
+ protected void internalInit() {
+ configureInsertMode(SMART_INSERT, false);
+ setDocumentProvider(new SimpleDocumentProvider());
+ }
+
+ /**
+ * Searches the IDocument for the specified string.
+ *
+ * @param search string to find, case-sensitive
+ * @return the integer line number of the string
+ */
+ public int find(String search) {
+ return findWithOptions(search, false);
+ }
+
+ /**
+ * Searches the IDocument for the specified regex.
+ * @param regex string regex to find
+ * @return the integer line number of the string
+ * @since 3.0
+ */
+ public int findRegex(String regex) {
+ return findWithOptions(regex, true);
+ }
+
+ private int findWithOptions(String search, boolean regExSearch) {
+ IDocument doc = getSourceViewer().getDocument();
+ FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter(doc);
+
+ int line = 0;
+
+ jumpToLocation(0, 0);
+ try {
+ IRegion reg = finder.find(0, search, true, !regExSearch, false, regExSearch);
+ int offset = reg.getOffset();
+ line = doc.getLineOfOffset(offset);
+ } catch (BadLocationException ble) {
+ // Pass
+ } catch (NullPointerException npe) {
+ line = -1;
+ }
+
+ return line;
+ }
+
+ /**
+ * Jumps to the location in the IDocument.
+ * @param line The line you wish to jump to.
+ * @param character The character you wish to jump to.
+ */
+ public void jumpToLocation(int line, int character) {
+ IDocument doc = getSourceViewer().getDocument();
+
+ try {
+ int offset = doc.getLineOffset(line-1) + character;
+ this.getSelectionProvider().setSelection(new TextSelection(doc, offset, 0));
+ } catch (BadLocationException boe) {
+ // Pass
+ }
+ }
+
+ /**
+ * Selects a line in the IDocument.
+ * @param line the line you wish to select
+ */
+ public void selectLine(int line) {
+ IDocument doc = getSourceViewer().getDocument();
+
+ try {
+ this.getSelectionProvider().setSelection(new TextSelection(doc, doc.getLineOffset(line-1), doc.getLineLength(line-1)-1));
+ } catch (BadLocationException boe) {
+ // Pass
+ }
+ }
+
+ /**
+ * Performs a SaveAs on the IDocument.
+ */
+ @Override
+ public void doSaveAs() {
+ File file = queryFile();
+ if (file == null) {
+ return;
+ }
+
+ IEditorInput inputFile = createEditorInput(file);
+
+ IDocument doc = getSourceViewer().getDocument();
+ String s = doc.get();
+
+ try (FileOutputStream fos = new FileOutputStream(file);
+ PrintStream ps = new PrintStream(fos)){
+ ps.print(s);
+ ps.close();
+ } catch (IOException fnfe) {
+ // Pass
+ }
+
+ setInput(inputFile);
+ setPartName(inputFile.getName());
+ }
+
+ /**
+ * Sets up an editor input based on the specified file.
+ * @param file the location of the file you wish to set.
+ * @return input object created.
+ */
+ private static IEditorInput createEditorInput(File file) {
+ IPath location= new Path(file.getAbsolutePath());
+ PathEditorInput input= new PathEditorInput(location);
+ return input;
+ }
+
+ /**
+ * Inserts text into the IDocument.
+ * @param text string to insert
+ */
+ public void insertText(String text) {
+ IDocument doc = getSourceViewer().getDocument();
+ String s = doc.get();
+ int offset = s.length();
+ s += text;
+ doc.set(s);
+ this.setHighlightRange(offset, 0, true);
+ }
+
+ /**
+ * Inserts text at the current location.
+ * @param text string to insert
+ */
+ public void insertTextAtCurrent(String text) {
+ ISelection selection = this.getSelectionProvider().getSelection();
+ IDocument doc = getSourceViewer().getDocument();
+
+ if (selection instanceof ITextSelection) {
+ ITextSelection s = (ITextSelection) selection;
+ StringBuffer sb = new StringBuffer(doc.get().substring(0, s.getOffset()));
+ sb.append(text.trim());
+ sb.append(doc.get().substring(s.getOffset() + s.getLength(), doc.get().length()));
+ doc.set(sb.toString());
+ this.setHighlightRange(s.getOffset() + text.trim().length(), 0, true);
+ }
+ }
+
+ private static File queryFile() {
+ FileDialog dialog= new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
+ dialog.setText(Localization.getString("NewFileAction.NewFile")); //$NON-NLS-1$
+ String path= dialog.open();
+ if (path != null && path.length() > 0) {
+ return new File(path);
+ }
+ return null;
+ }
+
+ /**
+ * Determines whether saving is allowed currently.
+ * @return boolean value indicating whether or not saving is allowed
+ */
+ @Override
+ public boolean isSaveAsAllowed() {
+ return true;
+ }
+
+ public static final String ID = "org.eclipse.linuxtools.systemtap.ui.editor.SimpleEditor"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/actions/file/NewFileAction.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/actions/file/NewFileAction.java
index ee0055e224..028f48d66b 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/actions/file/NewFileAction.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/actions/file/NewFileAction.java
@@ -17,14 +17,14 @@ import org.eclipse.swt.SWT;
public class NewFileAction extends OpenFileAction {
- @Override
- protected int dialogStyle() {
- return SWT.SAVE;
- }
+ @Override
+ protected int dialogStyle() {
+ return SWT.SAVE;
+ }
- @Override
- protected String dialogName() {
- return Localization.getString("NewFileAction.NewFile"); //$NON-NLS-1$
- }
+ @Override
+ protected String dialogName() {
+ return Localization.getString("NewFileAction.NewFile"); //$NON-NLS-1$
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/actions/file/OpenFileAction.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/actions/file/OpenFileAction.java
index f1b91706c9..fae9b80ca0 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/actions/file/OpenFileAction.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.editor/src/org/eclipse/linuxtools/systemtap/ui/editor/actions/file/OpenFileAction.java
@@ -38,125 +38,125 @@ import org.eclipse.ui.ide.IDE;
*/
public class OpenFileAction extends Action implements IWorkbenchWindowActionDelegate {
- private boolean successful;
- private IAction action;
-
- /**
- * @since 2.0
- */
- private IWorkbenchWindow window;
-
- public OpenFileAction() {
- super();
- setEnabled(true);
- successful = false;
- }
-
- @Override
- public void run(IAction act) {
- run();
- }
-
- /**
- * Queries the user for a Systemtap file to open, and opens that file's editor input.
- */
- @Override
- public void run() {
- if (window == null) {
- window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- }
- File file = queryFile();
- if (file != null) {
- runActions(file);
- }
- }
-
- /**
- * Opens the provided file's editor input, if it is a valid Systemtap file.
- * @since 3.0
- */
- public void run(File file) {
- if (window == null) {
- window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- }
- if (file != null && file.exists() && file.getName().endsWith(".stp")) { //$NON-NLS-1$
- runActions(file);
- }
- }
-
- private void runActions(File file) {
- successful = false;
- IFileStore fileStore = EFS.getLocalFileSystem().getStore(file.toURI());
- IWorkbenchPage page = window.getActivePage();
- try {
- IDE.openEditorOnFileStore(page, fileStore);
- successful = true;
- } catch (PartInitException e) {
- ErrorDialog.openError(window.getShell(),
- Localization.getString("OpenFileAction.Problem"), //$NON-NLS-1$
- Localization.getString("OpenFileAction.ProblemMessage"), //$NON-NLS-1$
- new Status(IStatus.ERROR, EditorPlugin.ID, e.getMessage(), e));
- }
- }
-
- /**
- * @return The style to use for the FileDialog when querying for a file.
- * @since 3.0
- */
- protected int dialogStyle() {
- return SWT.OPEN;
- }
-
- /**
- * @return The name to give to the FileDialog when querying for a file.
- * @since 3.0
- */
- protected String dialogName() {
- return Localization.getString("OpenFileAction.OpenFile"); //$NON-NLS-1$
- }
-
- /**
- * Request the name and location of the file to the user.
- * @return the File object associated to the selected file.
- */
- protected File queryFile() {
- FileDialog dialog = new FileDialog(window.getShell(), dialogStyle());
- dialog.setFilterExtensions(new String[]{"*.stp"}); //$NON-NLS-1$
- dialog.setText(dialogName());
- String path = dialog.open();
- if (path != null && path.length() > 0) {
- return new File(path);
- }
- return null;
- }
-
- public boolean isSuccessful() {
- return successful;
- }
-
- /**
- * @since 2.0
- */
- @Override
- public void init(IWorkbenchWindow window) {
- this.window = window;
- }
-
- /**
- * @since 2.0
- */
- @Override
- public void selectionChanged(IAction act, ISelection select) {
- action = act;
- action.setEnabled(true);
- }
-
- /**
- * @since 2.0
- */
- @Override
- public void dispose() {
- window = null;
- action = null;
- }
+ private boolean successful;
+ private IAction action;
+
+ /**
+ * @since 2.0
+ */
+ private IWorkbenchWindow window;
+
+ public OpenFileAction() {
+ super();
+ setEnabled(true);
+ successful = false;
+ }
+
+ @Override
+ public void run(IAction act) {
+ run();
+ }
+
+ /**
+ * Queries the user for a Systemtap file to open, and opens that file's editor input.
+ */
+ @Override
+ public void run() {
+ if (window == null) {
+ window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ }
+ File file = queryFile();
+ if (file != null) {
+ runActions(file);
+ }
+ }
+
+ /**
+ * Opens the provided file's editor input, if it is a valid Systemtap file.
+ * @since 3.0
+ */
+ public void run(File file) {
+ if (window == null) {
+ window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ }
+ if (file != null && file.exists() && file.getName().endsWith(".stp")) { //$NON-NLS-1$
+ runActions(file);
+ }
+ }
+
+ private void runActions(File file) {
+ successful = false;
+ IFileStore fileStore = EFS.getLocalFileSystem().getStore(file.toURI());
+ IWorkbenchPage page = window.getActivePage();
+ try {
+ IDE.openEditorOnFileStore(page, fileStore);
+ successful = true;
+ } catch (PartInitException e) {
+ ErrorDialog.openError(window.getShell(),
+ Localization.getString("OpenFileAction.Problem"), //$NON-NLS-1$
+ Localization.getString("OpenFileAction.ProblemMessage"), //$NON-NLS-1$
+ new Status(IStatus.ERROR, EditorPlugin.ID, e.getMessage(), e));
+ }
+ }
+
+ /**
+ * @return The style to use for the FileDialog when querying for a file.
+ * @since 3.0
+ */
+ protected int dialogStyle() {
+ return SWT.OPEN;
+ }
+
+ /**
+ * @return The name to give to the FileDialog when querying for a file.
+ * @since 3.0
+ */
+ protected String dialogName() {
+ return Localization.getString("OpenFileAction.OpenFile"); //$NON-NLS-1$
+ }
+
+ /**
+ * Request the name and location of the file to the user.
+ * @return the File object associated to the selected file.
+ */
+ protected File queryFile() {
+ FileDialog dialog = new FileDialog(window.getShell(), dialogStyle());
+ dialog.setFilterExtensions(new String[]{"*.stp"}); //$NON-NLS-1$
+ dialog.setText(dialogName());
+ String path = dialog.open();
+ if (path != null && path.length() > 0) {
+ return new File(path);
+ }
+ return null;
+ }
+
+ public boolean isSuccessful() {
+ return successful;
+ }
+
+ /**
+ * @since 2.0
+ */
+ @Override
+ public void init(IWorkbenchWindow window) {
+ this.window = window;
+ }
+
+ /**
+ * @since 2.0
+ */
+ @Override
+ public void selectionChanged(IAction act, ISelection select) {
+ action = act;
+ action.setEnabled(true);
+ }
+
+ /**
+ * @since 2.0
+ */
+ @Override
+ public void dispose() {
+ window = null;
+ action = null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/pom.xml b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/pom.xml
index 5ccf9c086b..345ef46e7f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/pom.xml
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/pom.xml
@@ -30,7 +30,7 @@
<artifactId>tycho-surefire-plugin</artifactId>
<version>${tycho-version}</version>
<configuration>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>false</useUIThread>
<product>org.eclipse.platform.ide</product>
</configuration>
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/AllTests.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/AllTests.java
index 53f897e29b..71334e4f15 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/AllTests.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/AllTests.java
@@ -24,8 +24,8 @@ import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ StapErrorParserTest.class, TreeSettingsTest.class,
- STPCompletionProcessorTest.class, STPToggleCommentTest.class,
- TestCreateSystemtapScript.class, ConditionalExpressionValidatorTest.class,
- DirectoryValidatorTest.class, STPFormattingTest.class, STPIndenterTest.class })
+ STPCompletionProcessorTest.class, STPToggleCommentTest.class,
+ TestCreateSystemtapScript.class, ConditionalExpressionValidatorTest.class,
+ DirectoryValidatorTest.class, STPFormattingTest.class, STPIndenterTest.class })
public class AllTests {
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/ConditionalExpressionValidatorTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/ConditionalExpressionValidatorTest.java
index c122774264..3d93782e24 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/ConditionalExpressionValidatorTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/ConditionalExpressionValidatorTest.java
@@ -19,21 +19,21 @@ import org.junit.Test;
public class ConditionalExpressionValidatorTest {
- @Test
- public void testIsValid() {
- ConditionalExpressionValidator validator = new ConditionalExpressionValidator();
-
- assertNotNull("Null not valid", validator.isValid(null));
- assertNotNull("Blank not valid", validator.isValid(""));
- assertNotNull("String not valid", validator.isValid("sdf"));
- assertNotNull("if not valid", validator.isValid("if"));
- assertNotNull("if( not valid", validator.isValid("if("));
- assertNotNull("if) not valid", validator.isValid("if)"));
- assertNotNull("if() not valid", validator.isValid("if()"));
- assertNull("if(a) valid", validator.isValid("if(a)"));
- assertNull("if (a) valid", validator.isValid("if ()"));
- assertNull("if(a=b) valid", validator.isValid("if(a=b)"));
- assertNotNull("if(a)b not valid", validator.isValid("if(a)d"));
- }
+ @Test
+ public void testIsValid() {
+ ConditionalExpressionValidator validator = new ConditionalExpressionValidator();
+
+ assertNotNull("Null not valid", validator.isValid(null));
+ assertNotNull("Blank not valid", validator.isValid(""));
+ assertNotNull("String not valid", validator.isValid("sdf"));
+ assertNotNull("if not valid", validator.isValid("if"));
+ assertNotNull("if( not valid", validator.isValid("if("));
+ assertNotNull("if) not valid", validator.isValid("if)"));
+ assertNotNull("if() not valid", validator.isValid("if()"));
+ assertNull("if(a) valid", validator.isValid("if(a)"));
+ assertNull("if (a) valid", validator.isValid("if ()"));
+ assertNull("if(a=b) valid", validator.isValid("if(a=b)"));
+ assertNotNull("if(a)b not valid", validator.isValid("if(a)d"));
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/DirectoryValidatorTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/DirectoryValidatorTest.java
index 8135155f64..cb7308b192 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/DirectoryValidatorTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/DirectoryValidatorTest.java
@@ -19,18 +19,18 @@ import org.junit.Test;
public class DirectoryValidatorTest {
- @Test
- public void testIsValid() {
- DirectoryValidator validator = new DirectoryValidator();
-
- assertNotNull("Null not valid", validator.isValid(null));
- assertNotNull("Blank not valid", validator.isValid(""));
- assertNotNull("String valid", validator.isValid("sdf"));
- assertNotNull("// not valid", validator.isValid("//"));
- assertNotNull("/root/ad not valid", validator.isValid("/root/ad"));
- assertNull("/ is valid", validator.isValid("/"));
- assertNull("/root/ is valid", validator.isValid("/root/"));
- assertNull("/blah/bld/ is valid", validator.isValid("/blah/bld/"));
- }
-
+ @Test
+ public void testIsValid() {
+ DirectoryValidator validator = new DirectoryValidator();
+
+ assertNotNull("Null not valid", validator.isValid(null));
+ assertNotNull("Blank not valid", validator.isValid(""));
+ assertNotNull("String valid", validator.isValid("sdf"));
+ assertNotNull("// not valid", validator.isValid("//"));
+ assertNotNull("/root/ad not valid", validator.isValid("/root/ad"));
+ assertNull("/ is valid", validator.isValid("/"));
+ assertNull("/root/ is valid", validator.isValid("/root/"));
+ assertNull("/blah/bld/ is valid", validator.isValid("/blah/bld/"));
+ }
+
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/AbstractAutoEditTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/AbstractAutoEditTest.java
index 9655d42b68..5fb8286c5b 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/AbstractAutoEditTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/AbstractAutoEditTest.java
@@ -31,209 +31,209 @@ import org.eclipse.linuxtools.systemtap.ui.tests.SystemtapTest;
*/
public class AbstractAutoEditTest extends SystemtapTest {
- private String name;
-
- protected AbstractAutoEditTest(String name) {
- super();
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- /**
- * Helper class to test the auto-edit strategies on a document.
- * Split out from CAutoIndentTest.
- */
- protected static class AutoEditTester {
- private IAutoEditStrategy tabsToSpacesConverter;
- private Map<String, IAutoEditStrategy> fStrategyMap = new HashMap<>();
- IDocument fDoc;
- private String fPartitioning;
- private int fCaretOffset;
-
- public AutoEditTester(IDocument doc, String partitioning) {
- super();
- fDoc = doc;
- fPartitioning = partitioning;
- }
-
- public void setTabsToSpacesConverter(IAutoEditStrategy converter) {
- tabsToSpacesConverter = converter;
- }
-
- public void setAutoEditStrategy(String contentType, IAutoEditStrategy aes) {
- fStrategyMap.put(contentType, aes);
- }
-
- public IAutoEditStrategy getAutoEditStrategy(String contentType) {
- return fStrategyMap.get(contentType);
- }
-
- /**
- * Empties the document, and returns the caret to the origin (0,0)
- * @return <code>this</code> for method chaining
- */
- public AutoEditTester reset() {
- try {
- goTo(0,0);
- fDoc.set("");
- } catch(BadLocationException ble) {
- fail(ble.getMessage());
- }
- return this;
- }
-
- public void type(String text) throws BadLocationException {
- for (int i = 0; i < text.length(); ++i) {
- type(text.charAt(i));
- }
- }
-
- public void type(char c) throws BadLocationException {
- TestDocumentCommand command = new TestDocumentCommand(fCaretOffset, 0, new String(new char[] { c }));
- customizeDocumentCommand(command);
- fCaretOffset = command.exec(fDoc);
- }
-
- private void customizeDocumentCommand(TestDocumentCommand command) throws BadLocationException {
- if (tabsToSpacesConverter != null) {
- tabsToSpacesConverter.customizeDocumentCommand(fDoc, command);
- }
- IAutoEditStrategy aes = getAutoEditStrategy(getContentType(command.offset));
- if (aes != null) {
- aes.customizeDocumentCommand(fDoc, command);
- }
- }
-
- public void type(int offset, String text) throws BadLocationException {
- fCaretOffset = offset;
- type(text);
- }
-
- public void type(int offset, char c) throws BadLocationException {
- fCaretOffset = offset;
- type(c);
- }
-
- public void paste(String text) throws BadLocationException {
- TestDocumentCommand command = new TestDocumentCommand(fCaretOffset, 0, text);
- customizeDocumentCommand(command);
- fCaretOffset = command.exec(fDoc);
- }
-
- public void paste(int offset, String text) throws BadLocationException {
- fCaretOffset = offset;
- paste(text);
- }
-
- public void backspace(int n) throws BadLocationException {
- for (int i = 0; i < n; ++i) {
- backspace();
- }
- }
-
- public void backspace() throws BadLocationException {
- TestDocumentCommand command = new TestDocumentCommand(fCaretOffset - 1, 1, ""); //$NON-NLS-1$
- customizeDocumentCommand(command);
- fCaretOffset = command.exec(fDoc);
- }
-
- public int getCaretOffset() {
- return fCaretOffset;
- }
-
- public int setCaretOffset(int offset) {
- fCaretOffset = offset;
- if (fCaretOffset < 0)
- fCaretOffset = 0;
- else if (fCaretOffset > fDoc.getLength())
- fCaretOffset = fDoc.getLength();
- return fCaretOffset;
- }
-
- /**
- * Moves caret right or left by the given number of characters.
- *
- * @param shift Move distance.
- * @return New caret offset.
- */
- public int moveCaret(int shift) {
- return setCaretOffset(fCaretOffset + shift);
- }
-
- public int goTo(int line) throws BadLocationException {
- fCaretOffset = fDoc.getLineOffset(line);
- return fCaretOffset;
- }
-
- public int goTo(int line, int column) throws BadLocationException {
- if (column < 0 || column > fDoc.getLineLength(line)) {
- throw new BadLocationException("No column " + column + " in line " + line); //$NON-NLS-1$ $NON-NLS-2$
- }
- fCaretOffset = fDoc.getLineOffset(line) + column;
- return fCaretOffset;
- }
-
- public int getCaretLine() throws BadLocationException {
- return fDoc.getLineOfOffset(fCaretOffset);
- }
-
- public int getCaretColumn() throws BadLocationException {
- IRegion region = fDoc.getLineInformationOfOffset(fCaretOffset);
- return fCaretOffset - region.getOffset();
- }
-
- public char getChar() throws BadLocationException {
- return getChar(0);
- }
-
- public char getChar(int i) throws BadLocationException {
- return fDoc.getChar(fCaretOffset+i);
- }
-
- public String getLine() throws BadLocationException {
- return getLine(0);
- }
-
- public String getLine(int i) throws BadLocationException {
- IRegion region = fDoc.getLineInformation(getCaretLine() + i);
- return fDoc.get(region.getOffset(), region.getLength());
- }
-
- public String getContentType(int offset) throws BadLocationException {
- return TextUtilities.getContentType(fDoc, fPartitioning, offset, false); //TRUE??
- }
- }
-
- /**
- * A DocumentCommand with public constructor and exec method.
- */
- protected static class TestDocumentCommand extends DocumentCommand {
-
- public TestDocumentCommand(int offset, int length, String text) {
- super();
- doit = true;
- this.text = text;
-
- this.offset = offset;
- this.length = length;
-
- owner = null;
- caretOffset = -1;
- }
-
- /**
- * @param doc
- * @return the new caret position.
- * @throws BadLocationException
- */
- public int exec(IDocument doc) throws BadLocationException {
- doc.replace(offset, length, text);
- return caretOffset != -1 ?
- caretOffset :
- offset + (text == null ? 0 : text.length());
- }
- }
+ private String name;
+
+ protected AbstractAutoEditTest(String name) {
+ super();
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Helper class to test the auto-edit strategies on a document.
+ * Split out from CAutoIndentTest.
+ */
+ protected static class AutoEditTester {
+ private IAutoEditStrategy tabsToSpacesConverter;
+ private Map<String, IAutoEditStrategy> fStrategyMap = new HashMap<>();
+ IDocument fDoc;
+ private String fPartitioning;
+ private int fCaretOffset;
+
+ public AutoEditTester(IDocument doc, String partitioning) {
+ super();
+ fDoc = doc;
+ fPartitioning = partitioning;
+ }
+
+ public void setTabsToSpacesConverter(IAutoEditStrategy converter) {
+ tabsToSpacesConverter = converter;
+ }
+
+ public void setAutoEditStrategy(String contentType, IAutoEditStrategy aes) {
+ fStrategyMap.put(contentType, aes);
+ }
+
+ public IAutoEditStrategy getAutoEditStrategy(String contentType) {
+ return fStrategyMap.get(contentType);
+ }
+
+ /**
+ * Empties the document, and returns the caret to the origin (0,0)
+ * @return <code>this</code> for method chaining
+ */
+ public AutoEditTester reset() {
+ try {
+ goTo(0,0);
+ fDoc.set("");
+ } catch(BadLocationException ble) {
+ fail(ble.getMessage());
+ }
+ return this;
+ }
+
+ public void type(String text) throws BadLocationException {
+ for (int i = 0; i < text.length(); ++i) {
+ type(text.charAt(i));
+ }
+ }
+
+ public void type(char c) throws BadLocationException {
+ TestDocumentCommand command = new TestDocumentCommand(fCaretOffset, 0, new String(new char[] { c }));
+ customizeDocumentCommand(command);
+ fCaretOffset = command.exec(fDoc);
+ }
+
+ private void customizeDocumentCommand(TestDocumentCommand command) throws BadLocationException {
+ if (tabsToSpacesConverter != null) {
+ tabsToSpacesConverter.customizeDocumentCommand(fDoc, command);
+ }
+ IAutoEditStrategy aes = getAutoEditStrategy(getContentType(command.offset));
+ if (aes != null) {
+ aes.customizeDocumentCommand(fDoc, command);
+ }
+ }
+
+ public void type(int offset, String text) throws BadLocationException {
+ fCaretOffset = offset;
+ type(text);
+ }
+
+ public void type(int offset, char c) throws BadLocationException {
+ fCaretOffset = offset;
+ type(c);
+ }
+
+ public void paste(String text) throws BadLocationException {
+ TestDocumentCommand command = new TestDocumentCommand(fCaretOffset, 0, text);
+ customizeDocumentCommand(command);
+ fCaretOffset = command.exec(fDoc);
+ }
+
+ public void paste(int offset, String text) throws BadLocationException {
+ fCaretOffset = offset;
+ paste(text);
+ }
+
+ public void backspace(int n) throws BadLocationException {
+ for (int i = 0; i < n; ++i) {
+ backspace();
+ }
+ }
+
+ public void backspace() throws BadLocationException {
+ TestDocumentCommand command = new TestDocumentCommand(fCaretOffset - 1, 1, ""); //$NON-NLS-1$
+ customizeDocumentCommand(command);
+ fCaretOffset = command.exec(fDoc);
+ }
+
+ public int getCaretOffset() {
+ return fCaretOffset;
+ }
+
+ public int setCaretOffset(int offset) {
+ fCaretOffset = offset;
+ if (fCaretOffset < 0)
+ fCaretOffset = 0;
+ else if (fCaretOffset > fDoc.getLength())
+ fCaretOffset = fDoc.getLength();
+ return fCaretOffset;
+ }
+
+ /**
+ * Moves caret right or left by the given number of characters.
+ *
+ * @param shift Move distance.
+ * @return New caret offset.
+ */
+ public int moveCaret(int shift) {
+ return setCaretOffset(fCaretOffset + shift);
+ }
+
+ public int goTo(int line) throws BadLocationException {
+ fCaretOffset = fDoc.getLineOffset(line);
+ return fCaretOffset;
+ }
+
+ public int goTo(int line, int column) throws BadLocationException {
+ if (column < 0 || column > fDoc.getLineLength(line)) {
+ throw new BadLocationException("No column " + column + " in line " + line); //$NON-NLS-1$ $NON-NLS-2$
+ }
+ fCaretOffset = fDoc.getLineOffset(line) + column;
+ return fCaretOffset;
+ }
+
+ public int getCaretLine() throws BadLocationException {
+ return fDoc.getLineOfOffset(fCaretOffset);
+ }
+
+ public int getCaretColumn() throws BadLocationException {
+ IRegion region = fDoc.getLineInformationOfOffset(fCaretOffset);
+ return fCaretOffset - region.getOffset();
+ }
+
+ public char getChar() throws BadLocationException {
+ return getChar(0);
+ }
+
+ public char getChar(int i) throws BadLocationException {
+ return fDoc.getChar(fCaretOffset+i);
+ }
+
+ public String getLine() throws BadLocationException {
+ return getLine(0);
+ }
+
+ public String getLine(int i) throws BadLocationException {
+ IRegion region = fDoc.getLineInformation(getCaretLine() + i);
+ return fDoc.get(region.getOffset(), region.getLength());
+ }
+
+ public String getContentType(int offset) throws BadLocationException {
+ return TextUtilities.getContentType(fDoc, fPartitioning, offset, false); //TRUE??
+ }
+ }
+
+ /**
+ * A DocumentCommand with public constructor and exec method.
+ */
+ protected static class TestDocumentCommand extends DocumentCommand {
+
+ public TestDocumentCommand(int offset, int length, String text) {
+ super();
+ doit = true;
+ this.text = text;
+
+ this.offset = offset;
+ this.length = length;
+
+ owner = null;
+ caretOffset = -1;
+ }
+
+ /**
+ * @param doc
+ * @return the new caret position.
+ * @throws BadLocationException
+ */
+ public int exec(IDocument doc) throws BadLocationException {
+ doc.replace(offset, length, text);
+ return caretOffset != -1 ?
+ caretOffset :
+ offset + (text == null ? 0 : text.length());
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPCompletionProcessorTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPCompletionProcessorTest.java
index db1a8fb695..234b4634b4 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPCompletionProcessorTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPCompletionProcessorTest.java
@@ -28,234 +28,234 @@ import org.junit.Test;
public class STPCompletionProcessorTest extends SystemtapTest {
- private static String TEST_STP_SCRIPT = ""+
- "\n"+
- "\n//marker1"+
- "probe syscall.write{\n"+
- " // Some comment inside a probe\n"+
- " printf(\"%s fd %d\taddr%d\tcount%dargstr%s\n\", name, fd, buf_uaddr, count, argstr)\n"+
- "}\n"+
- "\n";
-
- private static class MockSTPDocumentProvider extends STPDocumentProvider {
- private IDocument document;
-
- MockSTPDocumentProvider(IDocument document){
- this.document = document;
- this.setupDocument(document);
- }
-
- protected IDocument createDocument(Object element) {
- return document;
- }
- }
-
- private static class MockSTPEditor extends STPEditor {
- public MockSTPEditor(IDocument document) {
- super();
- setDocumentProvider(new MockSTPDocumentProvider(document));
- }
- }
-
- @Test
- public void testCompletionRequest() {
- Document testDocument = new Document("");
- STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
- ICompletionProposal[] proposals = completionProcessor
- .computeCompletionProposals(testDocument, 0);
- assertNotNull(proposals);
- }
-
- @Test
- public void testCompletionRequestAtEOF() {
- Document testDocument = new Document(TEST_STP_SCRIPT);
- STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
- ICompletionProposal[] proposals = completionProcessor
- .computeCompletionProposals(testDocument,
- TEST_STP_SCRIPT.length());
- assertNotNull(proposals);
- }
-
- @Test
- public void testGlobalCompletion() {
- MockSTPDocumentProvider provider = new MockSTPDocumentProvider(new Document(TEST_STP_SCRIPT));
- IDocument testDocument = provider.createDocument(null);
- int offset = TEST_STP_SCRIPT.indexOf("//marker1");
-
- STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
- completionProcessor.waitForInitialization();
- ICompletionProposal[] proposals = completionProcessor
- .computeCompletionProposals(testDocument,
- offset);
-
- assertTrue(proposalsContain(proposals, "probe "));
- assertTrue(proposalsContain(proposals, "global "));
- assertTrue(proposalsContain(proposals, "function "));
- }
-
- @Test
- public void testGlobalPartialCompletion() throws BadLocationException {
- String prefix = "prob";
- ICompletionProposal[] proposals = getCompletionsForPrefix(prefix);
- assertTrue(proposalsContain(proposals, "probe "));
- assertTrue(!proposalsContain(proposals, "global "));
- assertTrue(!proposalsContain(proposals, "function "));
- }
-
- //TODO Create dummy probe/function data to test with instead of relying on stap.
- @Test
- public void testProbeCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
-
- String prefix = "probe ";
- ICompletionProposal[] proposals = getCompletionsForPrefix(prefix);
- assertTrue(proposalsContain(proposals, "syscall"));
- assertTrue(!proposalsContain(proposals, "syscall.write"));
- }
-
- @Test
- public void testMultiProbeCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
-
- String prefix = "probe begin,e";
- ICompletionProposal[] proposals = getCompletionsForPrefix(prefix);
- assertTrue(proposalsContain(proposals, "end"));
- assertTrue(proposalsContain(proposals, "error"));
-
- prefix = "probe myBegin = b";
- proposals = getCompletionsForPrefix(prefix);
- assertTrue(proposalsContain(proposals, "begin"));
- }
-
- @Test
- public void testGlobalInvalidCompletion() throws BadLocationException {
- ICompletionProposal[] proposals = getCompletionsForPrefix("probe fake.fake");
- assertEquals(proposals.length, 0);
- }
-
- @Test
- public void testStaticProbeCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
-
- ICompletionProposal[] proposals = getCompletionsForPrefix("probe kernel.");
- assertTrue(proposalsContain(proposals, "kernel.function(string)"));
- assertTrue(proposalsContain(proposals, "kernel.mark(string)"));
- }
-
- @Test
- public void testEndProbeCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
-
- Document testDocument = new Document(TEST_STP_SCRIPT);
- @SuppressWarnings("unused")
- MockSTPEditor editor = new MockSTPEditor(testDocument);
-
- int offset = TEST_STP_SCRIPT.indexOf("//marker1");
- String prefix = "probe end{}";
- testDocument.replace(offset, 0, prefix);
- offset += prefix.length() - 1;
-
- STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
- completionProcessor.waitForInitialization();
- ICompletionProposal[] proposals = completionProcessor
- .computeCompletionProposals(testDocument,
- offset);
-
- assertTrue(proposalsContain(proposals, "addr"));
- assertTrue(proposalsContain(proposals, "backtrace"));
- assertTrue(proposalsContain(proposals, "cmdline_args"));
- }
-
- @Test
- public void testProbeVariableCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
-
- Document testDocument = new Document(TEST_STP_SCRIPT);
- @SuppressWarnings("unused")
- MockSTPEditor editor = new MockSTPEditor(testDocument);
-
- int offset = TEST_STP_SCRIPT.indexOf("//marker1");
- String prefix = "probe syscall.write{}";
- testDocument.replace(offset, 0, prefix);
- offset += prefix.length() - 1;
-
- STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
- ICompletionProposal[] proposals = completionProcessor
- .computeCompletionProposals(testDocument,
- offset);
-
- assertTrue(proposalsContain(proposals, "fd:long"));
- assertTrue(proposalsContain(proposals, "name:string"));
- assertTrue(proposalsContain(proposals, "buf_uaddr:long"));
- }
-
- @Test
- public void testStaticProbeNormalizationCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
-
- ICompletionProposal[] proposals = getCompletionsForPrefix("probe kernel.function(\"PATTERNASDF\").");
- assertTrue(proposalsContain(proposals, "kernel.function(string).return"));
+ private static String TEST_STP_SCRIPT = ""+
+ "\n"+
+ "\n//marker1"+
+ "probe syscall.write{\n"+
+ " // Some comment inside a probe\n"+
+ " printf(\"%s fd %d\taddr%d\tcount%dargstr%s\n\", name, fd, buf_uaddr, count, argstr)\n"+
+ "}\n"+
+ "\n";
+
+ private static class MockSTPDocumentProvider extends STPDocumentProvider {
+ private IDocument document;
+
+ MockSTPDocumentProvider(IDocument document){
+ this.document = document;
+ this.setupDocument(document);
+ }
+
+ protected IDocument createDocument(Object element) {
+ return document;
+ }
+ }
+
+ private static class MockSTPEditor extends STPEditor {
+ public MockSTPEditor(IDocument document) {
+ super();
+ setDocumentProvider(new MockSTPDocumentProvider(document));
+ }
+ }
+
+ @Test
+ public void testCompletionRequest() {
+ Document testDocument = new Document("");
+ STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
+ ICompletionProposal[] proposals = completionProcessor
+ .computeCompletionProposals(testDocument, 0);
+ assertNotNull(proposals);
+ }
+
+ @Test
+ public void testCompletionRequestAtEOF() {
+ Document testDocument = new Document(TEST_STP_SCRIPT);
+ STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
+ ICompletionProposal[] proposals = completionProcessor
+ .computeCompletionProposals(testDocument,
+ TEST_STP_SCRIPT.length());
+ assertNotNull(proposals);
+ }
+
+ @Test
+ public void testGlobalCompletion() {
+ MockSTPDocumentProvider provider = new MockSTPDocumentProvider(new Document(TEST_STP_SCRIPT));
+ IDocument testDocument = provider.createDocument(null);
+ int offset = TEST_STP_SCRIPT.indexOf("//marker1");
+
+ STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
+ completionProcessor.waitForInitialization();
+ ICompletionProposal[] proposals = completionProcessor
+ .computeCompletionProposals(testDocument,
+ offset);
+
+ assertTrue(proposalsContain(proposals, "probe "));
+ assertTrue(proposalsContain(proposals, "global "));
+ assertTrue(proposalsContain(proposals, "function "));
+ }
+
+ @Test
+ public void testGlobalPartialCompletion() throws BadLocationException {
+ String prefix = "prob";
+ ICompletionProposal[] proposals = getCompletionsForPrefix(prefix);
+ assertTrue(proposalsContain(proposals, "probe "));
+ assertTrue(!proposalsContain(proposals, "global "));
+ assertTrue(!proposalsContain(proposals, "function "));
+ }
+
+ //TODO Create dummy probe/function data to test with instead of relying on stap.
+ @Test
+ public void testProbeCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+
+ String prefix = "probe ";
+ ICompletionProposal[] proposals = getCompletionsForPrefix(prefix);
+ assertTrue(proposalsContain(proposals, "syscall"));
+ assertTrue(!proposalsContain(proposals, "syscall.write"));
+ }
+
+ @Test
+ public void testMultiProbeCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+
+ String prefix = "probe begin,e";
+ ICompletionProposal[] proposals = getCompletionsForPrefix(prefix);
+ assertTrue(proposalsContain(proposals, "end"));
+ assertTrue(proposalsContain(proposals, "error"));
+
+ prefix = "probe myBegin = b";
+ proposals = getCompletionsForPrefix(prefix);
+ assertTrue(proposalsContain(proposals, "begin"));
+ }
+
+ @Test
+ public void testGlobalInvalidCompletion() throws BadLocationException {
+ ICompletionProposal[] proposals = getCompletionsForPrefix("probe fake.fake");
+ assertEquals(proposals.length, 0);
+ }
+
+ @Test
+ public void testStaticProbeCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+
+ ICompletionProposal[] proposals = getCompletionsForPrefix("probe kernel.");
+ assertTrue(proposalsContain(proposals, "kernel.function(string)"));
+ assertTrue(proposalsContain(proposals, "kernel.mark(string)"));
+ }
+
+ @Test
+ public void testEndProbeCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+
+ Document testDocument = new Document(TEST_STP_SCRIPT);
+ @SuppressWarnings("unused")
+ MockSTPEditor editor = new MockSTPEditor(testDocument);
+
+ int offset = TEST_STP_SCRIPT.indexOf("//marker1");
+ String prefix = "probe end{}";
+ testDocument.replace(offset, 0, prefix);
+ offset += prefix.length() - 1;
+
+ STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
+ completionProcessor.waitForInitialization();
+ ICompletionProposal[] proposals = completionProcessor
+ .computeCompletionProposals(testDocument,
+ offset);
+
+ assertTrue(proposalsContain(proposals, "addr"));
+ assertTrue(proposalsContain(proposals, "backtrace"));
+ assertTrue(proposalsContain(proposals, "cmdline_args"));
+ }
+
+ @Test
+ public void testProbeVariableCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+
+ Document testDocument = new Document(TEST_STP_SCRIPT);
+ @SuppressWarnings("unused")
+ MockSTPEditor editor = new MockSTPEditor(testDocument);
+
+ int offset = TEST_STP_SCRIPT.indexOf("//marker1");
+ String prefix = "probe syscall.write{}";
+ testDocument.replace(offset, 0, prefix);
+ offset += prefix.length() - 1;
+
+ STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
+ ICompletionProposal[] proposals = completionProcessor
+ .computeCompletionProposals(testDocument,
+ offset);
+
+ assertTrue(proposalsContain(proposals, "fd:long"));
+ assertTrue(proposalsContain(proposals, "name:string"));
+ assertTrue(proposalsContain(proposals, "buf_uaddr:long"));
+ }
+
+ @Test
+ public void testStaticProbeNormalizationCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+
+ ICompletionProposal[] proposals = getCompletionsForPrefix("probe kernel.function(\"PATTERNASDF\").");
+ assertTrue(proposalsContain(proposals, "kernel.function(string).return"));
proposals = getCompletionsForPrefix("probe probe process(\"PAT/H/\").");
- assertTrue(proposalsContain(proposals, "process(string).begin"));
- assertTrue(proposalsContain(proposals, "process(string).end"));
+ assertTrue(proposalsContain(proposals, "process(string).begin"));
+ assertTrue(proposalsContain(proposals, "process(string).end"));
proposals = getCompletionsForPrefix("probe process(123).");
- assertTrue(proposalsContain(proposals, "process(number).begin"));
- assertTrue(proposalsContain(proposals, "process(number).end"));
+ assertTrue(proposalsContain(proposals, "process(number).begin"));
+ assertTrue(proposalsContain(proposals, "process(number).end"));
proposals = getCompletionsForPrefix("probe module(\"MPATTERasdfN\").");
- assertTrue(proposalsContain(proposals, "module(string).function(string)"));
- assertTrue(proposalsContain(proposals, "module(string).statement(string)"));
- }
-
- private ICompletionProposal[] getCompletionsForPrefix(String prefix) throws BadLocationException {
- MockSTPDocumentProvider provider = new MockSTPDocumentProvider(new Document(TEST_STP_SCRIPT));
- IDocument testDocument = provider.createDocument(null);
- int offset = TEST_STP_SCRIPT.indexOf("//marker1");
- testDocument.replace(offset, 0, prefix);
- offset += prefix.length();
-
- STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
- completionProcessor.waitForInitialization();
-
- ICompletionProposal[] proposals = completionProcessor
- .computeCompletionProposals(testDocument,
- offset);
- return proposals;
- }
-
- @Test
- public void testFunctionCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
-
- Document testDocument = new Document(TEST_STP_SCRIPT);
- @SuppressWarnings("unused")
- MockSTPEditor editor = new MockSTPEditor(testDocument);
-
- int offset = TEST_STP_SCRIPT.indexOf("//marker1");
- String prefix = "probe syscall.write{addr}";
- testDocument.replace(offset, 0, prefix);
- offset += prefix.length() - 1;
-
- STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
- completionProcessor.waitForInitialization();
-
- ICompletionProposal[] proposals = completionProcessor
- .computeCompletionProposals(testDocument,
- offset);
-
- assertTrue(proposalsContain(proposals, "addr"));
- assertTrue(proposalsContain(proposals, "addr_from_rqst"));
- assertTrue(proposalsContain(proposals, "addr_from_rqst_str"));
- }
-
- private boolean proposalsContain(ICompletionProposal[] proposals, String proposal){
- for (ICompletionProposal p : proposals) {
- if (p.getDisplayString().contains(proposal)) {
- return true;
- }
- }
- return false;
- }
+ assertTrue(proposalsContain(proposals, "module(string).function(string)"));
+ assertTrue(proposalsContain(proposals, "module(string).statement(string)"));
+ }
+
+ private ICompletionProposal[] getCompletionsForPrefix(String prefix) throws BadLocationException {
+ MockSTPDocumentProvider provider = new MockSTPDocumentProvider(new Document(TEST_STP_SCRIPT));
+ IDocument testDocument = provider.createDocument(null);
+ int offset = TEST_STP_SCRIPT.indexOf("//marker1");
+ testDocument.replace(offset, 0, prefix);
+ offset += prefix.length();
+
+ STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
+ completionProcessor.waitForInitialization();
+
+ ICompletionProposal[] proposals = completionProcessor
+ .computeCompletionProposals(testDocument,
+ offset);
+ return proposals;
+ }
+
+ @Test
+ public void testFunctionCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+
+ Document testDocument = new Document(TEST_STP_SCRIPT);
+ @SuppressWarnings("unused")
+ MockSTPEditor editor = new MockSTPEditor(testDocument);
+
+ int offset = TEST_STP_SCRIPT.indexOf("//marker1");
+ String prefix = "probe syscall.write{addr}";
+ testDocument.replace(offset, 0, prefix);
+ offset += prefix.length() - 1;
+
+ STPCompletionProcessor completionProcessor = new STPCompletionProcessor();
+ completionProcessor.waitForInitialization();
+
+ ICompletionProposal[] proposals = completionProcessor
+ .computeCompletionProposals(testDocument,
+ offset);
+
+ assertTrue(proposalsContain(proposals, "addr"));
+ assertTrue(proposalsContain(proposals, "addr_from_rqst"));
+ assertTrue(proposalsContain(proposals, "addr_from_rqst_str"));
+ }
+
+ private boolean proposalsContain(ICompletionProposal[] proposals, String proposal){
+ for (ICompletionProposal p : proposals) {
+ if (p.getDisplayString().contains(proposal)) {
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPFormattingTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPFormattingTest.java
index c0a6ea73f4..4f8939c11f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPFormattingTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPFormattingTest.java
@@ -29,413 +29,413 @@ import org.junit.Test;
public class STPFormattingTest extends SystemtapTest{
- /**
- * A DocumentCommand with public constructor and exec method.
- */
- protected static class TestDocumentCommand extends DocumentCommand {
-
- public TestDocumentCommand(int offset, int length, String text) {
- super();
- doit = true;
- this.text = text;
-
- this.offset = offset;
- this.length = length;
-
- owner = null;
- caretOffset = -1;
- }
-
- /**
- * @param doc
- * @return the new caret position.
- * @throws BadLocationException
- */
- public int exec(IDocument doc) throws BadLocationException {
- doc.replace(offset, length, text);
- return caretOffset != -1 ?
- caretOffset :
- offset + (text == null ? 0 : text.length());
- }
- }
-
- /**
- * Sets up the document partitioner for the given document for the given partitioning.
- *
- * @param document
- * @param partitioning
- * @param owner may be null
- */
- private void setupDocumentPartitioner(IDocument document, String partitioning) {
- IDocumentPartitioner partitioner = new STPPartitioner(new STPPartitionScanner(), STPPartitionScanner.STP_PARTITION_TYPES);
- if (document instanceof IDocumentExtension3) {
- IDocumentExtension3 extension3= (IDocumentExtension3) document;
- extension3.setDocumentPartitioner(partitioning, partitioner);
- } else {
- document.setDocumentPartitioner(partitioner);
- }
- partitioner.connect(document);
- }
-
- private AutoEditTester createAutoEditTester() {
- IDocument doc = new Document();
- setupDocumentPartitioner(doc, STPPartitionScanner.STP_PARTITIONING);
- AutoEditTester tester = new AutoEditTester(doc, STPPartitionScanner.STP_PARTITIONING);
-
- STPAutoEditStrategy s = new STPAutoEditStrategy(STPPartitionScanner.STP_PARTITIONING, null);
- tester.setAutoEditStrategy(IDocument.DEFAULT_CONTENT_TYPE, s);
- tester.setAutoEditStrategy(STPPartitionScanner.STP_COMMENT, s);
- tester.setAutoEditStrategy(STPPartitionScanner.STP_CONDITIONAL, s);
- tester.setAutoEditStrategy(STPPartitionScanner.STP_STRING, s);
- return tester;
- }
-
- @Test
- public void testEndProbeCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
- AutoEditTester tester = createAutoEditTester();
-
- tester.type("probe end {\n");
-
- // We are located on 2nd line
- assertEquals(1, tester.getCaretLine());
- // Nested location is indented
- assertEquals(1, tester.getCaretColumn());
- // The brace was closed automatically. Note, getLine() gets
- // line from current position which is on line 1 of doc.
- assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
- }
-
- @Test
- public void testSquareBracketCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
- AutoEditTester tester = createAutoEditTester();
-
- tester.type("probe end {\n");
-
- // We are located on 2nd line
- assertEquals(1, tester.getCaretLine());
-
- tester.type("a[");
-
- // Verify automatic completion of square brackets
- assertEquals(1, tester.getCaretLine());
- assertEquals(3, tester.getCaretColumn());
- assertEquals("\ta[]", tester.getLine());
-
- tester.type("2]");
-
- // Verify we can overwrite the end square-bracket
- assertEquals(1, tester.getCaretLine());
- assertEquals(5, tester.getCaretColumn());
- assertEquals("\ta[2]", tester.getLine());
-
- // Verify we don't add square brackets inside a string
- tester.type("=\"b[");
- assertEquals(1, tester.getCaretLine());
- assertEquals(9, tester.getCaretColumn());
- assertEquals("\ta[2]=\"b[\"", tester.getLine());
-
- // Verify we don't add square brackets inside a comment
- tester.goTo(tester.getCaretLine(), tester.getCaretColumn() + 1);
- tester.type(" /* a[2");
- assertEquals(1, tester.getCaretLine());
- assertEquals(17, tester.getCaretColumn());
- assertEquals("\ta[2]=\"b[\" /* a[2", tester.getLine());
-
- // Verify we don't add square brackets inside a line comment
- tester.type(" */ // a[2");
- assertEquals(1, tester.getCaretLine());
- assertEquals(27, tester.getCaretColumn());
- assertEquals("\ta[2]=\"b[\" /* a[2 */ // a[2", tester.getLine());
-
- // Verify we don't add square brackets inside a line comment
- tester.type("\n# a[2");
-
- assertEquals(2, tester.getCaretLine());
- assertEquals(5, tester.getCaretColumn());
- assertEquals("# a[2", tester.getLine());
-
- // Verify we don't add square brackets inside a char specifier
- tester.type("\na[3]='[");
-
- System.out.println(tester.fDoc.get());
- assertEquals(3, tester.getCaretLine());
- assertEquals(8, tester.getCaretColumn());
- assertEquals("\ta[3]='[", tester.getLine());
-
- }
-
- @Test
- public void testBracketCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
- AutoEditTester tester = createAutoEditTester();
-
- tester.type("probe end {\n");
-
- // We are located on 2nd line
- assertEquals(1, tester.getCaretLine());
+ /**
+ * A DocumentCommand with public constructor and exec method.
+ */
+ protected static class TestDocumentCommand extends DocumentCommand {
+
+ public TestDocumentCommand(int offset, int length, String text) {
+ super();
+ doit = true;
+ this.text = text;
+
+ this.offset = offset;
+ this.length = length;
+
+ owner = null;
+ caretOffset = -1;
+ }
+
+ /**
+ * @param doc
+ * @return the new caret position.
+ * @throws BadLocationException
+ */
+ public int exec(IDocument doc) throws BadLocationException {
+ doc.replace(offset, length, text);
+ return caretOffset != -1 ?
+ caretOffset :
+ offset + (text == null ? 0 : text.length());
+ }
+ }
+
+ /**
+ * Sets up the document partitioner for the given document for the given partitioning.
+ *
+ * @param document
+ * @param partitioning
+ * @param owner may be null
+ */
+ private void setupDocumentPartitioner(IDocument document, String partitioning) {
+ IDocumentPartitioner partitioner = new STPPartitioner(new STPPartitionScanner(), STPPartitionScanner.STP_PARTITION_TYPES);
+ if (document instanceof IDocumentExtension3) {
+ IDocumentExtension3 extension3= (IDocumentExtension3) document;
+ extension3.setDocumentPartitioner(partitioning, partitioner);
+ } else {
+ document.setDocumentPartitioner(partitioner);
+ }
+ partitioner.connect(document);
+ }
+
+ private AutoEditTester createAutoEditTester() {
+ IDocument doc = new Document();
+ setupDocumentPartitioner(doc, STPPartitionScanner.STP_PARTITIONING);
+ AutoEditTester tester = new AutoEditTester(doc, STPPartitionScanner.STP_PARTITIONING);
+
+ STPAutoEditStrategy s = new STPAutoEditStrategy(STPPartitionScanner.STP_PARTITIONING, null);
+ tester.setAutoEditStrategy(IDocument.DEFAULT_CONTENT_TYPE, s);
+ tester.setAutoEditStrategy(STPPartitionScanner.STP_COMMENT, s);
+ tester.setAutoEditStrategy(STPPartitionScanner.STP_CONDITIONAL, s);
+ tester.setAutoEditStrategy(STPPartitionScanner.STP_STRING, s);
+ return tester;
+ }
+
+ @Test
+ public void testEndProbeCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+ AutoEditTester tester = createAutoEditTester();
+
+ tester.type("probe end {\n");
+
+ // We are located on 2nd line
+ assertEquals(1, tester.getCaretLine());
+ // Nested location is indented
+ assertEquals(1, tester.getCaretColumn());
+ // The brace was closed automatically. Note, getLine() gets
+ // line from current position which is on line 1 of doc.
+ assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testSquareBracketCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+ AutoEditTester tester = createAutoEditTester();
+
+ tester.type("probe end {\n");
+
+ // We are located on 2nd line
+ assertEquals(1, tester.getCaretLine());
+
+ tester.type("a[");
+
+ // Verify automatic completion of square brackets
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(3, tester.getCaretColumn());
+ assertEquals("\ta[]", tester.getLine());
+
+ tester.type("2]");
+
+ // Verify we can overwrite the end square-bracket
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(5, tester.getCaretColumn());
+ assertEquals("\ta[2]", tester.getLine());
+
+ // Verify we don't add square brackets inside a string
+ tester.type("=\"b[");
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(9, tester.getCaretColumn());
+ assertEquals("\ta[2]=\"b[\"", tester.getLine());
+
+ // Verify we don't add square brackets inside a comment
+ tester.goTo(tester.getCaretLine(), tester.getCaretColumn() + 1);
+ tester.type(" /* a[2");
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(17, tester.getCaretColumn());
+ assertEquals("\ta[2]=\"b[\" /* a[2", tester.getLine());
+
+ // Verify we don't add square brackets inside a line comment
+ tester.type(" */ // a[2");
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(27, tester.getCaretColumn());
+ assertEquals("\ta[2]=\"b[\" /* a[2 */ // a[2", tester.getLine());
+
+ // Verify we don't add square brackets inside a line comment
+ tester.type("\n# a[2");
+
+ assertEquals(2, tester.getCaretLine());
+ assertEquals(5, tester.getCaretColumn());
+ assertEquals("# a[2", tester.getLine());
+
+ // Verify we don't add square brackets inside a char specifier
+ tester.type("\na[3]='[");
+
+ System.out.println(tester.fDoc.get());
+ assertEquals(3, tester.getCaretLine());
+ assertEquals(8, tester.getCaretColumn());
+ assertEquals("\ta[3]='[", tester.getLine());
+
+ }
+
+ @Test
+ public void testBracketCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+ AutoEditTester tester = createAutoEditTester();
+
+ tester.type("probe end {\n");
+
+ // We are located on 2nd line
+ assertEquals(1, tester.getCaretLine());
- // Verify we don't complete brackets inside a comment
- tester.type("// if (a == b) {\n");
-
- assertEquals(2, tester.getCaretLine());
- assertEquals(1, tester.getCaretColumn());
- assertEquals("\t", tester.getLine());
+ // Verify we don't complete brackets inside a comment
+ tester.type("// if (a == b) {\n");
+
+ assertEquals(2, tester.getCaretLine());
+ assertEquals(1, tester.getCaretColumn());
+ assertEquals("\t", tester.getLine());
- // verify we don't complete brackets inside a comment
- tester.type("# if (a == b) {\n");
+ // verify we don't complete brackets inside a comment
+ tester.type("# if (a == b) {\n");
- // Verify we can overwrite the end square-bracket
- assertEquals(3, tester.getCaretLine());
- assertEquals(1, tester.getCaretColumn());
- assertEquals("\t", tester.getLine());
+ // Verify we can overwrite the end square-bracket
+ assertEquals(3, tester.getCaretLine());
+ assertEquals(1, tester.getCaretColumn());
+ assertEquals("\t", tester.getLine());
- }
+ }
- @Test
- public void testQuoteCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
- AutoEditTester tester = createAutoEditTester();
+ @Test
+ public void testQuoteCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+ AutoEditTester tester = createAutoEditTester();
- tester.type("probe end {\n");
+ tester.type("probe end {\n");
- // We are located on 2nd line
- assertEquals(1, tester.getCaretLine());
+ // We are located on 2nd line
+ assertEquals(1, tester.getCaretLine());
- tester.type("a[2]=\"");
+ tester.type("a[2]=\"");
- // Verify automatic completion of quotes
- assertEquals(1, tester.getCaretLine());
- assertEquals(7, tester.getCaretColumn());
- assertEquals("\ta[2]=\"\"", tester.getLine());
+ // Verify automatic completion of quotes
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(7, tester.getCaretColumn());
+ assertEquals("\ta[2]=\"\"", tester.getLine());
- tester.type("\\\"\"");
+ tester.type("\\\"\"");
- // Verify we can overwrite the auto end-quote without appending
- // and escaped quotes can be added inside strings
- assertEquals(1, tester.getCaretLine());
- assertEquals(10, tester.getCaretColumn());
- assertEquals("\ta[2]=\"\\\"\"", tester.getLine());
+ // Verify we can overwrite the auto end-quote without appending
+ // and escaped quotes can be added inside strings
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(10, tester.getCaretColumn());
+ assertEquals("\ta[2]=\"\\\"\"", tester.getLine());
- // Verify we don't add quotes inside a comment
- tester.type(" /* \"");
- assertEquals(1, tester.getCaretLine());
- assertEquals(15, tester.getCaretColumn());
- assertEquals("\ta[2]=\"\\\"\" /* \"", tester.getLine());
+ // Verify we don't add quotes inside a comment
+ tester.type(" /* \"");
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(15, tester.getCaretColumn());
+ assertEquals("\ta[2]=\"\\\"\" /* \"", tester.getLine());
- // Verify we don't add quotes inside a line comment
- tester.type(" */ // \"");
- assertEquals(1, tester.getCaretLine());
- assertEquals(23, tester.getCaretColumn());
- assertEquals("\ta[2]=\"\\\"\" /* \" */ // \"", tester.getLine());
+ // Verify we don't add quotes inside a line comment
+ tester.type(" */ // \"");
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(23, tester.getCaretColumn());
+ assertEquals("\ta[2]=\"\\\"\" /* \" */ // \"", tester.getLine());
- // Verify we don't add quotes inside a line comment
- tester.type("\n# \"");
+ // Verify we don't add quotes inside a line comment
+ tester.type("\n# \"");
- assertEquals(2, tester.getCaretLine());
- assertEquals(3, tester.getCaretColumn());
- assertEquals("# \"", tester.getLine());
+ assertEquals(2, tester.getCaretLine());
+ assertEquals(3, tester.getCaretColumn());
+ assertEquals("# \"", tester.getLine());
- // Verify we don't add quotes inside a char specifier
- tester.type("\na[3]='\"");
+ // Verify we don't add quotes inside a char specifier
+ tester.type("\na[3]='\"");
- System.out.println(tester.fDoc.get());
- assertEquals(3, tester.getCaretLine());
- assertEquals(8, tester.getCaretColumn());
- assertEquals("\ta[3]='\"", tester.getLine());
+ System.out.println(tester.fDoc.get());
+ assertEquals(3, tester.getCaretLine());
+ assertEquals(8, tester.getCaretColumn());
+ assertEquals("\ta[3]='\"", tester.getLine());
- }
+ }
- @Test
- public void testIfCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
- AutoEditTester tester = createAutoEditTester();
+ @Test
+ public void testIfCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+ AutoEditTester tester = createAutoEditTester();
- tester.type("probe end {\n");
+ tester.type("probe end {\n");
- // We are located on 2nd line
- assertEquals(1, tester.getCaretLine());
- // Nested location is indented
- assertEquals(1, tester.getCaretColumn());
- // The brace was closed automatically. Note, getLine() gets
- // line from current position which is on line 1 of doc.
- assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
+ // We are located on 2nd line
+ assertEquals(1, tester.getCaretLine());
+ // Nested location is indented
+ assertEquals(1, tester.getCaretColumn());
+ // The brace was closed automatically. Note, getLine() gets
+ // line from current position which is on line 1 of doc.
+ assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
- tester.type("if (");
+ tester.type("if (");
- assertEquals(1, tester.getCaretLine());
- assertEquals(5, tester.getCaretColumn());
- assertEquals("\tif ()", tester.getLine());
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(5, tester.getCaretColumn());
+ assertEquals("\tif ()", tester.getLine());
- // Verify we can overwrite the closing bracket for if
- tester.type("a == b)");
+ // Verify we can overwrite the closing bracket for if
+ tester.type("a == b)");
- assertEquals(1, tester.getCaretLine());
- assertEquals(12, tester.getCaretColumn());
- assertEquals("\tif (a == b)", tester.getLine());
- }
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(12, tester.getCaretColumn());
+ assertEquals("\tif (a == b)", tester.getLine());
+ }
- @Test
- public void testElseBracketCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
- AutoEditTester tester = createAutoEditTester();
+ @Test
+ public void testElseBracketCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+ AutoEditTester tester = createAutoEditTester();
- tester.type("probe end {\n");
+ tester.type("probe end {\n");
- // We are located on 2nd line
- assertEquals(1, tester.getCaretLine());
- // Nested location is indented
- assertEquals(1, tester.getCaretColumn());
- // The brace was closed automatically. Note, getLine() gets
- // line from current position which is on line 1 of doc.
- assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
+ // We are located on 2nd line
+ assertEquals(1, tester.getCaretLine());
+ // Nested location is indented
+ assertEquals(1, tester.getCaretColumn());
+ // The brace was closed automatically. Note, getLine() gets
+ // line from current position which is on line 1 of doc.
+ assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
- tester.type("if (a == 2) {\n");
-
- assertEquals(2, tester.getCaretLine());
- assertEquals(2, tester.getCaretColumn());
- assertEquals("\tif (a == 2) {", tester.getLine(-1));
- assertEquals("\t}", tester.getLine(1));
-
- tester.goTo(3, 2);
-
- tester.type(" else {\n");
-
- assertEquals(4, tester.getCaretLine());
- assertEquals(2, tester.getCaretColumn());
- assertEquals("\t}", tester.getLine(1));
- }
-
- @Test
- public void testForCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
- AutoEditTester tester = createAutoEditTester();
-
- tester.type("probe end {\n");
-
- // We are located on 2nd line
- assertEquals(1, tester.getCaretLine());
- // Nested location is indented
- assertEquals(1, tester.getCaretColumn());
- // The brace was closed automatically. Note, getLine() gets
- // line from current position which is on line 1 of doc.
- assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
-
- tester.type("for (");
-
- assertEquals(1, tester.getCaretLine());
- assertEquals(6, tester.getCaretColumn());
- assertEquals("\tfor ()", tester.getLine());
- }
-
- @Test
- public void testForBracketCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
- AutoEditTester tester = createAutoEditTester();
-
- tester.type("probe end {\n");
-
- // We are located on 2nd line
- assertEquals(1, tester.getCaretLine());
- // Nested location is indented
- assertEquals(1, tester.getCaretColumn());
- // The brace was closed automatically. Note, getLine() gets
- // line from current position which is on line 1 of doc.
- assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
-
- tester.type("for (i = 0; i < 3; ++i) {\n");
-
- assertEquals(2, tester.getCaretLine());
- assertEquals(2, tester.getCaretColumn());
- assertEquals("\t}", tester.getLine(1));
- assertEquals("}", tester.getLine(2));
- }
-
- @Test
- public void testWhileCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
- AutoEditTester tester = createAutoEditTester();
-
- tester.type("probe end {\n");
-
- // We are located on 2nd line
- assertEquals(1, tester.getCaretLine());
- // Nested location is indented
- assertEquals(1, tester.getCaretColumn());
- // The brace was closed automatically. Note, getLine() gets
- // line from current position which is on line 1 of doc.
- assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
-
- tester.type("while (");
-
- assertEquals(1, tester.getCaretLine());
- assertEquals(8, tester.getCaretColumn());
- assertEquals("\twhile ()", tester.getLine());
- }
-
- @Test
- public void testWhileBracketCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
- AutoEditTester tester = createAutoEditTester();
-
- tester.type("probe end {\n");
-
- // We are located on 2nd line
- assertEquals(1, tester.getCaretLine());
- // Nested location is indented
- assertEquals(1, tester.getCaretColumn());
- // The brace was closed automatically. Note, getLine() gets
- // line from current position which is on line 1 of doc.
- assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
-
- tester.type("while (i == 0) {\n");
-
- assertEquals(2, tester.getCaretLine());
- assertEquals(2, tester.getCaretColumn());
- assertEquals("\t}", tester.getLine(1));
- assertEquals("}", tester.getLine(2));
- }
-
- @Test
- public void testForeachBracketCompletion() throws BadLocationException {
- assumeTrue(stapInstalled);
- AutoEditTester tester = createAutoEditTester();
-
- tester.type("probe end {\n");
-
- // We are located on 2nd line
- assertEquals(1, tester.getCaretLine());
- // Nested location is indented
- assertEquals(1, tester.getCaretColumn());
- // The brace was closed automatically. Note, getLine() gets
- // line from current position which is on line 1 of doc.
- assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
-
- tester.type("foreach (n in k+) {\n");
-
- assertEquals(2, tester.getCaretLine());
- assertEquals(2, tester.getCaretColumn());
- assertEquals("\t}", tester.getLine(1));
- assertEquals("}", tester.getLine(2));
- }
-
- @Test
- public void testPasteAutoIndent() throws BadLocationException {
- AutoEditTester tester = createAutoEditTester();
- tester.type("probe end {\n"); //$NON-NLS-1$
- tester.goTo(1, 0);
- tester.paste("if (a == b) {\n" +
- "\tfor (x = 0; x < 3; ++x) {\n" +
- "\t\tz = 4;\n" +
- "\t}\n" +
- "}\n"); //$NON-NLS-1$
- tester.goTo(1, 0);
- assertEquals("\tif (a == b) {", tester.getLine(0)); //$NON-NLS-1$
- assertEquals("\t\tfor (x = 0; x < 3; ++x) {", tester.getLine(1)); //$NON-NLS-1$
- assertEquals("\t\t\tz = 4;", tester.getLine(2)); //$NON-NLS-1$
- assertEquals("\t\t}", tester.getLine(3)); //$NON-NLS-1$
- assertEquals("\t}", tester.getLine(4)); //$NON-NLS-1$
- }
+ tester.type("if (a == 2) {\n");
+
+ assertEquals(2, tester.getCaretLine());
+ assertEquals(2, tester.getCaretColumn());
+ assertEquals("\tif (a == 2) {", tester.getLine(-1));
+ assertEquals("\t}", tester.getLine(1));
+
+ tester.goTo(3, 2);
+
+ tester.type(" else {\n");
+
+ assertEquals(4, tester.getCaretLine());
+ assertEquals(2, tester.getCaretColumn());
+ assertEquals("\t}", tester.getLine(1));
+ }
+
+ @Test
+ public void testForCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+ AutoEditTester tester = createAutoEditTester();
+
+ tester.type("probe end {\n");
+
+ // We are located on 2nd line
+ assertEquals(1, tester.getCaretLine());
+ // Nested location is indented
+ assertEquals(1, tester.getCaretColumn());
+ // The brace was closed automatically. Note, getLine() gets
+ // line from current position which is on line 1 of doc.
+ assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
+
+ tester.type("for (");
+
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(6, tester.getCaretColumn());
+ assertEquals("\tfor ()", tester.getLine());
+ }
+
+ @Test
+ public void testForBracketCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+ AutoEditTester tester = createAutoEditTester();
+
+ tester.type("probe end {\n");
+
+ // We are located on 2nd line
+ assertEquals(1, tester.getCaretLine());
+ // Nested location is indented
+ assertEquals(1, tester.getCaretColumn());
+ // The brace was closed automatically. Note, getLine() gets
+ // line from current position which is on line 1 of doc.
+ assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
+
+ tester.type("for (i = 0; i < 3; ++i) {\n");
+
+ assertEquals(2, tester.getCaretLine());
+ assertEquals(2, tester.getCaretColumn());
+ assertEquals("\t}", tester.getLine(1));
+ assertEquals("}", tester.getLine(2));
+ }
+
+ @Test
+ public void testWhileCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+ AutoEditTester tester = createAutoEditTester();
+
+ tester.type("probe end {\n");
+
+ // We are located on 2nd line
+ assertEquals(1, tester.getCaretLine());
+ // Nested location is indented
+ assertEquals(1, tester.getCaretColumn());
+ // The brace was closed automatically. Note, getLine() gets
+ // line from current position which is on line 1 of doc.
+ assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
+
+ tester.type("while (");
+
+ assertEquals(1, tester.getCaretLine());
+ assertEquals(8, tester.getCaretColumn());
+ assertEquals("\twhile ()", tester.getLine());
+ }
+
+ @Test
+ public void testWhileBracketCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+ AutoEditTester tester = createAutoEditTester();
+
+ tester.type("probe end {\n");
+
+ // We are located on 2nd line
+ assertEquals(1, tester.getCaretLine());
+ // Nested location is indented
+ assertEquals(1, tester.getCaretColumn());
+ // The brace was closed automatically. Note, getLine() gets
+ // line from current position which is on line 1 of doc.
+ assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
+
+ tester.type("while (i == 0) {\n");
+
+ assertEquals(2, tester.getCaretLine());
+ assertEquals(2, tester.getCaretColumn());
+ assertEquals("\t}", tester.getLine(1));
+ assertEquals("}", tester.getLine(2));
+ }
+
+ @Test
+ public void testForeachBracketCompletion() throws BadLocationException {
+ assumeTrue(stapInstalled);
+ AutoEditTester tester = createAutoEditTester();
+
+ tester.type("probe end {\n");
+
+ // We are located on 2nd line
+ assertEquals(1, tester.getCaretLine());
+ // Nested location is indented
+ assertEquals(1, tester.getCaretColumn());
+ // The brace was closed automatically. Note, getLine() gets
+ // line from current position which is on line 1 of doc.
+ assertEquals("}", tester.getLine(1)); //$NON-NLS-1$
+
+ tester.type("foreach (n in k+) {\n");
+
+ assertEquals(2, tester.getCaretLine());
+ assertEquals(2, tester.getCaretColumn());
+ assertEquals("\t}", tester.getLine(1));
+ assertEquals("}", tester.getLine(2));
+ }
+
+ @Test
+ public void testPasteAutoIndent() throws BadLocationException {
+ AutoEditTester tester = createAutoEditTester();
+ tester.type("probe end {\n"); //$NON-NLS-1$
+ tester.goTo(1, 0);
+ tester.paste("if (a == b) {\n" +
+ "\tfor (x = 0; x < 3; ++x) {\n" +
+ "\t\tz = 4;\n" +
+ "\t}\n" +
+ "}\n"); //$NON-NLS-1$
+ tester.goTo(1, 0);
+ assertEquals("\tif (a == b) {", tester.getLine(0)); //$NON-NLS-1$
+ assertEquals("\t\tfor (x = 0; x < 3; ++x) {", tester.getLine(1)); //$NON-NLS-1$
+ assertEquals("\t\t\tz = 4;", tester.getLine(2)); //$NON-NLS-1$
+ assertEquals("\t\t}", tester.getLine(3)); //$NON-NLS-1$
+ assertEquals("\t}", tester.getLine(4)); //$NON-NLS-1$
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPIndenterTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPIndenterTest.java
index 157e103863..fcb7ddcbd9 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPIndenterTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPIndenterTest.java
@@ -11,341 +11,239 @@
*******************************************************************************/
package org.eclipse.linuxtools.systemtap.ui.ide.test.editors.stp;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
+import static org.junit.Assert.assertEquals;
+
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.source.LineRange;
import org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.IndentUtil;
import org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.STPDocumentProvider;
-import org.junit.Assert;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleReference;
+import org.junit.Test;
/**
* Tests for the CIndenter.
*
* @since 4.0
*/
-public class STPIndenterTest extends TestCase {
-
- private static class MockSTPDocumentProvider extends STPDocumentProvider{
- MockSTPDocumentProvider(IDocument document){
- this.setupDocument(document);
- }
- }
-
- /**
- * Reads multiple sections in comments from the source of the given class.
- * @since 4.0
- */
- public StringBuilder[] getContentsForTest(int sections) throws IOException {
- ClassLoader cl = getClass().getClassLoader();
- Bundle bundle = null;
- if (cl instanceof BundleReference)
- bundle = ((BundleReference) cl).getBundle();
-
- return getContentsForTest(bundle, "src", //$NON-NLs-1$
- getClass(), getName(), sections);
- }
-
- /**
- * Returns an array of StringBuilder objects for each comment section found preceding the named
- * test in the source code.
- *
- * @param bundle the bundle containing the source, if {@code null} can try to load using
- * classpath (source folder has to be in the classpath for this to work)
- * @param srcRoot the directory inside the bundle containing the packages
- * @param clazz the name of the class containing the test
- * @param testName the name of the test
- * @param numSections the number of comment sections preceding the named test to return.
- * Pass zero to get all available sections.
- * @return an array of StringBuilder objects for each comment section found preceding the named
- * test in the source code.
- * @throws IOException
- */
- public static StringBuilder[] getContentsForTest(Bundle bundle, String srcRoot, Class<?> clazz,
- final String testName, int numSections) throws IOException {
- // Walk up the class inheritance chain until we find the test method.
- try {
- while (clazz.getMethod(testName).getDeclaringClass() != clazz) {
- clazz = clazz.getSuperclass();
- }
- } catch (SecurityException e) {
- Assert.fail(e.getMessage());
- } catch (NoSuchMethodException e) {
- Assert.fail(e.getMessage());
- }
-
- while (true) {
- // Find and open the .java file for the class clazz.
- String fqn = clazz.getName().replace('.', '/');
- fqn = fqn.indexOf("$") == -1 ? fqn : fqn.substring(0, fqn.indexOf("$"));
- String classFile = fqn + ".java";
- IPath filePath= new Path(srcRoot + '/' + classFile);
-
- InputStream in;
- Class<?> superclass = clazz.getSuperclass();
- try {
- if (bundle != null) {
- in = FileLocator.openStream(bundle, filePath, false);
- } else {
- try (InputStream inTry = clazz.getResourceAsStream('/' + classFile)) {
- in = inTry;
- }
- }
- } catch (IOException e) {
- if (superclass == null || !superclass.getPackage().equals(clazz.getPackage())) {
- throw e;
- }
- clazz = superclass;
- continue;
- }
-
- try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
- // Read the java file collecting comments until we encounter the test method.
- List<StringBuilder> contents = new ArrayList<>();
- StringBuilder content = new StringBuilder();
- for (String line = br.readLine(); line != null; line = br.readLine()) {
- line = line.replaceFirst("^\\s*", ""); // Replace leading whitespace, preserve trailing
- if (line.startsWith("//")) {
- content.append(line.substring(2) + "\n");
- } else {
- if (!line.startsWith("@") && content.length() > 0) {
- contents.add(content);
- if (numSections > 0 && contents.size() == numSections + 1)
- contents.remove(0);
- content = new StringBuilder();
- }
- if (line.length() > 0 && !contents.isEmpty()) {
- int idx= line.indexOf(testName);
- if (idx != -1 && !Character.isJavaIdentifierPart(line.charAt(idx + testName.length()))) {
- return contents.toArray(new StringBuilder[contents.size()]);
- }
- if (!line.startsWith("@")) {
- contents.clear();
- }
- }
- }
- }
- }
-
- if (superclass == null || !superclass.getPackage().equals(clazz.getPackage())) {
- throw new IOException("Test data not found for " + clazz.getName() + "." + testName);
- }
- clazz = superclass;
- }
- }
-
- protected void assertIndenterResult() throws Exception {
- StringBuilder[] contents= getContentsForTest(2);
- String before= contents[0].toString();
- IDocument document= new Document(before);
- String expected= contents[1].toString();
- new MockSTPDocumentProvider(document);
- int numLines = document.getNumberOfLines();
- if (document.getLineLength(numLines - 1) == 0) {
- numLines--; // Exclude an empty line at the end.
- }
- IndentUtil.indentLines(document, new LineRange(0, numLines), null, null);
- assertEquals(expected, document.get());
- }
-
- //if (a == b) {
- // k = 7
-
- //if (a == b) {
- // k = 7
- public void testIfStatement() throws Exception {
- assertIndenterResult();
- }
-
- //if (a == b)
- // k = 7
- // else
- //k = 9
-
- //if (a == b)
- // k = 7
- //else
- // k = 9
- public void testIfElseStatement() throws Exception {
- assertIndenterResult();
- }
-
- //for (i = 0; i < 3; ++i) {
- // k = 7
-
- //for (i = 0; i < 3; ++i) {
- // k = 7
- public void testForStatement() throws Exception {
- assertIndenterResult();
- }
-
- //while (i < 3) {
- // k = 7
-
- //while (i < 3) {
- // k = 7
- public void testWhileStatement() throws Exception {
- assertIndenterResult();
- }
-
- //foreach (i+ in arr) {
- // k = 7
-
- //foreach (i+ in arr) {
- // k = 7
- public void testForeachStatement() throws Exception {
- assertIndenterResult();
- }
-
- //foo(arg,
- //"string");
-
- //foo(arg,
- // "string");
- public void testStringLiteralAsLastArgument_1_Bug192412() throws Exception {
- assertIndenterResult();
- }
-
-
- //if (1)
- //foo->bar();
- //dontIndent();
-
- //if (1)
- // foo->bar();
- //dontIndent();
- public void testIndentationAfterArrowOperator_Bug192412() throws Exception {
- assertIndenterResult();
- }
-
- //if (1)
- //foo>>bar;
- // dontIndent();
-
- //if (1)
- // foo>>bar;
- //dontIndent();
- public void testIndentationAfterShiftRight_Bug192412() throws Exception {
- assertIndenterResult();
- }
-
- //if (1)
- //foo >= bar();
- // dontIndent();
-
- //if (1)
- // foo >= bar();
- //dontIndent();
- public void testIndentationAfterGreaterOrEquals_Bug192412() throws Exception {
- assertIndenterResult();
- }
-
- //int a[]=
- //{
- //1,
- //2
- //};
-
- //int a[]=
- //{
- // 1,
- // 2
- //};
- public void testInitializerLists_Bug194585() throws Exception {
- assertIndenterResult();
- }
-
-
- //x =
- //0;
-
- //x =
- // 0;
- public void testWrappedAssignment_1_Bug277624() throws Exception {
- assertIndenterResult();
- }
-
- //{
- //a = 0;
- //x = 2 +
- //2 +
- //2;
-
- //{
- // a = 0;
- // x = 2 +
- // 2 +
- // 2;
- public void testWrappedAssignment_2_Bug277624() throws Exception {
- assertIndenterResult();
- }
-
- //if (1 > 0) {
- //double d = a * b /
- //c;
-
- //if (1 > 0) {
- // double d = a * b /
- // c;
- public void testWrappedAssignment_3_Bug277624() throws Exception {
- assertIndenterResult();
- }
-
- //int x = 1 < 2 ?
- //f(0) :
- //1;
- //g();
-
- //int x = 1 < 2 ?
- // f(0) :
- // 1;
- //g();
- public void testConditionalExpression_Bug283970() throws Exception {
- assertIndenterResult();
- }
-
- //for (int i = 0;
- //i < 2; i++)
-
- //for (int i = 0;
- // i < 2; i++)
- public void testWrappedFor_1_Bug277625() throws Exception {
- assertIndenterResult();
- }
-
- //for (int i = 0; i < 2;
- //i++)
-
- //for (int i = 0; i < 2;
- // i++)
- public void testWrappedFor_2_Bug277625() throws Exception {
- assertIndenterResult();
- }
-
- //for (int i = 0;
- //i < 2;
- //i++)
- //{
-
- //for (int i = 0;
- // i < 2;
- // i++)
- //{
- public void testWrappedFor_3_Bug277625() throws Exception {
- assertIndenterResult();
- }
+public class STPIndenterTest {
+
+ private static class MockSTPDocumentProvider extends STPDocumentProvider{
+ MockSTPDocumentProvider(IDocument document){
+ this.setupDocument(document);
+ }
+ }
+
+ protected void assertIndenterResult(String before, String expected) throws Exception {
+ IDocument document= new Document(before);
+ new MockSTPDocumentProvider(document);
+ int numLines = document.getNumberOfLines();
+ if (document.getLineLength(numLines - 1) == 0) {
+ numLines--; // Exclude an empty line at the end.
+ }
+ IndentUtil.indentLines(document, new LineRange(0, numLines), null, null);
+ assertEquals(expected, document.get());
+ }
+
+ @Test
+ public void testIfStatement() throws Exception {
+ assertIndenterResult(
+ "if (a == b) {\n" +
+ " k = 7",
+
+ "if (a == b) {\n" +
+ "\tk = 7");
+ }
+
+ @Test
+ public void testIfElseStatement() throws Exception {
+ assertIndenterResult(
+ "if (a == b)\n" +
+ " k = 7\n" +
+ " else\n" +
+ "k = 9",
+
+ "if (a == b)\n" +
+ "\tk = 7\n" +
+ "else\n" +
+ "\tk = 9");
+ }
+
+ @Test
+ public void testForStatement() throws Exception {
+ assertIndenterResult(
+ "for (i = 0; i < 3; ++i) {\n" +
+ " k = 7",
+
+ "for (i = 0; i < 3; ++i) {\n" +
+ "\tk = 7");
+ }
+
+ @Test
+ public void testWhileStatement() throws Exception {
+ assertIndenterResult(
+ "while (i < 3) {\n" +
+ " k = 7",
+
+ "while (i < 3) {\n" +
+ "\tk = 7");
+ }
+
+ @Test
+ public void testForeachStatement() throws Exception {
+ assertIndenterResult(
+ "foreach (i+ in arr) {\n" +
+ " k = 7",
+
+ "foreach (i+ in arr) {\n" +
+ "\tk = 7");
+ }
+
+ @Test
+ public void testStringLiteralAsLastArgument_1_Bug192412() throws Exception {
+ assertIndenterResult(
+ "foo(arg,\n" +
+ "\"string\"",
+
+ "foo(arg,\n" +
+ "\t\"string\"");
+ }
+
+ @Test
+ public void testIndentationAfterArrowOperator_Bug192412() throws Exception {
+ assertIndenterResult(
+ "if (1)\n" +
+ "foo->bar();\n" +
+ "dontIndent();",
+
+ "if (1)\n" +
+ "\tfoo->bar();\n" +
+ "dontIndent();");
+ }
+
+ @Test
+ public void testIndentationAfterShiftRight_Bug192412() throws Exception {
+ assertIndenterResult(
+ "if (1)\n" +
+ "foo>>bar();\n" +
+ " dontIndent();",
+
+ "if (1)\n" +
+ "\tfoo>>bar();\n" +
+ "dontIndent();");
+ }
+
+ @Test
+ public void testIndentationAfterGreaterOrEquals_Bug192412() throws Exception {
+ assertIndenterResult(
+ "if (1)\n" +
+ "foo >= bar();\n" +
+ " dontIndent();",
+
+ "if (1)\n" +
+ "\tfoo >= bar();\n" +
+ "dontIndent();");
+ }
+
+ @Test
+ public void testInitializerLists_Bug194585() throws Exception {
+ assertIndenterResult(
+ "int a[]=\n" +
+ "{\n" +
+ "1,\n" +
+ "2\n" +
+ "}",
+
+ "int a[]=\n" +
+ "{\n" +
+ " 1,\n" +
+ " 2\n" +
+ "}");
+ }
+
+ @Test
+ public void testWrappedAssignment_1_Bug277624() throws Exception {
+ assertIndenterResult(
+ "x =\n" +
+ "0;",
+
+ "x =\n" +
+ "\t\t0;");
+ }
+
+ @Test
+ public void testWrappedAssignment_2_Bug277624() throws Exception {
+ assertIndenterResult(
+ "{\n" +
+ "a = 0;\n" +
+ "x = 2 +\n" +
+ "2 +\n" +
+ "2;",
+
+ "{\n" +
+ "\ta = 0;\n" +
+ "\tx = 2 +\n" +
+ "\t\t\t2 +\n" +
+ "\t\t\t2;");
+ }
+
+ @Test
+ public void testWrappedAssignment_3_Bug277624() throws Exception {
+ assertIndenterResult(
+ "if (1 > 0) {\n" +
+ "double d = a * b /\n" +
+ "c",
+
+ "if (1 > 0) {\n" +
+ "\tdouble d = a * b /\n" +
+ "\t\t\tc");
+ }
+
+ @Test
+ public void testConditionalExpression_Bug283970() throws Exception {
+ assertIndenterResult(
+ "int x = 1 < 2 ?\n" +
+ "f(0) :\n" +
+ "1;\n" +
+ "g();",
+
+ "int x = 1 < 2 ?\n" +
+ "\t\tf(0) :\n" +
+ "\t\t1;\n" +
+ "g();");
+ }
+
+ @Test
+ public void testWrappedFor_1_Bug277625() throws Exception {
+ assertIndenterResult(
+ "for (int i = 0;\n" +
+ "i < 2; i++)",
+
+ "for (int i = 0;\n" +
+ "\t\ti < 2; i++)");
+ }
+
+ @Test
+ public void testWrappedFor_2_Bug277625() throws Exception {
+ assertIndenterResult(
+ "for (int i = 0; i < 2;\n" +
+ "i++)",
+
+ "for (int i = 0; i < 2;\n" +
+ "\t\ti++)");
+ }
+
+ @Test
+ public void testWrappedFor_3_Bug277625() throws Exception {
+ assertIndenterResult(
+ "for (int i = 0;\n" +
+ "i < 2;\n" +
+ "i++)\n" +
+ "{",
+
+ "for (int i = 0;\n" +
+ "\t\ti < 2;\n" +
+ "\t\ti++)\n" +
+ "{");
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPToggleCommentTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPToggleCommentTest.java
index a9a8d2007e..8349c816d0 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPToggleCommentTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/editors/stp/STPToggleCommentTest.java
@@ -27,171 +27,171 @@ import org.junit.Test;
* Test class for {@link ToggleCommentHandler}.
*/
public class STPToggleCommentTest {
- private static final String[] PARTITIONED_SCRIPT = new String[]{
- "//comment\n", // line 0
- "probe syscall.write{\n", // line 1
- "// Some comment inside a probe\n", // line 2
- " printf(\"write syscall\")\n", // line 3
- "not//a//commented//block\n", // line 4
- "}\n", // line 5
- "\n", // line 6
- "" // line 7
- };
- private static String stpScript;
- private static ToggleCommentHandler cmdHandler;
- private static IDocument document;
-
- @BeforeClass
- public static void setUp() {
- StringBuffer stpScriptBuff = new StringBuffer();
- for (String scriptLine : PARTITIONED_SCRIPT) {
- stpScriptBuff.append(scriptLine);
- }
- stpScript = stpScriptBuff.toString();
- cmdHandler = new ToggleCommentHandler();
- document = new Document(stpScript);
- }
-
- private static class MockSTPDocumentProvider extends STPDocumentProvider{
- private IDocument document;
-
- MockSTPDocumentProvider(IDocument document){
- this.document = document;
- this.setupDocument(document);
- }
-
- private IDocument createDocument(Object element) {
- return document;
- }
- }
-
- @Test
- public void getFirstCompleteLineOfRegionTest() {
- IRegion scriptRegion;
- int i = 0;
- int curPos = 0;
- for (String scriptLine : PARTITIONED_SCRIPT) {
- int lineLength = scriptLine.length();
- int offset = stpScript.indexOf(scriptLine, curPos);
- scriptRegion = new Region(offset, lineLength);
- int actualIndex = cmdHandler.getFirstCompleteLineOfRegion(scriptRegion, document);
- assertEquals(i, actualIndex);
-
- curPos = offset + lineLength;
- i++;
- }
- }
-
- @Test
- public void isBlockEmptyTest() {
- int i = 0;
- for(String scriptLine : PARTITIONED_SCRIPT){
- // new lines are considered empty blocks
- boolean expected = "\n".equals(scriptLine) ? true : scriptLine.isEmpty();
- assertEquals(expected, cmdHandler.isBlockEmpty(i, i, document));
-
- i++;
- }
- }
-
- @Test
- public void isBlockCommentedTest() {
- MockSTPDocumentProvider provider = new MockSTPDocumentProvider(new Document(stpScript));
- IDocument document = provider.createDocument(null);
-
- int i = 0;
- for( String scriptLine : PARTITIONED_SCRIPT){
- // for the purposes of this test, commented blocks start with "//"
- assertEquals(scriptLine.startsWith("//"), cmdHandler.isBlockCommented(i, i, "//", document));
-
- i++;
- }
- }
-
- @Test
- public void getTextBlockFromSelectionTest() throws BadLocationException {
- int i = 0;
- int curPos = 0;
- for (String scriptLine : PARTITIONED_SCRIPT) {
- int lineLength = scriptLine.length();
- int offset = stpScript.indexOf(scriptLine, curPos);
-
- ITextSelection selection = new MockTextSelection(offset, lineLength, i, i, scriptLine);
- IRegion actualRegion = cmdHandler.getTextBlockFromSelection( selection, document);
- IRegion expectedRegion = new Region(offset, lineLength);
- assertEquals(scriptLine + " :", expectedRegion, actualRegion);
-
- curPos = offset + lineLength;
- i++;
- }
- }
-
- @Test
- public void isSelectionCommentedTest() {
- int i = 0;
- int curPos = 0;
- for (String scriptLine : PARTITIONED_SCRIPT) {
- int lineLength = scriptLine.length();
- int offset = stpScript.indexOf(scriptLine, curPos);
- ITextSelection selection = new MockTextSelection(offset, lineLength, i, i, scriptLine);
- MockSTPDocumentProvider provider = new MockSTPDocumentProvider(new Document(stpScript));
- IDocument document = provider.createDocument(null);
-
- // for the purposes of this test, commented blocks start with "//"
- assertEquals(scriptLine.startsWith("//"), cmdHandler.isSelectionCommented(selection, document));
-
- curPos = offset + lineLength;
- i++;
- }
- }
-
- /**
- * Mock {@link ITextSelection} implementation.
- */
- private static class MockTextSelection implements ITextSelection {
- private int offset;
- private int length;
- private int startLine;
- private int endLine;
- private String text;
-
- public MockTextSelection(int offset, int length, int startLine,
- int endLine, String text) {
- this.offset = offset;
- this.length = length;
- this.startLine = startLine;
- this.endLine = endLine;
- this.text = text;
- }
-
- @Override
- public boolean isEmpty() {
- return false;
- }
-
- @Override
- public int getOffset() {
- return offset;
- }
-
- @Override
- public int getLength() {
- return length;
- }
-
- @Override
- public int getStartLine() {
- return startLine;
- }
-
- @Override
- public int getEndLine() {
- return endLine;
- }
-
- @Override
- public String getText() {
- return text;
- }
- }
+ private static final String[] PARTITIONED_SCRIPT = new String[]{
+ "//comment\n", // line 0
+ "probe syscall.write{\n", // line 1
+ "// Some comment inside a probe\n", // line 2
+ " printf(\"write syscall\")\n", // line 3
+ "not//a//commented//block\n", // line 4
+ "}\n", // line 5
+ "\n", // line 6
+ "" // line 7
+ };
+ private static String stpScript;
+ private static ToggleCommentHandler cmdHandler;
+ private static IDocument document;
+
+ @BeforeClass
+ public static void setUp() {
+ StringBuffer stpScriptBuff = new StringBuffer();
+ for (String scriptLine : PARTITIONED_SCRIPT) {
+ stpScriptBuff.append(scriptLine);
+ }
+ stpScript = stpScriptBuff.toString();
+ cmdHandler = new ToggleCommentHandler();
+ document = new Document(stpScript);
+ }
+
+ private static class MockSTPDocumentProvider extends STPDocumentProvider{
+ private IDocument document;
+
+ MockSTPDocumentProvider(IDocument document){
+ this.document = document;
+ this.setupDocument(document);
+ }
+
+ private IDocument createDocument(Object element) {
+ return document;
+ }
+ }
+
+ @Test
+ public void getFirstCompleteLineOfRegionTest() {
+ IRegion scriptRegion;
+ int i = 0;
+ int curPos = 0;
+ for (String scriptLine : PARTITIONED_SCRIPT) {
+ int lineLength = scriptLine.length();
+ int offset = stpScript.indexOf(scriptLine, curPos);
+ scriptRegion = new Region(offset, lineLength);
+ int actualIndex = cmdHandler.getFirstCompleteLineOfRegion(scriptRegion, document);
+ assertEquals(i, actualIndex);
+
+ curPos = offset + lineLength;
+ i++;
+ }
+ }
+
+ @Test
+ public void isBlockEmptyTest() {
+ int i = 0;
+ for(String scriptLine : PARTITIONED_SCRIPT){
+ // new lines are considered empty blocks
+ boolean expected = "\n".equals(scriptLine) ? true : scriptLine.isEmpty();
+ assertEquals(expected, cmdHandler.isBlockEmpty(i, i, document));
+
+ i++;
+ }
+ }
+
+ @Test
+ public void isBlockCommentedTest() {
+ MockSTPDocumentProvider provider = new MockSTPDocumentProvider(new Document(stpScript));
+ IDocument document = provider.createDocument(null);
+
+ int i = 0;
+ for( String scriptLine : PARTITIONED_SCRIPT){
+ // for the purposes of this test, commented blocks start with "//"
+ assertEquals(scriptLine.startsWith("//"), cmdHandler.isBlockCommented(i, i, "//", document));
+
+ i++;
+ }
+ }
+
+ @Test
+ public void getTextBlockFromSelectionTest() throws BadLocationException {
+ int i = 0;
+ int curPos = 0;
+ for (String scriptLine : PARTITIONED_SCRIPT) {
+ int lineLength = scriptLine.length();
+ int offset = stpScript.indexOf(scriptLine, curPos);
+
+ ITextSelection selection = new MockTextSelection(offset, lineLength, i, i, scriptLine);
+ IRegion actualRegion = cmdHandler.getTextBlockFromSelection( selection, document);
+ IRegion expectedRegion = new Region(offset, lineLength);
+ assertEquals(scriptLine + " :", expectedRegion, actualRegion);
+
+ curPos = offset + lineLength;
+ i++;
+ }
+ }
+
+ @Test
+ public void isSelectionCommentedTest() {
+ int i = 0;
+ int curPos = 0;
+ for (String scriptLine : PARTITIONED_SCRIPT) {
+ int lineLength = scriptLine.length();
+ int offset = stpScript.indexOf(scriptLine, curPos);
+ ITextSelection selection = new MockTextSelection(offset, lineLength, i, i, scriptLine);
+ MockSTPDocumentProvider provider = new MockSTPDocumentProvider(new Document(stpScript));
+ IDocument document = provider.createDocument(null);
+
+ // for the purposes of this test, commented blocks start with "//"
+ assertEquals(scriptLine.startsWith("//"), cmdHandler.isSelectionCommented(selection, document));
+
+ curPos = offset + lineLength;
+ i++;
+ }
+ }
+
+ /**
+ * Mock {@link ITextSelection} implementation.
+ */
+ private static class MockTextSelection implements ITextSelection {
+ private int offset;
+ private int length;
+ private int startLine;
+ private int endLine;
+ private String text;
+
+ public MockTextSelection(int offset, int length, int startLine,
+ int endLine, String text) {
+ this.offset = offset;
+ this.length = length;
+ this.startLine = startLine;
+ this.endLine = endLine;
+ this.text = text;
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return false;
+ }
+
+ @Override
+ public int getOffset() {
+ return offset;
+ }
+
+ @Override
+ public int getLength() {
+ return length;
+ }
+
+ @Override
+ public int getStartLine() {
+ return startLine;
+ }
+
+ @Override
+ public int getEndLine() {
+ return endLine;
+ }
+
+ @Override
+ public String getText() {
+ return text;
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/structures/StapErrorParserTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/structures/StapErrorParserTest.java
index 66b609264e..20368e1939 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/structures/StapErrorParserTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/structures/StapErrorParserTest.java
@@ -21,39 +21,39 @@ import org.junit.Test;
public class StapErrorParserTest {
- @Test
- public void testStapErrorParser() {
- String[][] output;
-
- StapErrorParser parser = new StapErrorParser();
-
- output = parser.parseOutput(null);
- assertNull(output);
-
- output = parser.parseOutput("");
- assertNotNull(output);
- assertEquals(0, output.length);
-
- output = parser.parseOutput("this shouldn't have anything");
- assertNotNull(output);
- assertEquals(0, output.length);
-
- output = parser.parseOutput("parse error: expected identifier or '*' \n" +
- "saw: operator '{' at /home/morser/test.stp:14:7 \n" +
- "1 parse error(s). \n" +
- "Pass 1: parse failed. Try again with more '-v' (verbose) options.");
- assertNotNull(output);
- assertEquals(1, output.length);
- assertTrue("parse error:".equals(output[0][0]));
- assertTrue(output[0][3].startsWith("14"));
-
- output = parser.parseOutput("semantic error: probe_615 with type mismatch for identifier 'flags' at /home/morser/test.stp:22:6: string vs. long \n" +
- "semantic error: probe_615 with type mismatch for identifier 'mode' at /home/morser/test.stp:23:6: string vs. long \n" +
- "semantic error: probe_615 with type mismatch for identifier 'f' at /home/morser/test.stp:25:6: string vs. long \n" +
- "Pass 2: analysis failed. Try again with more '-v' (verbose) options.");
- assertNotNull(output);
- assertEquals(3, output.length);
- assertTrue("semantic error:".equals(output[0][0]));
- assertTrue(output[0][3].startsWith("22:6"));
- }
+ @Test
+ public void testStapErrorParser() {
+ String[][] output;
+
+ StapErrorParser parser = new StapErrorParser();
+
+ output = parser.parseOutput(null);
+ assertNull(output);
+
+ output = parser.parseOutput("");
+ assertNotNull(output);
+ assertEquals(0, output.length);
+
+ output = parser.parseOutput("this shouldn't have anything");
+ assertNotNull(output);
+ assertEquals(0, output.length);
+
+ output = parser.parseOutput("parse error: expected identifier or '*' \n" +
+ "saw: operator '{' at /home/morser/test.stp:14:7 \n" +
+ "1 parse error(s). \n" +
+ "Pass 1: parse failed. Try again with more '-v' (verbose) options.");
+ assertNotNull(output);
+ assertEquals(1, output.length);
+ assertTrue("parse error:".equals(output[0][0]));
+ assertTrue(output[0][3].startsWith("14"));
+
+ output = parser.parseOutput("semantic error: probe_615 with type mismatch for identifier 'flags' at /home/morser/test.stp:22:6: string vs. long \n" +
+ "semantic error: probe_615 with type mismatch for identifier 'mode' at /home/morser/test.stp:23:6: string vs. long \n" +
+ "semantic error: probe_615 with type mismatch for identifier 'f' at /home/morser/test.stp:25:6: string vs. long \n" +
+ "Pass 2: analysis failed. Try again with more '-v' (verbose) options.");
+ assertNotNull(output);
+ assertEquals(3, output.length);
+ assertTrue("semantic error:".equals(output[0][0]));
+ assertTrue(output[0][3].startsWith("22:6"));
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/structures/TreeSettingsTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/structures/TreeSettingsTest.java
index d672f30420..bf9fdec389 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/structures/TreeSettingsTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/structures/TreeSettingsTest.java
@@ -22,104 +22,104 @@ import org.junit.Test;
public class TreeSettingsTest {
- @Before
- public void setUp() {
- TreeSettings.setTrees(new TreeNode("func", false), new TreeNode("probe", false));
- }
-
- @Test
- public void testSetTrees() {
- TreeNode t = new TreeNode("f", false);
- TreeNode t1 = new TreeNode("as", "as3", false);
- TreeNode t2 = new TreeNode(null, false);
- TreeNode t3 = null;
-
- assertTrue("Set tree fine1", TreeSettings.setTrees(t, t));
- assertTrue("Set tree fine2", TreeSettings.setTrees(t1, t1));
- assertTrue("Set tree null obj", TreeSettings.setTrees(t2, t2));
- assertFalse("Set trees null", TreeSettings.setTrees(t3, t3));
- assertFalse("Set func null", TreeSettings.setTrees(t3, t));
- assertFalse("Set probe null", TreeSettings.setTrees(t, t3));
- }
-
- @Test
- public void testGetTreeFileDate() {
- long d1 = TreeSettings.getTreeFileDate();
- long d2 = TreeSettings.getTreeFileDate();
- assertEquals("TreeDate same", d1, d2);
-
- TreeSettings.setTrees(new TreeNode("f", false), new TreeNode("p", false));
- d2 = TreeSettings.getTreeFileDate();
-
- assertTrue("TreeDate changed", d1 < d2);
- }
-
- @Test
- public void testGetFunctionTree() {
- TreeNode temp;
- TreeNode t = new TreeNode("f", false);
- TreeNode t1 = new TreeNode(null, false);
- TreeNode t2 = new TreeNode(new StringBuilder("asfd"), true);
-
- TreeSettings.setTrees(t, t);
- temp = TreeSettings.getFunctionTree();
- assertEquals("Funcs no children", 0, temp.getChildCount());
- assertEquals("Funcs object", t.getData().toString(), temp.getData().toString());
- assertEquals("Funcs display", t.toString(),temp.toString());
-
- TreeSettings.setTrees(t1, t);
- temp = TreeSettings.getFunctionTree();
- assertEquals("Funcs no children", 0, temp.getChildCount());
- assertEquals("Funcs object", t1.getData(), temp.getData());
- assertEquals("Funcs display", t1.toString(), temp.toString());
-
- TreeSettings.setTrees(t2, t);
- temp = TreeSettings.getFunctionTree();
- assertEquals("Funcs no children", 0, temp.getChildCount());
- assertEquals("Funcs object", t2.getData().toString(),temp.getData());
- assertEquals("Funcs display", t2.toString(), temp.toString());
-
- t.add(t2);
- t.add(t1);
- TreeSettings.setTrees(t, t);
- temp = TreeSettings.getFunctionTree();
- assertEquals("Funcs has children", 2, temp.getChildCount());
- assertEquals("Funcs child object", t2.getData().toString(), temp.getChildAt(0).getData());
- assertEquals("Funcs child display", t2.toString(), temp.getChildAt(0).toString());
- }
-
- @Test
- public void testGetProbeTree() {
- TreeNode temp;
- TreeNode t = new TreeNode("f", false);
- TreeNode t1 = new TreeNode(null, false);
- TreeNode t2 = new TreeNode(new StringBuilder("asfd"), true);
-
- TreeSettings.setTrees(t, t);
- temp = TreeSettings.getProbeTree();
- assertEquals("Probs no children", 0, temp.getChildCount());
- assertEquals("Probs object", t.getData().toString(), temp.getData().toString());
- assertEquals("Probs display", t.toString(), temp.toString());
-
- TreeSettings.setTrees(t, t1);
- temp = TreeSettings.getProbeTree();
- assertEquals("Probs no children", 0, temp.getChildCount());
- assertEquals("Probs object", t1.getData(), temp.getData());
- assertEquals("Probs display", t1.toString(), temp.toString());
-
- TreeSettings.setTrees(t, t2);
- temp = TreeSettings.getProbeTree();
- assertEquals("Probs no children", 0, temp.getChildCount());
- assertEquals("Probs object", t2.getData().toString(), temp.getData());
- assertEquals("Probs display", t2.toString(), temp.toString());
-
- t.add(t2);
- t.add(t1);
- TreeSettings.setTrees(t, t);
- temp = TreeSettings.getProbeTree();
- assertEquals("Probs has children", 2, temp.getChildCount());
- assertEquals("Probs child object", t2.getData().toString(), temp.getChildAt(0).getData());
- assertEquals("Probs child display", t2.toString(), temp.getChildAt(0).toString());
-
- }
+ @Before
+ public void setUp() {
+ TreeSettings.setTrees(new TreeNode("func", false), new TreeNode("probe", false));
+ }
+
+ @Test
+ public void testSetTrees() {
+ TreeNode t = new TreeNode("f", false);
+ TreeNode t1 = new TreeNode("as", "as3", false);
+ TreeNode t2 = new TreeNode(null, false);
+ TreeNode t3 = null;
+
+ assertTrue("Set tree fine1", TreeSettings.setTrees(t, t));
+ assertTrue("Set tree fine2", TreeSettings.setTrees(t1, t1));
+ assertTrue("Set tree null obj", TreeSettings.setTrees(t2, t2));
+ assertFalse("Set trees null", TreeSettings.setTrees(t3, t3));
+ assertFalse("Set func null", TreeSettings.setTrees(t3, t));
+ assertFalse("Set probe null", TreeSettings.setTrees(t, t3));
+ }
+
+ @Test
+ public void testGetTreeFileDate() {
+ long d1 = TreeSettings.getTreeFileDate();
+ long d2 = TreeSettings.getTreeFileDate();
+ assertEquals("TreeDate same", d1, d2);
+
+ TreeSettings.setTrees(new TreeNode("f", false), new TreeNode("p", false));
+ d2 = TreeSettings.getTreeFileDate();
+
+ assertTrue("TreeDate changed", d1 < d2);
+ }
+
+ @Test
+ public void testGetFunctionTree() {
+ TreeNode temp;
+ TreeNode t = new TreeNode("f", false);
+ TreeNode t1 = new TreeNode(null, false);
+ TreeNode t2 = new TreeNode(new StringBuilder("asfd"), true);
+
+ TreeSettings.setTrees(t, t);
+ temp = TreeSettings.getFunctionTree();
+ assertEquals("Funcs no children", 0, temp.getChildCount());
+ assertEquals("Funcs object", t.getData().toString(), temp.getData().toString());
+ assertEquals("Funcs display", t.toString(),temp.toString());
+
+ TreeSettings.setTrees(t1, t);
+ temp = TreeSettings.getFunctionTree();
+ assertEquals("Funcs no children", 0, temp.getChildCount());
+ assertEquals("Funcs object", t1.getData(), temp.getData());
+ assertEquals("Funcs display", t1.toString(), temp.toString());
+
+ TreeSettings.setTrees(t2, t);
+ temp = TreeSettings.getFunctionTree();
+ assertEquals("Funcs no children", 0, temp.getChildCount());
+ assertEquals("Funcs object", t2.getData().toString(),temp.getData());
+ assertEquals("Funcs display", t2.toString(), temp.toString());
+
+ t.add(t2);
+ t.add(t1);
+ TreeSettings.setTrees(t, t);
+ temp = TreeSettings.getFunctionTree();
+ assertEquals("Funcs has children", 2, temp.getChildCount());
+ assertEquals("Funcs child object", t2.getData().toString(), temp.getChildAt(0).getData());
+ assertEquals("Funcs child display", t2.toString(), temp.getChildAt(0).toString());
+ }
+
+ @Test
+ public void testGetProbeTree() {
+ TreeNode temp;
+ TreeNode t = new TreeNode("f", false);
+ TreeNode t1 = new TreeNode(null, false);
+ TreeNode t2 = new TreeNode(new StringBuilder("asfd"), true);
+
+ TreeSettings.setTrees(t, t);
+ temp = TreeSettings.getProbeTree();
+ assertEquals("Probs no children", 0, temp.getChildCount());
+ assertEquals("Probs object", t.getData().toString(), temp.getData().toString());
+ assertEquals("Probs display", t.toString(), temp.toString());
+
+ TreeSettings.setTrees(t, t1);
+ temp = TreeSettings.getProbeTree();
+ assertEquals("Probs no children", 0, temp.getChildCount());
+ assertEquals("Probs object", t1.getData(), temp.getData());
+ assertEquals("Probs display", t1.toString(), temp.toString());
+
+ TreeSettings.setTrees(t, t2);
+ temp = TreeSettings.getProbeTree();
+ assertEquals("Probs no children", 0, temp.getChildCount());
+ assertEquals("Probs object", t2.getData().toString(), temp.getData());
+ assertEquals("Probs display", t2.toString(), temp.toString());
+
+ t.add(t2);
+ t.add(t1);
+ TreeSettings.setTrees(t, t);
+ temp = TreeSettings.getProbeTree();
+ assertEquals("Probs has children", 2, temp.getChildCount());
+ assertEquals("Probs child object", t2.getData().toString(), temp.getChildAt(0).getData());
+ assertEquals("Probs child display", t2.toString(), temp.getChildAt(0).toString());
+
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/swtbot/TestCreateSystemtapScript.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/swtbot/TestCreateSystemtapScript.java
index 10fb24e143..b884db5ad9 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/swtbot/TestCreateSystemtapScript.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide.tests/src/org/eclipse/linuxtools/systemtap/ui/ide/test/swtbot/TestCreateSystemtapScript.java
@@ -72,1388 +72,1388 @@ import org.swtchart.Range;
@RunWith(SWTBotJunit4ClassRunner.class)
public class TestCreateSystemtapScript {
- private static final String SYSTEMTAP_PROJECT_NAME = "SystemtapTest";
-
- private static SWTWorkbenchBot bot;
- private static boolean stapInstalled;
- private static SWTBotView projectExplorer;
-
-
- private static class NodeAvailableAndSelect extends DefaultCondition {
-
- private SWTBotTree tree;
- private String parent;
- private String node;
-
- /**
- * Wait for a tree node (with a known parent) to become visible, and select it
- * when it does. Note that this wait condition should only be used after having
- * made an attempt to reveal the node.
- * @param tree The SWTBotTree that contains the node to select.
- * @param parent The text of the parent node that contains the node to select.
- * @param node The text of the node to select.
- */
- NodeAvailableAndSelect(SWTBotTree tree, String parent, String node) {
- this.tree = tree;
- this.node = node;
- this.parent = parent;
- }
-
- @Override
- public boolean test() {
- try {
- SWTBotTreeItem parentNode = tree.getTreeItem(parent);
- parentNode.getNode(node).select();
- return true;
- } catch (WidgetNotFoundException e) {
- return false;
- }
- }
-
- @Override
- public String getFailureMessage() {
- return "Timed out waiting for " + node; //$NON-NLS-1$
- }
- }
-
- private static class TreePopulated extends DefaultCondition {
-
- private SWTBotTree parent;
-
- TreePopulated(SWTBotTree parent) {
- this.parent = parent;
- }
-
- @Override
- public boolean test() {
- return this.parent.getAllItems().length > 0;
- }
-
- @Override
- public String getFailureMessage() {
- return "Timed out waiting for tree to populate.";
- }
- }
-
- private static class TreeItemPopulated extends DefaultCondition {
-
- private SWTBotTreeItem parent;
-
- TreeItemPopulated(SWTBotTreeItem parent) {
- this.parent = parent;
- }
-
- @Override
- public boolean test() {
- return this.parent.getItems().length > 0;
- }
-
- @Override
- public String getFailureMessage() {
- return "Timed out waiting for tree to populate.";
- }
- }
-
- private static class ConsoleIsReady extends DefaultCondition {
-
- private String scriptName;
- public ConsoleIsReady(String scriptName) {
- this.scriptName = scriptName;
- }
-
- @Override
- public boolean test() {
- SWTBotView console = TestCreateSystemtapScript.bot.viewById("org.eclipse.ui.console.ConsoleView");
- console.setFocus();
- return console.bot().label().getText().contains(scriptName);
- }
-
- @Override
- public String getFailureMessage() {
- return "Timed out waiting for console to appear";
- }
-
- }
-
- private static class StapHasExited extends DefaultCondition {
-
- @Override
- public boolean test() {
- SWTBotView console = TestCreateSystemtapScript.bot.viewById("org.eclipse.ui.console.ConsoleView");
- console.setFocus();
- return (!console.toolbarButton("Stop Script").isEnabled());
- }
-
- @Override
- public String getFailureMessage() {
- return "Timed out waiting for stap to exit";
- }
- }
-
- private static class TableHasUpdated extends DefaultCondition {
-
- private String scriptName;
- private int graphSetNum;
- private int expectedRows;
- private boolean exact;
- /**
- * Wait for the provided GraphSelectorEditor to be fully updated.
- * Note that using this will set focus to the Data View tab of the specified graph set.
- * @param scriptName The name of the script that is being graphed.
- * @param graphSetNum Which graph set to focus on & watch for updates.
- * @param expectedRows How many entries/rows are expected to be in the table when it's fully updated.
- * @param exact Set this to <code>true</code> if the number of graph columns should exactly match the
- * expected amount, or <code>false</code> if it may be greater than the expected amount.
- */
- public TableHasUpdated(String scriptName, int graphSetNum, int expectedRows, boolean exact) {
- this.scriptName = scriptName;
- this.graphSetNum = graphSetNum;
- this.expectedRows = expectedRows;
- this.exact = exact;
- }
- @Override
- public boolean test() {
- SWTBotEditor graphEditor = TestCreateSystemtapScript.bot.editorByTitle(scriptName.concat(" Graphs"));
- graphEditor.setFocus();
- graphEditor.bot().cTabItem(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, graphSetNum)).activate();
- graphEditor.bot().cTabItem("Data View").activate();
- if (!exact) {
- return bot.table().rowCount() >= expectedRows;
- } else {
- return bot.table().rowCount() == expectedRows;
- }
- }
-
- @Override
- public String getFailureMessage() {
- return "Timed out waiting for data table to update";
- }
- }
-
- private static class ChartHasUpdated extends DefaultCondition {
-
- private Chart chart;
- int oldCount;
- int expectedCount;
- /**
- * Wait for the provided chart to become updated.
- * @param chart The chart to watch for an update.
- * @param expectedCount The expected number of series points. Set to -1 to instead
- * check for when there are more points than there were at the beginning.
- */
- public ChartHasUpdated(Chart chart, int expectedCount) {
- this.chart = chart;
- ISeries[] seriesSet = chart.getSeriesSet().getSeries();
- this.oldCount = seriesSet.length > 0 ? seriesSet[0].getXSeries().length : 0;
- this.expectedCount = expectedCount;
- }
- @Override
- public boolean test() {
- ISeries[] seriesSet = chart.getSeriesSet().getSeries();
- int newCount = seriesSet.length > 0 ? seriesSet[0].getXSeries().length : 0;
- return expectedCount < 0 ? newCount > oldCount : newCount == expectedCount;
- }
-
- @Override
- public String getFailureMessage() {
- return "Timed out waiting for chart to update";
- }
-
- }
-
- @BeforeClass
- public static void beforeClass() {
- bot = new SWTWorkbenchBot();
- stapInstalled = true;
-
- // Dismiss "Systemtap not installed" dialog(s) if present.
- try {
- SWTBotShell shell = bot.shell("Cannot Run SystemTap").activate();
- stapInstalled = false;
- shell.close();
-
- shell = bot.shell("Cannot Run SystemTap").activate();
- shell.close();
- } catch (WidgetNotFoundException e) {
- //ignore
- }
-
- try {
- bot.viewByTitle("Welcome").close();
- // hide Subclipse Usage stats popup if present/installed
- bot.shell("Subclipse Usage").activate();
- bot.button("Cancel").click();
- } catch (WidgetNotFoundException e) {
- //ignore
- }
-
- // Set SystemTap IDE perspective.
- bot.perspectiveByLabel("SystemTap IDE").activate();
- bot.sleep(500);
- for (SWTBotShell sh : bot.shells()) {
- if (sh.getText().startsWith("SystemTap IDE")) {
- sh.activate();
- bot.sleep(500);
- break;
- }
- }
-
- // Create a Systemtap project.
- SWTBotMenu fileMenu = bot.menu("File");
- SWTBotMenu newMenu = fileMenu.menu("New");
- SWTBotMenu projectMenu = newMenu.menu("Project...");
- projectMenu.click();
-
- SWTBotShell shell = bot.shell("New Project");
- shell.setFocus();
- shell.bot().text().setText("Project");
- bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "General", "Project"));
- bot.button("Next >").click();
- bot.textWithLabel("Project name:").setText(SYSTEMTAP_PROJECT_NAME);
- bot.button("Finish").click();
- bot.waitUntil(Conditions.shellCloses(shell));
- projectExplorer = bot.viewByTitle("Project Explorer");
- projectExplorer.setFocus();
- projectExplorer.bot().tree().select(SYSTEMTAP_PROJECT_NAME)
- .contextMenu("Go Into").click();
-
- // Open the Debug view.
- bot.menu("Window").menu("Show View").menu("Other...").click();
- shell = bot.shell("Show View");
- shell.setFocus();
- shell.bot().text().setText("Debug");
- bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "Debug", "Debug"));
- bot.button("OK").click();
- }
-
- @After
- public void cleanUp() {
- SWTBotShell[] shells = bot.shells();
- for (final SWTBotShell shell : shells) {
- String shellTitle = shell.getText();
- if (shellTitle.length() > 0
- && !shellTitle.startsWith("SystemTap IDE")
- && !shellTitle.startsWith("Quick Access")) {
- UIThreadRunnable.syncExec(new VoidResult() {
- @Override
- public void run() {
- if (shell.widget.getParent() != null) {
- shell.close();
- }
- }
- });
- }
- }
- bot.closeAllEditors();
- }
-
- @AfterClass
- public static void finalCleanUp() {
- if (ScriptConsole.anyRunning()) {
- ScriptConsole.stopAll();
- bot.waitUntil(new StapHasExited());
- }
-
- projectExplorer.setFocus();
- SWTBotToolbarButton forwardButton = projectExplorer.toolbarPushButton("Forward");
- projectExplorer.toolbarPushButton("Back to Workspace").click();
- bot.waitUntil(Conditions.widgetIsEnabled(forwardButton));
-
- projectExplorer.bot().tree().select(SYSTEMTAP_PROJECT_NAME)
- .contextMenu("Delete").click();
- SWTBotShell deleteShell = bot.shell("Delete Resources");
- deleteShell.bot().button("OK").click();
- bot.waitUntil(Conditions.shellCloses(deleteShell));
- }
-
- public static void createScript(SWTWorkbenchBot bot, String scriptName) {
- SWTBotMenu fileMenu = bot.menu("File");
- SWTBotMenu newMenu = fileMenu.menu("New");
- SWTBotMenu projectMenu = newMenu.menu("Other...");
- projectMenu.click();
-
- SWTBotShell shell = bot.shell("New");
- shell.setFocus();
- shell.bot().text().setText("SystemTap");
- bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "SystemTap", "SystemTap Script"));
- bot.button("Next >").click();
-
- SWTBotText text = bot.textWithLabel("Script Name:").setText(scriptName);
- assertEquals(scriptName, text.getText());
- text = bot.textWithLabel("Project:").setText(SYSTEMTAP_PROJECT_NAME);
- assertEquals(SYSTEMTAP_PROJECT_NAME, text.getText());
-
- bot.button("Finish").click();
- bot.waitUntil(Conditions.shellCloses(shell));
-
- assertEquals(scriptName, bot.activeEditor().getTitle());
- }
-
- private SWTBotShell prepareScript(String scriptName, String scriptContents) {
- createScript(bot, scriptName);
- if (scriptContents != null) {
- SWTBotEclipseEditor editor = bot.editorByTitle(scriptName).toTextEditor();
- editor.setText(scriptContents);
- editor.save();
- }
-
- openRunConfigurations(scriptName);
- SWTBotShell shell = bot.shell("Run Configurations");
- shell.setFocus();
- bot.tree().select("SystemTap").contextMenu("New").click();
-
- // Select the "Graphing" tab and enable output graphing.
- bot.cTabItem(Messages.SystemTapScriptGraphOptionsTab_graphingTitle).activate();
- bot.checkBox(Messages.SystemTapScriptGraphOptionsTab_graphOutputRun).click();
- return shell;
- }
-
- private void clearAllTerminated() {
- SWTBotView debugView = bot.viewByTitle("Debug");
- debugView.setFocus();
- SWTBotTree debugTable = debugView.bot().tree();
- assertTrue(debugTable.getAllItems().length > 0);
- SWTBotToolbarButton remButton = debugView.toolbarPushButton("Remove All Terminated Launches");
- assertTrue(remButton.isEnabled());
- remButton.click();
- assertEquals(debugTable.getAllItems().length, 0);
- assertFalse(remButton.isEnabled());
- }
-
- @Test
- public void testCreateScript() {
- String scriptName = "testScript.stp";
- createScript(bot, scriptName);
-
- // Type a script
- SWTBotEclipseEditor editor = bot.editorByTitle(scriptName).toTextEditor();
- editor.typeText(0, editor.getText().length(), "\nprobe begin{log(\"began");
- editor.typeText(0, editor.getText().length() - 1, "); exit(");
- editor.typeText(0, editor.getText().length(), "}");
- editor.save();
-
- openRunConfigurations(scriptName);
- SWTBotShell shell = bot.shell("Run Configurations");
- shell.setFocus();
- bot.tree().select("SystemTap").contextMenu("New").click();
-
- if (stapInstalled) {
- bot.button("Run").click();
- bot.waitUntil(Conditions.shellCloses(shell));
-
- bot.waitUntil(new ConsoleIsReady(scriptName));
- bot.waitUntil(new StapHasExited(), 10000); // The script should end on its own
- }
- }
-
- @Test
- public void testAddProbes() {
- // TODO Create dummy probe tree data that can be tested instead of relying on stap.
- assumeTrue(stapInstalled);
-
- // Create a blank script and add a probe to it while it's open.
- String scriptName = "probeScript.stp";
- createScript(bot, scriptName);
-
- SWTBotView probeView = bot.viewByTitle("Probe Alias");
- SWTBotTree probeTree = probeView.bot().tree();
- bot.waitUntil(new TreePopulated(probeTree), 10000);
-
- // Root level entries are categories of probe types. Enter them to access probe groups
- SWTBotTreeItem[] items = probeTree.getAllItems();
- items[0].doubleClick();
- bot.waitUntil(new TreeItemPopulated(items[0]));
- items = items[0].getItems();
- items[0].doubleClick();
- SWTBotEclipseEditor editor = bot.activeEditor().toTextEditor();
- assertTrue(editor.getText().contains("probe " + items[0].getText() + ".*\n"));
-
- // Open a non-stap file and add a probe. This should bring up a dialog
- // asking if the probe should be added to the only open .stp file.
- SWTBotMenu fileMenu = bot.menu("File");
- SWTBotMenu newMenu = fileMenu.menu("New");
- SWTBotMenu projectMenu = newMenu.menu("Other...");
- projectMenu.click();
- SWTBotShell shell = bot.shell("New");
- shell.setFocus();
- shell.bot().text().setText("Untitled Text File");
- bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "General", "Untitled Text File"));
- bot.button("Finish").click();
-
- String probeDialogTitle = "Select Script";
- items[1].doubleClick();
- shell = bot.shell(probeDialogTitle);
- shell.setFocus();
- bot.button("Yes").click();
- bot.waitUntil(Conditions.shellCloses(shell));
-
- // The editor containing the script should now be in focus.
- editor = bot.activeEditor().toTextEditor();
- assertEquals(scriptName, editor.getTitle());
- assertTrue(editor.getText().contains("probe " + items[0].getText() + ".*\n"));
- assertTrue(editor.getText().contains("probe " + items[1].getText() + ".*\n"));
-
- // Adding a probe while an .stp editor is in focus should always add it
- // to that editor, even if multiple .stp editors are open.
- String scriptName2 = "probeScript2.stp";
- createScript(bot, scriptName2);
- editor = bot.activeEditor().toTextEditor();
- assertEquals(scriptName2, editor.getTitle());
- items[2].doubleClick();
- assertTrue(editor.getText().contains("probe " + items[2].getText() + ".*\n"));
- editor = bot.editorByTitle(scriptName).toTextEditor();
- assertFalse(editor.getText().contains("probe " + items[2].getText() + ".*\n"));
-
- // Switch to the non-stp editor, and add a probe. A dialog should appear
- // to let the user choose which of the open files to add to.
- editor = bot.editorByTitle("Untitled 1").toTextEditor();
- editor.show();
- items[3].doubleClick();
- shell = bot.shell(probeDialogTitle);
- shell.setFocus();
- SWTBotTable table = bot.table();
- assertTrue(table.containsItem(scriptName));
- assertTrue(table.containsItem(scriptName2));
- table.select(scriptName2);
- bot.button("OK").click();
- bot.waitUntil(Conditions.shellCloses(shell));
- editor = bot.activeEditor().toTextEditor();
- assertFalse(editor.getTitle().equals("Untitled 1"));
- assertTrue(editor.getText().contains("probe " + items[3].getText() + ".*\n"));
- }
-
- @Test
- public void testGraphErrors() {
- SWTBotShell shell = prepareScript("missingColumns.stp", null);
-
- SWTBotButton runButton = bot.button("Run");
- SWTBotButton addButton = bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton);
- SWTBotButton editButton = bot.button(Messages.SystemTapScriptGraphOptionsTab_EditGraphButton);
- SWTBotButton dupButton = bot.button(Messages.SystemTapScriptGraphOptionsTab_DuplicateGraphButton);
- SWTBotButton remButton = bot.button(Messages.SystemTapScriptGraphOptionsTab_RemoveGraphButton);
- String graphID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.scatterchartbuilder";
-
- // As soon as the Graphing tab is entered, no regular expression exists & nothing can be run.
- SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
- assertEquals("", combo.getText());
- assertFalse(runButton.isEnabled());
- assertFalse(addButton.isEnabled());
- combo.setText("(1)(2)");
- assertEquals("(1)(2)", combo.getText());
- assertTrue(runButton.isEnabled());
- assertTrue(addButton.isEnabled());
-
- setupGraphWithTests("Graph");
- assertTrue(runButton.isEnabled());
-
- // Removing groups from the regex disables graphs that rely on those groups.
- combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
- combo.setText("(1)");
- assertFalse(runButton.isEnabled());
- combo.setText("(1)(2)(3)");
- assertTrue(runButton.isEnabled());
-
- final SWTBotTable table = bot.table();
- table.select(0);
- dupButton.click();
- assertEquals(2, table.rowCount());
- assertTrue(runButton.isEnabled());
-
- combo.setText("(1)");
- assertFalse(runButton.isEnabled());
- for (int i = 0, n = table.rowCount(); i < n; i++) {
- String itemTitle = table.getTableItem(i).getText();
- assertTrue("Graph " + i + " should be invalid, but it's not: " + itemTitle,
- table.getTableItem(i).getText().contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraph));
- }
-
- setupGraphGeneral("Safe", 1, graphID, true);
- assertFalse(table.getTableItem(2).getText().contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraph));
- combo.setText("(1)(2)(3)");
- assertTrue(runButton.isEnabled());
-
- setupGraphGeneral("Unsafe", 3, graphID, true);
- assertTrue(runButton.isEnabled());
- combo.setText("(1)(2)");
- assertFalse(runButton.isEnabled());
- for (int i = 0, n = table.rowCount(); i < n; i++) {
- String itemTitle = table.getTableItem(i).getText();
- assertTrue("Graph " + i + " has incorrect validity: " + itemTitle,
- !itemTitle.contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraph)
- || itemTitle.contains("Unsafe"));
- }
-
- table.select(3);
- dupButton.click();
- remButton.click();
- assertTrue(!runButton.isEnabled());
-
- table.select(3);
- editButton.click();
- bot.waitUntil(Conditions.shellIsActive("Edit Graph"));
- SWTBotShell graphShell = bot.activeShell();
- SWTBotButton finishButton = bot.button("Finish");
- assertTrue(!finishButton.isEnabled());
- bot.comboBox("<Deleted>").setSelection("NA");
- finishButton.click();
- bot.waitUntil(Conditions.shellCloses(graphShell));
- shell.setFocus();
- assertTrue(runButton.isEnabled());
-
- // Perform tests when graphs have an invalid graphID.
- UIThreadRunnable.syncExec(new VoidResult() {
-
- @Override
- public void run() {
- GraphData gd = (GraphData) table.getTableItem(0).widget.getData();
- gd.graphID = "invalidID";
- table.getTableItem(0).widget.setData(gd);
- }
- });
-
- combo.setText(combo.getText().concat(" ")); // Just to refresh the dialog
- assertFalse(runButton.isEnabled());
- assertTrue(table.getTableItem(0).getText().contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraphID));
-
- table.select(0);
- dupButton.click();
- remButton.click();
- assertFalse(runButton.isEnabled());
- assertTrue(table.getTableItem(table.rowCount() - 1).getText().contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraphID));
-
- table.select(table.rowCount() - 1);
- editButton.click();
- bot.waitUntil(Conditions.shellIsActive("Edit Graph"));
- graphShell = bot.activeShell();
- finishButton = bot.button("Finish");
- assertFalse(finishButton.isEnabled());
- bot.radio(0).click();
- finishButton.click();
- bot.waitUntil(Conditions.shellCloses(graphShell));
- shell.setFocus();
- assertTrue(runButton.isEnabled());
-
- // Removing all invalid graphs should restore validity.
- combo.setText("(1)");
- assertFalse(runButton.isEnabled());
- for (int i = table.rowCount() - 1; i >= 0; i--) {
- if (table.getTableItem(i).getText().contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraph)) {
- table.select(i);
- remButton.click();
- }
- }
- assertTrue(runButton.isEnabled());
- while (table.rowCount() > 0) {
- table.select(0);
- remButton.click();
- }
-
- bot.button("Apply").click();
- }
-
- @Test
- public void testDeleteBlankRegex() {
- SWTBotShell shell = prepareScript("blank.stp", null);
-
- // Confirm that adding a new regex when the current one is blank has no effect.
- SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
- assertEquals(2, combo.itemCount());
- combo.setSelection(1);
- assertEquals(2, combo.itemCount());
- assertEquals(0, combo.selectionIndex());
-
- // Confirm that adding a regex works when the current regex is not empty.
- combo.setText("(a) b (c)");
- assertEquals("(a) b (c)", combo.getText());
- combo.setSelection(1);
- assertEquals(3, combo.itemCount());
- assertEquals(1, combo.selectionIndex());
-
- // Confirm that a blank regex is not removed when other data is not empty.
- combo.setText("(a)");
- bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton).click();
- bot.waitUntil(Conditions.shellIsActive("Create Graph"));
- SWTBotShell graphShell = bot.activeShell();
- graphShell.setFocus();
- bot.textWithLabel("Title:").setText("Test");
- bot.button("Finish").click();
- bot.waitUntil(Conditions.shellCloses(graphShell));
- shell.setFocus();
- combo.setText("");
- assertEquals("", combo.getText());
- combo.setSelection(0);
- assertEquals(3, combo.itemCount());
-
- // Confirm that auto-deleting a blank regex in the middle of the regex list works properly.
- combo.setSelection(2);
- assertEquals(4, combo.itemCount());
- combo.setText("sample");
- combo.setSelection(1);
- assertEquals(4, combo.itemCount());
- SWTBotTable table = bot.table();
- SWTBotButton remButton = bot.button(Messages.SystemTapScriptGraphOptionsTab_RemoveGraphButton);
- assertTrue(!remButton.isEnabled());
- table.select(0);
- assertTrue(remButton.isEnabled());
- remButton.click();
- assertTrue(!remButton.isEnabled());
- combo.setSelection(2);
- assertEquals(3, combo.itemCount());
- assertEquals("sample", combo.getText());
- assertEquals("(a) b (c)", combo.items()[0]);
- assertEquals("sample", combo.items()[1]);
-
- // Confirm that auto-deleting a regex from the beginning of the list works properly.
- combo.setSelection(2);
- combo.setText("another sample");
- combo.setSelection(0);
- combo.setText("");
- combo.setSelection(1);
- assertEquals(3, combo.itemCount());
- assertEquals("sample", combo.getText());
- assertEquals("sample", combo.items()[0]);
- assertEquals("another sample", combo.items()[1]);
- }
-
- @Test
- public void testGraphScript() {
- String scriptName = "testGraph.stp";
- createScript(bot, scriptName);
-
- // Write a script
- SWTBotEclipseEditor editor = bot.editorByTitle(scriptName).toTextEditor();
- editor.setText("#!/usr/bin/env stap"
- + "\nglobal i,j,k"
- + "\nprobe begin{i=0;j=0;k=0}"
- + "\nprobe timer.ms(100){printf(\"Value:%d %d\\n\",i,j);i++;j+=2}"
- + "\nprobe timer.ms(250){printf(\"Other:%d %d\\n\",i,k);k++}"
- + "\nprobe timer.ms(1000){exit()}");
- editor.save();
-
- final String val0 = "i";
- final String val1 = "j";
- final String val2 = "k";
-
- openRunConfigurations(scriptName);
- SWTBotShell shell = bot.shell("Run Configurations");
- shell.setFocus();
- bot.tree().select("SystemTap").contextMenu("New").click();
- bot.textWithLabel("Name:").setText(scriptName);
-
- // Select the "Graphing" tab.
- SWTBotCTabItem tab = bot.cTabItem(Messages.SystemTapScriptGraphOptionsTab_graphingTitle);
- tab.activate();
-
- // Enable output graphing.
- bot.checkBox(Messages.SystemTapScriptGraphOptionsTab_graphOutputRun).click();
- SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
- combo.setText("Value:(\\d+) (\\d+)");
- assertEquals("Value:(\\d+) (\\d+)", combo.getText());
-
- SWTBotText text = bot.textWithLabel(Messages.SystemTapScriptGraphOptionsTab_sampleOutputLabel);
- text.setText("Value:1 2");
- assertEquals("Value:1 2", text.getText());
-
- text = bot.text(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase, 1));
- text.setText(val0);
- assertEquals(val0, text.getText());
- text = bot.text(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase, 2));
- text.setText(val1);
- assertEquals(val1, text.getText());
-
- // Add a graph.
- setupGraphWithTests("Values");
- String setTitle1 = MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, 1);
- String graphTitle1 = "Values - Scatter Graph";
-
- // Make a second regex, and a graph for it.
- shell.setFocus();
- combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
- assertEquals(2, combo.itemCount());
- combo.setSelection(combo.selectionIndex() + 1);
- assertEquals(3, combo.itemCount());
- assertEquals("", combo.getText());
- combo.setText("Other:(\\d+) (\\d+)");
- assertEquals("Other:(\\d+) (\\d+)", combo.getText());
-
- text = bot.text(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase, 1));
- text.setText(val0);
- assertEquals(val0, text.getText());
- text = bot.text(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase, 2));
- text.setText(val2);
- assertEquals(val2, text.getText());
-
- text = bot.textWithLabel(Messages.SystemTapScriptGraphOptionsTab_sampleOutputLabel);
- assertEquals("", text.getText());
-
- setupGraphWithTests("Others");
- String setTitle2 = MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, 2);
- String graphTitle2 = "Others - Scatter Graph";
-
- // Apply the changes, then close the menu & reopen it to make sure settings were saved.
- shell.setFocus();
- bot.button("Apply").click();
- bot.button("Close").click();
- bot.waitUntil(Conditions.shellCloses(shell));
- openRunConfigurations(scriptName);
- shell = bot.shell("Run Configurations");
- shell.setFocus();
- shell.bot().text().setText(scriptName); // Set the filter text to show configs of the current script
- bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "SystemTap", scriptName));
- tab = bot.cTabItem(Messages.SystemTapScriptGraphOptionsTab_graphingTitle);
- tab.activate();
-
- combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
- text = bot.textWithLabel(Messages.SystemTapScriptGraphOptionsTab_sampleOutputLabel);
- SWTBotTable table = bot.table();
- assertEquals(3, combo.itemCount());
- assertEquals("Value:(\\d+) (\\d+)", combo.getText());
- assertEquals("Value:1 2", text.getText());
- assertEquals(1, table.rowCount());
- String graphName = GraphFactory.getGraphName("org.eclipse.linuxtools.systemtap.graphing.ui.charts.scatterchartbuilder");
- assertTrue(table.containsItem(graphName.concat(":Values")));
- combo.setSelection(1);
- assertEquals("Other:(\\d+) (\\d+)", combo.getText());
- assertEquals("", text.getText());
- assertEquals(1, table.rowCount());
- assertTrue(table.containsItem(graphName.concat(":Others")));
-
- // If Systemtap is not installed, don't test graph output. Otherwise, do.
- if (!stapInstalled) {
- return;
- }
-
- bot.button("Run").click();
- bot.waitUntil(Conditions.shellCloses(shell));
- SWTBotView console = bot.viewById("org.eclipse.ui.console.ConsoleView");
- console.setFocus();
- bot.waitUntil(new StapHasExited()); // The script should end on its own
-
- // Give time for the table to be fully constructed.
- SWTBotEditor graphEditor = bot.activeEditor();
- bot.waitUntil(new TableHasUpdated(scriptName, 1, 10, false));
- bot.waitUntil(new TableHasUpdated(scriptName, 2, 4, false));
-
- // Test table & graph contents.
- graphEditor.setFocus();
- graphEditor.bot().cTabItem(setTitle1).activate();
- graphEditor.bot().cTabItem("Data View").activate();
- SWTBotTable dataTable = bot.table();
- List<String> colNames = dataTable.columns();
- assertEquals(3, colNames.size());
- assertEquals(val0, colNames.get(1));
- assertEquals(val1, colNames.get(2));
- assertEquals("2", dataTable.cell(2, 1));
- assertEquals("4", dataTable.cell(2, 2));
-
- graphEditor.bot().cTabItem(graphTitle1).activate();
- Matcher<AbstractChartBuilder> matcher = widgetOfType(AbstractChartBuilder.class);
- AbstractChartBuilder cb = bot.widget(matcher);
- ISeries[] series = cb.getChart().getSeriesSet().getSeries();
- assertEquals(2, series.length);
- assertEquals(10, series[0].getXSeries().length);
- assertEquals(10, series[1].getXSeries().length);
- assertEquals(2, (int) series[0].getYSeries()[2]);
- assertEquals(4, (int) series[1].getYSeries()[2]);
-
- graphEditor.bot().cTabItem(setTitle2).activate();
- graphEditor.bot().cTabItem("Data View").activate();
- dataTable = bot.table();
- colNames = dataTable.columns();
- assertEquals(3, colNames.size());
- assertEquals(val0, colNames.get(1));
- assertEquals(val2, colNames.get(2));
- assertEquals("7", dataTable.cell(2, 1));
- assertEquals("2", dataTable.cell(2, 2));
-
- graphEditor.bot().cTabItem(graphTitle2).activate();
- cb = bot.widget(matcher);
- series = cb.getChart().getSeriesSet().getSeries();
- assertEquals(2, series.length);
- assertEquals(4, series[0].getXSeries().length);
- assertEquals(4, series[1].getXSeries().length);
- assertEquals(7, (int) series[0].getYSeries()[2]);
- assertEquals(2, (int) series[1].getYSeries()[2]);
-
- // Test filters on the data table & graphs.
- graphEditor.bot().cTabItem(setTitle1).activate();
- graphEditor.bot().cTabItem("Data View").activate();
- dataTable = bot.table();
- click(ContextMenuHelper.contextMenu(dataTable, "Add filter..."));
- shell = bot.shell("Create Filter");
- shell.setFocus();
-
- // Match Filter - Remove a matching
- bot.button("Match Filter").click();
- bot.button("Next >").click();
- bot.text().setText("2");
- deselectDefaultSelection(0);
- bot.radio(1).click();
- bot.button("Finish").click();
- bot.waitUntil(Conditions.shellCloses(shell));
- bot.waitUntil(new TableHasUpdated(scriptName, 1, 9, true));
- assertEquals("3", dataTable.cell(2, 1));
- assertEquals("6", dataTable.cell(2, 2));
-
- // Filters should be applied to graphs as well as data tables.
- graphEditor.bot().cTabItem(graphTitle1).activate();
- cb = bot.widget(matcher);
- series = cb.getChart().getSeriesSet().getSeries();
- bot.waitUntil(new ChartHasUpdated(cb.getChart(), 9));
- assertEquals(3, (int) series[0].getYSeries()[2]);
- assertEquals(6, (int) series[1].getYSeries()[2]);
-
- // Each graph set should have its own filters.
- graphEditor.bot().cTabItem(setTitle2).activate();
- graphEditor.bot().cTabItem("Data View").activate();
- dataTable = bot.table();
- assertEquals(4, dataTable.rowCount());
- assertEquals("2", dataTable.cell(0, 1));
-
- // Test removing a filter.
- graphEditor.bot().cTabItem(setTitle1).activate();
- graphEditor.bot().cTabItem("Data View").activate();
- dataTable = bot.table();
- click(ContextMenuHelper.contextMenu(dataTable, "Remove filter...", "Match Filter: \"" + val0 + "\" removing \"2\""));
- bot.waitUntil(new TableHasUpdated(scriptName, 1, 10, true));
- assertEquals("2", dataTable.cell(2, 1));
- assertEquals("4", dataTable.cell(2, 2));
-
- clearAllTerminated();
- }
-
- @Test
- public void testGenerateFromPrintf() {
- SWTBotShell shell = prepareScript("testGenerates.stp", "#!/usr/bin/env stap"
- + "\nglobal i,j,k,a"
- + "\nprobe begin{i=0;j=5;k=20;a=65}"
- + "\n#probe begin{printf(\"%1b%1b%1blo %1b%1brld\\n\", 72,101,108,87,111)}"
- + "\nprobe timer.ms(100){printf(\"%5i|\\n%10.5d|\\n%-10.5i|\\n%05c\\n\",i,j,k,a);i++;j+=5;k+=20;a++}"
- + "\n//printf(\"this is a comment\\n\");"
- + "\n/*printf(\"this is a...\\n\");"
- + "\nprintf(\"...multiline comment\\n\");*/"
- + "\nprobe begin{b = sprintf(\"Here\"); printf(\"-->%s<--\\n\", b)}"
- + "\nprobe timer.ms(100){printf(\"%x - %#x - %#X\\n\",i,i,i);}"
- + "\nprobe timer.ms(100){printf(\"%o - %#o\\n\",i,i);}"
- + "\nprobe begin{printf(\"%1b-\\\\n-%p\\n\", 65, 0x8000000002345678)}");
-
- // Generate regexs.
- bot.button(Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsButton).click();
-
- SWTBotShell dialogShell = bot.shell(Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsTitle);
- dialogShell.setFocus();
- bot.button("Yes").click();
- bot.waitUntil(Conditions.shellCloses(dialogShell));
- shell.setFocus();
-
- SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
- assertEquals(9, combo.itemCount()); // One extra entry for "Add New Regex"
-
- String[] expectedRegexs = new String[]{
- " {0,4}(-?\\d+)\\|",
- " {0,9}(-?\\d+)\\|",
- "(-?\\d+) {0,9}\\|",
- " {0,4}(.)",
- "-->(.+)<--",
- "([a-f0-9]+) - (0x[a-f0-9]+) - (0X[A-F0-9]+)",
- "(\\d+) - (0\\d+)",
- "(.)-\\\\n-(0x[a-f0-9]+)",
- Messages.SystemTapScriptGraphOptionsTab_regexAddNew
- };
- for (int i = 0, n = combo.itemCount(); i < n; i++) {
- assertEquals(expectedRegexs[i], combo.items()[i]);
- }
- bot.button("Apply").click();
- }
-
- @Test
- public void testLabelledGraphScript() {
- // TODO If Systemtap is not installed, nothing can be graphed, so don't bother performing this test.
- // Once the ability to read in pre-saved chart data is restored, this test can be run with sample data.
- assumeTrue(stapInstalled);
-
- String scriptName = "testLabels.stp";
- SWTBotShell shell = prepareScript(scriptName, "#!/usr/bin/env stap"
- + "\nprobe begin{"
- + "\nprintf(\"Apples: 2 14 16\\n\");"
- + "\nprintf(\"1: 1 2 3\\n\");"
- + "\nprintf(\"Bananas (2): 10 10 10\\n\");"
- + "\nprintf(\"Cherries: 10 20 30\\n\");"
- + "\nprintf(\"2: 2 4 6\\n\");"
- + "\nprintf(\"Apples: 12 5 16\\n\");"
- + "\nprintf(\"Bananas: 0 1 0\\n\");"
- + "\nprintf(\"3: 3 6 9\\n\");"
- + "\nprintf(\"Dates: 12 5 16\\n\");"
- + "\nprintf(\"Bananas: 2 1 2\\n\");"
- + "\nprintf(\"4: 4 8 12\\n\");"
- + "\nprintf(\"Apples: 12 5 16\\n\");"
- + "\nprintf(\"Bananas (2): 3 1 3\\n\");"
- + "\nexit();}");
- int numItems = 13;
- int numNumberItems = 4;
- int numCategories = 3;
-
- // Enter a regex.
- SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
- SWTBotButton button = bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton);
- assertFalse(button.isEnabled());
- combo.setText("(.*): (\\d+) (\\d+) (\\d+)");
-
- // Add bar, pie, and line graphs that use the same column data.
- String title = "Fruit Info";
- setupGraphGeneral(title, 4, "org.eclipse.linuxtools.systemtap.graphing.ui.charts.barchartbuilder", false);
- setupGraphGeneral(title, 4, "org.eclipse.linuxtools.systemtap.graphing.ui.charts.piechartbuilder", false);
- setupGraphGeneral(title, 4, "org.eclipse.linuxtools.systemtap.graphing.ui.charts.linechartbuilder", false);
-
- bot.button("Run").click();
- bot.waitUntil(Conditions.shellCloses(shell));
- SWTBotView console = bot.viewById("org.eclipse.ui.console.ConsoleView");
- console.setFocus();
- bot.waitUntil(new StapHasExited()); // The script should end on its own
-
- // Give time for the table to be fully constructed.
- SWTBotEditor graphEditor = bot.activeEditor();
- bot.waitUntil(new TableHasUpdated(scriptName, 1, numItems, false));
-
- // Confirm that the bar & pie charts display the String categories, but the line chart ignores them.
- String titleBar = title + " - Bar Graph";
- String titlePie = title + " - Pie Chart";
- String titleLine = title + " - Line Graph";
- graphEditor.bot().cTabItem(titleLine).activate();
- Matcher<AbstractChartBuilder> matcher = widgetOfType(AbstractChartBuilder.class);
- AbstractChartBuilder cb = bot.widget(matcher);
- assertEquals(numNumberItems, cb.getChart().getSeriesSet().getSeries()[0].getXSeries().length);
-
- graphEditor.bot().cTabItem(titlePie).activate();
- cb = bot.widget(matcher);
- assertEquals(numItems, cb.getChart().getSeriesSet().getSeries().length);
-
- graphEditor.bot().cTabItem(titleBar).activate();
- cb = bot.widget(matcher);
- assertEquals(numItems, cb.getChart().getSeriesSet().getSeries()[0].getXSeries().length);
-
- // Test graph scaling & scrolling
- discreteXControlTests(cb, numItems); //Bar Chart
- continuousControlTests(cb, false);
- graphEditor.bot().cTabItem(titlePie).activate();
- cb = bot.widget(matcher);
- discreteXControlTests(cb, numCategories);
- graphEditor.bot().cTabItem(titleLine).activate();
- cb = bot.widget(matcher);
- continuousControlTests(cb, true);
- continuousControlTests(cb, false);
-
- clearAllTerminated();
- }
-
- private void discreteXControlTests(AbstractChartBuilder cb, int numAxisItems) {
- // Check that default range shows 100% of data.
- IAxis axis = cb.getChart().getAxisSet().getXAxis(0);
- Range range = axis.getRange();
- double scale = cb.getScale();
- double scroll = cb.getScroll();
- assertTrue(range.upper - range.lower == axis.getCategorySeries().length - 1 && range.upper - range.lower == numAxisItems - 1);
- assertTrue(scale == 1.0 && scroll == 1.0);
-
- // Check that scroll buttons are disabled at 100% range.
- SWTBotButton firstButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_First);
- SWTBotButton leftButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_Left);
- SWTBotButton rightButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_Right);
- SWTBotButton lastButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_Last);
- assertFalse(firstButton.isEnabled());
- assertFalse(leftButton.isEnabled());
- assertFalse(rightButton.isEnabled());
- assertFalse(lastButton.isEnabled());
-
- // Test zooming in. The amount of zoom is arbitrary for this test--just make sure zooming happened.
- SWTBotButton zoomInButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_ZoomIn);
- SWTBotButton zoomOutButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_ZoomOut);
- SWTBotButton allButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_All);
- assertTrue(zoomInButton.isEnabled());
- assertFalse(zoomOutButton.isEnabled());
- assertFalse(allButton.isEnabled());
- zoomInButton.click();
- assertTrue(zoomOutButton.isEnabled());
- assertTrue(allButton.isEnabled());
-
- // By default, zooming in should zoom in on the end of the axis (newest data).
- range = axis.getRange();
- assertTrue(range.upper == numAxisItems - 1 && range.lower > 0 && cb.getScale() < scale && cb.getScroll() == 1.0);
-
- // Left scrolling should now be enabled.
- assertTrue(firstButton.isEnabled());
- assertTrue(leftButton.isEnabled());
- assertFalse(rightButton.isEnabled());
- assertFalse(lastButton.isEnabled());
-
- // Test scrolling left. Again, the specific amount is arbitrary, just make sure scrolling happened.
- leftButton.click();
- range = axis.getRange();
- assertTrue(range.upper < numAxisItems - 1 && cb.getScroll() < scroll);
- int rstore = (int) range.lower;
- assertTrue(rightButton.isEnabled());
- assertTrue(lastButton.isEnabled());
-
- // Zooming out should bring the range back to 100%.
- zoomOutButton.click();
- range = axis.getRange();
- assertTrue(range.upper - range.lower == numAxisItems - 1 && cb.getScale() == 1.0 && cb.getScroll() < scroll);
- assertTrue(zoomInButton.isEnabled());
- assertFalse(zoomOutButton.isEnabled());
- assertFalse(allButton.isEnabled());
- assertFalse(firstButton.isEnabled());
- assertFalse(leftButton.isEnabled());
- assertFalse(rightButton.isEnabled());
- assertFalse(lastButton.isEnabled());
-
- // For convenience, zooming out after having scrolled somewhere should make zooming in
- // zoom back to the area that was scrolled to.
- scroll = cb.getScroll();
- zoomInButton.click();
- assertTrue(rstore == axis.getRange().lower && scroll == cb.getScroll());
-
- // Scrolling right should take the range back to the end of the axis.
- rightButton.click();
- range = axis.getRange();
- assertTrue(range.upper == numAxisItems - 1 && range.lower > 0 && cb.getScroll() > scroll);
- assertTrue(firstButton.isEnabled());
- assertTrue(leftButton.isEnabled());
- assertFalse(rightButton.isEnabled());
- assertFalse(lastButton.isEnabled());
-
- // Zoom in as much as possible (range should show only one item),
- // and step right/left. Add a loop limit for safety.
- for (int i = 0; i < numAxisItems; i++) {
- range = axis.getRange();
- if (range.upper == range.lower) {
- break;
- }
- zoomInButton.click();
- }
- range = axis.getRange();
- assertTrue(range.upper == range.lower && range.upper == numAxisItems - 1);
- assertTrue(!zoomInButton.isEnabled());
- for (int i = 0; i < numAxisItems; i++) {
- if (axis.getRange().lower == 0) {
- break;
- }
- leftButton.click();
- assertTrue(axis.getRange().lower < range.lower);
- range = axis.getRange();
- assertEquals(range.lower, range.upper, 0.0);
- }
- assertEquals(axis.getRange().lower, 0, 0.0);
- for (int i = 0; i < numAxisItems; i++) {
- if (axis.getRange().upper == numAxisItems - 1) {
- break;
- }
- rightButton.click();
- assertTrue(axis.getRange().upper > range.upper);
- range = axis.getRange();
- assertEquals(range.lower, range.upper, 0.0);
- }
- assertEquals(axis.getRange().upper, numAxisItems - 1, 0);
-
- firstButton.click();
- assertEquals(axis.getRange().lower, 0, 0);
- assertFalse(firstButton.isEnabled());
- assertFalse(leftButton.isEnabled());
- assertTrue(rightButton.isEnabled());
- assertTrue(lastButton.isEnabled());
-
- lastButton.click();
- assertEquals(axis.getRange().upper, numAxisItems - 1, 0);
- assertTrue(firstButton.isEnabled());
- assertTrue(leftButton.isEnabled());
- assertFalse(rightButton.isEnabled());
- assertFalse(lastButton.isEnabled());
- }
-
- private double getAxisScale(AbstractChartBuilder cb, boolean isXAxis) {
- return isXAxis ? cb.getScale() : cb.getScaleY();
- }
-
- private double getAxisScroll(AbstractChartBuilder cb, boolean isXAxis) {
- return isXAxis ? cb.getScroll() : cb.getScrollY();
- }
-
- private void continuousControlTests(AbstractChartBuilder cb, boolean isXAxis) {
- // Continuous scaling/scrolling is less strict/predictable than discrete scrolling,
- // so just check that the controls perform their intended actions.
- IAxis axis;
- SWTBotButton zoomInButton, zoomOutButton;
- SWTBotScale zoomScale;
- SWTBotSlider scrollBar;
- int flipSign;
- if (isXAxis) {
- axis = cb.getChart().getAxisSet().getXAxis(0);
- zoomInButton = bot.buttonWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousXControl_ZoomInTooltip);
- zoomOutButton = bot.buttonWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousXControl_ZoomOutTooltip);
- zoomScale = bot.scaleWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousXControl_ScaleMessage);
- scrollBar = bot.sliderWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousXControl_ScrollMessage);
- flipSign = 1;
- } else {
- axis = cb.getChart().getAxisSet().getYAxis(0);
- zoomInButton = bot.buttonWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousYControl_ZoomInTooltip);
- zoomOutButton = bot.buttonWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousYControl_ZoomOutTooltip);
- zoomScale = bot.scaleWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousYControl_ScaleMessage);
- scrollBar = bot.sliderWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousYControl_ScrollMessage);
- flipSign = -1;
- }
- double scale = getAxisScale(cb, isXAxis);
- double scroll = getAxisScroll(cb, isXAxis);
- int thumb = scrollBar.getThumb();
-
- // Default range should be 100%, so zooming out shouldn't have an effect yet.
- assertEquals(scale, 1.0, 0);
- int zoomValue = zoomScale.getValue();
- Range range = axis.getRange();
- zoomOutButton.click();
- Range range2 = axis.getRange();
- assertTrue(range.upper == range2.upper && range.lower == range2.lower && zoomScale.getValue() == zoomValue && getAxisScale(cb, isXAxis) == scale && scrollBar.getThumb() == thumb);
-
- // Zoom in & back out with the zoom buttons.
- zoomInButton.click();
- range2 = axis.getRange();
- assertTrue(range2.upper - range2.lower < range.upper - range.lower && flipSign * (zoomScale.getValue() - zoomValue) > 0 && getAxisScale(cb, isXAxis) < scale && scrollBar.getThumb() < thumb);
- zoomOutButton.click();
- range2 = axis.getRange();
- assertTrue(range.upper == range2.upper && range.lower == range2.lower && zoomScale.getValue() == zoomValue && getAxisScale(cb, isXAxis) == scale && scrollBar.getThumb() == thumb);
-
- // Zoom in with the Scale control.
- int controlRange = zoomScale.getMaximum() - zoomScale.getMinimum();
- zoomScale.setValue(zoomScale.getValue() + controlRange / 2 * flipSign);
- // Note: the charts need some time to be updated after using the scale/slider controls.
- // Sleeping for a brief moment is faster than using a bot wait condition.
- bot.sleep(100);
- range2 = axis.getRange();
- assertTrue(range2.upper - range2.lower < range.upper - range.lower && getAxisScale(cb, isXAxis) < scale && scrollBar.getThumb() < thumb);
-
- range = range2;
- thumb = scrollBar.getThumb();
- scale = getAxisScale(cb, isXAxis);
- zoomScale.setValue(zoomScale.getValue() - controlRange / 4 * flipSign);
- bot.sleep(100);
- range2 = axis.getRange();
- assertTrue(range2.upper - range2.lower > range.upper - range.lower && getAxisScale(cb, isXAxis) > scale && scrollBar.getThumb() > thumb);
-
- // Test scrolling. Don't assume an initial scroll position, as it may be changed
- // in future versions (it's more likely to change than default zoom, at least).
- thumb = scrollBar.getThumb();
- controlRange = scrollBar.getMaximum() - scrollBar.getThumb() - scrollBar.getMinimum();
- scrollBar.setSelection(controlRange / 2);
- bot.sleep(100);
- assertEquals(scrollBar.getThumb(), thumb);
-
- // Scroll towards origin.
- range = axis.getRange();
- scrollBar.setSelection(scrollBar.getSelection() - controlRange / 4 * flipSign);
- bot.sleep(100);
- range2 = axis.getRange();
- assertTrue(range2.upper - range2.lower == range.upper - range.lower && range2.upper < range.upper && getAxisScroll(cb, isXAxis) < scroll);
-
- // Scroll away from origin.
- range = range2;
- scroll = getAxisScroll(cb, isXAxis);
- scrollBar.setSelection(scrollBar.getSelection() + controlRange / 8 * flipSign);
- bot.sleep(100);
- range2 = axis.getRange();
- assertTrue(range2.upper - range2.lower == range.upper - range.lower && range2.upper > range.upper && getAxisScroll(cb, isXAxis) > scroll);
- }
-
- @Test
- public void testGraphTooltips() {
- // TODO If Systemtap is not installed, nothing can be graphed, so don't bother performing this test.
- // Once the ability to read in pre-saved chart data is restored, this test can be run with sample data.
- assumeTrue(stapInstalled);
-
- String scriptName = "testGraphTooltips.stp";
- SWTBotShell shell = prepareScript(scriptName, "#!/usr/bin/env stap"
- + "\nglobal y"
- + "\nprobe begin{y=5}"
- + "\nprobe timer.ms(1000){printf(\"%d\\n\",y);y++}"
- + "\nprobe timer.ms(5000){exit()}");
-
- // Enter a regex.
- SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
- assertFalse(bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton).isEnabled());
- combo.setText("(\\d+)");
-
- // Add bar, pie, and line graphs that use the same column data.
- String title = "Info";
- setupGraphGeneral(title, 1, "org.eclipse.linuxtools.systemtap.graphing.ui.charts.linechartbuilder", true);
- setupGraphGeneral(title, 1, "org.eclipse.linuxtools.systemtap.graphing.ui.charts.barchartbuilder", true);
-
- bot.button("Run").click();
- bot.waitUntil(Conditions.shellCloses(shell));
-
- // Perform mouse hover tests on graphs as they are being updated
- SWTBotEditor graphEditor = TestCreateSystemtapScript.bot.editorByTitle(scriptName.concat(" Graphs"));
- graphEditor.setFocus();
- graphEditor.bot().cTabItem("Info - Bar Graph").activate();
- final Matcher<AbstractChartBuilder> matcher = widgetOfType(AbstractChartBuilder.class);
- AbstractChartBuilder cb = bot.widget(matcher);
- bot.waitUntil(new ChartHasUpdated(cb.getChart(), 1));
- String tooltipFormat = "{0}: {1}";
- checkTooltipAtDataPoint(cb, 0, 0, new Point(0, 20), MessageFormat.format(tooltipFormat, "Column 1", "5"), true);
-
- graphEditor.bot().cTabItem("Info - Line Graph").activate();
- cb = bot.widget(matcher);
- bot.waitUntil(new ChartHasUpdated(cb.getChart(), 2));
- tooltipFormat = "Series: {0}\nx: {1}\ny: {2}";
- checkTooltipAtDataPoint(cb, 0, 1, null, MessageFormat.format(tooltipFormat, "Column 1", "2", "6"), true);
-
- // The tooltip should disappear when a point moves away from the mouse, without need for mouse movement.
- bot.waitUntil(new ChartHasUpdated(cb.getChart(), -1));
- checkTooltipAtDataPoint(cb, 0, -1, null, MessageFormat.format(tooltipFormat, "Column 1", "2", "6"), false);
-
- ScriptConsole.stopAll();
- bot.waitUntil(new StapHasExited());
- clearAllTerminated();
- }
-
- /**
- * May move the mouse to a desired data point on a chart and test for the tooltip that appears.
- * @param cb The AbstractChartBuilder containing the chart to test.
- * @param series The index of the data series to hover over.
- * @param dataPoint The data point of the series to move the mouse to. Set this to -1
- * or less if the mouse should stay where it is.
- * @param adjustment Move the mouse's x & y coordinates by the values of this Point,
- * or set this to <code>null</code> to make no adjustment.
- * @param expectedTooltip The expected contents of the tooltip.
- * @param shellShouldExist Set to <code>false</code> if the tooltip should not be found.
- */
- private void checkTooltipAtDataPoint(final AbstractChartBuilder cb, final int series,
- final int dataPoint, final Point adjustment, final String expectedTooltip,
- final boolean shellShouldExist) {
- if (dataPoint >= 0) {
- UIThreadRunnable.syncExec(new VoidResult() {
-
- @Override
- public void run() {
- Event event = new Event();
- event.type = SWT.MouseMove;
- Point mousePoint = cb.getChart().getPlotArea().toDisplay(
- cb.getChart().getSeriesSet().getSeries()[0].getPixelCoordinates(dataPoint));
- event.x = mousePoint.x + (adjustment != null ? adjustment.x : 0);
- event.y = mousePoint.y + (adjustment != null ? adjustment.y : 0);
- bot.getDisplay().post(event);
- }
- });
- }
-
- bot.sleep(100); // Give some time for the tooltip to appear/change
- UIThreadRunnable.syncExec(new VoidResult() {
-
- @Override
- public void run() {
- for (SWTBotShell bshell : bot.shells()) {
- Control[] children = bshell.widget.getChildren();
- if (children.length == 1 && children[0] instanceof Text && expectedTooltip.equals(((Text) children[0]).getText())) {
- if (!shellShouldExist) {
- throw new AssertionError("Did not expect to find this tooltip, but found it: " + expectedTooltip);
- }
- return;
- }
- }
- if (shellShouldExist) {
- throw new AssertionError("Didn't find the expected tooltip: " + expectedTooltip);
- }
- }
- });
- }
-
- private void openRunConfigurations(String scriptName) {
- // Focus on project explorer view.
- projectExplorer.setFocus();
- projectExplorer.bot().tree().select(scriptName);
- bot.menu("Run").menu("Run Configurations...").click();
- }
-
- private void setupGraphWithTests(String title) {
- SWTBotShell firstShell = bot.activeShell();
-
- bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton).click();
- SWTBotShell shell = bot.shell("Create Graph");
- shell.setFocus();
-
- SWTBotText text = bot.textWithLabel("Title:");
- text.setText(title);
- assertEquals(title, text.getText());
-
- SWTBotCombo comboX = bot.comboBoxWithLabel("X Series:");
- assertEquals(3, comboX.itemCount()); // X Series includes "Row Num" as a selection
- SWTBotCombo comboY0 = bot.comboBoxWithLabel("Y Series 0:");
- assertEquals(2, comboY0.itemCount()); // Y Series 0 only includes series entries
- comboY0.setSelection(0);
- SWTBotCombo comboY1 = bot.comboBoxWithLabel("Y Series 1:");
- assertEquals(3, comboY1.itemCount()); // Y Series (i>0) has extra "NA" option as first entry
- comboY1.setSelection(1);
- assertFalse(bot.button("Finish").isEnabled()); // Don't allow duplicate selections
- comboY1.setSelection(2);
- bot.button("Finish").click();
-
- bot.waitUntil(Conditions.shellCloses(shell));
- firstShell.setFocus();
- }
-
- private void setupGraphGeneral(String title, int numItems, String graphID, boolean useRowNum) {
- int offset = useRowNum ? 0 : 1;
- SWTBotShell firstShell = bot.activeShell();
-
- bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton).click();
- SWTBotShell shell = bot.shell("Create Graph");
- shell.setFocus();
-
- deselectDefaultSelection(0);
- bot.radioWithTooltip(GraphFactory.getGraphName(graphID) + "\n\n" +
- GraphFactory.getGraphDescription(graphID)).click();
-
- SWTBotText text = bot.textWithLabel("Title:");
- text.setText(title);
-
- bot.comboBoxWithLabel("X Series:").setSelection(offset);
- bot.comboBoxWithLabel("Y Series 0:").setSelection(offset);
- for (int i = 1; i < numItems - offset; i++) {
- bot.comboBoxWithLabel(MessageFormat.format("Y Series {0}:", i)).setSelection(i + 1 + offset);
- }
- if (!useRowNum) {
- bot.comboBoxWithLabel(MessageFormat.format("Y Series {0}:", numItems - 1)).setSelection(0);
- }
- bot.button("Finish").click();
- bot.waitUntil(Conditions.shellCloses(shell));
- firstShell.setFocus();
- }
-
- /**
- * Deselects a radio button.
- * Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=344484
- * @param currSelection The index of the radiobutton to deselect
- */
- private void deselectDefaultSelection(final int currSelection) {
- UIThreadRunnable.syncExec(new VoidResult() {
- @Override
- public void run() {
- @SuppressWarnings("unchecked")
- Matcher<Widget> matcher = allOf(widgetOfType(Button.class), withStyle(SWT.RADIO, "SWT.RADIO"));
- Button b = (Button) bot.widget(matcher, currSelection);
- b.setSelection(false);
- }
- });
- }
-
- public static void click(final MenuItem menuItem) {
- final Event event = new Event();
- event.time = (int) System.currentTimeMillis();
- event.widget = menuItem;
- event.display = menuItem.getDisplay();
- event.type = SWT.Selection;
-
- UIThreadRunnable.asyncExec(menuItem.getDisplay(), new VoidResult() {
- @Override
- public void run() {
- menuItem.notifyListeners(SWT.Selection, event);
- }
- });
- }
+ private static final String SYSTEMTAP_PROJECT_NAME = "SystemtapTest";
+
+ private static SWTWorkbenchBot bot;
+ private static boolean stapInstalled;
+ private static SWTBotView projectExplorer;
+
+
+ private static class NodeAvailableAndSelect extends DefaultCondition {
+
+ private SWTBotTree tree;
+ private String parent;
+ private String node;
+
+ /**
+ * Wait for a tree node (with a known parent) to become visible, and select it
+ * when it does. Note that this wait condition should only be used after having
+ * made an attempt to reveal the node.
+ * @param tree The SWTBotTree that contains the node to select.
+ * @param parent The text of the parent node that contains the node to select.
+ * @param node The text of the node to select.
+ */
+ NodeAvailableAndSelect(SWTBotTree tree, String parent, String node) {
+ this.tree = tree;
+ this.node = node;
+ this.parent = parent;
+ }
+
+ @Override
+ public boolean test() {
+ try {
+ SWTBotTreeItem parentNode = tree.getTreeItem(parent);
+ parentNode.getNode(node).select();
+ return true;
+ } catch (WidgetNotFoundException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return "Timed out waiting for " + node; //$NON-NLS-1$
+ }
+ }
+
+ private static class TreePopulated extends DefaultCondition {
+
+ private SWTBotTree parent;
+
+ TreePopulated(SWTBotTree parent) {
+ this.parent = parent;
+ }
+
+ @Override
+ public boolean test() {
+ return this.parent.getAllItems().length > 0;
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return "Timed out waiting for tree to populate.";
+ }
+ }
+
+ private static class TreeItemPopulated extends DefaultCondition {
+
+ private SWTBotTreeItem parent;
+
+ TreeItemPopulated(SWTBotTreeItem parent) {
+ this.parent = parent;
+ }
+
+ @Override
+ public boolean test() {
+ return this.parent.getItems().length > 0;
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return "Timed out waiting for tree to populate.";
+ }
+ }
+
+ private static class ConsoleIsReady extends DefaultCondition {
+
+ private String scriptName;
+ public ConsoleIsReady(String scriptName) {
+ this.scriptName = scriptName;
+ }
+
+ @Override
+ public boolean test() {
+ SWTBotView console = TestCreateSystemtapScript.bot.viewById("org.eclipse.ui.console.ConsoleView");
+ console.setFocus();
+ return console.bot().label().getText().contains(scriptName);
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return "Timed out waiting for console to appear";
+ }
+
+ }
+
+ private static class StapHasExited extends DefaultCondition {
+
+ @Override
+ public boolean test() {
+ SWTBotView console = TestCreateSystemtapScript.bot.viewById("org.eclipse.ui.console.ConsoleView");
+ console.setFocus();
+ return (!console.toolbarButton("Stop Script").isEnabled());
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return "Timed out waiting for stap to exit";
+ }
+ }
+
+ private static class TableHasUpdated extends DefaultCondition {
+
+ private String scriptName;
+ private int graphSetNum;
+ private int expectedRows;
+ private boolean exact;
+ /**
+ * Wait for the provided GraphSelectorEditor to be fully updated.
+ * Note that using this will set focus to the Data View tab of the specified graph set.
+ * @param scriptName The name of the script that is being graphed.
+ * @param graphSetNum Which graph set to focus on & watch for updates.
+ * @param expectedRows How many entries/rows are expected to be in the table when it's fully updated.
+ * @param exact Set this to <code>true</code> if the number of graph columns should exactly match the
+ * expected amount, or <code>false</code> if it may be greater than the expected amount.
+ */
+ public TableHasUpdated(String scriptName, int graphSetNum, int expectedRows, boolean exact) {
+ this.scriptName = scriptName;
+ this.graphSetNum = graphSetNum;
+ this.expectedRows = expectedRows;
+ this.exact = exact;
+ }
+ @Override
+ public boolean test() {
+ SWTBotEditor graphEditor = TestCreateSystemtapScript.bot.editorByTitle(scriptName.concat(" Graphs"));
+ graphEditor.setFocus();
+ graphEditor.bot().cTabItem(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, graphSetNum)).activate();
+ graphEditor.bot().cTabItem("Data View").activate();
+ if (!exact) {
+ return bot.table().rowCount() >= expectedRows;
+ } else {
+ return bot.table().rowCount() == expectedRows;
+ }
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return "Timed out waiting for data table to update";
+ }
+ }
+
+ private static class ChartHasUpdated extends DefaultCondition {
+
+ private Chart chart;
+ int oldCount;
+ int expectedCount;
+ /**
+ * Wait for the provided chart to become updated.
+ * @param chart The chart to watch for an update.
+ * @param expectedCount The expected number of series points. Set to -1 to instead
+ * check for when there are more points than there were at the beginning.
+ */
+ public ChartHasUpdated(Chart chart, int expectedCount) {
+ this.chart = chart;
+ ISeries[] seriesSet = chart.getSeriesSet().getSeries();
+ this.oldCount = seriesSet.length > 0 ? seriesSet[0].getXSeries().length : 0;
+ this.expectedCount = expectedCount;
+ }
+ @Override
+ public boolean test() {
+ ISeries[] seriesSet = chart.getSeriesSet().getSeries();
+ int newCount = seriesSet.length > 0 ? seriesSet[0].getXSeries().length : 0;
+ return expectedCount < 0 ? newCount > oldCount : newCount == expectedCount;
+ }
+
+ @Override
+ public String getFailureMessage() {
+ return "Timed out waiting for chart to update";
+ }
+
+ }
+
+ @BeforeClass
+ public static void beforeClass() {
+ bot = new SWTWorkbenchBot();
+ stapInstalled = true;
+
+ // Dismiss "Systemtap not installed" dialog(s) if present.
+ try {
+ SWTBotShell shell = bot.shell("Cannot Run SystemTap").activate();
+ stapInstalled = false;
+ shell.close();
+
+ shell = bot.shell("Cannot Run SystemTap").activate();
+ shell.close();
+ } catch (WidgetNotFoundException e) {
+ //ignore
+ }
+
+ try {
+ bot.viewByTitle("Welcome").close();
+ // hide Subclipse Usage stats popup if present/installed
+ bot.shell("Subclipse Usage").activate();
+ bot.button("Cancel").click();
+ } catch (WidgetNotFoundException e) {
+ //ignore
+ }
+
+ // Set SystemTap IDE perspective.
+ bot.perspectiveByLabel("SystemTap IDE").activate();
+ bot.sleep(500);
+ for (SWTBotShell sh : bot.shells()) {
+ if (sh.getText().startsWith("SystemTap IDE")) {
+ sh.activate();
+ bot.sleep(500);
+ break;
+ }
+ }
+
+ // Create a Systemtap project.
+ SWTBotMenu fileMenu = bot.menu("File");
+ SWTBotMenu newMenu = fileMenu.menu("New");
+ SWTBotMenu projectMenu = newMenu.menu("Project...");
+ projectMenu.click();
+
+ SWTBotShell shell = bot.shell("New Project");
+ shell.setFocus();
+ shell.bot().text().setText("Project");
+ bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "General", "Project"));
+ bot.button("Next >").click();
+ bot.textWithLabel("Project name:").setText(SYSTEMTAP_PROJECT_NAME);
+ bot.button("Finish").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+ projectExplorer = bot.viewByTitle("Project Explorer");
+ projectExplorer.setFocus();
+ projectExplorer.bot().tree().select(SYSTEMTAP_PROJECT_NAME)
+ .contextMenu("Go Into").click();
+
+ // Open the Debug view.
+ bot.menu("Window").menu("Show View").menu("Other...").click();
+ shell = bot.shell("Show View");
+ shell.setFocus();
+ shell.bot().text().setText("Debug");
+ bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "Debug", "Debug"));
+ bot.button("OK").click();
+ }
+
+ @After
+ public void cleanUp() {
+ SWTBotShell[] shells = bot.shells();
+ for (final SWTBotShell shell : shells) {
+ String shellTitle = shell.getText();
+ if (shellTitle.length() > 0
+ && !shellTitle.startsWith("SystemTap IDE")
+ && !shellTitle.startsWith("Quick Access")) {
+ UIThreadRunnable.syncExec(new VoidResult() {
+ @Override
+ public void run() {
+ if (shell.widget.getParent() != null) {
+ shell.close();
+ }
+ }
+ });
+ }
+ }
+ bot.closeAllEditors();
+ }
+
+ @AfterClass
+ public static void finalCleanUp() {
+ if (ScriptConsole.anyRunning()) {
+ ScriptConsole.stopAll();
+ bot.waitUntil(new StapHasExited());
+ }
+
+ projectExplorer.setFocus();
+ SWTBotToolbarButton forwardButton = projectExplorer.toolbarPushButton("Forward");
+ projectExplorer.toolbarPushButton("Back to Workspace").click();
+ bot.waitUntil(Conditions.widgetIsEnabled(forwardButton));
+
+ projectExplorer.bot().tree().select(SYSTEMTAP_PROJECT_NAME)
+ .contextMenu("Delete").click();
+ SWTBotShell deleteShell = bot.shell("Delete Resources");
+ deleteShell.bot().button("OK").click();
+ bot.waitUntil(Conditions.shellCloses(deleteShell));
+ }
+
+ public static void createScript(SWTWorkbenchBot bot, String scriptName) {
+ SWTBotMenu fileMenu = bot.menu("File");
+ SWTBotMenu newMenu = fileMenu.menu("New");
+ SWTBotMenu projectMenu = newMenu.menu("Other...");
+ projectMenu.click();
+
+ SWTBotShell shell = bot.shell("New");
+ shell.setFocus();
+ shell.bot().text().setText("SystemTap");
+ bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "SystemTap", "SystemTap Script"));
+ bot.button("Next >").click();
+
+ SWTBotText text = bot.textWithLabel("Script Name:").setText(scriptName);
+ assertEquals(scriptName, text.getText());
+ text = bot.textWithLabel("Project:").setText(SYSTEMTAP_PROJECT_NAME);
+ assertEquals(SYSTEMTAP_PROJECT_NAME, text.getText());
+
+ bot.button("Finish").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+
+ assertEquals(scriptName, bot.activeEditor().getTitle());
+ }
+
+ private SWTBotShell prepareScript(String scriptName, String scriptContents) {
+ createScript(bot, scriptName);
+ if (scriptContents != null) {
+ SWTBotEclipseEditor editor = bot.editorByTitle(scriptName).toTextEditor();
+ editor.setText(scriptContents);
+ editor.save();
+ }
+
+ openRunConfigurations(scriptName);
+ SWTBotShell shell = bot.shell("Run Configurations");
+ shell.setFocus();
+ bot.tree().select("SystemTap").contextMenu("New").click();
+
+ // Select the "Graphing" tab and enable output graphing.
+ bot.cTabItem(Messages.SystemTapScriptGraphOptionsTab_graphingTitle).activate();
+ bot.checkBox(Messages.SystemTapScriptGraphOptionsTab_graphOutputRun).click();
+ return shell;
+ }
+
+ private void clearAllTerminated() {
+ SWTBotView debugView = bot.viewByTitle("Debug");
+ debugView.setFocus();
+ SWTBotTree debugTable = debugView.bot().tree();
+ assertTrue(debugTable.getAllItems().length > 0);
+ SWTBotToolbarButton remButton = debugView.toolbarPushButton("Remove All Terminated Launches");
+ assertTrue(remButton.isEnabled());
+ remButton.click();
+ assertEquals(debugTable.getAllItems().length, 0);
+ assertFalse(remButton.isEnabled());
+ }
+
+ @Test
+ public void testCreateScript() {
+ String scriptName = "testScript.stp";
+ createScript(bot, scriptName);
+
+ // Type a script
+ SWTBotEclipseEditor editor = bot.editorByTitle(scriptName).toTextEditor();
+ editor.typeText(0, editor.getText().length(), "\nprobe begin{log(\"began");
+ editor.typeText(0, editor.getText().length() - 1, "); exit(");
+ editor.typeText(0, editor.getText().length(), "}");
+ editor.save();
+
+ openRunConfigurations(scriptName);
+ SWTBotShell shell = bot.shell("Run Configurations");
+ shell.setFocus();
+ bot.tree().select("SystemTap").contextMenu("New").click();
+
+ if (stapInstalled) {
+ bot.button("Run").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+
+ bot.waitUntil(new ConsoleIsReady(scriptName));
+ bot.waitUntil(new StapHasExited(), 10000); // The script should end on its own
+ }
+ }
+
+ @Test
+ public void testAddProbes() {
+ // TODO Create dummy probe tree data that can be tested instead of relying on stap.
+ assumeTrue(stapInstalled);
+
+ // Create a blank script and add a probe to it while it's open.
+ String scriptName = "probeScript.stp";
+ createScript(bot, scriptName);
+
+ SWTBotView probeView = bot.viewByTitle("Probe Alias");
+ SWTBotTree probeTree = probeView.bot().tree();
+ bot.waitUntil(new TreePopulated(probeTree), 10000);
+
+ // Root level entries are categories of probe types. Enter them to access probe groups
+ SWTBotTreeItem[] items = probeTree.getAllItems();
+ items[0].doubleClick();
+ bot.waitUntil(new TreeItemPopulated(items[0]));
+ items = items[0].getItems();
+ items[0].doubleClick();
+ SWTBotEclipseEditor editor = bot.activeEditor().toTextEditor();
+ assertTrue(editor.getText().contains("probe " + items[0].getText() + ".*\n"));
+
+ // Open a non-stap file and add a probe. This should bring up a dialog
+ // asking if the probe should be added to the only open .stp file.
+ SWTBotMenu fileMenu = bot.menu("File");
+ SWTBotMenu newMenu = fileMenu.menu("New");
+ SWTBotMenu projectMenu = newMenu.menu("Other...");
+ projectMenu.click();
+ SWTBotShell shell = bot.shell("New");
+ shell.setFocus();
+ shell.bot().text().setText("Untitled Text File");
+ bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "General", "Untitled Text File"));
+ bot.button("Finish").click();
+
+ String probeDialogTitle = "Select Script";
+ items[1].doubleClick();
+ shell = bot.shell(probeDialogTitle);
+ shell.setFocus();
+ bot.button("Yes").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+
+ // The editor containing the script should now be in focus.
+ editor = bot.activeEditor().toTextEditor();
+ assertEquals(scriptName, editor.getTitle());
+ assertTrue(editor.getText().contains("probe " + items[0].getText() + ".*\n"));
+ assertTrue(editor.getText().contains("probe " + items[1].getText() + ".*\n"));
+
+ // Adding a probe while an .stp editor is in focus should always add it
+ // to that editor, even if multiple .stp editors are open.
+ String scriptName2 = "probeScript2.stp";
+ createScript(bot, scriptName2);
+ editor = bot.activeEditor().toTextEditor();
+ assertEquals(scriptName2, editor.getTitle());
+ items[2].doubleClick();
+ assertTrue(editor.getText().contains("probe " + items[2].getText() + ".*\n"));
+ editor = bot.editorByTitle(scriptName).toTextEditor();
+ assertFalse(editor.getText().contains("probe " + items[2].getText() + ".*\n"));
+
+ // Switch to the non-stp editor, and add a probe. A dialog should appear
+ // to let the user choose which of the open files to add to.
+ editor = bot.editorByTitle("Untitled 1").toTextEditor();
+ editor.show();
+ items[3].doubleClick();
+ shell = bot.shell(probeDialogTitle);
+ shell.setFocus();
+ SWTBotTable table = bot.table();
+ assertTrue(table.containsItem(scriptName));
+ assertTrue(table.containsItem(scriptName2));
+ table.select(scriptName2);
+ bot.button("OK").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+ editor = bot.activeEditor().toTextEditor();
+ assertFalse(editor.getTitle().equals("Untitled 1"));
+ assertTrue(editor.getText().contains("probe " + items[3].getText() + ".*\n"));
+ }
+
+ @Test
+ public void testGraphErrors() {
+ SWTBotShell shell = prepareScript("missingColumns.stp", null);
+
+ SWTBotButton runButton = bot.button("Run");
+ SWTBotButton addButton = bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton);
+ SWTBotButton editButton = bot.button(Messages.SystemTapScriptGraphOptionsTab_EditGraphButton);
+ SWTBotButton dupButton = bot.button(Messages.SystemTapScriptGraphOptionsTab_DuplicateGraphButton);
+ SWTBotButton remButton = bot.button(Messages.SystemTapScriptGraphOptionsTab_RemoveGraphButton);
+ String graphID = "org.eclipse.linuxtools.systemtap.graphing.ui.charts.scatterchartbuilder";
+
+ // As soon as the Graphing tab is entered, no regular expression exists & nothing can be run.
+ SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
+ assertEquals("", combo.getText());
+ assertFalse(runButton.isEnabled());
+ assertFalse(addButton.isEnabled());
+ combo.setText("(1)(2)");
+ assertEquals("(1)(2)", combo.getText());
+ assertTrue(runButton.isEnabled());
+ assertTrue(addButton.isEnabled());
+
+ setupGraphWithTests("Graph");
+ assertTrue(runButton.isEnabled());
+
+ // Removing groups from the regex disables graphs that rely on those groups.
+ combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
+ combo.setText("(1)");
+ assertFalse(runButton.isEnabled());
+ combo.setText("(1)(2)(3)");
+ assertTrue(runButton.isEnabled());
+
+ final SWTBotTable table = bot.table();
+ table.select(0);
+ dupButton.click();
+ assertEquals(2, table.rowCount());
+ assertTrue(runButton.isEnabled());
+
+ combo.setText("(1)");
+ assertFalse(runButton.isEnabled());
+ for (int i = 0, n = table.rowCount(); i < n; i++) {
+ String itemTitle = table.getTableItem(i).getText();
+ assertTrue("Graph " + i + " should be invalid, but it's not: " + itemTitle,
+ table.getTableItem(i).getText().contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraph));
+ }
+
+ setupGraphGeneral("Safe", 1, graphID, true);
+ assertFalse(table.getTableItem(2).getText().contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraph));
+ combo.setText("(1)(2)(3)");
+ assertTrue(runButton.isEnabled());
+
+ setupGraphGeneral("Unsafe", 3, graphID, true);
+ assertTrue(runButton.isEnabled());
+ combo.setText("(1)(2)");
+ assertFalse(runButton.isEnabled());
+ for (int i = 0, n = table.rowCount(); i < n; i++) {
+ String itemTitle = table.getTableItem(i).getText();
+ assertTrue("Graph " + i + " has incorrect validity: " + itemTitle,
+ !itemTitle.contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraph)
+ || itemTitle.contains("Unsafe"));
+ }
+
+ table.select(3);
+ dupButton.click();
+ remButton.click();
+ assertTrue(!runButton.isEnabled());
+
+ table.select(3);
+ editButton.click();
+ bot.waitUntil(Conditions.shellIsActive("Edit Graph"));
+ SWTBotShell graphShell = bot.activeShell();
+ SWTBotButton finishButton = bot.button("Finish");
+ assertTrue(!finishButton.isEnabled());
+ bot.comboBox("<Deleted>").setSelection("NA");
+ finishButton.click();
+ bot.waitUntil(Conditions.shellCloses(graphShell));
+ shell.setFocus();
+ assertTrue(runButton.isEnabled());
+
+ // Perform tests when graphs have an invalid graphID.
+ UIThreadRunnable.syncExec(new VoidResult() {
+
+ @Override
+ public void run() {
+ GraphData gd = (GraphData) table.getTableItem(0).widget.getData();
+ gd.graphID = "invalidID";
+ table.getTableItem(0).widget.setData(gd);
+ }
+ });
+
+ combo.setText(combo.getText().concat(" ")); // Just to refresh the dialog
+ assertFalse(runButton.isEnabled());
+ assertTrue(table.getTableItem(0).getText().contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraphID));
+
+ table.select(0);
+ dupButton.click();
+ remButton.click();
+ assertFalse(runButton.isEnabled());
+ assertTrue(table.getTableItem(table.rowCount() - 1).getText().contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraphID));
+
+ table.select(table.rowCount() - 1);
+ editButton.click();
+ bot.waitUntil(Conditions.shellIsActive("Edit Graph"));
+ graphShell = bot.activeShell();
+ finishButton = bot.button("Finish");
+ assertFalse(finishButton.isEnabled());
+ bot.radio(0).click();
+ finishButton.click();
+ bot.waitUntil(Conditions.shellCloses(graphShell));
+ shell.setFocus();
+ assertTrue(runButton.isEnabled());
+
+ // Removing all invalid graphs should restore validity.
+ combo.setText("(1)");
+ assertFalse(runButton.isEnabled());
+ for (int i = table.rowCount() - 1; i >= 0; i--) {
+ if (table.getTableItem(i).getText().contains(Messages.SystemTapScriptGraphOptionsTab_invalidGraph)) {
+ table.select(i);
+ remButton.click();
+ }
+ }
+ assertTrue(runButton.isEnabled());
+ while (table.rowCount() > 0) {
+ table.select(0);
+ remButton.click();
+ }
+
+ bot.button("Apply").click();
+ }
+
+ @Test
+ public void testDeleteBlankRegex() {
+ SWTBotShell shell = prepareScript("blank.stp", null);
+
+ // Confirm that adding a new regex when the current one is blank has no effect.
+ SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
+ assertEquals(2, combo.itemCount());
+ combo.setSelection(1);
+ assertEquals(2, combo.itemCount());
+ assertEquals(0, combo.selectionIndex());
+
+ // Confirm that adding a regex works when the current regex is not empty.
+ combo.setText("(a) b (c)");
+ assertEquals("(a) b (c)", combo.getText());
+ combo.setSelection(1);
+ assertEquals(3, combo.itemCount());
+ assertEquals(1, combo.selectionIndex());
+
+ // Confirm that a blank regex is not removed when other data is not empty.
+ combo.setText("(a)");
+ bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton).click();
+ bot.waitUntil(Conditions.shellIsActive("Create Graph"));
+ SWTBotShell graphShell = bot.activeShell();
+ graphShell.setFocus();
+ bot.textWithLabel("Title:").setText("Test");
+ bot.button("Finish").click();
+ bot.waitUntil(Conditions.shellCloses(graphShell));
+ shell.setFocus();
+ combo.setText("");
+ assertEquals("", combo.getText());
+ combo.setSelection(0);
+ assertEquals(3, combo.itemCount());
+
+ // Confirm that auto-deleting a blank regex in the middle of the regex list works properly.
+ combo.setSelection(2);
+ assertEquals(4, combo.itemCount());
+ combo.setText("sample");
+ combo.setSelection(1);
+ assertEquals(4, combo.itemCount());
+ SWTBotTable table = bot.table();
+ SWTBotButton remButton = bot.button(Messages.SystemTapScriptGraphOptionsTab_RemoveGraphButton);
+ assertTrue(!remButton.isEnabled());
+ table.select(0);
+ assertTrue(remButton.isEnabled());
+ remButton.click();
+ assertTrue(!remButton.isEnabled());
+ combo.setSelection(2);
+ assertEquals(3, combo.itemCount());
+ assertEquals("sample", combo.getText());
+ assertEquals("(a) b (c)", combo.items()[0]);
+ assertEquals("sample", combo.items()[1]);
+
+ // Confirm that auto-deleting a regex from the beginning of the list works properly.
+ combo.setSelection(2);
+ combo.setText("another sample");
+ combo.setSelection(0);
+ combo.setText("");
+ combo.setSelection(1);
+ assertEquals(3, combo.itemCount());
+ assertEquals("sample", combo.getText());
+ assertEquals("sample", combo.items()[0]);
+ assertEquals("another sample", combo.items()[1]);
+ }
+
+ @Test
+ public void testGraphScript() {
+ String scriptName = "testGraph.stp";
+ createScript(bot, scriptName);
+
+ // Write a script
+ SWTBotEclipseEditor editor = bot.editorByTitle(scriptName).toTextEditor();
+ editor.setText("#!/usr/bin/env stap"
+ + "\nglobal i,j,k"
+ + "\nprobe begin{i=0;j=0;k=0}"
+ + "\nprobe timer.ms(100){printf(\"Value:%d %d\\n\",i,j);i++;j+=2}"
+ + "\nprobe timer.ms(250){printf(\"Other:%d %d\\n\",i,k);k++}"
+ + "\nprobe timer.ms(1000){exit()}");
+ editor.save();
+
+ final String val0 = "i";
+ final String val1 = "j";
+ final String val2 = "k";
+
+ openRunConfigurations(scriptName);
+ SWTBotShell shell = bot.shell("Run Configurations");
+ shell.setFocus();
+ bot.tree().select("SystemTap").contextMenu("New").click();
+ bot.textWithLabel("Name:").setText(scriptName);
+
+ // Select the "Graphing" tab.
+ SWTBotCTabItem tab = bot.cTabItem(Messages.SystemTapScriptGraphOptionsTab_graphingTitle);
+ tab.activate();
+
+ // Enable output graphing.
+ bot.checkBox(Messages.SystemTapScriptGraphOptionsTab_graphOutputRun).click();
+ SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
+ combo.setText("Value:(\\d+) (\\d+)");
+ assertEquals("Value:(\\d+) (\\d+)", combo.getText());
+
+ SWTBotText text = bot.textWithLabel(Messages.SystemTapScriptGraphOptionsTab_sampleOutputLabel);
+ text.setText("Value:1 2");
+ assertEquals("Value:1 2", text.getText());
+
+ text = bot.text(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase, 1));
+ text.setText(val0);
+ assertEquals(val0, text.getText());
+ text = bot.text(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase, 2));
+ text.setText(val1);
+ assertEquals(val1, text.getText());
+
+ // Add a graph.
+ setupGraphWithTests("Values");
+ String setTitle1 = MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, 1);
+ String graphTitle1 = "Values - Scatter Graph";
+
+ // Make a second regex, and a graph for it.
+ shell.setFocus();
+ combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
+ assertEquals(2, combo.itemCount());
+ combo.setSelection(combo.selectionIndex() + 1);
+ assertEquals(3, combo.itemCount());
+ assertEquals("", combo.getText());
+ combo.setText("Other:(\\d+) (\\d+)");
+ assertEquals("Other:(\\d+) (\\d+)", combo.getText());
+
+ text = bot.text(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase, 1));
+ text.setText(val0);
+ assertEquals(val0, text.getText());
+ text = bot.text(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase, 2));
+ text.setText(val2);
+ assertEquals(val2, text.getText());
+
+ text = bot.textWithLabel(Messages.SystemTapScriptGraphOptionsTab_sampleOutputLabel);
+ assertEquals("", text.getText());
+
+ setupGraphWithTests("Others");
+ String setTitle2 = MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, 2);
+ String graphTitle2 = "Others - Scatter Graph";
+
+ // Apply the changes, then close the menu & reopen it to make sure settings were saved.
+ shell.setFocus();
+ bot.button("Apply").click();
+ bot.button("Close").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+ openRunConfigurations(scriptName);
+ shell = bot.shell("Run Configurations");
+ shell.setFocus();
+ shell.bot().text().setText(scriptName); // Set the filter text to show configs of the current script
+ bot.waitUntil(new NodeAvailableAndSelect(bot.tree(), "SystemTap", scriptName));
+ tab = bot.cTabItem(Messages.SystemTapScriptGraphOptionsTab_graphingTitle);
+ tab.activate();
+
+ combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
+ text = bot.textWithLabel(Messages.SystemTapScriptGraphOptionsTab_sampleOutputLabel);
+ SWTBotTable table = bot.table();
+ assertEquals(3, combo.itemCount());
+ assertEquals("Value:(\\d+) (\\d+)", combo.getText());
+ assertEquals("Value:1 2", text.getText());
+ assertEquals(1, table.rowCount());
+ String graphName = GraphFactory.getGraphName("org.eclipse.linuxtools.systemtap.graphing.ui.charts.scatterchartbuilder");
+ assertTrue(table.containsItem(graphName.concat(":Values")));
+ combo.setSelection(1);
+ assertEquals("Other:(\\d+) (\\d+)", combo.getText());
+ assertEquals("", text.getText());
+ assertEquals(1, table.rowCount());
+ assertTrue(table.containsItem(graphName.concat(":Others")));
+
+ // If Systemtap is not installed, don't test graph output. Otherwise, do.
+ if (!stapInstalled) {
+ return;
+ }
+
+ bot.button("Run").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+ SWTBotView console = bot.viewById("org.eclipse.ui.console.ConsoleView");
+ console.setFocus();
+ bot.waitUntil(new StapHasExited()); // The script should end on its own
+
+ // Give time for the table to be fully constructed.
+ SWTBotEditor graphEditor = bot.activeEditor();
+ bot.waitUntil(new TableHasUpdated(scriptName, 1, 10, false));
+ bot.waitUntil(new TableHasUpdated(scriptName, 2, 4, false));
+
+ // Test table & graph contents.
+ graphEditor.setFocus();
+ graphEditor.bot().cTabItem(setTitle1).activate();
+ graphEditor.bot().cTabItem("Data View").activate();
+ SWTBotTable dataTable = bot.table();
+ List<String> colNames = dataTable.columns();
+ assertEquals(3, colNames.size());
+ assertEquals(val0, colNames.get(1));
+ assertEquals(val1, colNames.get(2));
+ assertEquals("2", dataTable.cell(2, 1));
+ assertEquals("4", dataTable.cell(2, 2));
+
+ graphEditor.bot().cTabItem(graphTitle1).activate();
+ Matcher<AbstractChartBuilder> matcher = widgetOfType(AbstractChartBuilder.class);
+ AbstractChartBuilder cb = bot.widget(matcher);
+ ISeries[] series = cb.getChart().getSeriesSet().getSeries();
+ assertEquals(2, series.length);
+ assertEquals(10, series[0].getXSeries().length);
+ assertEquals(10, series[1].getXSeries().length);
+ assertEquals(2, (int) series[0].getYSeries()[2]);
+ assertEquals(4, (int) series[1].getYSeries()[2]);
+
+ graphEditor.bot().cTabItem(setTitle2).activate();
+ graphEditor.bot().cTabItem("Data View").activate();
+ dataTable = bot.table();
+ colNames = dataTable.columns();
+ assertEquals(3, colNames.size());
+ assertEquals(val0, colNames.get(1));
+ assertEquals(val2, colNames.get(2));
+ assertEquals("7", dataTable.cell(2, 1));
+ assertEquals("2", dataTable.cell(2, 2));
+
+ graphEditor.bot().cTabItem(graphTitle2).activate();
+ cb = bot.widget(matcher);
+ series = cb.getChart().getSeriesSet().getSeries();
+ assertEquals(2, series.length);
+ assertEquals(4, series[0].getXSeries().length);
+ assertEquals(4, series[1].getXSeries().length);
+ assertEquals(7, (int) series[0].getYSeries()[2]);
+ assertEquals(2, (int) series[1].getYSeries()[2]);
+
+ // Test filters on the data table & graphs.
+ graphEditor.bot().cTabItem(setTitle1).activate();
+ graphEditor.bot().cTabItem("Data View").activate();
+ dataTable = bot.table();
+ click(ContextMenuHelper.contextMenu(dataTable, "Add filter..."));
+ shell = bot.shell("Create Filter");
+ shell.setFocus();
+
+ // Match Filter - Remove a matching
+ bot.button("Match Filter").click();
+ bot.button("Next >").click();
+ bot.text().setText("2");
+ deselectDefaultSelection(0);
+ bot.radio(1).click();
+ bot.button("Finish").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+ bot.waitUntil(new TableHasUpdated(scriptName, 1, 9, true));
+ assertEquals("3", dataTable.cell(2, 1));
+ assertEquals("6", dataTable.cell(2, 2));
+
+ // Filters should be applied to graphs as well as data tables.
+ graphEditor.bot().cTabItem(graphTitle1).activate();
+ cb = bot.widget(matcher);
+ series = cb.getChart().getSeriesSet().getSeries();
+ bot.waitUntil(new ChartHasUpdated(cb.getChart(), 9));
+ assertEquals(3, (int) series[0].getYSeries()[2]);
+ assertEquals(6, (int) series[1].getYSeries()[2]);
+
+ // Each graph set should have its own filters.
+ graphEditor.bot().cTabItem(setTitle2).activate();
+ graphEditor.bot().cTabItem("Data View").activate();
+ dataTable = bot.table();
+ assertEquals(4, dataTable.rowCount());
+ assertEquals("2", dataTable.cell(0, 1));
+
+ // Test removing a filter.
+ graphEditor.bot().cTabItem(setTitle1).activate();
+ graphEditor.bot().cTabItem("Data View").activate();
+ dataTable = bot.table();
+ click(ContextMenuHelper.contextMenu(dataTable, "Remove filter...", "Match Filter: \"" + val0 + "\" removing \"2\""));
+ bot.waitUntil(new TableHasUpdated(scriptName, 1, 10, true));
+ assertEquals("2", dataTable.cell(2, 1));
+ assertEquals("4", dataTable.cell(2, 2));
+
+ clearAllTerminated();
+ }
+
+ @Test
+ public void testGenerateFromPrintf() {
+ SWTBotShell shell = prepareScript("testGenerates.stp", "#!/usr/bin/env stap"
+ + "\nglobal i,j,k,a"
+ + "\nprobe begin{i=0;j=5;k=20;a=65}"
+ + "\n#probe begin{printf(\"%1b%1b%1blo %1b%1brld\\n\", 72,101,108,87,111)}"
+ + "\nprobe timer.ms(100){printf(\"%5i|\\n%10.5d|\\n%-10.5i|\\n%05c\\n\",i,j,k,a);i++;j+=5;k+=20;a++}"
+ + "\n//printf(\"this is a comment\\n\");"
+ + "\n/*printf(\"this is a...\\n\");"
+ + "\nprintf(\"...multiline comment\\n\");*/"
+ + "\nprobe begin{b = sprintf(\"Here\"); printf(\"-->%s<--\\n\", b)}"
+ + "\nprobe timer.ms(100){printf(\"%x - %#x - %#X\\n\",i,i,i);}"
+ + "\nprobe timer.ms(100){printf(\"%o - %#o\\n\",i,i);}"
+ + "\nprobe begin{printf(\"%1b-\\\\n-%p\\n\", 65, 0x8000000002345678)}");
+
+ // Generate regexs.
+ bot.button(Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsButton).click();
+
+ SWTBotShell dialogShell = bot.shell(Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsTitle);
+ dialogShell.setFocus();
+ bot.button("Yes").click();
+ bot.waitUntil(Conditions.shellCloses(dialogShell));
+ shell.setFocus();
+
+ SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
+ assertEquals(9, combo.itemCount()); // One extra entry for "Add New Regex"
+
+ String[] expectedRegexs = new String[]{
+ " {0,4}(-?\\d+)\\|",
+ " {0,9}(-?\\d+)\\|",
+ "(-?\\d+) {0,9}\\|",
+ " {0,4}(.)",
+ "-->(.+)<--",
+ "([a-f0-9]+) - (0x[a-f0-9]+) - (0X[A-F0-9]+)",
+ "(\\d+) - (0\\d+)",
+ "(.)-\\\\n-(0x[a-f0-9]+)",
+ Messages.SystemTapScriptGraphOptionsTab_regexAddNew
+ };
+ for (int i = 0, n = combo.itemCount(); i < n; i++) {
+ assertEquals(expectedRegexs[i], combo.items()[i]);
+ }
+ bot.button("Apply").click();
+ }
+
+ @Test
+ public void testLabelledGraphScript() {
+ // TODO If Systemtap is not installed, nothing can be graphed, so don't bother performing this test.
+ // Once the ability to read in pre-saved chart data is restored, this test can be run with sample data.
+ assumeTrue(stapInstalled);
+
+ String scriptName = "testLabels.stp";
+ SWTBotShell shell = prepareScript(scriptName, "#!/usr/bin/env stap"
+ + "\nprobe begin{"
+ + "\nprintf(\"Apples: 2 14 16\\n\");"
+ + "\nprintf(\"1: 1 2 3\\n\");"
+ + "\nprintf(\"Bananas (2): 10 10 10\\n\");"
+ + "\nprintf(\"Cherries: 10 20 30\\n\");"
+ + "\nprintf(\"2: 2 4 6\\n\");"
+ + "\nprintf(\"Apples: 12 5 16\\n\");"
+ + "\nprintf(\"Bananas: 0 1 0\\n\");"
+ + "\nprintf(\"3: 3 6 9\\n\");"
+ + "\nprintf(\"Dates: 12 5 16\\n\");"
+ + "\nprintf(\"Bananas: 2 1 2\\n\");"
+ + "\nprintf(\"4: 4 8 12\\n\");"
+ + "\nprintf(\"Apples: 12 5 16\\n\");"
+ + "\nprintf(\"Bananas (2): 3 1 3\\n\");"
+ + "\nexit();}");
+ int numItems = 13;
+ int numNumberItems = 4;
+ int numCategories = 3;
+
+ // Enter a regex.
+ SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
+ SWTBotButton button = bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton);
+ assertFalse(button.isEnabled());
+ combo.setText("(.*): (\\d+) (\\d+) (\\d+)");
+
+ // Add bar, pie, and line graphs that use the same column data.
+ String title = "Fruit Info";
+ setupGraphGeneral(title, 4, "org.eclipse.linuxtools.systemtap.graphing.ui.charts.barchartbuilder", false);
+ setupGraphGeneral(title, 4, "org.eclipse.linuxtools.systemtap.graphing.ui.charts.piechartbuilder", false);
+ setupGraphGeneral(title, 4, "org.eclipse.linuxtools.systemtap.graphing.ui.charts.linechartbuilder", false);
+
+ bot.button("Run").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+ SWTBotView console = bot.viewById("org.eclipse.ui.console.ConsoleView");
+ console.setFocus();
+ bot.waitUntil(new StapHasExited()); // The script should end on its own
+
+ // Give time for the table to be fully constructed.
+ SWTBotEditor graphEditor = bot.activeEditor();
+ bot.waitUntil(new TableHasUpdated(scriptName, 1, numItems, false));
+
+ // Confirm that the bar & pie charts display the String categories, but the line chart ignores them.
+ String titleBar = title + " - Bar Graph";
+ String titlePie = title + " - Pie Chart";
+ String titleLine = title + " - Line Graph";
+ graphEditor.bot().cTabItem(titleLine).activate();
+ Matcher<AbstractChartBuilder> matcher = widgetOfType(AbstractChartBuilder.class);
+ AbstractChartBuilder cb = bot.widget(matcher);
+ assertEquals(numNumberItems, cb.getChart().getSeriesSet().getSeries()[0].getXSeries().length);
+
+ graphEditor.bot().cTabItem(titlePie).activate();
+ cb = bot.widget(matcher);
+ assertEquals(numItems, cb.getChart().getSeriesSet().getSeries().length);
+
+ graphEditor.bot().cTabItem(titleBar).activate();
+ cb = bot.widget(matcher);
+ assertEquals(numItems, cb.getChart().getSeriesSet().getSeries()[0].getXSeries().length);
+
+ // Test graph scaling & scrolling
+ discreteXControlTests(cb, numItems); //Bar Chart
+ continuousControlTests(cb, false);
+ graphEditor.bot().cTabItem(titlePie).activate();
+ cb = bot.widget(matcher);
+ discreteXControlTests(cb, numCategories);
+ graphEditor.bot().cTabItem(titleLine).activate();
+ cb = bot.widget(matcher);
+ continuousControlTests(cb, true);
+ continuousControlTests(cb, false);
+
+ clearAllTerminated();
+ }
+
+ private void discreteXControlTests(AbstractChartBuilder cb, int numAxisItems) {
+ // Check that default range shows 100% of data.
+ IAxis axis = cb.getChart().getAxisSet().getXAxis(0);
+ Range range = axis.getRange();
+ double scale = cb.getScale();
+ double scroll = cb.getScroll();
+ assertTrue(range.upper - range.lower == axis.getCategorySeries().length - 1 && range.upper - range.lower == numAxisItems - 1);
+ assertTrue(scale == 1.0 && scroll == 1.0);
+
+ // Check that scroll buttons are disabled at 100% range.
+ SWTBotButton firstButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_First);
+ SWTBotButton leftButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_Left);
+ SWTBotButton rightButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_Right);
+ SWTBotButton lastButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_Last);
+ assertFalse(firstButton.isEnabled());
+ assertFalse(leftButton.isEnabled());
+ assertFalse(rightButton.isEnabled());
+ assertFalse(lastButton.isEnabled());
+
+ // Test zooming in. The amount of zoom is arbitrary for this test--just make sure zooming happened.
+ SWTBotButton zoomInButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_ZoomIn);
+ SWTBotButton zoomOutButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_ZoomOut);
+ SWTBotButton allButton = bot.button(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphDiscreteXControl_All);
+ assertTrue(zoomInButton.isEnabled());
+ assertFalse(zoomOutButton.isEnabled());
+ assertFalse(allButton.isEnabled());
+ zoomInButton.click();
+ assertTrue(zoomOutButton.isEnabled());
+ assertTrue(allButton.isEnabled());
+
+ // By default, zooming in should zoom in on the end of the axis (newest data).
+ range = axis.getRange();
+ assertTrue(range.upper == numAxisItems - 1 && range.lower > 0 && cb.getScale() < scale && cb.getScroll() == 1.0);
+
+ // Left scrolling should now be enabled.
+ assertTrue(firstButton.isEnabled());
+ assertTrue(leftButton.isEnabled());
+ assertFalse(rightButton.isEnabled());
+ assertFalse(lastButton.isEnabled());
+
+ // Test scrolling left. Again, the specific amount is arbitrary, just make sure scrolling happened.
+ leftButton.click();
+ range = axis.getRange();
+ assertTrue(range.upper < numAxisItems - 1 && cb.getScroll() < scroll);
+ int rstore = (int) range.lower;
+ assertTrue(rightButton.isEnabled());
+ assertTrue(lastButton.isEnabled());
+
+ // Zooming out should bring the range back to 100%.
+ zoomOutButton.click();
+ range = axis.getRange();
+ assertTrue(range.upper - range.lower == numAxisItems - 1 && cb.getScale() == 1.0 && cb.getScroll() < scroll);
+ assertTrue(zoomInButton.isEnabled());
+ assertFalse(zoomOutButton.isEnabled());
+ assertFalse(allButton.isEnabled());
+ assertFalse(firstButton.isEnabled());
+ assertFalse(leftButton.isEnabled());
+ assertFalse(rightButton.isEnabled());
+ assertFalse(lastButton.isEnabled());
+
+ // For convenience, zooming out after having scrolled somewhere should make zooming in
+ // zoom back to the area that was scrolled to.
+ scroll = cb.getScroll();
+ zoomInButton.click();
+ assertTrue(rstore == axis.getRange().lower && scroll == cb.getScroll());
+
+ // Scrolling right should take the range back to the end of the axis.
+ rightButton.click();
+ range = axis.getRange();
+ assertTrue(range.upper == numAxisItems - 1 && range.lower > 0 && cb.getScroll() > scroll);
+ assertTrue(firstButton.isEnabled());
+ assertTrue(leftButton.isEnabled());
+ assertFalse(rightButton.isEnabled());
+ assertFalse(lastButton.isEnabled());
+
+ // Zoom in as much as possible (range should show only one item),
+ // and step right/left. Add a loop limit for safety.
+ for (int i = 0; i < numAxisItems; i++) {
+ range = axis.getRange();
+ if (range.upper == range.lower) {
+ break;
+ }
+ zoomInButton.click();
+ }
+ range = axis.getRange();
+ assertTrue(range.upper == range.lower && range.upper == numAxisItems - 1);
+ assertTrue(!zoomInButton.isEnabled());
+ for (int i = 0; i < numAxisItems; i++) {
+ if (axis.getRange().lower == 0) {
+ break;
+ }
+ leftButton.click();
+ assertTrue(axis.getRange().lower < range.lower);
+ range = axis.getRange();
+ assertEquals(range.lower, range.upper, 0.0);
+ }
+ assertEquals(axis.getRange().lower, 0, 0.0);
+ for (int i = 0; i < numAxisItems; i++) {
+ if (axis.getRange().upper == numAxisItems - 1) {
+ break;
+ }
+ rightButton.click();
+ assertTrue(axis.getRange().upper > range.upper);
+ range = axis.getRange();
+ assertEquals(range.lower, range.upper, 0.0);
+ }
+ assertEquals(axis.getRange().upper, numAxisItems - 1, 0);
+
+ firstButton.click();
+ assertEquals(axis.getRange().lower, 0, 0);
+ assertFalse(firstButton.isEnabled());
+ assertFalse(leftButton.isEnabled());
+ assertTrue(rightButton.isEnabled());
+ assertTrue(lastButton.isEnabled());
+
+ lastButton.click();
+ assertEquals(axis.getRange().upper, numAxisItems - 1, 0);
+ assertTrue(firstButton.isEnabled());
+ assertTrue(leftButton.isEnabled());
+ assertFalse(rightButton.isEnabled());
+ assertFalse(lastButton.isEnabled());
+ }
+
+ private double getAxisScale(AbstractChartBuilder cb, boolean isXAxis) {
+ return isXAxis ? cb.getScale() : cb.getScaleY();
+ }
+
+ private double getAxisScroll(AbstractChartBuilder cb, boolean isXAxis) {
+ return isXAxis ? cb.getScroll() : cb.getScrollY();
+ }
+
+ private void continuousControlTests(AbstractChartBuilder cb, boolean isXAxis) {
+ // Continuous scaling/scrolling is less strict/predictable than discrete scrolling,
+ // so just check that the controls perform their intended actions.
+ IAxis axis;
+ SWTBotButton zoomInButton, zoomOutButton;
+ SWTBotScale zoomScale;
+ SWTBotSlider scrollBar;
+ int flipSign;
+ if (isXAxis) {
+ axis = cb.getChart().getAxisSet().getXAxis(0);
+ zoomInButton = bot.buttonWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousXControl_ZoomInTooltip);
+ zoomOutButton = bot.buttonWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousXControl_ZoomOutTooltip);
+ zoomScale = bot.scaleWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousXControl_ScaleMessage);
+ scrollBar = bot.sliderWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousXControl_ScrollMessage);
+ flipSign = 1;
+ } else {
+ axis = cb.getChart().getAxisSet().getYAxis(0);
+ zoomInButton = bot.buttonWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousYControl_ZoomInTooltip);
+ zoomOutButton = bot.buttonWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousYControl_ZoomOutTooltip);
+ zoomScale = bot.scaleWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousYControl_ScaleMessage);
+ scrollBar = bot.sliderWithTooltip(org.eclipse.linuxtools.systemtap.graphing.ui.widgets.Messages.GraphContinuousYControl_ScrollMessage);
+ flipSign = -1;
+ }
+ double scale = getAxisScale(cb, isXAxis);
+ double scroll = getAxisScroll(cb, isXAxis);
+ int thumb = scrollBar.getThumb();
+
+ // Default range should be 100%, so zooming out shouldn't have an effect yet.
+ assertEquals(scale, 1.0, 0);
+ int zoomValue = zoomScale.getValue();
+ Range range = axis.getRange();
+ zoomOutButton.click();
+ Range range2 = axis.getRange();
+ assertTrue(range.upper == range2.upper && range.lower == range2.lower && zoomScale.getValue() == zoomValue && getAxisScale(cb, isXAxis) == scale && scrollBar.getThumb() == thumb);
+
+ // Zoom in & back out with the zoom buttons.
+ zoomInButton.click();
+ range2 = axis.getRange();
+ assertTrue(range2.upper - range2.lower < range.upper - range.lower && flipSign * (zoomScale.getValue() - zoomValue) > 0 && getAxisScale(cb, isXAxis) < scale && scrollBar.getThumb() < thumb);
+ zoomOutButton.click();
+ range2 = axis.getRange();
+ assertTrue(range.upper == range2.upper && range.lower == range2.lower && zoomScale.getValue() == zoomValue && getAxisScale(cb, isXAxis) == scale && scrollBar.getThumb() == thumb);
+
+ // Zoom in with the Scale control.
+ int controlRange = zoomScale.getMaximum() - zoomScale.getMinimum();
+ zoomScale.setValue(zoomScale.getValue() + controlRange / 2 * flipSign);
+ // Note: the charts need some time to be updated after using the scale/slider controls.
+ // Sleeping for a brief moment is faster than using a bot wait condition.
+ bot.sleep(100);
+ range2 = axis.getRange();
+ assertTrue(range2.upper - range2.lower < range.upper - range.lower && getAxisScale(cb, isXAxis) < scale && scrollBar.getThumb() < thumb);
+
+ range = range2;
+ thumb = scrollBar.getThumb();
+ scale = getAxisScale(cb, isXAxis);
+ zoomScale.setValue(zoomScale.getValue() - controlRange / 4 * flipSign);
+ bot.sleep(100);
+ range2 = axis.getRange();
+ assertTrue(range2.upper - range2.lower > range.upper - range.lower && getAxisScale(cb, isXAxis) > scale && scrollBar.getThumb() > thumb);
+
+ // Test scrolling. Don't assume an initial scroll position, as it may be changed
+ // in future versions (it's more likely to change than default zoom, at least).
+ thumb = scrollBar.getThumb();
+ controlRange = scrollBar.getMaximum() - scrollBar.getThumb() - scrollBar.getMinimum();
+ scrollBar.setSelection(controlRange / 2);
+ bot.sleep(100);
+ assertEquals(scrollBar.getThumb(), thumb);
+
+ // Scroll towards origin.
+ range = axis.getRange();
+ scrollBar.setSelection(scrollBar.getSelection() - controlRange / 4 * flipSign);
+ bot.sleep(100);
+ range2 = axis.getRange();
+ assertTrue(range2.upper - range2.lower == range.upper - range.lower && range2.upper < range.upper && getAxisScroll(cb, isXAxis) < scroll);
+
+ // Scroll away from origin.
+ range = range2;
+ scroll = getAxisScroll(cb, isXAxis);
+ scrollBar.setSelection(scrollBar.getSelection() + controlRange / 8 * flipSign);
+ bot.sleep(100);
+ range2 = axis.getRange();
+ assertTrue(range2.upper - range2.lower == range.upper - range.lower && range2.upper > range.upper && getAxisScroll(cb, isXAxis) > scroll);
+ }
+
+ @Test
+ public void testGraphTooltips() {
+ // TODO If Systemtap is not installed, nothing can be graphed, so don't bother performing this test.
+ // Once the ability to read in pre-saved chart data is restored, this test can be run with sample data.
+ assumeTrue(stapInstalled);
+
+ String scriptName = "testGraphTooltips.stp";
+ SWTBotShell shell = prepareScript(scriptName, "#!/usr/bin/env stap"
+ + "\nglobal y"
+ + "\nprobe begin{y=5}"
+ + "\nprobe timer.ms(1000){printf(\"%d\\n\",y);y++}"
+ + "\nprobe timer.ms(5000){exit()}");
+
+ // Enter a regex.
+ SWTBotCombo combo = bot.comboBoxWithLabel(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
+ assertFalse(bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton).isEnabled());
+ combo.setText("(\\d+)");
+
+ // Add bar, pie, and line graphs that use the same column data.
+ String title = "Info";
+ setupGraphGeneral(title, 1, "org.eclipse.linuxtools.systemtap.graphing.ui.charts.linechartbuilder", true);
+ setupGraphGeneral(title, 1, "org.eclipse.linuxtools.systemtap.graphing.ui.charts.barchartbuilder", true);
+
+ bot.button("Run").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+
+ // Perform mouse hover tests on graphs as they are being updated
+ SWTBotEditor graphEditor = TestCreateSystemtapScript.bot.editorByTitle(scriptName.concat(" Graphs"));
+ graphEditor.setFocus();
+ graphEditor.bot().cTabItem("Info - Bar Graph").activate();
+ final Matcher<AbstractChartBuilder> matcher = widgetOfType(AbstractChartBuilder.class);
+ AbstractChartBuilder cb = bot.widget(matcher);
+ bot.waitUntil(new ChartHasUpdated(cb.getChart(), 1));
+ String tooltipFormat = "{0}: {1}";
+ checkTooltipAtDataPoint(cb, 0, 0, new Point(0, 20), MessageFormat.format(tooltipFormat, "Column 1", "5"), true);
+
+ graphEditor.bot().cTabItem("Info - Line Graph").activate();
+ cb = bot.widget(matcher);
+ bot.waitUntil(new ChartHasUpdated(cb.getChart(), 2));
+ tooltipFormat = "Series: {0}\nx: {1}\ny: {2}";
+ checkTooltipAtDataPoint(cb, 0, 1, null, MessageFormat.format(tooltipFormat, "Column 1", "2", "6"), true);
+
+ // The tooltip should disappear when a point moves away from the mouse, without need for mouse movement.
+ bot.waitUntil(new ChartHasUpdated(cb.getChart(), -1));
+ checkTooltipAtDataPoint(cb, 0, -1, null, MessageFormat.format(tooltipFormat, "Column 1", "2", "6"), false);
+
+ ScriptConsole.stopAll();
+ bot.waitUntil(new StapHasExited());
+ clearAllTerminated();
+ }
+
+ /**
+ * May move the mouse to a desired data point on a chart and test for the tooltip that appears.
+ * @param cb The AbstractChartBuilder containing the chart to test.
+ * @param series The index of the data series to hover over.
+ * @param dataPoint The data point of the series to move the mouse to. Set this to -1
+ * or less if the mouse should stay where it is.
+ * @param adjustment Move the mouse's x & y coordinates by the values of this Point,
+ * or set this to <code>null</code> to make no adjustment.
+ * @param expectedTooltip The expected contents of the tooltip.
+ * @param shellShouldExist Set to <code>false</code> if the tooltip should not be found.
+ */
+ private void checkTooltipAtDataPoint(final AbstractChartBuilder cb, final int series,
+ final int dataPoint, final Point adjustment, final String expectedTooltip,
+ final boolean shellShouldExist) {
+ if (dataPoint >= 0) {
+ UIThreadRunnable.syncExec(new VoidResult() {
+
+ @Override
+ public void run() {
+ Event event = new Event();
+ event.type = SWT.MouseMove;
+ Point mousePoint = cb.getChart().getPlotArea().toDisplay(
+ cb.getChart().getSeriesSet().getSeries()[0].getPixelCoordinates(dataPoint));
+ event.x = mousePoint.x + (adjustment != null ? adjustment.x : 0);
+ event.y = mousePoint.y + (adjustment != null ? adjustment.y : 0);
+ bot.getDisplay().post(event);
+ }
+ });
+ }
+
+ bot.sleep(100); // Give some time for the tooltip to appear/change
+ UIThreadRunnable.syncExec(new VoidResult() {
+
+ @Override
+ public void run() {
+ for (SWTBotShell bshell : bot.shells()) {
+ Control[] children = bshell.widget.getChildren();
+ if (children.length == 1 && children[0] instanceof Text && expectedTooltip.equals(((Text) children[0]).getText())) {
+ if (!shellShouldExist) {
+ throw new AssertionError("Did not expect to find this tooltip, but found it: " + expectedTooltip);
+ }
+ return;
+ }
+ }
+ if (shellShouldExist) {
+ throw new AssertionError("Didn't find the expected tooltip: " + expectedTooltip);
+ }
+ }
+ });
+ }
+
+ private void openRunConfigurations(String scriptName) {
+ // Focus on project explorer view.
+ projectExplorer.setFocus();
+ projectExplorer.bot().tree().select(scriptName);
+ bot.menu("Run").menu("Run Configurations...").click();
+ }
+
+ private void setupGraphWithTests(String title) {
+ SWTBotShell firstShell = bot.activeShell();
+
+ bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton).click();
+ SWTBotShell shell = bot.shell("Create Graph");
+ shell.setFocus();
+
+ SWTBotText text = bot.textWithLabel("Title:");
+ text.setText(title);
+ assertEquals(title, text.getText());
+
+ SWTBotCombo comboX = bot.comboBoxWithLabel("X Series:");
+ assertEquals(3, comboX.itemCount()); // X Series includes "Row Num" as a selection
+ SWTBotCombo comboY0 = bot.comboBoxWithLabel("Y Series 0:");
+ assertEquals(2, comboY0.itemCount()); // Y Series 0 only includes series entries
+ comboY0.setSelection(0);
+ SWTBotCombo comboY1 = bot.comboBoxWithLabel("Y Series 1:");
+ assertEquals(3, comboY1.itemCount()); // Y Series (i>0) has extra "NA" option as first entry
+ comboY1.setSelection(1);
+ assertFalse(bot.button("Finish").isEnabled()); // Don't allow duplicate selections
+ comboY1.setSelection(2);
+ bot.button("Finish").click();
+
+ bot.waitUntil(Conditions.shellCloses(shell));
+ firstShell.setFocus();
+ }
+
+ private void setupGraphGeneral(String title, int numItems, String graphID, boolean useRowNum) {
+ int offset = useRowNum ? 0 : 1;
+ SWTBotShell firstShell = bot.activeShell();
+
+ bot.button(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton).click();
+ SWTBotShell shell = bot.shell("Create Graph");
+ shell.setFocus();
+
+ deselectDefaultSelection(0);
+ bot.radioWithTooltip(GraphFactory.getGraphName(graphID) + "\n\n" +
+ GraphFactory.getGraphDescription(graphID)).click();
+
+ SWTBotText text = bot.textWithLabel("Title:");
+ text.setText(title);
+
+ bot.comboBoxWithLabel("X Series:").setSelection(offset);
+ bot.comboBoxWithLabel("Y Series 0:").setSelection(offset);
+ for (int i = 1; i < numItems - offset; i++) {
+ bot.comboBoxWithLabel(MessageFormat.format("Y Series {0}:", i)).setSelection(i + 1 + offset);
+ }
+ if (!useRowNum) {
+ bot.comboBoxWithLabel(MessageFormat.format("Y Series {0}:", numItems - 1)).setSelection(0);
+ }
+ bot.button("Finish").click();
+ bot.waitUntil(Conditions.shellCloses(shell));
+ firstShell.setFocus();
+ }
+
+ /**
+ * Deselects a radio button.
+ * Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=344484
+ * @param currSelection The index of the radiobutton to deselect
+ */
+ private void deselectDefaultSelection(final int currSelection) {
+ UIThreadRunnable.syncExec(new VoidResult() {
+ @Override
+ public void run() {
+ @SuppressWarnings("unchecked")
+ Matcher<Widget> matcher = allOf(widgetOfType(Button.class), withStyle(SWT.RADIO, "SWT.RADIO"));
+ Button b = (Button) bot.widget(matcher, currSelection);
+ b.setSelection(false);
+ }
+ });
+ }
+
+ public static void click(final MenuItem menuItem) {
+ final Event event = new Event();
+ event.time = (int) System.currentTimeMillis();
+ event.widget = menuItem;
+ event.display = menuItem.getDisplay();
+ event.type = SWT.Selection;
+
+ UIThreadRunnable.asyncExec(menuItem.getDisplay(), new VoidResult() {
+ @Override
+ public void run() {
+ menuItem.notifyListeners(SWT.Selection, event);
+ }
+ });
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/CommentRemover.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/CommentRemover.java
index 5eb76a78a8..a4751e88e6 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/CommentRemover.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/CommentRemover.java
@@ -23,98 +23,98 @@ public final class CommentRemover {
private CommentRemover() {}
- /**
- * Remove comments from a .stp file in the filesystem.
- * @param filename The filename of the script to remove comments from.
- * @return The copy of the script with comments removed.
- */
- public static String execWithFile(String filename) {
- try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
- StringBuffer buffer = new StringBuffer();
- String line;
- while ((line = br.readLine()) != null) {
- buffer.append(line.concat("\n")); //$NON-NLS-1$
- }
- // No need to format line breaks, since this did it already with newlines.
- return exec(buffer.toString(), false);
- } catch (IOException e) {
- return ""; //$NON-NLS-1$
- }
- }
+ /**
+ * Remove comments from a .stp file in the filesystem.
+ * @param filename The filename of the script to remove comments from.
+ * @return The copy of the script with comments removed.
+ */
+ public static String execWithFile(String filename) {
+ try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
+ StringBuffer buffer = new StringBuffer();
+ String line;
+ while ((line = br.readLine()) != null) {
+ buffer.append(line.concat("\n")); //$NON-NLS-1$
+ }
+ // No need to format line breaks, since this did it already with newlines.
+ return exec(buffer.toString(), false);
+ } catch (IOException e) {
+ return ""; //$NON-NLS-1$
+ }
+ }
- /**
- * Remove comments from a .stp script. Also, line breaks will be formatted to newlines.
- * @param contents A complete .stp script.
- * @return A copy of the script with comments removed.
- */
- public static String exec(String contents) {
- return exec(contents, true);
- }
+ /**
+ * Remove comments from a .stp script. Also, line breaks will be formatted to newlines.
+ * @param contents A complete .stp script.
+ * @return A copy of the script with comments removed.
+ */
+ public static String exec(String contents) {
+ return exec(contents, true);
+ }
- private static String exec(String contents, boolean standardizeLineBreaks) {
- if (contents == null || contents.isEmpty()) {
- return ""; //$NON-NLS-1$
- }
- if (standardizeLineBreaks) {
- contents = doStandardizeLineBreaks(contents);
- }
+ private static String exec(String contents, boolean standardizeLineBreaks) {
+ if (contents == null || contents.isEmpty()) {
+ return ""; //$NON-NLS-1$
+ }
+ if (standardizeLineBreaks) {
+ contents = doStandardizeLineBreaks(contents);
+ }
- char curchar, nxtchar;
- boolean inQuotes = false;
- boolean inComment = false;
+ char curchar, nxtchar;
+ boolean inQuotes = false;
+ boolean inComment = false;
- int c = 0;
- StringBuffer buffer = new StringBuffer();
+ int c = 0;
+ StringBuffer buffer = new StringBuffer();
- do {
- curchar = contents.charAt(c++);
- nxtchar = c < contents.length() ? contents.charAt(c) : '\0';
+ do {
+ curchar = contents.charAt(c++);
+ nxtchar = c < contents.length() ? contents.charAt(c) : '\0';
- // Comment tags don't count if they are in a string.
- if (!inQuotes) {
- if (!inComment) {
- if (curchar == '#' || (curchar == '/' && nxtchar == '/')) {
- buffer.append('\n'); // Replace the rest of this line with a newline.
- c = contents.indexOf('\n', c); // Skip past the next newline, if one exists.
- if (c == -1) {
- break;
- }
- c++; // Skip the newline character on the next character scan.
- continue;
- }
- if (curchar == '/' && nxtchar == '*') {
- inComment = true;
- c++; // Skip the * on the next character scan.
- continue;
- }
- } else if (curchar == '*' && nxtchar == '/') {
- inComment = false;
- c++; // Skip the / on the next character scan.
- continue;
- }
- }
+ // Comment tags don't count if they are in a string.
+ if (!inQuotes) {
+ if (!inComment) {
+ if (curchar == '#' || (curchar == '/' && nxtchar == '/')) {
+ buffer.append('\n'); // Replace the rest of this line with a newline.
+ c = contents.indexOf('\n', c); // Skip past the next newline, if one exists.
+ if (c == -1) {
+ break;
+ }
+ c++; // Skip the newline character on the next character scan.
+ continue;
+ }
+ if (curchar == '/' && nxtchar == '*') {
+ inComment = true;
+ c++; // Skip the * on the next character scan.
+ continue;
+ }
+ } else if (curchar == '*' && nxtchar == '/') {
+ inComment = false;
+ c++; // Skip the / on the next character scan.
+ continue;
+ }
+ }
- // Quotes only count if they aren't commented out.
- if (!inComment) {
- if (curchar == '\"') {
- inQuotes = !inQuotes;
- }
- else if (curchar == '\n' && inQuotes) {
- inQuotes = false;
- }
- buffer.append(curchar);
- }
- else if (curchar == '\n') {
- // Print the line breaks of multiline comments.
- buffer.append(curchar);
- }
+ // Quotes only count if they aren't commented out.
+ if (!inComment) {
+ if (curchar == '\"') {
+ inQuotes = !inQuotes;
+ }
+ else if (curchar == '\n' && inQuotes) {
+ inQuotes = false;
+ }
+ buffer.append(curchar);
+ }
+ else if (curchar == '\n') {
+ // Print the line breaks of multiline comments.
+ buffer.append(curchar);
+ }
- } while (c < contents.length());
+ } while (c < contents.length());
- return buffer.toString();
- }
+ return buffer.toString();
+ }
- private static String doStandardizeLineBreaks(String contents) {
- return contents.replaceAll("(\\r\\n)|(\\n)", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
+ private static String doStandardizeLineBreaks(String contents) {
+ return contents.replaceAll("(\\r\\n)|(\\n)", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDECloseMonitor.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDECloseMonitor.java
index 2e5521247c..92c7520dee 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDECloseMonitor.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDECloseMonitor.java
@@ -27,20 +27,20 @@ import org.eclipse.ui.IWorkbenchWindow;
* @author Ryan Morse
*/
public class IDECloseMonitor implements IWorkbenchListener {
- @Override
- public boolean preShutdown(IWorkbench workbench, boolean forced) {
- boolean close = true;
- if(!forced) {
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
+ @Override
+ public boolean preShutdown(IWorkbench workbench, boolean forced) {
+ boolean close = true;
+ if(!forced) {
+ IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- if(ScriptConsole.anyRunning()) {
- String msg = MessageFormat.format(Localization.getString("IDECloseMonitor.StillRunning"),(Object[]) null); //$NON-NLS-1$
- close = MessageDialog.openQuestion(window.getShell(), "Closing...", msg); //$NON-NLS-1$
- }
- }
- return close;
- }
+ if(ScriptConsole.anyRunning()) {
+ String msg = MessageFormat.format(Localization.getString("IDECloseMonitor.StillRunning"),(Object[]) null); //$NON-NLS-1$
+ close = MessageDialog.openQuestion(window.getShell(), "Closing...", msg); //$NON-NLS-1$
+ }
+ }
+ return close;
+ }
- @Override
- public void postShutdown(IWorkbench workbench) {}
+ @Override
+ public void postShutdown(IWorkbench workbench) {}
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDEPerspective.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDEPerspective.java
index 5a0fd7abcd..2fd6152339 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDEPerspective.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDEPerspective.java
@@ -29,40 +29,40 @@ import org.eclipse.ui.console.IConsoleConstants;
* @author Ryan Morse
*/
public class IDEPerspective implements IPerspectiveFactory {
- public static String ID = "org.eclipse.linuxtools.systemtap.ui.ide.IDEPerspective"; //$NON-NLS-1$
+ public static String ID = "org.eclipse.linuxtools.systemtap.ui.ide.IDEPerspective"; //$NON-NLS-1$
- @Override
- public void createInitialLayout(IPageLayout layout) {
- String editorArea = layout.getEditorArea();
- layout.setEditorAreaVisible(true);
+ @Override
+ public void createInitialLayout(IPageLayout layout) {
+ String editorArea = layout.getEditorArea();
+ layout.setEditorAreaVisible(true);
- IFolderLayout browsers = layout.createFolder("browsers", IPageLayout.LEFT, 0.25f, editorArea); //$NON-NLS-1$
- browsers.addPlaceholder(ProbeAliasBrowserView.ID + ":*"); //$NON-NLS-1$
+ IFolderLayout browsers = layout.createFolder("browsers", IPageLayout.LEFT, 0.25f, editorArea); //$NON-NLS-1$
+ browsers.addPlaceholder(ProbeAliasBrowserView.ID + ":*"); //$NON-NLS-1$
- browsers.addView(ProbeAliasBrowserView.ID);
- browsers.addView(FunctionBrowserView.ID);
- browsers.addView(KernelBrowserView.ID);
- browsers.addView(IPageLayout.ID_PROJECT_EXPLORER);
+ browsers.addView(ProbeAliasBrowserView.ID);
+ browsers.addView(FunctionBrowserView.ID);
+ browsers.addView(KernelBrowserView.ID);
+ browsers.addView(IPageLayout.ID_PROJECT_EXPLORER);
- layout.getViewLayout(ProbeAliasBrowserView.ID).setCloseable(false);
- layout.getViewLayout(FunctionBrowserView.ID).setCloseable(false);
- layout.getViewLayout(KernelBrowserView.ID).setCloseable(false);
+ layout.getViewLayout(ProbeAliasBrowserView.ID).setCloseable(false);
+ layout.getViewLayout(FunctionBrowserView.ID).setCloseable(false);
+ layout.getViewLayout(KernelBrowserView.ID).setCloseable(false);
- IFolderLayout output = layout.createFolder("output", IPageLayout.BOTTOM, 0.75f, editorArea); //$NON-NLS-1$
- output.addPlaceholder(ErrorView.ID + ":*"); //$NON-NLS-1$
- output.addView(ErrorView.ID);
- output.addView(IConsoleConstants.ID_CONSOLE_VIEW);
+ IFolderLayout output = layout.createFolder("output", IPageLayout.BOTTOM, 0.75f, editorArea); //$NON-NLS-1$
+ output.addPlaceholder(ErrorView.ID + ":*"); //$NON-NLS-1$
+ output.addView(ErrorView.ID);
+ output.addView(IConsoleConstants.ID_CONSOLE_VIEW);
- layout.getViewLayout(IConsoleConstants.ID_CONSOLE_VIEW).setCloseable(false);
- layout.getViewLayout(ErrorView.ID).setCloseable(false);
+ layout.getViewLayout(IConsoleConstants.ID_CONSOLE_VIEW).setCloseable(false);
+ layout.getViewLayout(ErrorView.ID).setCloseable(false);
- layout.addShowViewShortcut(ProbeAliasBrowserView.ID);
- layout.addShowViewShortcut(FunctionBrowserView.ID);
- layout.addShowViewShortcut(KernelBrowserView.ID);
- layout.addShowViewShortcut(ErrorView.ID);
- layout.addShowViewShortcut(IConsoleConstants.ID_CONSOLE_VIEW);
+ layout.addShowViewShortcut(ProbeAliasBrowserView.ID);
+ layout.addShowViewShortcut(FunctionBrowserView.ID);
+ layout.addShowViewShortcut(KernelBrowserView.ID);
+ layout.addShowViewShortcut(ErrorView.ID);
+ layout.addShowViewShortcut(IConsoleConstants.ID_CONSOLE_VIEW);
- layout.addPerspectiveShortcut(ID);
- }
+ layout.addPerspectiveShortcut(ID);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDEPlugin.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDEPlugin.java
index de8824469d..efcf6ebe28 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDEPlugin.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDEPlugin.java
@@ -36,90 +36,90 @@ import org.osgi.framework.BundleContext;
* @author Ryan Morse
*/
public class IDEPlugin extends AbstractUIPlugin {
- private IWorkbenchListener workbenchListener;
- private static IDEPlugin plugin;
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.systemtap.ui.ide"; //$NON-NLS-1$
- public static final String SPACE = "space"; //$NON-NLS-1$
- public static final String TAB = "tab"; //$NON-NLS-1$
+ private IWorkbenchListener workbenchListener;
+ private static IDEPlugin plugin;
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.systemtap.ui.ide"; //$NON-NLS-1$
+ public static final String SPACE = "space"; //$NON-NLS-1$
+ public static final String TAB = "tab"; //$NON-NLS-1$
- public IDEPlugin() {
- plugin = this;
- }
+ public IDEPlugin() {
+ plugin = this;
+ }
- /**
- * Called by the Eclipse Workbench at plugin activation time. Starts the plugin lifecycle.
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
+ /**
+ * Called by the Eclipse Workbench at plugin activation time. Starts the plugin lifecycle.
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
- workbenchListener = new IDECloseMonitor();
- plugin.getWorkbench().addWorkbenchListener(workbenchListener);
- TapsetLibrary.init();
- }
+ workbenchListener = new IDECloseMonitor();
+ plugin.getWorkbench().addWorkbenchListener(workbenchListener);
+ TapsetLibrary.init();
+ }
- /**
- * Called by the Eclipse Workbench to deactivate the plugin.
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- super.stop(context);
- TapsetLibrary.stop();
- ScriptConsole.stopAll();
- plugin.getWorkbench().removeWorkbenchListener(workbenchListener);
- plugin = null;
- }
+ /**
+ * Called by the Eclipse Workbench to deactivate the plugin.
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ super.stop(context);
+ TapsetLibrary.stop();
+ ScriptConsole.stopAll();
+ plugin.getWorkbench().removeWorkbenchListener(workbenchListener);
+ plugin = null;
+ }
- /**
- * Returns this plugin's instance.
- */
- public static IDEPlugin getDefault() {
- return plugin;
- }
+ /**
+ * Returns this plugin's instance.
+ */
+ public static IDEPlugin getDefault() {
+ return plugin;
+ }
- /**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path.
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return AbstractUIPlugin.imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
+ /**
+ * Returns an image descriptor for the image file at the given
+ * plug-in relative path.
+ *
+ * @param path the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ return AbstractUIPlugin.imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
- /**
- * Create an uri to be used to connect to the remote machine
- */
- public URI createRemoteUri(String path) {
- IPreferenceStore p = ConsoleLogPlugin.getDefault().getPreferenceStore();
- String user = p.getString(ConsoleLogPreferenceConstants.SCP_USER);
- String host = p.getString(ConsoleLogPreferenceConstants.HOST_NAME);
- if (path == null)
- {
- path = ""; //$NON-NLS-1$
- }
- try {
- URI uri = new URI("ssh", user, host, -1, path, null, null); //$NON-NLS-1$
- return uri;
- } catch (URISyntaxException uri) {
- return null;
- }
- }
-
- public static void log(IStatus status) {
- ResourcesPlugin.getPlugin().getLog().log(status);
- }
+ /**
+ * Create an uri to be used to connect to the remote machine
+ */
+ public URI createRemoteUri(String path) {
+ IPreferenceStore p = ConsoleLogPlugin.getDefault().getPreferenceStore();
+ String user = p.getString(ConsoleLogPreferenceConstants.SCP_USER);
+ String host = p.getString(ConsoleLogPreferenceConstants.HOST_NAME);
+ if (path == null)
+ {
+ path = ""; //$NON-NLS-1$
+ }
+ try {
+ URI uri = new URI("ssh", user, host, -1, path, null, null); //$NON-NLS-1$
+ return uri;
+ } catch (URISyntaxException uri) {
+ return null;
+ }
+ }
- public static void log(Throwable e) {
- if (e instanceof InvocationTargetException)
- e = ((InvocationTargetException) e).getTargetException();
- IStatus status = null;
- if (e instanceof CoreException)
- status = ((CoreException) e).getStatus();
- else
- status = new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, e.getMessage(), e);
- log(status);
- }
+ public static void log(IStatus status) {
+ ResourcesPlugin.getPlugin().getLog().log(status);
+ }
+
+ public static void log(Throwable e) {
+ if (e instanceof InvocationTargetException)
+ e = ((InvocationTargetException) e).getTargetException();
+ IStatus status = null;
+ if (e instanceof CoreException)
+ status = ((CoreException) e).getStatus();
+ else
+ status = new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, e.getMessage(), e);
+ log(status);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDESessionSettings.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDESessionSettings.java
index 6c790f19b2..7c71890c83 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDESessionSettings.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/IDESessionSettings.java
@@ -34,148 +34,148 @@ import org.eclipse.ui.dialogs.ListDialog;
* @author Ryan Morse
*/
public class IDESessionSettings {
- public static String tapsetLocation = ""; //$NON-NLS-1$
-
- /**
- * Use {@link IDESessionSettings#setActiveSTPEditor(STPEditor)} and
- * {@link IDESessionSettings#getActiveSTPEditor()}
- */
- private static STPEditor activeSTPEditor = null;
-
- /**
- * Returns the most recent active {@link STPEditor} script editor if one was
- * set. If one was not set and there is only one {@link STPEditor} script editor
- * open then that one is returned. Otherwise returns null.
- * @return The most recent active {@link STPEditor}
- * @since 1.2
- */
- public static STPEditor getActiveSTPEditor() {
- if (activeSTPEditor == null) {
- // If no active editor is et and there is only one
- // opened stap script editor, set it to be the active editor.
- IEditorReference[] editors = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences();
- STPEditor stpEditor = null;
- for (IEditorReference editor: editors) {
- if (editor.getId().equals(STPEditor.ID)) {
- if (stpEditor == null) {
- stpEditor = (STPEditor) editor.getEditor(true);
- } else {
- return null;
- }
- }
- }
- activeSTPEditor = stpEditor;
- }
- return activeSTPEditor;
- }
-
- /**
- * Sets the current active editor.
- * @param editor the active editor.
- * @since 1.2
- */
- public static void setActiveSTPEditor(STPEditor editor) {
- activeSTPEditor = editor;
- }
-
- /**
- * Restore and return an STPEditor based on the user's choice.
- * @param checkCurrent Set to <code>true</code> if the currently active editor may be returned
- * if it is an {@link STPEditor}.
- * @return
- */
- public static STPEditor getOrAskForActiveSTPEditor(boolean checkCurrent) {
- STPEditor stpEditor;
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- IWorkbenchPage page = window.getActivePage();
- if (checkCurrent) {
- IEditorPart editor = page.getActiveEditor();
- stpEditor = editor instanceof STPEditor ? (STPEditor) editor : askForSTPEditor(window);
- } else {
- stpEditor = askForSTPEditor(window);
- }
- if (stpEditor != null) {
- page.activate(stpEditor);
- }
- return stpEditor;
- }
-
- private static STPEditor askForSTPEditor(IWorkbenchWindow window) {
- final List<STPEditor> allEditors = new LinkedList<>();
- for (IEditorReference editor : window.getActivePage().getEditorReferences()) {
- if (editor.getId().equals(STPEditor.ID)) {
- allEditors.add((STPEditor) editor.getEditor(true));
- }
- }
-
- switch (allEditors.size()) {
- // If only one file is found, open it. Give user the option to open another file.
- case 1:
- MessageDialog messageDialog = new MessageDialog(window.getShell(),
- Localization.getString("GetEditorAction.DialogTitle"), null, //$NON-NLS-1$
- MessageFormat.format(Localization.getString("GetEditorAction.AskBeforeOpenMessage"), //$NON-NLS-1$
- allEditors.get(0).getEditorInput().getName() ),
- MessageDialog.QUESTION,
- new String[]{Localization.getString("GetEditorAction.AskBeforeOpenCancel"), //$NON-NLS-1$
- Localization.getString("GetEditorAction.AskBeforeOpenAnother"), //$NON-NLS-1$
- Localization.getString("GetEditorAction.AskBeforeOpenYes")}, 2); //$NON-NLS-1$
-
- switch (messageDialog.open()) {
- case 2:
- return allEditors.get(0);
-
- case 1:
- return openNewFile(window);
-
- default:
- return null;
- }
-
- // If no files found, prompt user to open a new file
- case 0:
- return openNewFile(window);
-
- // If multiple files found, prompt user to select one of them
- default:
- return openNewFileFromMultiple(window, allEditors);
- }
- }
-
- private static STPEditor openNewFileFromMultiple(IWorkbenchWindow window, final List<STPEditor> allEditors) {
- ListDialog listDialog = new ListDialog(window.getShell());
- listDialog.setTitle(Localization.getString("GetEditorAction.DialogTitle")); //$NON-NLS-1$
- listDialog.setContentProvider(new ArrayContentProvider());
-
- listDialog.setLabelProvider(new LabelProvider() {
- @Override
- public String getText(Object element) {
- int i = (Integer) element;
- return i != -1 ? allEditors.get(i).getEditorInput().getName()
- : Localization.getString("GetEditorAction.OtherFile"); //$NON-NLS-1$
- }
- });
-
- Integer[] editorIndexes = new Integer[allEditors.size() + 1];
- for (int i = 0; i < editorIndexes.length - 1; i++) {
- editorIndexes[i] = i;
- }
- editorIndexes[editorIndexes.length - 1] = -1;
- listDialog.setInput(editorIndexes);
- listDialog.setMessage(Localization.getString("GetEditorAction.SelectEditor")); //$NON-NLS-1$
- if (listDialog.open() == Window.OK) {
- int result = (Integer) listDialog.getResult()[0];
- return result != -1 ? allEditors.get(result) : openNewFile(window);
- }
- // Abort if user cancels
- return null;
- }
-
- private static STPEditor openNewFile(IWorkbenchWindow window) {
- NewFileAction action = new NewFileAction();
- action.run();
- if (action.isSuccessful()) {
- return (STPEditor) window.getActivePage().getActiveEditor();
- }
- return null;
- }
+ public static String tapsetLocation = ""; //$NON-NLS-1$
+
+ /**
+ * Use {@link IDESessionSettings#setActiveSTPEditor(STPEditor)} and
+ * {@link IDESessionSettings#getActiveSTPEditor()}
+ */
+ private static STPEditor activeSTPEditor = null;
+
+ /**
+ * Returns the most recent active {@link STPEditor} script editor if one was
+ * set. If one was not set and there is only one {@link STPEditor} script editor
+ * open then that one is returned. Otherwise returns null.
+ * @return The most recent active {@link STPEditor}
+ * @since 1.2
+ */
+ public static STPEditor getActiveSTPEditor() {
+ if (activeSTPEditor == null) {
+ // If no active editor is et and there is only one
+ // opened stap script editor, set it to be the active editor.
+ IEditorReference[] editors = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences();
+ STPEditor stpEditor = null;
+ for (IEditorReference editor: editors) {
+ if (editor.getId().equals(STPEditor.ID)) {
+ if (stpEditor == null) {
+ stpEditor = (STPEditor) editor.getEditor(true);
+ } else {
+ return null;
+ }
+ }
+ }
+ activeSTPEditor = stpEditor;
+ }
+ return activeSTPEditor;
+ }
+
+ /**
+ * Sets the current active editor.
+ * @param editor the active editor.
+ * @since 1.2
+ */
+ public static void setActiveSTPEditor(STPEditor editor) {
+ activeSTPEditor = editor;
+ }
+
+ /**
+ * Restore and return an STPEditor based on the user's choice.
+ * @param checkCurrent Set to <code>true</code> if the currently active editor may be returned
+ * if it is an {@link STPEditor}.
+ * @return
+ */
+ public static STPEditor getOrAskForActiveSTPEditor(boolean checkCurrent) {
+ STPEditor stpEditor;
+ IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ IWorkbenchPage page = window.getActivePage();
+ if (checkCurrent) {
+ IEditorPart editor = page.getActiveEditor();
+ stpEditor = editor instanceof STPEditor ? (STPEditor) editor : askForSTPEditor(window);
+ } else {
+ stpEditor = askForSTPEditor(window);
+ }
+ if (stpEditor != null) {
+ page.activate(stpEditor);
+ }
+ return stpEditor;
+ }
+
+ private static STPEditor askForSTPEditor(IWorkbenchWindow window) {
+ final List<STPEditor> allEditors = new LinkedList<>();
+ for (IEditorReference editor : window.getActivePage().getEditorReferences()) {
+ if (editor.getId().equals(STPEditor.ID)) {
+ allEditors.add((STPEditor) editor.getEditor(true));
+ }
+ }
+
+ switch (allEditors.size()) {
+ // If only one file is found, open it. Give user the option to open another file.
+ case 1:
+ MessageDialog messageDialog = new MessageDialog(window.getShell(),
+ Localization.getString("GetEditorAction.DialogTitle"), null, //$NON-NLS-1$
+ MessageFormat.format(Localization.getString("GetEditorAction.AskBeforeOpenMessage"), //$NON-NLS-1$
+ allEditors.get(0).getEditorInput().getName() ),
+ MessageDialog.QUESTION,
+ new String[]{Localization.getString("GetEditorAction.AskBeforeOpenCancel"), //$NON-NLS-1$
+ Localization.getString("GetEditorAction.AskBeforeOpenAnother"), //$NON-NLS-1$
+ Localization.getString("GetEditorAction.AskBeforeOpenYes")}, 2); //$NON-NLS-1$
+
+ switch (messageDialog.open()) {
+ case 2:
+ return allEditors.get(0);
+
+ case 1:
+ return openNewFile(window);
+
+ default:
+ return null;
+ }
+
+ // If no files found, prompt user to open a new file
+ case 0:
+ return openNewFile(window);
+
+ // If multiple files found, prompt user to select one of them
+ default:
+ return openNewFileFromMultiple(window, allEditors);
+ }
+ }
+
+ private static STPEditor openNewFileFromMultiple(IWorkbenchWindow window, final List<STPEditor> allEditors) {
+ ListDialog listDialog = new ListDialog(window.getShell());
+ listDialog.setTitle(Localization.getString("GetEditorAction.DialogTitle")); //$NON-NLS-1$
+ listDialog.setContentProvider(new ArrayContentProvider());
+
+ listDialog.setLabelProvider(new LabelProvider() {
+ @Override
+ public String getText(Object element) {
+ int i = (Integer) element;
+ return i != -1 ? allEditors.get(i).getEditorInput().getName()
+ : Localization.getString("GetEditorAction.OtherFile"); //$NON-NLS-1$
+ }
+ });
+
+ Integer[] editorIndexes = new Integer[allEditors.size() + 1];
+ for (int i = 0; i < editorIndexes.length - 1; i++) {
+ editorIndexes[i] = i;
+ }
+ editorIndexes[editorIndexes.length - 1] = -1;
+ listDialog.setInput(editorIndexes);
+ listDialog.setMessage(Localization.getString("GetEditorAction.SelectEditor")); //$NON-NLS-1$
+ if (listDialog.open() == Window.OK) {
+ int result = (Integer) listDialog.getResult()[0];
+ return result != -1 ? allEditors.get(result) : openNewFile(window);
+ }
+ // Abort if user cancels
+ return null;
+ }
+
+ private static STPEditor openNewFile(IWorkbenchWindow window) {
+ NewFileAction action = new NewFileAction();
+ action.run();
+ if (action.isSuccessful()) {
+ return (STPEditor) window.getActivePage().getActiveEditor();
+ }
+ return null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/Localization.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/Localization.java
index b8194956e5..581386db5a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/Localization.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/Localization.java
@@ -15,19 +15,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Localization {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.localization"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.localization"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Localization() {
- }
+ private Localization() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/StringOutputStream.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/StringOutputStream.java
index 30b629105b..4e3139f9a3 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/StringOutputStream.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/StringOutputStream.java
@@ -14,15 +14,15 @@ package org.eclipse.linuxtools.internal.systemtap.ui.ide;
import java.io.OutputStream;
public class StringOutputStream extends OutputStream {
- private StringBuffer str = new StringBuffer();
+ private StringBuffer str = new StringBuffer();
- @Override
- public String toString() {
- return str.toString();
- }
+ @Override
+ public String toString() {
+ return str.toString();
+ }
- @Override
- public void write(int b) {
- str.append((char)b);
- }
+ @Override
+ public void write(int b) {
+ str.append((char)b);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/BrowserViewAction.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/BrowserViewAction.java
index aba71c915c..601164969b 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/BrowserViewAction.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/BrowserViewAction.java
@@ -22,56 +22,56 @@ import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
public abstract class BrowserViewAction extends Action implements ISelectionListener, IDoubleClickListener {
- private final IWorkbenchWindow window;
- private final BrowserView viewer;
- private IStructuredSelection selection;
- private TreeExpandCollapseAction expandAction;
+ private final IWorkbenchWindow window;
+ private final BrowserView viewer;
+ private IStructuredSelection selection;
+ private TreeExpandCollapseAction expandAction;
- /**
- * The Default Constructor. Takes the <code>IWorkbenchWindow</code> that it effects
- * as well as the <code>BrowserView</code> that will fire this action.
- * @param window window effected by this event
- * @param browser browser that fires this action
- */
- public BrowserViewAction(IWorkbenchWindow window, BrowserView browser) {
- this.window = window;
- window.getSelectionService().addSelectionListener(this);
- viewer = browser;
- expandAction = new TreeExpandCollapseAction(viewer);
- }
+ /**
+ * The Default Constructor. Takes the <code>IWorkbenchWindow</code> that it effects
+ * as well as the <code>BrowserView</code> that will fire this action.
+ * @param window window effected by this event
+ * @param browser browser that fires this action
+ */
+ public BrowserViewAction(IWorkbenchWindow window, BrowserView browser) {
+ this.window = window;
+ window.getSelectionService().addSelectionListener(this);
+ viewer = browser;
+ expandAction = new TreeExpandCollapseAction(viewer);
+ }
- public void dispose() {
- window.getSelectionService().removeSelectionListener(this);
- selection = null;
- expandAction.dispose();
- expandAction = null;
- }
+ public void dispose() {
+ window.getSelectionService().removeSelectionListener(this);
+ selection = null;
+ expandAction.dispose();
+ expandAction = null;
+ }
- /**
- * Updates <code>selection</code> with the current selection whenever the user changes
- * the current selection.
- */
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
- if (incoming instanceof IStructuredSelection) {
- selection = (IStructuredSelection) incoming;
- setEnabled(selection.size() == 1);
- } else {
- // Other selections, for example containing text or of other kinds.
- setEnabled(false);
- }
- }
+ /**
+ * Updates <code>selection</code> with the current selection whenever the user changes
+ * the current selection.
+ */
+ @Override
+ public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
+ if (incoming instanceof IStructuredSelection) {
+ selection = (IStructuredSelection) incoming;
+ setEnabled(selection.size() == 1);
+ } else {
+ // Other selections, for example containing text or of other kinds.
+ setEnabled(false);
+ }
+ }
- @Override
- public void doubleClick(DoubleClickEvent event) {
- run();
- }
+ @Override
+ public void doubleClick(DoubleClickEvent event) {
+ run();
+ }
- protected Object getSelectedElement() {
- return ((IStructuredSelection) viewer.getViewer().getSelection()).getFirstElement();
- }
+ protected Object getSelectedElement() {
+ return ((IStructuredSelection) viewer.getViewer().getSelection()).getFirstElement();
+ }
- protected void runExpandAction() {
- expandAction.run();
- }
+ protected void runExpandAction() {
+ expandAction.run();
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ExportDataSetHandler.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ExportDataSetHandler.java
index c36a4ab0fa..2e1e2fbf60 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ExportDataSetHandler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ExportDataSetHandler.java
@@ -26,32 +26,32 @@ import org.eclipse.ui.PlatformUI;
*/
public class ExportDataSetHandler extends AbstractHandler {
- private GraphSelectorEditor getActiveGraphEditor() {
- IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- return editor instanceof GraphSelectorEditor ? (GraphSelectorEditor) editor : null;
- }
-
- @Override
- public Object execute(ExecutionEvent event) {
- GraphSelectorEditor editor = getActiveGraphEditor();
- if (editor == null) {
- return null;
- }
- FileDialog dialog = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
- dialog.setOverwrite(true);
- dialog.setFilterExtensions(new String[]{Messages.DataSetFileExtension});
- dialog.setText(MessageFormat.format(Messages.ExportDataSetAction_DialogTitle, editor.getActiveTitle()));
- dialog.setFileName(editor.getActiveTitle().replaceAll(" ", "")); //$NON-NLS-1$ //$NON-NLS-2$
- String path = dialog.open();
- if (path != null) {
- editor.getActiveDisplaySet().getDataSet().writeToFile(new File(path));
- }
- return null;
- }
-
- @Override
- public boolean isEnabled() {
- return getActiveGraphEditor() != null;
- }
+ private GraphSelectorEditor getActiveGraphEditor() {
+ IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
+ return editor instanceof GraphSelectorEditor ? (GraphSelectorEditor) editor : null;
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) {
+ GraphSelectorEditor editor = getActiveGraphEditor();
+ if (editor == null) {
+ return null;
+ }
+ FileDialog dialog = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
+ dialog.setOverwrite(true);
+ dialog.setFilterExtensions(new String[]{Messages.DataSetFileExtension});
+ dialog.setText(MessageFormat.format(Messages.ExportDataSetAction_DialogTitle, editor.getActiveTitle()));
+ dialog.setFileName(editor.getActiveTitle().replaceAll(" ", "")); //$NON-NLS-1$ //$NON-NLS-2$
+ String path = dialog.open();
+ if (path != null) {
+ editor.getActiveDisplaySet().getDataSet().writeToFile(new File(path));
+ }
+ return null;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return getActiveGraphEditor() != null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/FunctionBrowserAction.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/FunctionBrowserAction.java
index ceeec32046..8f09de3340 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/FunctionBrowserAction.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/FunctionBrowserAction.java
@@ -34,38 +34,38 @@ import org.eclipse.ui.IWorkbenchWindow;
* @see org.eclipse.linuxtools.internal.systemtap.ui.ide.actions.TreeExpandCollapseAction
*/
public class FunctionBrowserAction extends BrowserViewAction {
- private static final String ID = "org.eclipse.linuxtools.systemtap.ui.ide.FunctionAction"; //$NON-NLS-1$
+ private static final String ID = "org.eclipse.linuxtools.systemtap.ui.ide.FunctionAction"; //$NON-NLS-1$
- public FunctionBrowserAction(IWorkbenchWindow window, FunctionBrowserView browser) {
- super(window, browser);
- setId(ID);
- setActionDefinitionId(ID);
- setText(Localization.getString("FunctionBrowserAction.Insert")); //$NON-NLS-1$
- setToolTipText(Localization
- .getString("FunctionBrowserAction.InsertFunction")); //$NON-NLS-1$
- }
+ public FunctionBrowserAction(IWorkbenchWindow window, FunctionBrowserView browser) {
+ super(window, browser);
+ setId(ID);
+ setActionDefinitionId(ID);
+ setText(Localization.getString("FunctionBrowserAction.Insert")); //$NON-NLS-1$
+ setToolTipText(Localization
+ .getString("FunctionBrowserAction.InsertFunction")); //$NON-NLS-1$
+ }
- /**
- * The main action code, invoked when this action is fired. This code checks the current
- * selection's clickable property, and either invokes the <code>TreeExpandCollapseAction</code> if
- * the selection is not clickable (i.e. the selection is not a function, but a category of functions),
- * or it inserts text for a function call to the selected function in the active STPEditor
- * (creating a new editor if there is not one currently open).
- */
- @Override
- public void run() {
- Object o = getSelectedElement();
- if (o instanceof TreeNode) {
- TreeNode t = (TreeNode) o;
- if (t.isClickable()) {
- STPEditor stpeditor = IDESessionSettings.getOrAskForActiveSTPEditor(true);
- if (stpeditor != null) {
- stpeditor.insertTextAtCurrent(t.toString() + "\n"); //$NON-NLS-1$
- }
- } else {
- runExpandAction();
- }
- }
- }
+ /**
+ * The main action code, invoked when this action is fired. This code checks the current
+ * selection's clickable property, and either invokes the <code>TreeExpandCollapseAction</code> if
+ * the selection is not clickable (i.e. the selection is not a function, but a category of functions),
+ * or it inserts text for a function call to the selected function in the active STPEditor
+ * (creating a new editor if there is not one currently open).
+ */
+ @Override
+ public void run() {
+ Object o = getSelectedElement();
+ if (o instanceof TreeNode) {
+ TreeNode t = (TreeNode) o;
+ if (t.isClickable()) {
+ STPEditor stpeditor = IDESessionSettings.getOrAskForActiveSTPEditor(true);
+ if (stpeditor != null) {
+ stpeditor.insertTextAtCurrent(t.toString() + "\n"); //$NON-NLS-1$
+ }
+ } else {
+ runExpandAction();
+ }
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ImportDataSetHandler.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ImportDataSetHandler.java
index 13b549f6c8..99f974d8b2 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ImportDataSetHandler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ImportDataSetHandler.java
@@ -42,52 +42,52 @@ import org.eclipse.ui.WorkbenchException;
*/
public class ImportDataSetHandler extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) {
- FileDialog dialog = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OPEN);
- dialog.setFilterExtensions(new String[]{Messages.DataSetFileExtension});
- dialog.setText(Messages.ImportDataSetAction_DialogTitle);
- String path = dialog.open();
- if (path == null) {
- return null;
- }
+ @Override
+ public Object execute(ExecutionEvent event) {
+ FileDialog dialog = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OPEN);
+ dialog.setFilterExtensions(new String[]{Messages.DataSetFileExtension});
+ dialog.setText(Messages.ImportDataSetAction_DialogTitle);
+ String path = dialog.open();
+ if (path == null) {
+ return null;
+ }
- IFilteredDataSet dataset = null;
- File file = new File(path);
- try (InputStreamReader fr = new InputStreamReader(new FileInputStream(file), Charset.defaultCharset());
- BufferedReader br = new BufferedReader(fr)) {
- String id = br.readLine();
- String[] titles = br.readLine().split(", "); //$NON-NLS-1$
+ IFilteredDataSet dataset = null;
+ File file = new File(path);
+ try (InputStreamReader fr = new InputStreamReader(new FileInputStream(file), Charset.defaultCharset());
+ BufferedReader br = new BufferedReader(fr)) {
+ String id = br.readLine();
+ String[] titles = br.readLine().split(", "); //$NON-NLS-1$
- if (id == null && titles == null) {
- throw new IOException();
- } else if (id.equals(RowDataSet.ID)) {
- dataset = new FilteredRowDataSet(titles);
- } else if (id.equals(TableDataSet.ID)) {
- dataset = new FilteredTableDataSet(titles);
- } else {
- throw new IOException();
- }
- dataset.readFromFile(file);
+ if (id == null && titles == null) {
+ throw new IOException();
+ } else if (id.equals(RowDataSet.ID)) {
+ dataset = new FilteredRowDataSet(titles);
+ } else if (id.equals(TableDataSet.ID)) {
+ dataset = new FilteredTableDataSet(titles);
+ } else {
+ throw new IOException();
+ }
+ dataset.readFromFile(file);
- String title = path.substring(path.lastIndexOf('/')+1);
- IWorkbenchPage p = PlatformUI.getWorkbench().showPerspective(IDEPerspective.ID, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
- GraphSelectorEditor ivp = (GraphSelectorEditor)p.openEditor(new GraphSelectorEditorInput(title), GraphSelectorEditor.ID);
- ivp.createScriptSets(path, Arrays.asList(title), Arrays.asList(dataset));
- } catch (FileNotFoundException fnfe) {
- ExceptionErrorDialog.openError(Messages.ImportDataSetAction_FileNotFound, fnfe);
- } catch (IOException ioe) {
- ExceptionErrorDialog.openError(Messages.ImportDataSetAction_FileInvalid, ioe);
- } catch (WorkbenchException we) {
- ExceptionErrorDialog.openError(Messages.RunScriptChartAction_couldNotSwitchToGraphicPerspective, we);
- }
+ String title = path.substring(path.lastIndexOf('/')+1);
+ IWorkbenchPage p = PlatformUI.getWorkbench().showPerspective(IDEPerspective.ID, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
+ GraphSelectorEditor ivp = (GraphSelectorEditor)p.openEditor(new GraphSelectorEditorInput(title), GraphSelectorEditor.ID);
+ ivp.createScriptSets(path, Arrays.asList(title), Arrays.asList(dataset));
+ } catch (FileNotFoundException fnfe) {
+ ExceptionErrorDialog.openError(Messages.ImportDataSetAction_FileNotFound, fnfe);
+ } catch (IOException ioe) {
+ ExceptionErrorDialog.openError(Messages.ImportDataSetAction_FileInvalid, ioe);
+ } catch (WorkbenchException we) {
+ ExceptionErrorDialog.openError(Messages.RunScriptChartAction_couldNotSwitchToGraphicPerspective, we);
+ }
- return null;
- }
+ return null;
+ }
- @Override
- public boolean isEnabled() {
- return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().
- getPerspective().getId().equals(IDEPerspective.ID);
- }
+ @Override
+ public boolean isEnabled() {
+ return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().
+ getPerspective().getId().equals(IDEPerspective.ID);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ImportTapsetHandler.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ImportTapsetHandler.java
index 731c564e66..d26794f053 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ImportTapsetHandler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ImportTapsetHandler.java
@@ -19,16 +19,16 @@ import org.eclipse.ui.handlers.HandlerUtil;
public class ImportTapsetHandler extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) {
- String pageID = "org.eclipse.linuxtools.systemtap.prefs.ide.tapsets"; //$NON-NLS-1$
- PreferencesUtil.createPreferenceDialogOn(HandlerUtil.getActiveShell(event), pageID, new String[]{pageID}, null).open();
- return null;
- }
+ @Override
+ public Object execute(ExecutionEvent event) {
+ String pageID = "org.eclipse.linuxtools.systemtap.prefs.ide.tapsets"; //$NON-NLS-1$
+ PreferencesUtil.createPreferenceDialogOn(HandlerUtil.getActiveShell(event), pageID, new String[]{pageID}, null).open();
+ return null;
+ }
- @Override
- public boolean isEnabled() {
- return true;
- }
+ @Override
+ public boolean isEnabled() {
+ return true;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/IndentHandler.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/IndentHandler.java
index 845dd84f76..449ee316c4 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/IndentHandler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/IndentHandler.java
@@ -51,459 +51,459 @@ import org.eclipse.ui.texteditor.ITextEditor;
* complete AST must be present, the indentation is computed using heuristics.
* The algorithm used is fast for single lines, but does not store any
* information and therefore not so efficient for large line ranges.
- *
+ *
* @see org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.STPHeuristicScanner
* @see org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.STPIndenter
*/
public class IndentHandler extends AbstractHandler {
- /** The caret offset after an indent operation. */
- private int fCaretOffset;
-
- private class STPRunnable implements Runnable {
- private ITextEditor editor;
-
- public STPRunnable(ITextEditor editor) {
- this.editor = editor;
- }
-
- public ITextEditor getTextEditor() {
- return editor;
- }
-
- @Override
- public void run() {
- }
- }
-
- /**
- * Whether this is the action invoked by TAB. When <code>true</code>,
- * indentation behaves differently to accommodate normal TAB operation.
- */
- private final boolean fIsTabAction = false;
-
- @Override
- public Object execute(ExecutionEvent event) { // Update has been called by
- // the framework
- if (!isEnabled())
- return null;
-
- ITextEditor editor = (ITextEditor) HandlerUtil.getActiveEditor(event);
- if (editor == null || !editor.isEditable()) {
- return null;
- }
-
- ITextSelection selection = getSelection(editor);
- final IDocument document = getDocument(editor);
-
- if (document != null) {
- final int offset = selection.getOffset();
- final int length = selection.getLength();
- final Position end = new Position(offset + length);
- final int firstLine, nLines;
- fCaretOffset = -1;
-
- try {
- firstLine = document.getLineOfOffset(offset);
- // check for marginal (zero-length) lines
- int minusOne = length == 0 ? 0 : 1;
- nLines = document.getLineOfOffset(offset + length - minusOne)
- - firstLine + 1;
- document.addPosition(end);
- } catch (BadLocationException e) {
- // will only happen on concurrent modification
- IDEPlugin.log(new Status(IStatus.ERROR,
- IDEPlugin.PLUGIN_ID, IStatus.OK, "", e)); //$NON-NLS-1$
- return null;
- }
-
- Runnable runnable = new STPRunnable(editor) {
- @Override
- public void run() {
- IRewriteTarget target = (IRewriteTarget) getTextEditor()
- .getAdapter(IRewriteTarget.class);
- if (target != null) {
- target.beginCompoundChange();
- }
-
- try {
- STPHeuristicScanner scanner = new STPHeuristicScanner(
- document);
- STPIndenter indenter = new STPIndenter(document,
- scanner, getProject(getTextEditor()));
- final boolean multiLine = nLines > 1;
- boolean hasChanged = false;
- for (int i = 0; i < nLines; i++) {
+ /** The caret offset after an indent operation. */
+ private int fCaretOffset;
+
+ private class STPRunnable implements Runnable {
+ private ITextEditor editor;
+
+ public STPRunnable(ITextEditor editor) {
+ this.editor = editor;
+ }
+
+ public ITextEditor getTextEditor() {
+ return editor;
+ }
+
+ @Override
+ public void run() {
+ }
+ }
+
+ /**
+ * Whether this is the action invoked by TAB. When <code>true</code>,
+ * indentation behaves differently to accommodate normal TAB operation.
+ */
+ private final boolean fIsTabAction = false;
+
+ @Override
+ public Object execute(ExecutionEvent event) { // Update has been called by
+ // the framework
+ if (!isEnabled())
+ return null;
+
+ ITextEditor editor = (ITextEditor) HandlerUtil.getActiveEditor(event);
+ if (editor == null || !editor.isEditable()) {
+ return null;
+ }
+
+ ITextSelection selection = getSelection(editor);
+ final IDocument document = getDocument(editor);
+
+ if (document != null) {
+ final int offset = selection.getOffset();
+ final int length = selection.getLength();
+ final Position end = new Position(offset + length);
+ final int firstLine, nLines;
+ fCaretOffset = -1;
+
+ try {
+ firstLine = document.getLineOfOffset(offset);
+ // check for marginal (zero-length) lines
+ int minusOne = length == 0 ? 0 : 1;
+ nLines = document.getLineOfOffset(offset + length - minusOne)
+ - firstLine + 1;
+ document.addPosition(end);
+ } catch (BadLocationException e) {
+ // will only happen on concurrent modification
+ IDEPlugin.log(new Status(IStatus.ERROR,
+ IDEPlugin.PLUGIN_ID, IStatus.OK, "", e)); //$NON-NLS-1$
+ return null;
+ }
+
+ Runnable runnable = new STPRunnable(editor) {
+ @Override
+ public void run() {
+ IRewriteTarget target = (IRewriteTarget) getTextEditor()
+ .getAdapter(IRewriteTarget.class);
+ if (target != null) {
+ target.beginCompoundChange();
+ }
+
+ try {
+ STPHeuristicScanner scanner = new STPHeuristicScanner(
+ document);
+ STPIndenter indenter = new STPIndenter(document,
+ scanner, getProject(getTextEditor()));
+ final boolean multiLine = nLines > 1;
+ boolean hasChanged = false;
+ for (int i = 0; i < nLines; i++) {
hasChanged |= indentLine(document, firstLine + i,
offset, indenter, scanner, multiLine);
- }
-
- // update caret position: move to new position when
- // indenting just one line
- // keep selection when indenting multiple
- int newOffset, newLength;
- if (!fIsTabAction && multiLine) {
- newOffset = offset;
- newLength = end.getOffset() - offset;
- } else {
- newOffset = fCaretOffset;
- newLength = 0;
- }
-
- // always reset the selection if anything was replaced
- // but not when we had a single line non-tab invocation
- if (newOffset != -1
- && (hasChanged || newOffset != offset || newLength != length))
- selectAndReveal(getTextEditor(), newOffset,
- newLength);
-
- } catch (BadLocationException e) {
- // will only happen on concurrent modification
- IDEPlugin.log(new Status(IStatus.ERROR, IDEPlugin
- .PLUGIN_ID, IStatus.OK,
- "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$
- } finally {
- document.removePosition(end);
- if (target != null) {
- target.endCompoundChange();
- }
- }
- }
- };
-
- if (nLines > 50) {
- Display display = editor.getEditorSite().getWorkbenchWindow()
- .getShell().getDisplay();
- BusyIndicator.showWhile(display, runnable);
- } else {
- runnable.run();
- }
- }
-
- return null;
- }
-
- /**
- * Selects the given range on the editor.
- *
- * @param newOffset
- * the selection offset
- * @param newLength
- * the selection range
- */
- private void selectAndReveal(ITextEditor editor, int newOffset,
- int newLength) {
- Assert.isTrue(newOffset >= 0);
- Assert.isTrue(newLength >= 0);
- if (editor instanceof STPEditor) {
- ISourceViewer viewer = ((STPEditor) editor).getMySourceViewer();
- if (viewer != null) {
- viewer.setSelectedRange(newOffset, newLength);
- }
- } else {
- // this is too intrusive, but will never get called anyway
- editor.selectAndReveal(newOffset, newLength);
- }
- }
-
- /**
- * Indents a single line using the heuristic scanner. Multiline comments are
- * indented as specified by the <code>CCommentAutoIndentStrategy</code>.
- *
- * @param document
- * the document
- * @param line
- * the line to be indented
- * @param caret
- * the caret position
- * @param indenter
- * the indenter
- * @param scanner
- * the heuristic scanner
- * @param multiLine
- * <code>true</code> if more than one line is being indented
- * @return <code>true</code> if <code>document</code> was modified,
- * <code>false</code> otherwise
- * @throws BadLocationException
- * if the document got changed concurrently
- */
- private boolean indentLine(IDocument document,
- int line, int caret, STPIndenter indenter,
- STPHeuristicScanner scanner, boolean multiLine)
- throws BadLocationException {
- IRegion currentLine = document.getLineInformation(line);
- int offset = currentLine.getOffset();
- int wsStart = offset; // where we start searching for non-WS; after the
- // "//" in single line comments
-
- String indent = null;
- if (offset < document.getLength()) {
- ITypedRegion partition = TextUtilities.getPartition(document,
- STPPartitionScanner.STP_PARTITIONING, offset, true);
- ITypedRegion startingPartition = TextUtilities.getPartition(
- document, STPPartitionScanner.STP_PARTITIONING, offset,
- false);
- String type = partition.getType();
- if (type.equals(STPPartitionScanner.STP_MULTILINE_COMMENT)) {
- indent = computeCommentIndent(document, line, scanner,
- startingPartition);
- } else if (startingPartition.getType().equals(
- STPPartitionScanner.STP_CONDITIONAL)) {
- indent = computePreprocessorIndent(document, line,
- startingPartition);
- } else if (startingPartition.getType().equals(
- STPPartitionScanner.STP_STRING)
- && offset > startingPartition.getOffset()) {
- // don't indent inside (raw-)string
- return false;
- } else if (!fIsTabAction
- && startingPartition.getOffset() == offset
- && startingPartition.getType().equals(
- STPPartitionScanner.STP_COMMENT)) {
- // line comment starting at position 0 -> indent inside
- if (indentInsideLineComments()) {
- int max = document.getLength() - offset;
- int slashes = 2;
- while (slashes < max - 1
- && document.get(offset + slashes, 2).equals("//")) //$NON-NLS-1$
- slashes += 2;
-
- wsStart = offset + slashes;
-
- StringBuilder computed = indenter
- .computeIndentation(offset);
- if (computed == null)
- computed = new StringBuilder(0);
- int tabSize = getTabSize();
- while (slashes > 0 && computed.length() > 0) {
- char c = computed.charAt(0);
- if (c == '\t') {
- if (slashes > tabSize) {
- slashes -= tabSize;
- } else {
- break;
- }
- } else if (c == ' ') {
- slashes--;
- } else {
- break;
- }
-
- computed.deleteCharAt(0);
- }
-
- indent = document.get(offset, wsStart - offset) + computed;
- }
- }
- }
-
- // standard C code indentation
- if (indent == null) {
- StringBuilder computed = indenter.computeIndentation(offset);
- if (computed != null) {
- indent = computed.toString();
- } else {
- indent = ""; //$NON-NLS-1$
- }
- }
-
- // change document:
- // get current white space
- int lineLength = currentLine.getLength();
- int end = scanner.findNonWhitespaceForwardInAnyPartition(wsStart,
- offset + lineLength);
- if (end == STPHeuristicScanner.NOT_FOUND) {
- // an empty line
- end = offset + lineLength;
- if (multiLine && !indentEmptyLines()) {
- indent = ""; //$NON-NLS-1$
- }
- }
- int length = end - offset;
- String currentIndent = document.get(offset, length);
-
- // set the caret offset so it can be used when setting the selection
- if (caret >= offset && caret <= end) {
- fCaretOffset = offset + indent.length();
- } else {
- fCaretOffset = -1;
- }
-
- // only change the document if it is a real change
- if (!indent.equals(currentIndent)) {
- document.replace(offset, length, indent);
- return true;
- }
- return false;
- }
-
- /**
- * Computes and returns the indentation for a block comment line.
- *
- * @param document
- * the document
- * @param line
- * the line in document
- * @param scanner
- * the scanner
- * @param partition
- * the comment partition
- * @return the indent, or <code>null</code> if not computable
- * @throws BadLocationException
- */
- private String computeCommentIndent(IDocument document, int line,
- STPHeuristicScanner scanner, ITypedRegion partition)
- throws BadLocationException {
- return IndentUtil.computeCommentIndent(document, line, scanner,
- partition);
- }
-
- /**
- * Computes and returns the indentation for a preprocessor line.
- *
- * @param document
- * the document
- * @param line
- * the line in document
- * @param partition
- * the comment partition
- * @return the indent, or <code>null</code> if not computable
- * @throws BadLocationException
- */
- private String computePreprocessorIndent(IDocument document, int line,
- ITypedRegion partition) throws BadLocationException {
- return IndentUtil.computePreprocessorIndent(document, line, partition);
- }
-
- /**
- * Returns the tab size used by the editor, which is deduced from the
- * formatter preferences.
- *
- * @return the tab size as defined in the current formatter preferences
- */
- private int getTabSize() {
- return getCoreFormatterOption(
- STPDefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 4);
- }
-
- /**
- * Returns <code>true</code> if empty lines should be indented,
- * <code>false</code> otherwise.
- *
- * @return <code>true</code> if empty lines should be indented,
- * <code>false</code> otherwise
- */
- private boolean indentEmptyLines() {
- return STPDefaultCodeFormatterConstants.TRUE
- .equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES));
- }
-
- /**
- * Returns <code>true</code> if line comments at column 0 should be indented
- * inside, <code>false</code> otherwise.
- *
- * @return <code>true</code> if line comments at column 0 should be indented
- * inside, <code>false</code> otherwise.
- */
- private boolean indentInsideLineComments() {
- return STPDefaultCodeFormatterConstants.TRUE
- .equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_INSIDE_LINE_COMMENTS));
- }
-
- /**
- * Returns the possibly project-specific core preference defined under
- * <code>key</code>.
- *
- * @param key
- * the key of the preference
- * @return the value of the preference
- */
- private String getCoreFormatterOption(String key) {
- return "false"; //$NON-NLS-1$
- }
-
- /**
- * Returns the possibly project-specific core preference defined under
- * <code>key</code>, or <code>def</code> if the value is not a integer.
- *
- * @param key
- * the key of the preference
- * @param def
- * the default value
- * @return the value of the preference
- */
- private int getCoreFormatterOption(String key, int def) {
- try {
- return Integer.parseInt(getCoreFormatterOption(key));
- } catch (NumberFormatException e) {
- return def;
- }
- }
-
- /**
- * Returns the <code>IProject</code> of the current editor input, or
- * <code>null</code> if it cannot be found.
- *
- * @return the <code>IProject</code> of the current editor input, or
- * <code>null</code> if it cannot be found
- */
- private IProject getProject(ITextEditor editor) {
- if (editor == null)
- return null;
-
- IEditorInput input = editor.getEditorInput();
- if (input instanceof IFileEditorInput)
- return ((IFileEditorInput) input).getFile().getProject();
- return null;
- }
-
- /**
- * Returns the editor's selection provider.
- *
- * @return the editor's selection provider or <code>null</code>
- */
- private ISelectionProvider getSelectionProvider(ITextEditor editor) {
- if (editor != null) {
- return editor.getSelectionProvider();
- }
- return null;
- }
-
- /*
- * @see org.eclipse.ui.texteditor.IUpdate#update()
- */
-
- /**
- * Returns the document currently displayed in the editor, or
- * <code>null</code> if none can be obtained.
- *
- * @return the current document or <code>null</code>
- */
- private IDocument getDocument(ITextEditor editor) {
- if (editor != null) {
- IDocumentProvider provider = editor.getDocumentProvider();
- IEditorInput input = editor.getEditorInput();
- if (provider != null && input != null)
- return provider.getDocument(input);
-
- }
- return null;
- }
-
- /**
- * Returns the selection on the editor or an invalid selection if none can
- * be obtained. Returns never <code>null</code>.
- *
- * @return the current selection, never <code>null</code>
- */
- private ITextSelection getSelection(ITextEditor editor) {
- ISelectionProvider provider = getSelectionProvider(editor);
- if (provider != null) {
- ISelection selection = provider.getSelection();
- if (selection instanceof ITextSelection)
- return (ITextSelection) selection;
- }
-
- // null object
- return TextSelection.emptySelection();
- }
+ }
+
+ // update caret position: move to new position when
+ // indenting just one line
+ // keep selection when indenting multiple
+ int newOffset, newLength;
+ if (!fIsTabAction && multiLine) {
+ newOffset = offset;
+ newLength = end.getOffset() - offset;
+ } else {
+ newOffset = fCaretOffset;
+ newLength = 0;
+ }
+
+ // always reset the selection if anything was replaced
+ // but not when we had a single line non-tab invocation
+ if (newOffset != -1
+ && (hasChanged || newOffset != offset || newLength != length))
+ selectAndReveal(getTextEditor(), newOffset,
+ newLength);
+
+ } catch (BadLocationException e) {
+ // will only happen on concurrent modification
+ IDEPlugin.log(new Status(IStatus.ERROR, IDEPlugin
+ .PLUGIN_ID, IStatus.OK,
+ "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$
+ } finally {
+ document.removePosition(end);
+ if (target != null) {
+ target.endCompoundChange();
+ }
+ }
+ }
+ };
+
+ if (nLines > 50) {
+ Display display = editor.getEditorSite().getWorkbenchWindow()
+ .getShell().getDisplay();
+ BusyIndicator.showWhile(display, runnable);
+ } else {
+ runnable.run();
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Selects the given range on the editor.
+ *
+ * @param newOffset
+ * the selection offset
+ * @param newLength
+ * the selection range
+ */
+ private void selectAndReveal(ITextEditor editor, int newOffset,
+ int newLength) {
+ Assert.isTrue(newOffset >= 0);
+ Assert.isTrue(newLength >= 0);
+ if (editor instanceof STPEditor) {
+ ISourceViewer viewer = ((STPEditor) editor).getMySourceViewer();
+ if (viewer != null) {
+ viewer.setSelectedRange(newOffset, newLength);
+ }
+ } else {
+ // this is too intrusive, but will never get called anyway
+ editor.selectAndReveal(newOffset, newLength);
+ }
+ }
+
+ /**
+ * Indents a single line using the heuristic scanner. Multiline comments are
+ * indented as specified by the <code>CCommentAutoIndentStrategy</code>.
+ *
+ * @param document
+ * the document
+ * @param line
+ * the line to be indented
+ * @param caret
+ * the caret position
+ * @param indenter
+ * the indenter
+ * @param scanner
+ * the heuristic scanner
+ * @param multiLine
+ * <code>true</code> if more than one line is being indented
+ * @return <code>true</code> if <code>document</code> was modified,
+ * <code>false</code> otherwise
+ * @throws BadLocationException
+ * if the document got changed concurrently
+ */
+ private boolean indentLine(IDocument document,
+ int line, int caret, STPIndenter indenter,
+ STPHeuristicScanner scanner, boolean multiLine)
+ throws BadLocationException {
+ IRegion currentLine = document.getLineInformation(line);
+ int offset = currentLine.getOffset();
+ int wsStart = offset; // where we start searching for non-WS; after the
+ // "//" in single line comments
+
+ String indent = null;
+ if (offset < document.getLength()) {
+ ITypedRegion partition = TextUtilities.getPartition(document,
+ STPPartitionScanner.STP_PARTITIONING, offset, true);
+ ITypedRegion startingPartition = TextUtilities.getPartition(
+ document, STPPartitionScanner.STP_PARTITIONING, offset,
+ false);
+ String type = partition.getType();
+ if (type.equals(STPPartitionScanner.STP_MULTILINE_COMMENT)) {
+ indent = computeCommentIndent(document, line, scanner,
+ startingPartition);
+ } else if (startingPartition.getType().equals(
+ STPPartitionScanner.STP_CONDITIONAL)) {
+ indent = computePreprocessorIndent(document, line,
+ startingPartition);
+ } else if (startingPartition.getType().equals(
+ STPPartitionScanner.STP_STRING)
+ && offset > startingPartition.getOffset()) {
+ // don't indent inside (raw-)string
+ return false;
+ } else if (!fIsTabAction
+ && startingPartition.getOffset() == offset
+ && startingPartition.getType().equals(
+ STPPartitionScanner.STP_COMMENT)) {
+ // line comment starting at position 0 -> indent inside
+ if (indentInsideLineComments()) {
+ int max = document.getLength() - offset;
+ int slashes = 2;
+ while (slashes < max - 1
+ && document.get(offset + slashes, 2).equals("//")) //$NON-NLS-1$
+ slashes += 2;
+
+ wsStart = offset + slashes;
+
+ StringBuilder computed = indenter
+ .computeIndentation(offset);
+ if (computed == null)
+ computed = new StringBuilder(0);
+ int tabSize = getTabSize();
+ while (slashes > 0 && computed.length() > 0) {
+ char c = computed.charAt(0);
+ if (c == '\t') {
+ if (slashes > tabSize) {
+ slashes -= tabSize;
+ } else {
+ break;
+ }
+ } else if (c == ' ') {
+ slashes--;
+ } else {
+ break;
+ }
+
+ computed.deleteCharAt(0);
+ }
+
+ indent = document.get(offset, wsStart - offset) + computed;
+ }
+ }
+ }
+
+ // standard C code indentation
+ if (indent == null) {
+ StringBuilder computed = indenter.computeIndentation(offset);
+ if (computed != null) {
+ indent = computed.toString();
+ } else {
+ indent = ""; //$NON-NLS-1$
+ }
+ }
+
+ // change document:
+ // get current white space
+ int lineLength = currentLine.getLength();
+ int end = scanner.findNonWhitespaceForwardInAnyPartition(wsStart,
+ offset + lineLength);
+ if (end == STPHeuristicScanner.NOT_FOUND) {
+ // an empty line
+ end = offset + lineLength;
+ if (multiLine && !indentEmptyLines()) {
+ indent = ""; //$NON-NLS-1$
+ }
+ }
+ int length = end - offset;
+ String currentIndent = document.get(offset, length);
+
+ // set the caret offset so it can be used when setting the selection
+ if (caret >= offset && caret <= end) {
+ fCaretOffset = offset + indent.length();
+ } else {
+ fCaretOffset = -1;
+ }
+
+ // only change the document if it is a real change
+ if (!indent.equals(currentIndent)) {
+ document.replace(offset, length, indent);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Computes and returns the indentation for a block comment line.
+ *
+ * @param document
+ * the document
+ * @param line
+ * the line in document
+ * @param scanner
+ * the scanner
+ * @param partition
+ * the comment partition
+ * @return the indent, or <code>null</code> if not computable
+ * @throws BadLocationException
+ */
+ private String computeCommentIndent(IDocument document, int line,
+ STPHeuristicScanner scanner, ITypedRegion partition)
+ throws BadLocationException {
+ return IndentUtil.computeCommentIndent(document, line, scanner,
+ partition);
+ }
+
+ /**
+ * Computes and returns the indentation for a preprocessor line.
+ *
+ * @param document
+ * the document
+ * @param line
+ * the line in document
+ * @param partition
+ * the comment partition
+ * @return the indent, or <code>null</code> if not computable
+ * @throws BadLocationException
+ */
+ private String computePreprocessorIndent(IDocument document, int line,
+ ITypedRegion partition) throws BadLocationException {
+ return IndentUtil.computePreprocessorIndent(document, line, partition);
+ }
+
+ /**
+ * Returns the tab size used by the editor, which is deduced from the
+ * formatter preferences.
+ *
+ * @return the tab size as defined in the current formatter preferences
+ */
+ private int getTabSize() {
+ return getCoreFormatterOption(
+ STPDefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 4);
+ }
+
+ /**
+ * Returns <code>true</code> if empty lines should be indented,
+ * <code>false</code> otherwise.
+ *
+ * @return <code>true</code> if empty lines should be indented,
+ * <code>false</code> otherwise
+ */
+ private boolean indentEmptyLines() {
+ return STPDefaultCodeFormatterConstants.TRUE
+ .equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES));
+ }
+
+ /**
+ * Returns <code>true</code> if line comments at column 0 should be indented
+ * inside, <code>false</code> otherwise.
+ *
+ * @return <code>true</code> if line comments at column 0 should be indented
+ * inside, <code>false</code> otherwise.
+ */
+ private boolean indentInsideLineComments() {
+ return STPDefaultCodeFormatterConstants.TRUE
+ .equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_INSIDE_LINE_COMMENTS));
+ }
+
+ /**
+ * Returns the possibly project-specific core preference defined under
+ * <code>key</code>.
+ *
+ * @param key
+ * the key of the preference
+ * @return the value of the preference
+ */
+ private String getCoreFormatterOption(String key) {
+ return "false"; //$NON-NLS-1$
+ }
+
+ /**
+ * Returns the possibly project-specific core preference defined under
+ * <code>key</code>, or <code>def</code> if the value is not a integer.
+ *
+ * @param key
+ * the key of the preference
+ * @param def
+ * the default value
+ * @return the value of the preference
+ */
+ private int getCoreFormatterOption(String key, int def) {
+ try {
+ return Integer.parseInt(getCoreFormatterOption(key));
+ } catch (NumberFormatException e) {
+ return def;
+ }
+ }
+
+ /**
+ * Returns the <code>IProject</code> of the current editor input, or
+ * <code>null</code> if it cannot be found.
+ *
+ * @return the <code>IProject</code> of the current editor input, or
+ * <code>null</code> if it cannot be found
+ */
+ private IProject getProject(ITextEditor editor) {
+ if (editor == null)
+ return null;
+
+ IEditorInput input = editor.getEditorInput();
+ if (input instanceof IFileEditorInput)
+ return ((IFileEditorInput) input).getFile().getProject();
+ return null;
+ }
+
+ /**
+ * Returns the editor's selection provider.
+ *
+ * @return the editor's selection provider or <code>null</code>
+ */
+ private ISelectionProvider getSelectionProvider(ITextEditor editor) {
+ if (editor != null) {
+ return editor.getSelectionProvider();
+ }
+ return null;
+ }
+
+ /*
+ * @see org.eclipse.ui.texteditor.IUpdate#update()
+ */
+
+ /**
+ * Returns the document currently displayed in the editor, or
+ * <code>null</code> if none can be obtained.
+ *
+ * @return the current document or <code>null</code>
+ */
+ private IDocument getDocument(ITextEditor editor) {
+ if (editor != null) {
+ IDocumentProvider provider = editor.getDocumentProvider();
+ IEditorInput input = editor.getEditorInput();
+ if (provider != null && input != null)
+ return provider.getDocument(input);
+
+ }
+ return null;
+ }
+
+ /**
+ * Returns the selection on the editor or an invalid selection if none can
+ * be obtained. Returns never <code>null</code>.
+ *
+ * @return the current selection, never <code>null</code>
+ */
+ private ITextSelection getSelection(ITextEditor editor) {
+ ISelectionProvider provider = getSelectionProvider(editor);
+ if (provider != null) {
+ ISelection selection = provider.getSelection();
+ if (selection instanceof ITextSelection)
+ return (ITextSelection) selection;
+ }
+
+ // null object
+ return TextSelection.emptySelection();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/KernelSourceAction.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/KernelSourceAction.java
index 6256a016c4..e0d3ba090c 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/KernelSourceAction.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/KernelSourceAction.java
@@ -35,57 +35,57 @@ import org.eclipse.ui.ide.FileStoreEditorInput;
* @see org.eclipse.linuxtools.internal.systemtap.ui.ide.views.KernelBrowserView
*/
public class KernelSourceAction extends BrowserViewAction {
- public final static String ID = "org.eclipse.linuxtools.systemtap.ui.ide.KBAction"; //$NON-NLS-1$
- private static final String CDT_EDITOR_ID = "org.eclipse.cdt.ui.editor.CEditor"; //$NON-NLS-1$
+ public final static String ID = "org.eclipse.linuxtools.systemtap.ui.ide.KBAction"; //$NON-NLS-1$
+ private static final String CDT_EDITOR_ID = "org.eclipse.cdt.ui.editor.CEditor"; //$NON-NLS-1$
- /**
- * The default constructor for the <code>KernelSourceAction</code>. Takes the window that it affects
- * and the <code>KernelBrowserView</code> that will fire the event as arguments.
- * @param window The <code>IWorkbenchWindow</code> that the action operates on.
- * @param browser The <code>KernelBrowserView</code> that fires this action.
- */
- public KernelSourceAction(IWorkbenchWindow window, KernelBrowserView browser) {
- super(window, browser);
- setId(ID);
- setActionDefinitionId(ID);
- setText(Localization.getString("KernelSourceAction.Insert")); //$NON-NLS-1$
- setToolTipText(Localization
- .getString("KernelSourceAction.InsertSelectedFunction")); //$NON-NLS-1$
- }
+ /**
+ * The default constructor for the <code>KernelSourceAction</code>. Takes the window that it affects
+ * and the <code>KernelBrowserView</code> that will fire the event as arguments.
+ * @param window The <code>IWorkbenchWindow</code> that the action operates on.
+ * @param browser The <code>KernelBrowserView</code> that fires this action.
+ */
+ public KernelSourceAction(IWorkbenchWindow window, KernelBrowserView browser) {
+ super(window, browser);
+ setId(ID);
+ setActionDefinitionId(ID);
+ setText(Localization.getString("KernelSourceAction.Insert")); //$NON-NLS-1$
+ setToolTipText(Localization
+ .getString("KernelSourceAction.InsertSelectedFunction")); //$NON-NLS-1$
+ }
- /**
- * The main code body for this action. Causes one of the following to occur:
- * <ul>
- * <li>If the selected node is clickable, as specified in <code>TreeNode.isClickable</code>
- * the browser creates an instance of <code>CEditor</code> on the file specified in the selection
- * (<code>KernelBrowserView</code>'s tree only marks clickable on files, not folders) and
- * opens it on the current window</li>
- * <li>If the selected node is not clickable, the code runs the action specified in
- * <code>TreeExpandCollapseAction</code></li>
- * @see org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.c.CEditor
- * @see TreeNode#isClickable()
- * @see TreeExpandCollapseAction
- */
- @Override
- public void run() {
- IWorkbench wb = PlatformUI.getWorkbench();
- Object o = getSelectedElement();
- if (o instanceof TreeNode) {
- TreeNode t = (TreeNode) o;
- if (t.isClickable()) {
- IFileStore fs = (IFileStore) t.getData();
- if (fs != null) {
- IEditorInput input = new FileStoreEditorInput(fs);
- try {
- wb.getActiveWorkbenchWindow().getActivePage().openEditor(input, CDT_EDITOR_ID);
- } catch (PartInitException e) {
- ExceptionErrorDialog.openError(Messages.ScriptRunAction_errorDialogTitle, e);
- }
- }
- } else {
- runExpandAction();
- }
- }
- }
+ /**
+ * The main code body for this action. Causes one of the following to occur:
+ * <ul>
+ * <li>If the selected node is clickable, as specified in <code>TreeNode.isClickable</code>
+ * the browser creates an instance of <code>CEditor</code> on the file specified in the selection
+ * (<code>KernelBrowserView</code>'s tree only marks clickable on files, not folders) and
+ * opens it on the current window</li>
+ * <li>If the selected node is not clickable, the code runs the action specified in
+ * <code>TreeExpandCollapseAction</code></li>
+ * @see org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.c.CEditor
+ * @see TreeNode#isClickable()
+ * @see TreeExpandCollapseAction
+ */
+ @Override
+ public void run() {
+ IWorkbench wb = PlatformUI.getWorkbench();
+ Object o = getSelectedElement();
+ if (o instanceof TreeNode) {
+ TreeNode t = (TreeNode) o;
+ if (t.isClickable()) {
+ IFileStore fs = (IFileStore) t.getData();
+ if (fs != null) {
+ IEditorInput input = new FileStoreEditorInput(fs);
+ try {
+ wb.getActiveWorkbenchWindow().getActivePage().openEditor(input, CDT_EDITOR_ID);
+ } catch (PartInitException e) {
+ ExceptionErrorDialog.openError(Messages.ScriptRunAction_errorDialogTitle, e);
+ }
+ }
+ } else {
+ runExpandAction();
+ }
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/Messages.java
index 6d3de68a58..ee86c74c1e 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/Messages.java
@@ -17,24 +17,24 @@ import org.eclipse.osgi.util.NLS;
* @since 2.0
*/
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.actions.messages"; //$NON-NLS-1$
- public static String ScriptRunAction_InvalidScriptTitle;
- public static String ScriptRunAction_InvalidScriptTMessage;
- public static String ScriptRunAction_errorDialogTitle;
- public static String RunScriptAction_alreadyRunningDialogTitle;
- public static String RunScriptAction_alreadyRunningDialogMessage;
- public static String RunScriptChartAction_couldNotSwitchToGraphicPerspective;
- public static String DataSetFileExtension;
- public static String ExportDataSetAction_DialogTitle;
- public static String ImportDataSetAction_DialogTitle;
- public static String ImportDataSetAction_FileInvalid;
- public static String ImportDataSetAction_FileNotFound;
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.actions.messages"; //$NON-NLS-1$
+ public static String ScriptRunAction_InvalidScriptTitle;
+ public static String ScriptRunAction_InvalidScriptTMessage;
+ public static String ScriptRunAction_errorDialogTitle;
+ public static String RunScriptAction_alreadyRunningDialogTitle;
+ public static String RunScriptAction_alreadyRunningDialogMessage;
+ public static String RunScriptChartAction_couldNotSwitchToGraphicPerspective;
+ public static String DataSetFileExtension;
+ public static String ExportDataSetAction_DialogTitle;
+ public static String ImportDataSetAction_DialogTitle;
+ public static String ImportDataSetAction_FileInvalid;
+ public static String ImportDataSetAction_FileNotFound;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ProbeAliasAction.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ProbeAliasAction.java
index 7de9559ac3..9b6d75f789 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ProbeAliasAction.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ProbeAliasAction.java
@@ -33,63 +33,63 @@ import org.eclipse.ui.IWorkbenchWindow;
* @see org.eclipse.jface.action.Action
*/
public class ProbeAliasAction extends BrowserViewAction {
- private static final String ID = "org.eclipse.linuxtools.systemtap.ui.ide.ProbeAliasAction"; //$NON-NLS-1$
+ private static final String ID = "org.eclipse.linuxtools.systemtap.ui.ide.ProbeAliasAction"; //$NON-NLS-1$
- public ProbeAliasAction(IWorkbenchWindow window, ProbeAliasBrowserView view) {
- super(window, view);
- setId(ID);
- setActionDefinitionId(ID);
- setText(Localization.getString("ProbeAliasAction.Insert")); //$NON-NLS-1$
- setToolTipText(Localization
- .getString("ProbeAliasAction.InsertSelectedProbe")); //$NON-NLS-1$
- }
+ public ProbeAliasAction(IWorkbenchWindow window, ProbeAliasBrowserView view) {
+ super(window, view);
+ setId(ID);
+ setActionDefinitionId(ID);
+ setText(Localization.getString("ProbeAliasAction.Insert")); //$NON-NLS-1$
+ setToolTipText(Localization
+ .getString("ProbeAliasAction.InsertSelectedProbe")); //$NON-NLS-1$
+ }
- /**
- * The main body of the action. This method checks for the current editor, creating one
- * if there is no active <code>STPEditor</code>, and then inserts a template probe for the
- * item that the user clicked on.
- */
- @Override
- public void run() {
- Object o = getSelectedElement();
- if (o instanceof TreeNode) {
- TreeNode t = (TreeNode) o;
- if (t.isClickable()) {
- STPEditor stpeditor = IDESessionSettings.getOrAskForActiveSTPEditor(true);
- if (stpeditor != null) {
- stpeditor.insertText(buildString((TreeNode) o));
- }
- } else {
- runExpandAction();
- }
- }
- }
+ /**
+ * The main body of the action. This method checks for the current editor, creating one
+ * if there is no active <code>STPEditor</code>, and then inserts a template probe for the
+ * item that the user clicked on.
+ */
+ @Override
+ public void run() {
+ Object o = getSelectedElement();
+ if (o instanceof TreeNode) {
+ TreeNode t = (TreeNode) o;
+ if (t.isClickable()) {
+ STPEditor stpeditor = IDESessionSettings.getOrAskForActiveSTPEditor(true);
+ if (stpeditor != null) {
+ stpeditor.insertText(buildString((TreeNode) o));
+ }
+ } else {
+ runExpandAction();
+ }
+ }
+ }
- private String buildString(TreeNode t) {
- //build the string
- StringBuilder s = new StringBuilder("\nprobe " + t.toString()); //$NON-NLS-1$
- if (t.getChildCount() > 0 && t.getChildAt(0).getData() instanceof ProbeNodeData) {
- s.append(".*"); //$NON-NLS-1$
- }
- s.append("\n{\n"); //$NON-NLS-1$
- if (t.getChildCount() > 0 && t.getChildAt(0).getData() instanceof ProbevarNodeData) {
- s.append("\t/*\n\t * " + //$NON-NLS-1$
- Localization
- .getString("ProbeAliasAction.AvailableVariables") + //$NON-NLS-1$
- "\n\t * "); //$NON-NLS-1$
- boolean first = true;
- for(int i = 0; i < t.getChildCount(); i++) {
- if(first) {
- first = false;
- } else {
- s.append(", "); //$NON-NLS-1$
- }
- s.append(t.getChildAt(i).toString());
- }
- s.append("\n\t */\n"); //$NON-NLS-1$
- }
- s.append("\n}\n"); //$NON-NLS-1$
- return s.toString();
- }
+ private String buildString(TreeNode t) {
+ //build the string
+ StringBuilder s = new StringBuilder("\nprobe " + t.toString()); //$NON-NLS-1$
+ if (t.getChildCount() > 0 && t.getChildAt(0).getData() instanceof ProbeNodeData) {
+ s.append(".*"); //$NON-NLS-1$
+ }
+ s.append("\n{\n"); //$NON-NLS-1$
+ if (t.getChildCount() > 0 && t.getChildAt(0).getData() instanceof ProbevarNodeData) {
+ s.append("\t/*\n\t * " + //$NON-NLS-1$
+ Localization
+ .getString("ProbeAliasAction.AvailableVariables") + //$NON-NLS-1$
+ "\n\t * "); //$NON-NLS-1$
+ boolean first = true;
+ for(int i = 0; i < t.getChildCount(); i++) {
+ if(first) {
+ first = false;
+ } else {
+ s.append(", "); //$NON-NLS-1$
+ }
+ s.append(t.getChildAt(i).toString());
+ }
+ s.append("\n\t */\n"); //$NON-NLS-1$
+ }
+ s.append("\n}\n"); //$NON-NLS-1$
+ return s.toString();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/RunScriptChartHandler.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/RunScriptChartHandler.java
index c8b04659ac..62ba6d47b0 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/RunScriptChartHandler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/RunScriptChartHandler.java
@@ -34,44 +34,44 @@ import org.eclipse.ui.WorkbenchException;
*/
public class RunScriptChartHandler extends RunScriptHandler {
- private List<IDataSetParser> parsers;
- private List<IFilteredDataSet> dataSets;
- private List<String> names;
- private List<LinkedList<GraphData>> graphs;
+ private List<IDataSetParser> parsers;
+ private List<IFilteredDataSet> dataSets;
+ private List<String> names;
+ private List<LinkedList<GraphData>> graphs;
- public RunScriptChartHandler(List<IDataSetParser> parsers, List<IFilteredDataSet> dataSet, List<String> names, List<LinkedList<GraphData>> graphs) {
- super();
- this.parsers = parsers;
- this.dataSets = dataSet;
- this.names = names;
- this.graphs = graphs;
- }
+ public RunScriptChartHandler(List<IDataSetParser> parsers, List<IFilteredDataSet> dataSet, List<String> names, List<LinkedList<GraphData>> graphs) {
+ super();
+ this.parsers = parsers;
+ this.dataSets = dataSet;
+ this.names = names;
+ this.graphs = graphs;
+ }
- @Override
- protected void scriptConsoleInitialized(ScriptConsole console){
- int n = parsers.size();
- for (int i = 0; i < n; i++) {
- console.getCommand().addInputStreamListener(new ChartStreamDaemon(dataSets.get(i), parsers.get(i)));
- }
- try {
- String name = console.getName();
- String title = name.substring(name.lastIndexOf('/')+1);
+ @Override
+ protected void scriptConsoleInitialized(ScriptConsole console){
+ int n = parsers.size();
+ for (int i = 0; i < n; i++) {
+ console.getCommand().addInputStreamListener(new ChartStreamDaemon(dataSets.get(i), parsers.get(i)));
+ }
+ try {
+ String name = console.getName();
+ String title = name.substring(name.lastIndexOf('/')+1);
- IWorkbenchPage p = PlatformUI.getWorkbench().showPerspective(IDEPerspective.ID, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
- GraphSelectorEditor ivp = (GraphSelectorEditor)p.openEditor(new GraphSelectorEditorInput(title), GraphSelectorEditor.ID);
+ IWorkbenchPage p = PlatformUI.getWorkbench().showPerspective(IDEPerspective.ID, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
+ GraphSelectorEditor ivp = (GraphSelectorEditor)p.openEditor(new GraphSelectorEditorInput(title), GraphSelectorEditor.ID);
- String scriptName = console.getName();
- ivp.createScriptSets(scriptName, names, dataSets);
+ String scriptName = console.getName();
+ ivp.createScriptSets(scriptName, names, dataSets);
- for (int i = 0; i < n; i++) {
- for (GraphData graph : graphs.get(i)) {
- ivp.getDisplaySet(i).addGraph(graph);
- }
- }
- } catch(WorkbenchException we) {
- ExceptionErrorDialog.openError(Messages.RunScriptChartAction_couldNotSwitchToGraphicPerspective, we);
- }
- super.scriptConsoleInitialized(console);
- }
+ for (int i = 0; i < n; i++) {
+ for (GraphData graph : graphs.get(i)) {
+ ivp.getDisplaySet(i).addGraph(graph);
+ }
+ }
+ } catch(WorkbenchException we) {
+ ExceptionErrorDialog.openError(Messages.RunScriptChartAction_couldNotSwitchToGraphicPerspective, we);
+ }
+ super.scriptConsoleInitialized(console);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/RunScriptHandler.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/RunScriptHandler.java
index 8838a5da03..d46d43094e 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/RunScriptHandler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/RunScriptHandler.java
@@ -76,475 +76,475 @@ import com.jcraft.jsch.JSchException;
public class RunScriptHandler extends AbstractHandler {
- /**
- * @since 2.0
- */
- protected boolean continueRun = true;
- private RemoteScriptOptions remoteOptions = null;
- private IEditorPart ed = null;
- private String fileName = null;
- private String tmpfileName = null;
- private String serverfileName = null;
- private IPath path;
- private IProject project;
- private SystemTapScriptLaunch launch;
- private final List<String> cmdList;
-
-
- public RunScriptHandler(){
- this.cmdList = new ArrayList<>();
- }
-
- /**
- * @since 2.0
- */
- public void setPath(IPath path){
- this.path = path;
- URI uri = URIUtil.toURI(path);
- IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(uri);
- if (files.length > 0) {
- this.project = files[0].getProject();
- }
- }
-
- /**
- * @since 2.1
- */
- public IProject getProject() {
- return project;
- }
-
- /**
- * @since 2.3
- */
- public void setLaunch(SystemTapScriptLaunch launch){
- this.launch = launch;
- }
-
- /**
- * Finds the editor containing the target script to run, so the script can be saved
- * when it is run, if appropriate.
- * The script is saved when it is run with the "simple" run button on the toolbar (path == null),
- * or if the script is outside of a project (working with a PathEditorInput).
- */
- private void findTargetEditor() {
- ed = null;
-
- if (path == null) {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- ed = window.getActivePage().getActiveEditor();
- return;
- }
-
- for (IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
- IEditorPart edTest = window.getActivePage().getActiveEditor();
- if (edTest != null && matchesEditor(edTest.getEditorInput(), edTest)) {
- return;
- }
- for (IEditorReference ref : window.getActivePage().getEditorReferences()) {
- try {
- if (matchesEditor(ref.getEditorInput(), ref.getEditor(false))) {
- return;
- }
- } catch (PartInitException e) {
- continue;
- }
- }
- }
- }
-
- private boolean matchesEditor(IEditorInput input, IEditorPart editor) {
- if (input instanceof IPathEditorInput && ((IPathEditorInput) (input)).getPath().equals(this.path)) {
- // Only save the editor when working with a file without a project (PathEditorInput),
- // otherwise the editor isn't needed at all (saving is handled elsewhere in that case).
- if (input instanceof PathEditorInput) {
- this.ed = editor;
- }
- return true;
- }
- return false;
- }
-
- /**
- * The main body of this event. Starts by making sure the current editor is valid to run,
- * then builds the command line arguments for stap and retrieves the environment variables.
- * Finally, it gets an instance of <code>ScriptConsole</code> to run the script.
- */
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- findTargetEditor();
- final boolean local = getRunLocal();
- if(isValid()) {
- if(!local && !prepareNonLocalScript()) {
- return null;
- }
- final String[] script = buildStandardScript();
- final String[] envVars = getEnvironmentVariables();
- if (continueRun) {
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- String name = !local ? serverfileName : fileName;
- if (ScriptConsole.instanceIsRunning(name)) {
- MessageDialog dialog = new MessageDialog(
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
- Messages.RunScriptAction_alreadyRunningDialogTitle, null,
- MessageFormat.format(Messages.RunScriptAction_alreadyRunningDialogMessage, fileName),
- MessageDialog.QUESTION, new String[]{"Yes", "No"}, 0); //$NON-NLS-1$ //$NON-NLS-2$
- if (dialog.open() != Window.OK) {
- if (launch != null) {
- launch.forceRemove();
- }
- return;
- }
- }
- final ScriptConsole console;
- if (!local) {
- console = ScriptConsole.getInstance(serverfileName);
- } else {
- console = ScriptConsole.getInstance(fileName);
- }
- synchronized (console) {
- if (!local) {
- console.run(script, envVars, remoteOptions, new StapErrorParser());
- } else {
- console.runLocally(script, envVars, new StapErrorParser(), getProject());
- }
- scriptConsoleInitialized(console);
- }
- }
- });
- }
- }
-
- return null;
- }
-
- /**
- * Attempts to set up a channel for a script that runs on a non-local host or user.
- * @return <code>true</code> on success, <code>false</code> on failure.
- * @throws ExecutionException If failure occurs during a (non-simple) launch,
- * this will throw an exception instead of returning <code>false</code>.
- */
- private boolean prepareNonLocalScript() throws ExecutionException {
- try {
- ScpClient scpclient = new ScpClient(remoteOptions);
- serverfileName = fileName.substring(fileName.lastIndexOf('/')+1);
- tmpfileName="/tmp/"+ serverfileName; //$NON-NLS-1$
- scpclient.transfer(fileName,tmpfileName);
- } catch (final JSchException | IOException e) {
- final String message = e instanceof JSchException ? Localization.getString("RunScriptHandler.checkCredentials") //$NON-NLS-1$
- : Localization.getString("RunScriptHandler.ioError"); //$NON-NLS-1$
- if (launch == null) {
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- if (e instanceof JSchException) {
- ErrorDialog.openError(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getShell(),
- Localization.getString("RunScriptHandler.serverError"), Localization.getString("RunScriptHandler.serverError"), //$NON-NLS-1$ //$NON-NLS-2$
- new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID, message));
- } else {
- ExceptionErrorDialog.openError(Localization.getString("RunScriptHandler.ioError"), e); //$NON-NLS-1$
- }
- }
- });
- return false;
- } else {
- throw new ExecutionException(message, e);
- }
- }
- return true;
- }
-
- /**
- * Once a console for running the script has been created this
- * function is called so that observers can be added for example
- * @param console
- * @since 2.0
- */
- protected void scriptConsoleInitialized(ScriptConsole console){
- if (launch != null && path != null) {
- launch.setConsole(console);
- }
- }
-
- /**
- * Returns the path that was set for this action. If one was not set it
- * returns the path of the current editor in the window this action is
- * associated with.
- *
- * @return The string representation of the path of the script to run.
- */
- protected String getFilePath() {
- if (path != null){
- return path.toOSString();
- }
- if (ed == null) {
- return ""; //$NON-NLS-1$
- }
- if(ed.getEditorInput() instanceof PathEditorInput){
- return ((PathEditorInput)ed.getEditorInput()).getPath().toString();
- } else {
- return ResourceUtil.getFile(ed.getEditorInput()).getLocation().toString();
- }
- }
-
- /**
- * Checks if the current editor is operating on a file that actually exists and can be
- * used as an argument to stap (as opposed to an unsaved buffer).
- * @return True if the file is valid.
- */
- private boolean isValid() {
- // If the path is not set this action will run the script from
- // the active editor
- if(!tryEditorSave()){
- if (this.path == null){
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- String msg = MessageFormat.format(Localization.getString("RunScriptAction.NoScriptFile"),(Object[]) null); //$NON-NLS-1$
- MessageDialog.openWarning(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Localization.getString("RunScriptAction.Problem"), msg); //$NON-NLS-1$
- }
- });
- return false;
- }
- }
- String filePath = this.getFilePath();
- return filePath.endsWith(".stp") //$NON-NLS-1$
- && isValidDirectory(filePath);
- }
-
- private boolean tryEditorSave() {
- if(null == ed) {
- return false;
- }
-
- if(ed.isDirty()) {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- ed.doSave(new ProgressMonitorPart(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), new FillLayout()));
- }
- });
- }
-
- return true;
- }
-
- /**
- * Checks whether the directory to which the given file
- * belongs is a valid directory. Currently this function just
- * checks if the given file does not belong to the tapset
- * directory.
- * @param fileName
- * @return true if the given path is valid false otherwise.
- * @since 1.2
- */
- private boolean isValidDirectory(String fileName) {
- this.fileName = fileName;
- if(0 == IDESessionSettings.tapsetLocation.trim().length()){
- TapsetLibrary.getTapsetLocation(IDEPlugin.getDefault().getPreferenceStore());
- }
-
- if(fileName.contains(IDESessionSettings.tapsetLocation)) {
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- String msg = MessageFormat.format(Localization.getString("RunScriptAction.TapsetDirectoryRun"),(Object []) null); //$NON-NLS-1$
- MessageDialog.openWarning(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Localization.getString("RunScriptAction.Error"), msg); //$NON-NLS-1$
- }
- });
- return false;
- }
- return true;
- }
-
- /**
- * Adds the given String to the list of commands to be
- * passed to systemtap when running the command
- * @param option
- */
- public void addComandLineOptions(String option){
- this.cmdList.add(option);
- }
-
- /**
- * The command line argument generation method used by <code>RunScriptAction</code>. This generates
- * a stap command line that includes the tapsets specified in user preferences, a guru mode flag
- * if necessary, and the path to the script on disk.
- * @return The command to invoke to start the script running in stap.
- * @since 2.0
- */
- private String[] buildStandardScript() {
- getImportedTapsets(cmdList);
-
- if(isGuru()) {
- cmdList.add("-g"); //$NON-NLS-1$
- }
-
- return finalizeScript(cmdList);
- }
-
- /**
- * Adds the tapsets that the user has added in preferences to the input <code>ArrayList</code>
- * @param cmdList The list to add the user-specified tapset locations to.
- * @since 2.0
- */
-
- private void getImportedTapsets(List<String> cmdList) {
- IPreferenceStore preferenceStore = IDEPlugin.getDefault().getPreferenceStore();
- String[] tapsets = preferenceStore.getString(IDEPreferenceConstants.P_TAPSETS).split(File.pathSeparator);
-
- //Get all imported tapsets
- if(tapsets.length > 0 && tapsets[0].trim().length() > 0) {
- for(int i=0; i<tapsets.length; i++) {
- cmdList.add("-I"); //$NON-NLS-1$
- cmdList.add(tapsets[i]);
- }
- }
- }
-
- /**
- * Checks the current script to determine if guru mode is required in order to run. This is determined
- * by the presence of embedded C.
- * @return True if the script contains embedded C code.
- */
- private boolean isGuru() {
- File f = new File(fileName);
- try (FileReader fr = new FileReader(f)){
- int curr = 0;
- int prev = 0;
- boolean front = false;
- boolean imbedded = false;
- boolean inLineComment = false;
- boolean inBlockComment = false;
- while(-1 != (curr = fr.read())) {
- if(!inLineComment && !inBlockComment && '%' == prev && '{' == curr) {
- front = true;
- } else if(!inLineComment && !inBlockComment && '%' == prev && '}' == curr && front) {
- imbedded = true;
- break;
- } else if(!inBlockComment && (('/' == prev && '/' == curr) || '#' == curr)) {
- inLineComment = true;
- } else if(!inLineComment && '/' == prev && '*' == curr) {
- inBlockComment = true;
- } else if('\n' == curr) {
- inLineComment = false;
- } else if('*' == prev && '/' == curr) {
- inBlockComment = false;
- }
- prev = curr;
- }
- fr.close();
- if(imbedded) {
- return true;
- }
- } catch (FileNotFoundException fnfe) {
- ExceptionErrorDialog.openError(Localization.getString("RunScriptHandler.couldNotOpenScriptFile"), fnfe); //$NON-NLS-1$
- } catch (IOException ie) {
- ExceptionErrorDialog.openError(Localization.getString("RunScriptHandler.fileIOError"), ie); //$NON-NLS-1$
- }
- return false;
- }
-
- /**
- * Produces a <code>String[]</code> from the <code>ArrayList</code> passed in with stap inserted
- * as the first entry, and the filename as the last entry. Used to convert the arguments generated
- * earlier in <code>buildStandardScript</code> such as tapset locations and guru mode into an actual
- * command line argument array that can be passed to <code>Runtime.exec</code>.
- * @param cmdList The list of arguments for stap for this script
- * @return An array suitable to pass to <code>Runtime.exec</code> to start stap on this file.
- * @since 2.0
- */
- private String[] finalizeScript(List<String> cmdList) {
-
- String[] script;
-
- script = new String[cmdList.size() + 4];
- script[0] = "stap"; //$NON-NLS-1$
-
- if(getRunLocal() == false) {
- script[script.length-1] = tmpfileName;
- } else {
- script[script.length-1] = fileName;
- }
-
- for(int i=0; i< cmdList.size(); i++) {
- script[i+1] = cmdList.get(i);
- }
- script[script.length-3]="-m"; //$NON-NLS-1$
-
- String modname;
- if(getRunLocal() == false) {
- modname = serverfileName.substring(0, serverfileName.lastIndexOf(".stp")); //$NON-NLS-1$
- }
- /* We need to remove the directory prefix here because in the case of
- * running the script remotely, this is already done. Not doing so
- * causes a modname error.
- */
- else {
- modname = fileName.substring(fileName.lastIndexOf('/')+1);
- modname = modname.substring(0, modname.lastIndexOf(".stp")); //$NON-NLS-1$
- }
-
- // Make sure script name only contains underscores and/or alphanumeric characters.
- Pattern validModName = Pattern.compile("^[a-z0-9_A-Z]+$"); //$NON-NLS-1$
- Matcher modNameMatch = validModName.matcher(modname);
- if (!modNameMatch.matches()) {
- continueRun = false;
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
-
- Shell parent = PlatformUI.getWorkbench().getDisplay()
- .getActiveShell();
- MessageDialog.openError(parent,
- Messages.ScriptRunAction_InvalidScriptTitle,
- Messages.ScriptRunAction_InvalidScriptTMessage);
- }
- });
- return new String[0];
- }
-
- script[script.length-2]=modname;
- return script;
- }
-
- private String[] getEnvironmentVariables() {
- return EnvironmentVariablesPreferencePage.getEnvironmentVariables();
- }
-
- @Override
- public boolean isEnabled() {
- return (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor() instanceof STPEditor);
- }
-
- /**
- * Set the options for running the script remotely. If the script is to be run locally,
- * pass <code>null</code> as the only parameter.
- * @param remoteOptions The remote options of the script run, or <code>null</code> if the script
- * is to be run locally.
- * @since 3.0
- */
- public void setRemoteScriptOptions(RemoteScriptOptions remoteOptions) {
- this.remoteOptions = remoteOptions;
- }
-
- private boolean getRunLocal() {
- return remoteOptions == null;
- }
-
- @Override
- public void addHandlerListener(IHandlerListener handlerListener) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void removeHandlerListener(IHandlerListener handlerListener) {
- // TODO Auto-generated method stub
-
- }
+ /**
+ * @since 2.0
+ */
+ protected boolean continueRun = true;
+ private RemoteScriptOptions remoteOptions = null;
+ private IEditorPart ed = null;
+ private String fileName = null;
+ private String tmpfileName = null;
+ private String serverfileName = null;
+ private IPath path;
+ private IProject project;
+ private SystemTapScriptLaunch launch;
+ private final List<String> cmdList;
+
+
+ public RunScriptHandler(){
+ this.cmdList = new ArrayList<>();
+ }
+
+ /**
+ * @since 2.0
+ */
+ public void setPath(IPath path){
+ this.path = path;
+ URI uri = URIUtil.toURI(path);
+ IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(uri);
+ if (files.length > 0) {
+ this.project = files[0].getProject();
+ }
+ }
+
+ /**
+ * @since 2.1
+ */
+ public IProject getProject() {
+ return project;
+ }
+
+ /**
+ * @since 2.3
+ */
+ public void setLaunch(SystemTapScriptLaunch launch){
+ this.launch = launch;
+ }
+
+ /**
+ * Finds the editor containing the target script to run, so the script can be saved
+ * when it is run, if appropriate.
+ * The script is saved when it is run with the "simple" run button on the toolbar (path == null),
+ * or if the script is outside of a project (working with a PathEditorInput).
+ */
+ private void findTargetEditor() {
+ ed = null;
+
+ if (path == null) {
+ IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ ed = window.getActivePage().getActiveEditor();
+ return;
+ }
+
+ for (IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
+ IEditorPart edTest = window.getActivePage().getActiveEditor();
+ if (edTest != null && matchesEditor(edTest.getEditorInput(), edTest)) {
+ return;
+ }
+ for (IEditorReference ref : window.getActivePage().getEditorReferences()) {
+ try {
+ if (matchesEditor(ref.getEditorInput(), ref.getEditor(false))) {
+ return;
+ }
+ } catch (PartInitException e) {
+ continue;
+ }
+ }
+ }
+ }
+
+ private boolean matchesEditor(IEditorInput input, IEditorPart editor) {
+ if (input instanceof IPathEditorInput && ((IPathEditorInput) (input)).getPath().equals(this.path)) {
+ // Only save the editor when working with a file without a project (PathEditorInput),
+ // otherwise the editor isn't needed at all (saving is handled elsewhere in that case).
+ if (input instanceof PathEditorInput) {
+ this.ed = editor;
+ }
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * The main body of this event. Starts by making sure the current editor is valid to run,
+ * then builds the command line arguments for stap and retrieves the environment variables.
+ * Finally, it gets an instance of <code>ScriptConsole</code> to run the script.
+ */
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ findTargetEditor();
+ final boolean local = getRunLocal();
+ if(isValid()) {
+ if(!local && !prepareNonLocalScript()) {
+ return null;
+ }
+ final String[] script = buildStandardScript();
+ final String[] envVars = getEnvironmentVariables();
+ if (continueRun) {
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ String name = !local ? serverfileName : fileName;
+ if (ScriptConsole.instanceIsRunning(name)) {
+ MessageDialog dialog = new MessageDialog(
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
+ Messages.RunScriptAction_alreadyRunningDialogTitle, null,
+ MessageFormat.format(Messages.RunScriptAction_alreadyRunningDialogMessage, fileName),
+ MessageDialog.QUESTION, new String[]{"Yes", "No"}, 0); //$NON-NLS-1$ //$NON-NLS-2$
+ if (dialog.open() != Window.OK) {
+ if (launch != null) {
+ launch.forceRemove();
+ }
+ return;
+ }
+ }
+ final ScriptConsole console;
+ if (!local) {
+ console = ScriptConsole.getInstance(serverfileName);
+ } else {
+ console = ScriptConsole.getInstance(fileName);
+ }
+ synchronized (console) {
+ if (!local) {
+ console.run(script, envVars, remoteOptions, new StapErrorParser());
+ } else {
+ console.runLocally(script, envVars, new StapErrorParser(), getProject());
+ }
+ scriptConsoleInitialized(console);
+ }
+ }
+ });
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Attempts to set up a channel for a script that runs on a non-local host or user.
+ * @return <code>true</code> on success, <code>false</code> on failure.
+ * @throws ExecutionException If failure occurs during a (non-simple) launch,
+ * this will throw an exception instead of returning <code>false</code>.
+ */
+ private boolean prepareNonLocalScript() throws ExecutionException {
+ try {
+ ScpClient scpclient = new ScpClient(remoteOptions);
+ serverfileName = fileName.substring(fileName.lastIndexOf('/')+1);
+ tmpfileName="/tmp/"+ serverfileName; //$NON-NLS-1$
+ scpclient.transfer(fileName,tmpfileName);
+ } catch (final JSchException | IOException e) {
+ final String message = e instanceof JSchException ? Localization.getString("RunScriptHandler.checkCredentials") //$NON-NLS-1$
+ : Localization.getString("RunScriptHandler.ioError"); //$NON-NLS-1$
+ if (launch == null) {
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ if (e instanceof JSchException) {
+ ErrorDialog.openError(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getShell(),
+ Localization.getString("RunScriptHandler.serverError"), Localization.getString("RunScriptHandler.serverError"), //$NON-NLS-1$ //$NON-NLS-2$
+ new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID, message));
+ } else {
+ ExceptionErrorDialog.openError(Localization.getString("RunScriptHandler.ioError"), e); //$NON-NLS-1$
+ }
+ }
+ });
+ return false;
+ } else {
+ throw new ExecutionException(message, e);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Once a console for running the script has been created this
+ * function is called so that observers can be added for example
+ * @param console
+ * @since 2.0
+ */
+ protected void scriptConsoleInitialized(ScriptConsole console){
+ if (launch != null && path != null) {
+ launch.setConsole(console);
+ }
+ }
+
+ /**
+ * Returns the path that was set for this action. If one was not set it
+ * returns the path of the current editor in the window this action is
+ * associated with.
+ *
+ * @return The string representation of the path of the script to run.
+ */
+ protected String getFilePath() {
+ if (path != null){
+ return path.toOSString();
+ }
+ if (ed == null) {
+ return ""; //$NON-NLS-1$
+ }
+ if(ed.getEditorInput() instanceof PathEditorInput){
+ return ((PathEditorInput)ed.getEditorInput()).getPath().toString();
+ } else {
+ return ResourceUtil.getFile(ed.getEditorInput()).getLocation().toString();
+ }
+ }
+
+ /**
+ * Checks if the current editor is operating on a file that actually exists and can be
+ * used as an argument to stap (as opposed to an unsaved buffer).
+ * @return True if the file is valid.
+ */
+ private boolean isValid() {
+ // If the path is not set this action will run the script from
+ // the active editor
+ if(!tryEditorSave()){
+ if (this.path == null){
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ String msg = MessageFormat.format(Localization.getString("RunScriptAction.NoScriptFile"),(Object[]) null); //$NON-NLS-1$
+ MessageDialog.openWarning(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Localization.getString("RunScriptAction.Problem"), msg); //$NON-NLS-1$
+ }
+ });
+ return false;
+ }
+ }
+ String filePath = this.getFilePath();
+ return filePath.endsWith(".stp") //$NON-NLS-1$
+ && isValidDirectory(filePath);
+ }
+
+ private boolean tryEditorSave() {
+ if(null == ed) {
+ return false;
+ }
+
+ if(ed.isDirty()) {
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ ed.doSave(new ProgressMonitorPart(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), new FillLayout()));
+ }
+ });
+ }
+
+ return true;
+ }
+
+ /**
+ * Checks whether the directory to which the given file
+ * belongs is a valid directory. Currently this function just
+ * checks if the given file does not belong to the tapset
+ * directory.
+ * @param fileName
+ * @return true if the given path is valid false otherwise.
+ * @since 1.2
+ */
+ private boolean isValidDirectory(String fileName) {
+ this.fileName = fileName;
+ if(0 == IDESessionSettings.tapsetLocation.trim().length()){
+ TapsetLibrary.getTapsetLocation(IDEPlugin.getDefault().getPreferenceStore());
+ }
+
+ if(fileName.contains(IDESessionSettings.tapsetLocation)) {
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ String msg = MessageFormat.format(Localization.getString("RunScriptAction.TapsetDirectoryRun"),(Object []) null); //$NON-NLS-1$
+ MessageDialog.openWarning(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Localization.getString("RunScriptAction.Error"), msg); //$NON-NLS-1$
+ }
+ });
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Adds the given String to the list of commands to be
+ * passed to systemtap when running the command
+ * @param option
+ */
+ public void addComandLineOptions(String option){
+ this.cmdList.add(option);
+ }
+
+ /**
+ * The command line argument generation method used by <code>RunScriptAction</code>. This generates
+ * a stap command line that includes the tapsets specified in user preferences, a guru mode flag
+ * if necessary, and the path to the script on disk.
+ * @return The command to invoke to start the script running in stap.
+ * @since 2.0
+ */
+ private String[] buildStandardScript() {
+ getImportedTapsets(cmdList);
+
+ if(isGuru()) {
+ cmdList.add("-g"); //$NON-NLS-1$
+ }
+
+ return finalizeScript(cmdList);
+ }
+
+ /**
+ * Adds the tapsets that the user has added in preferences to the input <code>ArrayList</code>
+ * @param cmdList The list to add the user-specified tapset locations to.
+ * @since 2.0
+ */
+
+ private void getImportedTapsets(List<String> cmdList) {
+ IPreferenceStore preferenceStore = IDEPlugin.getDefault().getPreferenceStore();
+ String[] tapsets = preferenceStore.getString(IDEPreferenceConstants.P_TAPSETS).split(File.pathSeparator);
+
+ //Get all imported tapsets
+ if(tapsets.length > 0 && tapsets[0].trim().length() > 0) {
+ for(int i=0; i<tapsets.length; i++) {
+ cmdList.add("-I"); //$NON-NLS-1$
+ cmdList.add(tapsets[i]);
+ }
+ }
+ }
+
+ /**
+ * Checks the current script to determine if guru mode is required in order to run. This is determined
+ * by the presence of embedded C.
+ * @return True if the script contains embedded C code.
+ */
+ private boolean isGuru() {
+ File f = new File(fileName);
+ try (FileReader fr = new FileReader(f)){
+ int curr = 0;
+ int prev = 0;
+ boolean front = false;
+ boolean imbedded = false;
+ boolean inLineComment = false;
+ boolean inBlockComment = false;
+ while(-1 != (curr = fr.read())) {
+ if(!inLineComment && !inBlockComment && '%' == prev && '{' == curr) {
+ front = true;
+ } else if(!inLineComment && !inBlockComment && '%' == prev && '}' == curr && front) {
+ imbedded = true;
+ break;
+ } else if(!inBlockComment && (('/' == prev && '/' == curr) || '#' == curr)) {
+ inLineComment = true;
+ } else if(!inLineComment && '/' == prev && '*' == curr) {
+ inBlockComment = true;
+ } else if('\n' == curr) {
+ inLineComment = false;
+ } else if('*' == prev && '/' == curr) {
+ inBlockComment = false;
+ }
+ prev = curr;
+ }
+ fr.close();
+ if(imbedded) {
+ return true;
+ }
+ } catch (FileNotFoundException fnfe) {
+ ExceptionErrorDialog.openError(Localization.getString("RunScriptHandler.couldNotOpenScriptFile"), fnfe); //$NON-NLS-1$
+ } catch (IOException ie) {
+ ExceptionErrorDialog.openError(Localization.getString("RunScriptHandler.fileIOError"), ie); //$NON-NLS-1$
+ }
+ return false;
+ }
+
+ /**
+ * Produces a <code>String[]</code> from the <code>ArrayList</code> passed in with stap inserted
+ * as the first entry, and the filename as the last entry. Used to convert the arguments generated
+ * earlier in <code>buildStandardScript</code> such as tapset locations and guru mode into an actual
+ * command line argument array that can be passed to <code>Runtime.exec</code>.
+ * @param cmdList The list of arguments for stap for this script
+ * @return An array suitable to pass to <code>Runtime.exec</code> to start stap on this file.
+ * @since 2.0
+ */
+ private String[] finalizeScript(List<String> cmdList) {
+
+ String[] script;
+
+ script = new String[cmdList.size() + 4];
+ script[0] = "stap"; //$NON-NLS-1$
+
+ if(getRunLocal() == false) {
+ script[script.length-1] = tmpfileName;
+ } else {
+ script[script.length-1] = fileName;
+ }
+
+ for(int i=0; i< cmdList.size(); i++) {
+ script[i+1] = cmdList.get(i);
+ }
+ script[script.length-3]="-m"; //$NON-NLS-1$
+
+ String modname;
+ if(getRunLocal() == false) {
+ modname = serverfileName.substring(0, serverfileName.lastIndexOf(".stp")); //$NON-NLS-1$
+ }
+ /* We need to remove the directory prefix here because in the case of
+ * running the script remotely, this is already done. Not doing so
+ * causes a modname error.
+ */
+ else {
+ modname = fileName.substring(fileName.lastIndexOf('/')+1);
+ modname = modname.substring(0, modname.lastIndexOf(".stp")); //$NON-NLS-1$
+ }
+
+ // Make sure script name only contains underscores and/or alphanumeric characters.
+ Pattern validModName = Pattern.compile("^[a-z0-9_A-Z]+$"); //$NON-NLS-1$
+ Matcher modNameMatch = validModName.matcher(modname);
+ if (!modNameMatch.matches()) {
+ continueRun = false;
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+
+ Shell parent = PlatformUI.getWorkbench().getDisplay()
+ .getActiveShell();
+ MessageDialog.openError(parent,
+ Messages.ScriptRunAction_InvalidScriptTitle,
+ Messages.ScriptRunAction_InvalidScriptTMessage);
+ }
+ });
+ return new String[0];
+ }
+
+ script[script.length-2]=modname;
+ return script;
+ }
+
+ private String[] getEnvironmentVariables() {
+ return EnvironmentVariablesPreferencePage.getEnvironmentVariables();
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor() instanceof STPEditor);
+ }
+
+ /**
+ * Set the options for running the script remotely. If the script is to be run locally,
+ * pass <code>null</code> as the only parameter.
+ * @param remoteOptions The remote options of the script run, or <code>null</code> if the script
+ * is to be run locally.
+ * @since 3.0
+ */
+ public void setRemoteScriptOptions(RemoteScriptOptions remoteOptions) {
+ this.remoteOptions = remoteOptions;
+ }
+
+ private boolean getRunLocal() {
+ return remoteOptions == null;
+ }
+
+ @Override
+ public void addHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void removeHandlerListener(IHandlerListener handlerListener) {
+ // TODO Auto-generated method stub
+
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ToggleCommentHandler.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ToggleCommentHandler.java
index 6a10a253ae..d1021ceae7 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ToggleCommentHandler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/ToggleCommentHandler.java
@@ -37,273 +37,273 @@ import org.eclipse.ui.texteditor.ITextEditor;
*/
public class ToggleCommentHandler extends AbstractHandler {
- /** The text operation target */
- private ITextOperationTarget operationTarget;
-
- /**
- * Checks if the selected lines are all commented or not and
- * uncomments/comments them respectively.
- */
- @Override
- public Object execute(ExecutionEvent event) {
- ITextEditor editor = (ITextEditor) HandlerUtil.getActiveEditor(event);
- if (editor == null || !editor.isEditable()) {
- return null;
- }
-
- updateOpTarget(editor);
- if (operationTarget == null) {
- return null;
- }
-
- ISelection selection = editor.getSelectionProvider().getSelection();
- IDocument document = editor.getDocumentProvider().getDocument(
- editor.getEditorInput());
-
- final int operationCode;
- if (isSelectionCommented(selection, document)) {
- operationCode = ITextOperationTarget.STRIP_PREFIX;
- } else {
- operationCode = ITextOperationTarget.PREFIX;
- }
-
- Shell shell = editor.getSite().getShell();
- if (!operationTarget.canDoOperation(operationCode)) {
- if (shell != null) {
- MessageDialog.openError(shell,
- Localization.getString("ToggleComment_error_title"), //$NON-NLS-1$
- Localization.getString("ToggleComment_error_message")); //$NON-NLS-1$
- }
- return null;
- }
-
- Display display = null;
- if (shell != null && !shell.isDisposed()) {
- display = shell.getDisplay();
- }
-
- BusyIndicator.showWhile(display, new Runnable() {
- @Override
- public void run() {
- operationTarget.doOperation(operationCode);
- }
- });
-
- return null;
- }
-
- /**
- * Creates a region describing the text block (something that starts at the
- * beginning of a line) completely containing the current selection.
- *
- * Note, the implementation has to match org.eclipse.jface.text.TextViewer;
- * .getTextBlockFromSelection().
- *
- * @param selection The selection to use
- * @param document The document
- * @return the region describing the text block comprising the given
- * selection
- * @throws BadLocationException
- */
- public IRegion getTextBlockFromSelection(ITextSelection selection,
- IDocument document) throws BadLocationException {
- int start = document.getLineOffset(selection.getStartLine());
- int end;
- int endLine = selection.getEndLine();
- if (document.getNumberOfLines() > endLine + 1) {
- end = document.getLineOffset(endLine + 1);
- } else {
- end = document.getLength();
- }
- return new Region(start, end - start);
- }
-
- /**
- * Is the given selection on the specified document single-line commented?
- *
- * @param selection Selection to check
- * @param document The document
- * @return <code>true</code> iff all selected lines are commented
- */
- public boolean isSelectionCommented(ISelection selection,
- IDocument document) {
-
- if (!(selection instanceof ITextSelection)) {
- return false;
- }
-
- ITextSelection textSelection = (ITextSelection) selection;
- if (textSelection.getStartLine() < 0 || textSelection.getEndLine() < 0) {
- return false;
- }
-
- try {
- IRegion block = getTextBlockFromSelection(textSelection, document);
- ITypedRegion[] regions = TextUtilities.computePartitioning(
- document, STPPartitionScanner.STP_PARTITIONING,
- block.getOffset(), block.getLength(), false);
-
- int[] lines = new int[regions.length * 2]; // [startline, endline,
- // startline, endline,
- // ...]
-
- // For each partition in the text selection, figure out the
- // startline and endline.
- // Count the number of lines that are selected.
- for (int i = 0, j = 0; i < regions.length; i++, j += 2) {
- // Start line of region
- lines[j] = getFirstCompleteLineOfRegion(regions[i], document);
- // End line of region
- int length = regions[i].getLength();
- int offset = regions[i].getOffset() + length;
- if (length > 0) {
- offset--;
- }
-
- // If there is no startline for this region (startline = -1),
- // then there is no endline,
- // otherwise, get the line number of the endline and store it in
- // the array.
- lines[j + 1] = (lines[j] == -1 ? -1 : document
- .getLineOfOffset(offset));
-
- assert i < regions.length;
- assert j < regions.length * 2;
- }
-
- // Perform the check
- boolean hasComment = false;
- for (int i = 0, j = 0; i < regions.length; i++, j += 2) {
- String prefix = "//"; //$NON-NLS-1$
- if (lines[j] >= 0 && lines[j + 1] >= 0) {
- if (isBlockCommented(lines[j], lines[j + 1], prefix,
- document)) {
- hasComment = true;
- } else if (!isBlockEmpty(lines[j], lines[j + 1], document)) {
- return false;
- }
- }
- }
- return hasComment;
- } catch (BadLocationException e) {
- ExceptionErrorDialog.openError(e.getLocalizedMessage(), e);
- }
-
- return false;
- }
-
- /**
- * Returns the index of the first line whose start offset is in the given
- * text range.
- *
- * @param region the text range in characters where to find the line
- * @param document The document
- * @return the first line whose start index is in the given range, -1 if
- * there is no such line
- */
- public int getFirstCompleteLineOfRegion(IRegion region, IDocument document) {
- try {
- int startLine = document.getLineOfOffset(region.getOffset());
-
- int offset = document.getLineOffset(startLine);
- if (offset >= region.getOffset()) {
- return startLine;
- }
-
- offset = document.getLineOffset(startLine + 1);
- return (offset > region.getOffset() + region.getLength() ? -1
- : startLine + 1);
- } catch (BadLocationException e) {
- ExceptionErrorDialog.openError(e.getLocalizedMessage(), e);
- }
-
- return -1;
- }
-
- /**
- * Determines whether each line is empty
- *
- * @param startLine Start line in document
- * @param endLine End line in document
- * @param document The document
- * @return <code>true</code> if each line from <code>startLine</code> to and
- * including <code>endLine</code> is empty
- */
- public boolean isBlockEmpty(int startLine, int endLine, IDocument document) {
- try {
- for (int i = startLine; i <= endLine; i++) {
- IRegion line = document.getLineInformation(i);
- String text = document.get(line.getOffset(), line.getLength());
-
- boolean isEmptyLine = text.trim().length() == 0;
- if (!isEmptyLine) {
- return false;
- }
- }
- return true;
- } catch (BadLocationException e) {
- ExceptionErrorDialog.openError(e.getLocalizedMessage(), e);
- }
-
- return false;
- }
-
- /**
- * Determines whether each line is prefixed by one of the prefixes.
- *
- * @param startLine Start line in document
- * @param endLine End line in document
- * @param prefix Comment prefix
- * @param document The document
- * @return <code>true</code> iff each line from <code>startLine</code> to
- * and including <code>endLine</code> is prepended by the
- * <code>prefix</code>, ignoring whitespace at the begin of line
- */
- public boolean isBlockCommented(int startLine, int endLine, String prefix,
- IDocument document) {
- try {
- // Check for occurrences of prefixes in the given lines
- boolean hasComment = false;
- for (int i = startLine; i <= endLine; i++) {
- IRegion line = document.getLineInformation(i);
- String text = document.get(line.getOffset(), line.getLength());
-
- boolean isEmptyLine = text.trim().length() == 0;
- if (isEmptyLine) {
- continue;
- }
-
- int prefixIndex = text.indexOf(prefix, 0);
-
- if (prefixIndex == -1) {
- // Found a line which is not commented
- return false;
- }
- String s = document.get(line.getOffset(), prefixIndex);
- s = s.trim();
- if (s.length() != 0) {
- // Found a line which is not commented
- return false;
- }
- hasComment = true;
- }
- return hasComment;
- } catch (BadLocationException e) {
- ExceptionErrorDialog.openError(e.getLocalizedMessage(), e);
- }
-
- return false;
- }
-
- /**
- * Update text operation target based on the specified text editor.
- *
- * @param editor ITextEditor editor to associate operation target to.
- */
- private void updateOpTarget(ITextEditor editor) {
- if (editor != null) {
- operationTarget = (ITextOperationTarget) editor
- .getAdapter(ITextOperationTarget.class);
- }
- }
+ /** The text operation target */
+ private ITextOperationTarget operationTarget;
+
+ /**
+ * Checks if the selected lines are all commented or not and
+ * uncomments/comments them respectively.
+ */
+ @Override
+ public Object execute(ExecutionEvent event) {
+ ITextEditor editor = (ITextEditor) HandlerUtil.getActiveEditor(event);
+ if (editor == null || !editor.isEditable()) {
+ return null;
+ }
+
+ updateOpTarget(editor);
+ if (operationTarget == null) {
+ return null;
+ }
+
+ ISelection selection = editor.getSelectionProvider().getSelection();
+ IDocument document = editor.getDocumentProvider().getDocument(
+ editor.getEditorInput());
+
+ final int operationCode;
+ if (isSelectionCommented(selection, document)) {
+ operationCode = ITextOperationTarget.STRIP_PREFIX;
+ } else {
+ operationCode = ITextOperationTarget.PREFIX;
+ }
+
+ Shell shell = editor.getSite().getShell();
+ if (!operationTarget.canDoOperation(operationCode)) {
+ if (shell != null) {
+ MessageDialog.openError(shell,
+ Localization.getString("ToggleComment_error_title"), //$NON-NLS-1$
+ Localization.getString("ToggleComment_error_message")); //$NON-NLS-1$
+ }
+ return null;
+ }
+
+ Display display = null;
+ if (shell != null && !shell.isDisposed()) {
+ display = shell.getDisplay();
+ }
+
+ BusyIndicator.showWhile(display, new Runnable() {
+ @Override
+ public void run() {
+ operationTarget.doOperation(operationCode);
+ }
+ });
+
+ return null;
+ }
+
+ /**
+ * Creates a region describing the text block (something that starts at the
+ * beginning of a line) completely containing the current selection.
+ *
+ * Note, the implementation has to match org.eclipse.jface.text.TextViewer;
+ * .getTextBlockFromSelection().
+ *
+ * @param selection The selection to use
+ * @param document The document
+ * @return the region describing the text block comprising the given
+ * selection
+ * @throws BadLocationException
+ */
+ public IRegion getTextBlockFromSelection(ITextSelection selection,
+ IDocument document) throws BadLocationException {
+ int start = document.getLineOffset(selection.getStartLine());
+ int end;
+ int endLine = selection.getEndLine();
+ if (document.getNumberOfLines() > endLine + 1) {
+ end = document.getLineOffset(endLine + 1);
+ } else {
+ end = document.getLength();
+ }
+ return new Region(start, end - start);
+ }
+
+ /**
+ * Is the given selection on the specified document single-line commented?
+ *
+ * @param selection Selection to check
+ * @param document The document
+ * @return <code>true</code> iff all selected lines are commented
+ */
+ public boolean isSelectionCommented(ISelection selection,
+ IDocument document) {
+
+ if (!(selection instanceof ITextSelection)) {
+ return false;
+ }
+
+ ITextSelection textSelection = (ITextSelection) selection;
+ if (textSelection.getStartLine() < 0 || textSelection.getEndLine() < 0) {
+ return false;
+ }
+
+ try {
+ IRegion block = getTextBlockFromSelection(textSelection, document);
+ ITypedRegion[] regions = TextUtilities.computePartitioning(
+ document, STPPartitionScanner.STP_PARTITIONING,
+ block.getOffset(), block.getLength(), false);
+
+ int[] lines = new int[regions.length * 2]; // [startline, endline,
+ // startline, endline,
+ // ...]
+
+ // For each partition in the text selection, figure out the
+ // startline and endline.
+ // Count the number of lines that are selected.
+ for (int i = 0, j = 0; i < regions.length; i++, j += 2) {
+ // Start line of region
+ lines[j] = getFirstCompleteLineOfRegion(regions[i], document);
+ // End line of region
+ int length = regions[i].getLength();
+ int offset = regions[i].getOffset() + length;
+ if (length > 0) {
+ offset--;
+ }
+
+ // If there is no startline for this region (startline = -1),
+ // then there is no endline,
+ // otherwise, get the line number of the endline and store it in
+ // the array.
+ lines[j + 1] = (lines[j] == -1 ? -1 : document
+ .getLineOfOffset(offset));
+
+ assert i < regions.length;
+ assert j < regions.length * 2;
+ }
+
+ // Perform the check
+ boolean hasComment = false;
+ for (int i = 0, j = 0; i < regions.length; i++, j += 2) {
+ String prefix = "//"; //$NON-NLS-1$
+ if (lines[j] >= 0 && lines[j + 1] >= 0) {
+ if (isBlockCommented(lines[j], lines[j + 1], prefix,
+ document)) {
+ hasComment = true;
+ } else if (!isBlockEmpty(lines[j], lines[j + 1], document)) {
+ return false;
+ }
+ }
+ }
+ return hasComment;
+ } catch (BadLocationException e) {
+ ExceptionErrorDialog.openError(e.getLocalizedMessage(), e);
+ }
+
+ return false;
+ }
+
+ /**
+ * Returns the index of the first line whose start offset is in the given
+ * text range.
+ *
+ * @param region the text range in characters where to find the line
+ * @param document The document
+ * @return the first line whose start index is in the given range, -1 if
+ * there is no such line
+ */
+ public int getFirstCompleteLineOfRegion(IRegion region, IDocument document) {
+ try {
+ int startLine = document.getLineOfOffset(region.getOffset());
+
+ int offset = document.getLineOffset(startLine);
+ if (offset >= region.getOffset()) {
+ return startLine;
+ }
+
+ offset = document.getLineOffset(startLine + 1);
+ return (offset > region.getOffset() + region.getLength() ? -1
+ : startLine + 1);
+ } catch (BadLocationException e) {
+ ExceptionErrorDialog.openError(e.getLocalizedMessage(), e);
+ }
+
+ return -1;
+ }
+
+ /**
+ * Determines whether each line is empty
+ *
+ * @param startLine Start line in document
+ * @param endLine End line in document
+ * @param document The document
+ * @return <code>true</code> if each line from <code>startLine</code> to and
+ * including <code>endLine</code> is empty
+ */
+ public boolean isBlockEmpty(int startLine, int endLine, IDocument document) {
+ try {
+ for (int i = startLine; i <= endLine; i++) {
+ IRegion line = document.getLineInformation(i);
+ String text = document.get(line.getOffset(), line.getLength());
+
+ boolean isEmptyLine = text.trim().length() == 0;
+ if (!isEmptyLine) {
+ return false;
+ }
+ }
+ return true;
+ } catch (BadLocationException e) {
+ ExceptionErrorDialog.openError(e.getLocalizedMessage(), e);
+ }
+
+ return false;
+ }
+
+ /**
+ * Determines whether each line is prefixed by one of the prefixes.
+ *
+ * @param startLine Start line in document
+ * @param endLine End line in document
+ * @param prefix Comment prefix
+ * @param document The document
+ * @return <code>true</code> iff each line from <code>startLine</code> to
+ * and including <code>endLine</code> is prepended by the
+ * <code>prefix</code>, ignoring whitespace at the begin of line
+ */
+ public boolean isBlockCommented(int startLine, int endLine, String prefix,
+ IDocument document) {
+ try {
+ // Check for occurrences of prefixes in the given lines
+ boolean hasComment = false;
+ for (int i = startLine; i <= endLine; i++) {
+ IRegion line = document.getLineInformation(i);
+ String text = document.get(line.getOffset(), line.getLength());
+
+ boolean isEmptyLine = text.trim().length() == 0;
+ if (isEmptyLine) {
+ continue;
+ }
+
+ int prefixIndex = text.indexOf(prefix, 0);
+
+ if (prefixIndex == -1) {
+ // Found a line which is not commented
+ return false;
+ }
+ String s = document.get(line.getOffset(), prefixIndex);
+ s = s.trim();
+ if (s.length() != 0) {
+ // Found a line which is not commented
+ return false;
+ }
+ hasComment = true;
+ }
+ return hasComment;
+ } catch (BadLocationException e) {
+ ExceptionErrorDialog.openError(e.getLocalizedMessage(), e);
+ }
+
+ return false;
+ }
+
+ /**
+ * Update text operation target based on the specified text editor.
+ *
+ * @param editor ITextEditor editor to associate operation target to.
+ */
+ private void updateOpTarget(ITextEditor editor) {
+ if (editor != null) {
+ operationTarget = (ITextOperationTarget) editor
+ .getAdapter(ITextOperationTarget.class);
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/TreeExpandCollapseAction.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/TreeExpandCollapseAction.java
index 430f96cb05..4ff0e2ae5e 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/TreeExpandCollapseAction.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/actions/TreeExpandCollapseAction.java
@@ -28,67 +28,67 @@ import org.eclipse.ui.PlatformUI;
* @author Ryan Morse
*/
public class TreeExpandCollapseAction extends Action implements
- ISelectionListener {
- private final IWorkbenchWindow fWindow;
- private IStructuredSelection selection;
- private final BrowserView viewer;
+ ISelectionListener {
+ private final IWorkbenchWindow fWindow;
+ private IStructuredSelection selection;
+ private final BrowserView viewer;
- /**
- * The default constructor. Takes a <code>Class</code> representing the viewer that it is to expand
- * or collapse, as there is only one in the workbench at a time.
- * @param cls <code>Class</code> of the viewer to expand/collapse
- */
- public TreeExpandCollapseAction(BrowserView view) {
- super();
- fWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- fWindow.getSelectionService().addSelectionListener(this);
- this.viewer = view;
- }
+ /**
+ * The default constructor. Takes a <code>Class</code> representing the viewer that it is to expand
+ * or collapse, as there is only one in the workbench at a time.
+ * @param cls <code>Class</code> of the viewer to expand/collapse
+ */
+ public TreeExpandCollapseAction(BrowserView view) {
+ super();
+ fWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ fWindow.getSelectionService().addSelectionListener(this);
+ this.viewer = view;
+ }
- /**
- * Updates <code>selection</code> with the current selection whenever the user changes
- * the current selection.
- */
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
- if (incoming instanceof IStructuredSelection) {
- selection = (IStructuredSelection) incoming;
- setEnabled(selection.size() == 1);
- } else {
- // Other selections, for example containing text or of other kinds.
- setEnabled(false);
- }
- }
+ /**
+ * Updates <code>selection</code> with the current selection whenever the user changes
+ * the current selection.
+ */
+ @Override
+ public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
+ if (incoming instanceof IStructuredSelection) {
+ selection = (IStructuredSelection) incoming;
+ setEnabled(selection.size() == 1);
+ } else {
+ // Other selections, for example containing text or of other kinds.
+ setEnabled(false);
+ }
+ }
- public void dispose() {
- fWindow.getSelectionService().removeSelectionListener(this);
- }
+ public void dispose() {
+ fWindow.getSelectionService().removeSelectionListener(this);
+ }
- /**
- * The main body of the action. Expands or Collapses the viewer specified at construction to
- * the level of the current selection.
- */
- @Override
- public void run() {
- ISelection incoming = viewer.getViewer().getSelection();
- IStructuredSelection selection = (IStructuredSelection)incoming;
- Object o = selection.getFirstElement();
+ /**
+ * The main body of the action. Expands or Collapses the viewer specified at construction to
+ * the level of the current selection.
+ */
+ @Override
+ public void run() {
+ ISelection incoming = viewer.getViewer().getSelection();
+ IStructuredSelection selection = (IStructuredSelection)incoming;
+ Object o = selection.getFirstElement();
- if(o == null) {
- return;
- }
+ if(o == null) {
+ return;
+ }
- Object[] objs = viewer.getViewer().getVisibleExpandedElements();
- boolean doExpand = true;
+ Object[] objs = viewer.getViewer().getVisibleExpandedElements();
+ boolean doExpand = true;
- for(int i = 0; i < objs.length; i++)
- if(objs[i] == o)
- doExpand = false;
+ for(int i = 0; i < objs.length; i++)
+ if(objs[i] == o)
+ doExpand = false;
- if(doExpand) {
- viewer.getViewer().expandToLevel(o,1);
- } else {
- viewer.getViewer().collapseToLevel(o,1);
- }
- }
+ if(doExpand) {
+ viewer.getViewer().expandToLevel(o,1);
+ } else {
+ viewer.getViewer().collapseToLevel(o,1);
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/CodeFormatterUtil.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/CodeFormatterUtil.java
index 59ae5b77c0..eb8df0add8 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/CodeFormatterUtil.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/CodeFormatterUtil.java
@@ -13,12 +13,12 @@ package org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp;
public class CodeFormatterUtil {
- public static int getTabWidth() {
- return 4;
- }
+ public static int getTabWidth() {
+ return 4;
+ }
- public static int getIndentWidth() {
- return 4;
- }
+ public static int getIndentWidth() {
+ return 4;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/DocumentCharacterIterator.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/DocumentCharacterIterator.java
index ea027dcad2..92e8df3fc6 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/DocumentCharacterIterator.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/DocumentCharacterIterator.java
@@ -32,215 +32,215 @@ import org.eclipse.jface.text.IDocument;
*/
public class DocumentCharacterIterator implements CharacterIterator, CharSequence {
- private int fIndex= -1;
- private final IDocument fDocument;
- private final int fFirst;
- private final int fLast;
-
- private void invariant() {
- Assert.isTrue(fIndex >= fFirst);
- Assert.isTrue(fIndex <= fLast);
- }
-
- /**
- * Creates an iterator for the entire document.
- *
- * @param document the document backing this iterator
- */
- public DocumentCharacterIterator(IDocument document) {
- this(document, 0);
- }
-
- /**
- * Creates an iterator, starting at offset <code>first</code>.
- *
- * @param document the document backing this iterator
- * @param first the first character to consider
- * @throws IllegalArgumentException if the indices are out of bounds
- */
- public DocumentCharacterIterator(IDocument document, int first) {
- this(document, first, document.getLength());
- }
-
- /**
- * Creates an iterator for the document contents from <code>first</code>
- * (inclusive) to <code>last</code> (exclusive).
- *
- * @param document the document backing this iterator
- * @param first the first character to consider
- * @param last the last character index to consider
- * @throws IllegalArgumentException if the indices are out of bounds
- */
- public DocumentCharacterIterator(IDocument document, int first, int last) {
- if (document == null)
- throw new NullPointerException();
- if (first < 0 || first > last)
- throw new IllegalArgumentException();
- if (last > document.getLength())
- throw new IllegalArgumentException();
- fDocument= document;
- fFirst= first;
- fLast= last;
- fIndex= first;
- invariant();
- }
-
- /*
- * @see java.text.CharacterIterator#first()
- */
- @Override
- public char first() {
- return setIndex(getBeginIndex());
- }
-
- /*
- * @see java.text.CharacterIterator#last()
- */
- @Override
- public char last() {
- if (fFirst == fLast)
- return setIndex(getEndIndex());
- return setIndex(getEndIndex() - 1);
- }
-
- /*
- * @see java.text.CharacterIterator#current()
- */
- @Override
- public char current() {
- if (fIndex >= fFirst && fIndex < fLast)
- try {
- return fDocument.getChar(fIndex);
- } catch (BadLocationException e) {
- // ignore
- }
- return DONE;
- }
-
- /*
- * @see java.text.CharacterIterator#next()
- */
- @Override
- public char next() {
- return setIndex(Math.min(fIndex + 1, getEndIndex()));
- }
-
- /*
- * @see java.text.CharacterIterator#previous()
- */
- @Override
- public char previous() {
- if (fIndex > getBeginIndex()) {
- return setIndex(fIndex - 1);
- }
- return DONE;
- }
-
- /*
- * @see java.text.CharacterIterator#setIndex(int)
- */
- @Override
- public char setIndex(int position) {
- if (position >= getBeginIndex() && position <= getEndIndex())
- fIndex= position;
- else
- throw new IllegalArgumentException();
-
- invariant();
- return current();
- }
-
- /*
- * @see java.text.CharacterIterator#getBeginIndex()
- */
- @Override
- public int getBeginIndex() {
- return fFirst;
- }
-
- /*
- * @see java.text.CharacterIterator#getEndIndex()
- */
- @Override
- public int getEndIndex() {
- return fLast;
- }
-
- /*
- * @see java.text.CharacterIterator#getIndex()
- */
- @Override
- public int getIndex() {
- return fIndex;
- }
-
- /*
- * @see java.text.CharacterIterator#clone()
- */
- @Override
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- throw new InternalError();
- }
- }
-
- /*
- * @see java.lang.CharSequence#length()
- */
- @Override
- public int length() {
- return getEndIndex() - getBeginIndex();
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Note that, if the document is modified concurrently, this method may
- * return {@link CharacterIterator#DONE} if a {@link BadLocationException}
- * was thrown when accessing the backing document.
- * </p>
- *
- * @param index {@inheritDoc}
- * @return {@inheritDoc}
- */
- @Override
- public char charAt(int index) {
- if (index >= 0 && index < length())
- try {
- return fDocument.getChar(getBeginIndex() + index);
- } catch (BadLocationException e) {
- // ignore and return DONE
- return DONE;
- }
- throw new IndexOutOfBoundsException();
- }
-
- /*
- * @see java.lang.CharSequence#subSequence(int, int)
- */
- @Override
- public CharSequence subSequence(int start, int end) {
- if (start < 0)
- throw new IndexOutOfBoundsException();
- if (end < start)
- throw new IndexOutOfBoundsException();
- if (end > length())
- throw new IndexOutOfBoundsException();
- return new DocumentCharacterIterator(fDocument, getBeginIndex() + start, getBeginIndex() + end);
- }
-
- /*
- * @see java.lang.CharSequence#toString()
- */
- @Override
- public String toString() {
- int length = length();
- char[] chs = new char[length];
- for (int i=0; i<length; ++i) {
- chs[i] = charAt(i);
- }
- return new String(chs);
- }
+ private int fIndex= -1;
+ private final IDocument fDocument;
+ private final int fFirst;
+ private final int fLast;
+
+ private void invariant() {
+ Assert.isTrue(fIndex >= fFirst);
+ Assert.isTrue(fIndex <= fLast);
+ }
+
+ /**
+ * Creates an iterator for the entire document.
+ *
+ * @param document the document backing this iterator
+ */
+ public DocumentCharacterIterator(IDocument document) {
+ this(document, 0);
+ }
+
+ /**
+ * Creates an iterator, starting at offset <code>first</code>.
+ *
+ * @param document the document backing this iterator
+ * @param first the first character to consider
+ * @throws IllegalArgumentException if the indices are out of bounds
+ */
+ public DocumentCharacterIterator(IDocument document, int first) {
+ this(document, first, document.getLength());
+ }
+
+ /**
+ * Creates an iterator for the document contents from <code>first</code>
+ * (inclusive) to <code>last</code> (exclusive).
+ *
+ * @param document the document backing this iterator
+ * @param first the first character to consider
+ * @param last the last character index to consider
+ * @throws IllegalArgumentException if the indices are out of bounds
+ */
+ public DocumentCharacterIterator(IDocument document, int first, int last) {
+ if (document == null)
+ throw new NullPointerException();
+ if (first < 0 || first > last)
+ throw new IllegalArgumentException();
+ if (last > document.getLength())
+ throw new IllegalArgumentException();
+ fDocument= document;
+ fFirst= first;
+ fLast= last;
+ fIndex= first;
+ invariant();
+ }
+
+ /*
+ * @see java.text.CharacterIterator#first()
+ */
+ @Override
+ public char first() {
+ return setIndex(getBeginIndex());
+ }
+
+ /*
+ * @see java.text.CharacterIterator#last()
+ */
+ @Override
+ public char last() {
+ if (fFirst == fLast)
+ return setIndex(getEndIndex());
+ return setIndex(getEndIndex() - 1);
+ }
+
+ /*
+ * @see java.text.CharacterIterator#current()
+ */
+ @Override
+ public char current() {
+ if (fIndex >= fFirst && fIndex < fLast)
+ try {
+ return fDocument.getChar(fIndex);
+ } catch (BadLocationException e) {
+ // ignore
+ }
+ return DONE;
+ }
+
+ /*
+ * @see java.text.CharacterIterator#next()
+ */
+ @Override
+ public char next() {
+ return setIndex(Math.min(fIndex + 1, getEndIndex()));
+ }
+
+ /*
+ * @see java.text.CharacterIterator#previous()
+ */
+ @Override
+ public char previous() {
+ if (fIndex > getBeginIndex()) {
+ return setIndex(fIndex - 1);
+ }
+ return DONE;
+ }
+
+ /*
+ * @see java.text.CharacterIterator#setIndex(int)
+ */
+ @Override
+ public char setIndex(int position) {
+ if (position >= getBeginIndex() && position <= getEndIndex())
+ fIndex= position;
+ else
+ throw new IllegalArgumentException();
+
+ invariant();
+ return current();
+ }
+
+ /*
+ * @see java.text.CharacterIterator#getBeginIndex()
+ */
+ @Override
+ public int getBeginIndex() {
+ return fFirst;
+ }
+
+ /*
+ * @see java.text.CharacterIterator#getEndIndex()
+ */
+ @Override
+ public int getEndIndex() {
+ return fLast;
+ }
+
+ /*
+ * @see java.text.CharacterIterator#getIndex()
+ */
+ @Override
+ public int getIndex() {
+ return fIndex;
+ }
+
+ /*
+ * @see java.text.CharacterIterator#clone()
+ */
+ @Override
+ public Object clone() {
+ try {
+ return super.clone();
+ } catch (CloneNotSupportedException e) {
+ throw new InternalError();
+ }
+ }
+
+ /*
+ * @see java.lang.CharSequence#length()
+ */
+ @Override
+ public int length() {
+ return getEndIndex() - getBeginIndex();
+ }
+
+ /**
+ * {@inheritDoc}
+ * <p>
+ * Note that, if the document is modified concurrently, this method may
+ * return {@link CharacterIterator#DONE} if a {@link BadLocationException}
+ * was thrown when accessing the backing document.
+ * </p>
+ *
+ * @param index {@inheritDoc}
+ * @return {@inheritDoc}
+ */
+ @Override
+ public char charAt(int index) {
+ if (index >= 0 && index < length())
+ try {
+ return fDocument.getChar(getBeginIndex() + index);
+ } catch (BadLocationException e) {
+ // ignore and return DONE
+ return DONE;
+ }
+ throw new IndexOutOfBoundsException();
+ }
+
+ /*
+ * @see java.lang.CharSequence#subSequence(int, int)
+ */
+ @Override
+ public CharSequence subSequence(int start, int end) {
+ if (start < 0)
+ throw new IndexOutOfBoundsException();
+ if (end < start)
+ throw new IndexOutOfBoundsException();
+ if (end > length())
+ throw new IndexOutOfBoundsException();
+ return new DocumentCharacterIterator(fDocument, getBeginIndex() + start, getBeginIndex() + end);
+ }
+
+ /*
+ * @see java.lang.CharSequence#toString()
+ */
+ @Override
+ public String toString() {
+ int length = length();
+ char[] chs = new char[length];
+ for (int i=0; i<length; ++i) {
+ chs[i] = charAt(i);
+ }
+ return new String(chs);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/IndentUtil.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/IndentUtil.java
index e7da786141..15d6e125ea 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/IndentUtil.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/IndentUtil.java
@@ -27,301 +27,301 @@ import org.eclipse.jface.text.source.ILineRange;
*/
public final class IndentUtil {
- private static final String SLASHES= "//"; //$NON-NLS-1$
-
- /**
- * The result of an indentation operation. The result may be passed to
- * subsequent calls to
- * {@link IndentUtil#indentLines(IDocument, ILineRange, IProject, IndentUtil.IndentResult) indentLines}
- * to obtain consistent results with respect to the indentation of
- * line-comments.
- */
- public static final class IndentResult {
- private IndentResult(boolean[] commentLines) {
- commentLinesAtColumnZero= commentLines;
- }
- private boolean[] commentLinesAtColumnZero;
- }
-
- private IndentUtil() {
- // do not instantiate
- }
-
- /**
- * Indents the line range specified by <code>lines</code> in
- * <code>document</code>. The passed C project may be
- * <code>null</code>, it is used solely to obtain formatter preferences.
- *
- * @param document the document to be changed
- * @param lines the line range to be indented
- * @param project the C project to get the formatter preferences from, or
- * <code>null</code> if global preferences should be used
- * @param result the result from a previous call to <code>indentLines</code>,
- * in order to maintain comment line properties, or <code>null</code>.
- * Note that the passed result may be changed by the call.
- * @return an indent result that may be queried for changes and can be
- * reused in subsequent indentation operations
- * @throws BadLocationException if <code>lines</code> is not a valid line
- * range on <code>document</code>
- */
- public static IndentResult indentLines(IDocument document, ILineRange lines, IProject project, IndentResult result) throws BadLocationException {
- int numberOfLines= lines.getNumberOfLines();
-
- if (numberOfLines < 1)
- return new IndentResult(null);
-
- result= reuseOrCreateToken(result, numberOfLines);
-
- STPHeuristicScanner scanner= new STPHeuristicScanner(document);
- STPIndenter indenter= new STPIndenter(document, scanner, project);
- boolean indentInsideLineComments= true;
- for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++) {
- indentLine(document, line, indenter, scanner, result.commentLinesAtColumnZero, i++, indentInsideLineComments);
- }
-
- return result;
- }
-
- /**
- * Returns the indentation of the line <code>line</code> in <code>document</code>.
- * The returned string may contain pairs of leading slashes that are considered
- * part of the indentation.
- *
- * @param document the document
- * @param line the line
- * @param indentInsideLineComments option whether to indent inside line comments starting at column 0
- * @return the indentation of <code>line</code> in <code>document</code>
- * @throws BadLocationException if the document is changed concurrently
- */
- public static String getCurrentIndent(IDocument document, int line, boolean indentInsideLineComments) throws BadLocationException {
- IRegion region= document.getLineInformation(line);
- int from= region.getOffset();
- int endOffset= region.getOffset() + region.getLength();
-
- int to= from;
- if (indentInsideLineComments) {
- // go behind line comments
- while (to < endOffset - 2 && document.get(to, 2).equals(SLASHES))
- to += 2;
- }
-
- while (to < endOffset) {
- char ch= document.getChar(to);
- if (!Character.isWhitespace(ch))
- break;
- to++;
- }
-
- return document.get(from, to - from);
- }
-
- private static IndentResult reuseOrCreateToken(IndentResult token, int numberOfLines) {
- if (token == null)
- token= new IndentResult(new boolean[numberOfLines]);
- else if (token.commentLinesAtColumnZero == null)
- token.commentLinesAtColumnZero= new boolean[numberOfLines];
- else if (token.commentLinesAtColumnZero.length != numberOfLines) {
- boolean[] commentBooleans= new boolean[numberOfLines];
- System.arraycopy(token.commentLinesAtColumnZero, 0, commentBooleans, 0, Math.min(numberOfLines, token.commentLinesAtColumnZero.length));
- token.commentLinesAtColumnZero= commentBooleans;
- }
- return token;
- }
-
- /**
- * Indents a single line using the heuristic scanner. Multiline comments are
- * indented as specified by the <code>CCommentAutoIndentStrategy</code>.
- *
- * @param document the document
- * @param line the line to be indented
- * @param indenter the C indenter
- * @param scanner the heuristic scanner
- * @param commentLines the indent token comment booleans
- * @param lineIndex the zero-based line index
- * @param indentInsideLineComments option whether to indent inside line comments
- * starting at column 0
- * @throws BadLocationException if the document got changed concurrently
- */
- private static void indentLine(IDocument document, int line, STPIndenter indenter,
- STPHeuristicScanner scanner, boolean[] commentLines, int lineIndex,
- boolean indentInsideLineComments) throws BadLocationException {
- IRegion currentLine= document.getLineInformation(line);
- final int offset= currentLine.getOffset();
- int wsStart= offset; // where we start searching for non-WS; after the "//" in single line comments
-
- String indent= null;
- if (offset < document.getLength()) {
- ITypedRegion partition= TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, offset, true);
- ITypedRegion startingPartition= TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, offset, false);
- String type= partition.getType();
- if (type.equals(STPPartitionScanner.STP_MULTILINE_COMMENT)) {
- indent= computeCommentIndent(document, line, scanner, startingPartition);
- } else if (startingPartition.getType().equals(STPPartitionScanner.STP_CONDITIONAL)) {
- indent= computePreprocessorIndent(document, line, startingPartition);
- } else if (!commentLines[lineIndex] && startingPartition.getOffset() == offset && startingPartition.getType().equals(STPPartitionScanner.STP_COMMENT)) {
- return;
- }
- }
-
- // standard C code indentation
- if (indent == null) {
- StringBuilder computed= indenter.computeIndentation(offset);
- if (computed != null)
- indent= computed.toString();
- else
- indent= ""; //$NON-NLS-1$
- }
-
- // change document:
- // get current white space
- int lineLength= currentLine.getLength();
- int end= scanner.findNonWhitespaceForwardInAnyPartition(wsStart, offset + lineLength);
- if (end == STPHeuristicScanner.NOT_FOUND)
- end= offset + lineLength;
- int length= end - offset;
- String currentIndent= document.get(offset, length);
-
- // memorize the fact that a line is a single line comment (but not at column 0) and should be treated like code
- // as opposed to commented out code, which should keep its slashes at column 0
- // if 'indentInsideLineComments' is false, all comment lines are indented with the code
- if (length > 0 || !indentInsideLineComments) {
- ITypedRegion partition= TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, end, false);
- if (partition.getOffset() == end && STPPartitionScanner.STP_COMMENT.equals(partition.getType())) {
- commentLines[lineIndex]= true;
- }
- }
-
- // only change the document if it is a real change
- if (!indent.equals(currentIndent)) {
- document.replace(offset, length, indent);
- }
- }
-
- /**
- * Computes and returns the indentation for a source line.
- *
- * @param document the document
- * @param line the line in document
- * @param indenter the C indenter
- * @param scanner the scanner
- * @return the indent, never <code>null</code>
- * @throws BadLocationException
- */
- public static String computeIndent(IDocument document, int line, STPIndenter indenter, STPHeuristicScanner scanner) throws BadLocationException {
- IRegion currentLine= document.getLineInformation(line);
- final int offset= currentLine.getOffset();
-
- String indent= null;
- if (offset < document.getLength()) {
- ITypedRegion partition= TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, offset, true);
- ITypedRegion startingPartition= TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, offset, false);
- String type= partition.getType();
- if (type.equals(STPPartitionScanner.STP_COMMENT)) {
- indent= computeCommentIndent(document, line, scanner, startingPartition);
- } else if (startingPartition.getType().equals(STPPartitionScanner.STP_CONDITIONAL)) {
- indent= computePreprocessorIndent(document, line, startingPartition);
- }
- }
-
- // standard C code indentation
- if (indent == null) {
- StringBuilder computed= indenter.computeIndentation(offset);
- if (computed != null)
- indent= computed.toString();
- else
- indent= new String();
- }
- return indent;
- }
-
- /**
- * Computes and returns the indentation for a block comment line.
- *
- * @param document the document
- * @param line the line in document
- * @param scanner the scanner
- * @param partition the comment partition
- * @return the indent, or <code>null</code> if not computable
- * @throws BadLocationException
- */
- public static String computeCommentIndent(IDocument document, int line, STPHeuristicScanner scanner, ITypedRegion partition) throws BadLocationException {
- if (line == 0) // impossible - the first line is never inside a comment
- return null;
-
- // don't make any assumptions if the line does not start with \s*\* - it might be
- // commented out code, for which we don't want to change the indent
- final IRegion lineInfo= document.getLineInformation(line);
- final int lineStart= lineInfo.getOffset();
- final int lineLength= lineInfo.getLength();
- final int lineEnd= lineStart + lineLength;
- int nonWS= scanner.findNonWhitespaceForwardInAnyPartition(lineStart, lineEnd);
- if (nonWS == STPHeuristicScanner.NOT_FOUND || document.getChar(nonWS) != '*') {
- if (nonWS == STPHeuristicScanner.NOT_FOUND)
- return document.get(lineStart, lineLength);
- return document.get(lineStart, nonWS - lineStart);
- }
-
- // take the indent from the previous line and reuse
- IRegion previousLine= document.getLineInformation(line - 1);
- int previousLineStart= previousLine.getOffset();
- int previousLineLength= previousLine.getLength();
- int previousLineEnd= previousLineStart + previousLineLength;
-
- StringBuilder buf= new StringBuilder();
- int previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
- if (previousLineNonWS == STPHeuristicScanner.NOT_FOUND || document.getChar(previousLineNonWS) != '*') {
- // align with the comment start if the previous line is not an asterix line
- previousLine= document.getLineInformationOfOffset(partition.getOffset());
- previousLineStart= previousLine.getOffset();
- previousLineLength= previousLine.getLength();
- previousLineEnd= previousLineStart + previousLineLength;
- previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
- if (previousLineNonWS == STPHeuristicScanner.NOT_FOUND)
- previousLineNonWS= previousLineEnd;
-
- // add the initial space
- // TODO this may be controlled by a formatter preference in the future
- buf.append(' ');
- }
-
- String indentation= document.get(previousLineStart, previousLineNonWS - previousLineStart);
- buf.insert(0, indentation);
- return buf.toString();
- }
-
- /**
- * Computes and returns the indentation for a preprocessor line.
- *
- * @param document the document
- * @param line the line in document
- * @param partition the comment partition
- * @return the indent, or <code>null</code> if not computable
- * @throws BadLocationException
- */
- public static String computePreprocessorIndent(IDocument document, int line, ITypedRegion partition)
- throws BadLocationException {
- int ppFirstLine= document.getLineOfOffset(partition.getOffset());
- if (line == ppFirstLine) {
- return ""; //$NON-NLS-1$
- }
- STPHeuristicScanner ppScanner= new STPHeuristicScanner(document, STPPartitionScanner.STP_CONDITIONAL, partition.getType());
- STPIndenter ppIndenter= new STPIndenter(document, ppScanner);
- if (line == ppFirstLine + 1) {
- return ppIndenter.createReusingIndent(new StringBuilder(), ppIndenter.getContinuationLineIndent(), 0).toString();
- }
- StringBuilder computed= ppIndenter.computeIndentation(document.getLineOffset(line), false);
- if (computed != null) {
- return computed.toString();
- }
- // take the indent from the previous line and reuse
- IRegion previousLine= document.getLineInformation(line - 1);
- int previousLineStart= previousLine.getOffset();
- int previousLineLength= previousLine.getLength();
- int previousLineEnd= previousLineStart + previousLineLength;
-
- int previousLineNonWS= ppScanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
- String previousIndent= document.get(previousLineStart, previousLineNonWS - previousLineStart);
- computed= new StringBuilder(previousIndent);
- return computed.toString();
- }
+ private static final String SLASHES= "//"; //$NON-NLS-1$
+
+ /**
+ * The result of an indentation operation. The result may be passed to
+ * subsequent calls to
+ * {@link IndentUtil#indentLines(IDocument, ILineRange, IProject, IndentUtil.IndentResult) indentLines}
+ * to obtain consistent results with respect to the indentation of
+ * line-comments.
+ */
+ public static final class IndentResult {
+ private IndentResult(boolean[] commentLines) {
+ commentLinesAtColumnZero= commentLines;
+ }
+ private boolean[] commentLinesAtColumnZero;
+ }
+
+ private IndentUtil() {
+ // do not instantiate
+ }
+
+ /**
+ * Indents the line range specified by <code>lines</code> in
+ * <code>document</code>. The passed C project may be
+ * <code>null</code>, it is used solely to obtain formatter preferences.
+ *
+ * @param document the document to be changed
+ * @param lines the line range to be indented
+ * @param project the C project to get the formatter preferences from, or
+ * <code>null</code> if global preferences should be used
+ * @param result the result from a previous call to <code>indentLines</code>,
+ * in order to maintain comment line properties, or <code>null</code>.
+ * Note that the passed result may be changed by the call.
+ * @return an indent result that may be queried for changes and can be
+ * reused in subsequent indentation operations
+ * @throws BadLocationException if <code>lines</code> is not a valid line
+ * range on <code>document</code>
+ */
+ public static IndentResult indentLines(IDocument document, ILineRange lines, IProject project, IndentResult result) throws BadLocationException {
+ int numberOfLines= lines.getNumberOfLines();
+
+ if (numberOfLines < 1)
+ return new IndentResult(null);
+
+ result= reuseOrCreateToken(result, numberOfLines);
+
+ STPHeuristicScanner scanner= new STPHeuristicScanner(document);
+ STPIndenter indenter= new STPIndenter(document, scanner, project);
+ boolean indentInsideLineComments= true;
+ for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++) {
+ indentLine(document, line, indenter, scanner, result.commentLinesAtColumnZero, i++, indentInsideLineComments);
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the indentation of the line <code>line</code> in <code>document</code>.
+ * The returned string may contain pairs of leading slashes that are considered
+ * part of the indentation.
+ *
+ * @param document the document
+ * @param line the line
+ * @param indentInsideLineComments option whether to indent inside line comments starting at column 0
+ * @return the indentation of <code>line</code> in <code>document</code>
+ * @throws BadLocationException if the document is changed concurrently
+ */
+ public static String getCurrentIndent(IDocument document, int line, boolean indentInsideLineComments) throws BadLocationException {
+ IRegion region= document.getLineInformation(line);
+ int from= region.getOffset();
+ int endOffset= region.getOffset() + region.getLength();
+
+ int to= from;
+ if (indentInsideLineComments) {
+ // go behind line comments
+ while (to < endOffset - 2 && document.get(to, 2).equals(SLASHES))
+ to += 2;
+ }
+
+ while (to < endOffset) {
+ char ch= document.getChar(to);
+ if (!Character.isWhitespace(ch))
+ break;
+ to++;
+ }
+
+ return document.get(from, to - from);
+ }
+
+ private static IndentResult reuseOrCreateToken(IndentResult token, int numberOfLines) {
+ if (token == null)
+ token= new IndentResult(new boolean[numberOfLines]);
+ else if (token.commentLinesAtColumnZero == null)
+ token.commentLinesAtColumnZero= new boolean[numberOfLines];
+ else if (token.commentLinesAtColumnZero.length != numberOfLines) {
+ boolean[] commentBooleans= new boolean[numberOfLines];
+ System.arraycopy(token.commentLinesAtColumnZero, 0, commentBooleans, 0, Math.min(numberOfLines, token.commentLinesAtColumnZero.length));
+ token.commentLinesAtColumnZero= commentBooleans;
+ }
+ return token;
+ }
+
+ /**
+ * Indents a single line using the heuristic scanner. Multiline comments are
+ * indented as specified by the <code>CCommentAutoIndentStrategy</code>.
+ *
+ * @param document the document
+ * @param line the line to be indented
+ * @param indenter the C indenter
+ * @param scanner the heuristic scanner
+ * @param commentLines the indent token comment booleans
+ * @param lineIndex the zero-based line index
+ * @param indentInsideLineComments option whether to indent inside line comments
+ * starting at column 0
+ * @throws BadLocationException if the document got changed concurrently
+ */
+ private static void indentLine(IDocument document, int line, STPIndenter indenter,
+ STPHeuristicScanner scanner, boolean[] commentLines, int lineIndex,
+ boolean indentInsideLineComments) throws BadLocationException {
+ IRegion currentLine= document.getLineInformation(line);
+ final int offset= currentLine.getOffset();
+ int wsStart= offset; // where we start searching for non-WS; after the "//" in single line comments
+
+ String indent= null;
+ if (offset < document.getLength()) {
+ ITypedRegion partition= TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, offset, true);
+ ITypedRegion startingPartition= TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, offset, false);
+ String type= partition.getType();
+ if (type.equals(STPPartitionScanner.STP_MULTILINE_COMMENT)) {
+ indent= computeCommentIndent(document, line, scanner, startingPartition);
+ } else if (startingPartition.getType().equals(STPPartitionScanner.STP_CONDITIONAL)) {
+ indent= computePreprocessorIndent(document, line, startingPartition);
+ } else if (!commentLines[lineIndex] && startingPartition.getOffset() == offset && startingPartition.getType().equals(STPPartitionScanner.STP_COMMENT)) {
+ return;
+ }
+ }
+
+ // standard C code indentation
+ if (indent == null) {
+ StringBuilder computed= indenter.computeIndentation(offset);
+ if (computed != null)
+ indent= computed.toString();
+ else
+ indent= ""; //$NON-NLS-1$
+ }
+
+ // change document:
+ // get current white space
+ int lineLength= currentLine.getLength();
+ int end= scanner.findNonWhitespaceForwardInAnyPartition(wsStart, offset + lineLength);
+ if (end == STPHeuristicScanner.NOT_FOUND)
+ end= offset + lineLength;
+ int length= end - offset;
+ String currentIndent= document.get(offset, length);
+
+ // memorize the fact that a line is a single line comment (but not at column 0) and should be treated like code
+ // as opposed to commented out code, which should keep its slashes at column 0
+ // if 'indentInsideLineComments' is false, all comment lines are indented with the code
+ if (length > 0 || !indentInsideLineComments) {
+ ITypedRegion partition= TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, end, false);
+ if (partition.getOffset() == end && STPPartitionScanner.STP_COMMENT.equals(partition.getType())) {
+ commentLines[lineIndex]= true;
+ }
+ }
+
+ // only change the document if it is a real change
+ if (!indent.equals(currentIndent)) {
+ document.replace(offset, length, indent);
+ }
+ }
+
+ /**
+ * Computes and returns the indentation for a source line.
+ *
+ * @param document the document
+ * @param line the line in document
+ * @param indenter the C indenter
+ * @param scanner the scanner
+ * @return the indent, never <code>null</code>
+ * @throws BadLocationException
+ */
+ public static String computeIndent(IDocument document, int line, STPIndenter indenter, STPHeuristicScanner scanner) throws BadLocationException {
+ IRegion currentLine= document.getLineInformation(line);
+ final int offset= currentLine.getOffset();
+
+ String indent= null;
+ if (offset < document.getLength()) {
+ ITypedRegion partition= TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, offset, true);
+ ITypedRegion startingPartition= TextUtilities.getPartition(document, STPPartitionScanner.STP_PARTITIONING, offset, false);
+ String type= partition.getType();
+ if (type.equals(STPPartitionScanner.STP_COMMENT)) {
+ indent= computeCommentIndent(document, line, scanner, startingPartition);
+ } else if (startingPartition.getType().equals(STPPartitionScanner.STP_CONDITIONAL)) {
+ indent= computePreprocessorIndent(document, line, startingPartition);
+ }
+ }
+
+ // standard C code indentation
+ if (indent == null) {
+ StringBuilder computed= indenter.computeIndentation(offset);
+ if (computed != null)
+ indent= computed.toString();
+ else
+ indent= new String();
+ }
+ return indent;
+ }
+
+ /**
+ * Computes and returns the indentation for a block comment line.
+ *
+ * @param document the document
+ * @param line the line in document
+ * @param scanner the scanner
+ * @param partition the comment partition
+ * @return the indent, or <code>null</code> if not computable
+ * @throws BadLocationException
+ */
+ public static String computeCommentIndent(IDocument document, int line, STPHeuristicScanner scanner, ITypedRegion partition) throws BadLocationException {
+ if (line == 0) // impossible - the first line is never inside a comment
+ return null;
+
+ // don't make any assumptions if the line does not start with \s*\* - it might be
+ // commented out code, for which we don't want to change the indent
+ final IRegion lineInfo= document.getLineInformation(line);
+ final int lineStart= lineInfo.getOffset();
+ final int lineLength= lineInfo.getLength();
+ final int lineEnd= lineStart + lineLength;
+ int nonWS= scanner.findNonWhitespaceForwardInAnyPartition(lineStart, lineEnd);
+ if (nonWS == STPHeuristicScanner.NOT_FOUND || document.getChar(nonWS) != '*') {
+ if (nonWS == STPHeuristicScanner.NOT_FOUND)
+ return document.get(lineStart, lineLength);
+ return document.get(lineStart, nonWS - lineStart);
+ }
+
+ // take the indent from the previous line and reuse
+ IRegion previousLine= document.getLineInformation(line - 1);
+ int previousLineStart= previousLine.getOffset();
+ int previousLineLength= previousLine.getLength();
+ int previousLineEnd= previousLineStart + previousLineLength;
+
+ StringBuilder buf= new StringBuilder();
+ int previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
+ if (previousLineNonWS == STPHeuristicScanner.NOT_FOUND || document.getChar(previousLineNonWS) != '*') {
+ // align with the comment start if the previous line is not an asterix line
+ previousLine= document.getLineInformationOfOffset(partition.getOffset());
+ previousLineStart= previousLine.getOffset();
+ previousLineLength= previousLine.getLength();
+ previousLineEnd= previousLineStart + previousLineLength;
+ previousLineNonWS= scanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
+ if (previousLineNonWS == STPHeuristicScanner.NOT_FOUND)
+ previousLineNonWS= previousLineEnd;
+
+ // add the initial space
+ // TODO this may be controlled by a formatter preference in the future
+ buf.append(' ');
+ }
+
+ String indentation= document.get(previousLineStart, previousLineNonWS - previousLineStart);
+ buf.insert(0, indentation);
+ return buf.toString();
+ }
+
+ /**
+ * Computes and returns the indentation for a preprocessor line.
+ *
+ * @param document the document
+ * @param line the line in document
+ * @param partition the comment partition
+ * @return the indent, or <code>null</code> if not computable
+ * @throws BadLocationException
+ */
+ public static String computePreprocessorIndent(IDocument document, int line, ITypedRegion partition)
+ throws BadLocationException {
+ int ppFirstLine= document.getLineOfOffset(partition.getOffset());
+ if (line == ppFirstLine) {
+ return ""; //$NON-NLS-1$
+ }
+ STPHeuristicScanner ppScanner= new STPHeuristicScanner(document, STPPartitionScanner.STP_CONDITIONAL, partition.getType());
+ STPIndenter ppIndenter= new STPIndenter(document, ppScanner);
+ if (line == ppFirstLine + 1) {
+ return ppIndenter.createReusingIndent(new StringBuilder(), ppIndenter.getContinuationLineIndent(), 0).toString();
+ }
+ StringBuilder computed= ppIndenter.computeIndentation(document.getLineOffset(line), false);
+ if (computed != null) {
+ return computed.toString();
+ }
+ // take the indent from the previous line and reuse
+ IRegion previousLine= document.getLineInformation(line - 1);
+ int previousLineStart= previousLine.getOffset();
+ int previousLineLength= previousLine.getLength();
+ int previousLineEnd= previousLineStart + previousLineLength;
+
+ int previousLineNonWS= ppScanner.findNonWhitespaceForwardInAnyPartition(previousLineStart, previousLineEnd);
+ String previousIndent= document.get(previousLineStart, previousLineNonWS - previousLineStart);
+ computed= new StringBuilder(previousIndent);
+ return computed.toString();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/Messages.java
index b86f74750d..9ebd3a1633 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/Messages.java
@@ -14,16 +14,16 @@ package org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.messages"; //$NON-NLS-1$
- public static String STPCompletionProcessor_global;
- public static String STPCompletionProcessor_probe;
- public static String STPCompletionProcessor_function;
- public static String STPMetadataSingleton_noCompletions;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.messages"; //$NON-NLS-1$
+ public static String STPCompletionProcessor_global;
+ public static String STPCompletionProcessor_probe;
+ public static String STPCompletionProcessor_function;
+ public static String STPMetadataSingleton_noCompletions;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPAutoEditStrategy.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPAutoEditStrategy.java
index 26cf374a54..11efa8bcc1 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPAutoEditStrategy.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPAutoEditStrategy.java
@@ -30,1014 +30,1014 @@ import org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.STPIndenter.
* Very basic auto edit strategy simply completing opening with closing brackets and quotes.
*/
public class STPAutoEditStrategy extends
- DefaultIndentLineAutoEditStrategy {
- private static final String LINE_COMMENT= "//"; //$NON-NLS-1$
- private boolean fCloseBrace = true;
-
- private String fPartitioning;
- private IProject fProject;
-
- public STPAutoEditStrategy(String fPartitioning, IProject project) {
- this.fPartitioning = fPartitioning;
- this.fProject = project;
- }
-
- /**
- * Returns the block balance, i.e. zero if the blocks are balanced at
- * <code>offset</code>, a negative number if there are more closing than opening
- * braces, and a positive number if there are more opening than closing braces.
- *
- * @param document
- * @param offset
- * @param partitioning
- * @return the block balance
- */
- private static int getBlockBalance(IDocument document, int offset, String partitioning) {
- if (offset < 1)
- return -1;
- if (offset >= document.getLength())
- return 1;
-
- int begin = offset;
- int end = offset - 1;
-
- STPHeuristicScanner scanner = new STPHeuristicScanner(document);
-
- while (true) {
- begin = scanner.findOpeningPeer(begin - 1, '{', '}');
- end = scanner.findClosingPeer(end + 1, '{', '}');
- if (begin == -1 && end == -1)
- return 0;
- if (begin == -1)
- return -1;
- if (end == -1)
- return 1;
- }
- }
-
- @Override
- public void customizeDocumentCommand(IDocument document,
- DocumentCommand command) {
- boolean modified = false;
- boolean isNewLine= command.length == 0 && command.text != null
- && isLineDelimiter(document, command.text);
- if (isNewLine) {
- smartIndentAfterNewLine(document, command);
- } else if (command.text.length() == 1) {
- smartIndentOnKeypress(document, command);
- } else if (command.text.length() > 1
- && command.text.trim().length() != 0) {
- smartPaste(document, command); // no smart backspace for paste
- }
- if (command.text.equals("\"") && !inStringOrComment(document, command)) { //$NON-NLS-1$
- command.text = "\"\""; //$NON-NLS-1$
- modified = true;
- } else if (command.text.equals("(") && !inStringOrComment(document, command)) { //$NON-NLS-1$
- command.text = "()"; //$NON-NLS-1$
- modified = true;
- } else if (command.text.equals("[") && !inStringOrComment(document, command)) { //$NON-NLS-1$
- command.text = "[]"; //$NON-NLS-1$
- modified = true;
- }
-
- if (modified) {
- command.caretOffset = command.offset + 1;
- command.shiftsCaret = false;
- }
-
- super.customizeDocumentCommand(document, command);
- }
-
- private boolean inStringOrComment(IDocument d, DocumentCommand c) {
- int docLength = d.getLength();
- if (c.offset == -1 || docLength == 0)
- return false;
- try {
- ITypedRegion partition= TextUtilities.getPartition(d, fPartitioning, c.offset, false);
- String partitionType = partition.getType();
- if (c.offset > 0 &&
- (STPPartitionScanner.STP_COMMENT.equals(partitionType)
- || STPPartitionScanner.STP_MULTILINE_COMMENT.equals(partitionType)
- || STPPartitionScanner.STP_STRING.equals(partitionType))) {
- return true;
- }
- IRegion lineInfo = d.getLineInformationOfOffset(c.offset);
- int offset = lineInfo.getOffset();
- boolean inChar = false;
- boolean inString = false;
- boolean inComment = false;
- for (int i = offset; i < c.offset; ++i) {
- char ch = d.getChar(i);
- switch (ch) {
- case '\"':
- if (!inChar)
- inString = !inString;
- break;
- case '\'':
- if (!inString)
- inChar = !inChar;
- break;
- case '\\':
- ++i;
- break;
- case '/':
- if (!inString && !inChar) {
- ch = d.getChar(i + 1);
- if (ch == '/')
- return true; // We have a line comment
- else if (ch == '*')
- inComment = true;
- }
- break;
- case '#':
- if (!inString && !inChar)
- return true;
- break;
- case '*':
- if (!inString && !inChar) {
- if (inComment) {
- ch = d.getChar(i + 1);
- if (ch == '/')
- inComment = false;
- }
- }
- break;
- }
- }
- return inString || inChar || inComment;
-
- } catch (BadLocationException e) {
- IDEPlugin.log(e);
- }
- return false;
- }
-
-
- private void smartIndentAfterNewLine(IDocument d, DocumentCommand c) {
- int docLength = d.getLength();
- if (c.offset == -1 || docLength == 0)
- return;
-
- int addIndent= 0;
- STPHeuristicScanner scanner= new STPHeuristicScanner(d);
- try {
- ITypedRegion partition= TextUtilities.getPartition(d, fPartitioning, c.offset, false);
- if (STPPartitionScanner.STP_CONDITIONAL.equals(partition.getType()) && c.offset > 0 && d.getChar(c.offset-1) == '\\') {
- scanner = new STPHeuristicScanner(d, fPartitioning, STPPartitionScanner.STP_CONDITIONAL);
- addIndent= 1;
- }
-
- int line = d.getLineOfOffset(c.offset);
- IRegion reg = d.getLineInformation(line);
- int start = reg.getOffset();
- int lineEnd = start + reg.getLength();
-
- StringBuilder indent= null;
- STPIndenter indenter= new STPIndenter(d, scanner, fProject);
- indent= indenter.computeIndentation(c.offset);
- if (indent == null) {
- indent= new StringBuilder();
- }
- if (addIndent > 0 && indent.length() == 0) {
- indent= indenter.createReusingIndent(indent, addIndent, 0);
- }
-
- StringBuilder buf = new StringBuilder(c.text + indent);
- int contentStart = findEndOfWhiteSpace(d, c.offset, lineEnd);
- c.length = Math.max(contentStart - c.offset, 0);
-
- // insert closing brace on new line after an unclosed opening brace
- if (getBracketCount(d, start, c.offset, true) > 0 && fCloseBrace && !isClosedBrace(d, c.offset)) {
- c.caretOffset = c.offset + buf.length();
- c.shiftsCaret = false;
-
- // copy old content of line behind insertion point to new line
- // unless we think we are inserting an anonymous type definition
- if (c.offset == 0 || !(computeAnonymousPosition(d, c.offset - 1, fPartitioning, lineEnd) != -1)) {
- if (lineEnd - contentStart > 0) {
- c.length = lineEnd - c.offset;
- buf.append(d.get(contentStart, lineEnd - contentStart).toCharArray());
- }
- }
-
- buf.append(TextUtilities.getDefaultLineDelimiter(d));
- StringBuilder reference = null;
- int nonWS = findEndOfWhiteSpace(d, start, lineEnd);
- if (nonWS < c.offset && d.getChar(nonWS) == '{')
- reference = new StringBuilder(d.get(start, nonWS - start));
- else
- reference = indenter.getReferenceIndentation(c.offset);
- if (reference != null)
- buf.append(reference);
- buf.append('}');
- int bound= c.offset > 200 ? c.offset - 200 : STPHeuristicScanner.UNBOUND;
- int bracePos = scanner.findOpeningPeer(c.offset - 1, bound, '{', '}');
- if (bracePos != STPHeuristicScanner.NOT_FOUND) {
- if (scanner.looksLikeCompositeTypeDefinitionBackward(bracePos, bound) ||
- scanner.previousToken(bracePos - 1, bound) == STPSymbols.TokenEQUAL) {
- buf.append(';');
- }
- }
- }
- // insert extra line upon new line between two braces
- else if (c.offset > start && contentStart < lineEnd && d.getChar(contentStart) == '}') {
- int firstCharPos = scanner.findNonWhitespaceBackward(c.offset - 1, start);
- if (firstCharPos != STPHeuristicScanner.NOT_FOUND && d.getChar(firstCharPos) == '{') {
- c.caretOffset = c.offset + buf.length();
- c.shiftsCaret = false;
-
- StringBuilder reference = null;
- int nonWS = findEndOfWhiteSpace(d, start, lineEnd);
- if (nonWS < c.offset && d.getChar(nonWS) == '{')
- reference = new StringBuilder(d.get(start, nonWS - start));
- else
- reference = indenter.getReferenceIndentation(c.offset);
-
- buf.append(TextUtilities.getDefaultLineDelimiter(d));
-
- if (reference != null)
- buf.append(reference);
- }
- }
- c.text = buf.toString();
-
- } catch (BadLocationException e) {
- IDEPlugin.log(e);
- }
- }
-
- private void smartIndentUponE(IDocument doc, DocumentCommand c) {
- if (c.offset < 4 || doc.getLength() == 0)
- return;
-
- try {
- String content = doc.get(c.offset - 3, 3);
- if (content.equals("els")) { //$NON-NLS-1$
- STPHeuristicScanner scanner = new STPHeuristicScanner(doc);
- int p = c.offset - 3;
-
- // current line
- int line = doc.getLineOfOffset(p);
- int lineOffset = doc.getLineOffset(line);
-
- // make sure we don't have any leading comments etc.
- if (doc.get(lineOffset, p - lineOffset).trim().length() != 0)
- return;
-
- // Line of last C code
- int pos = scanner.findNonWhitespaceBackward(p - 1, STPHeuristicScanner.UNBOUND);
- if (pos == -1)
- return;
- int lastLine = doc.getLineOfOffset(pos);
-
- // Only shift if the last C line is further up and is a braceless block candidate
- if (lastLine < line) {
- STPIndenter indenter = new STPIndenter(doc, scanner, fProject);
- int ref = indenter.findReferencePosition(p, true, MatchMode.REGULAR);
- if (ref == STPHeuristicScanner.NOT_FOUND)
- return;
- int refLine = doc.getLineOfOffset(ref);
- String indent = getIndentOfLine(doc, refLine);
-
- if (indent != null) {
- c.text = indent + "else"; //$NON-NLS-1$
- c.length += c.offset - lineOffset;
- c.offset = lineOffset;
- }
- }
-
- return;
- }
-
- if (content.equals("cas")) { //$NON-NLS-1$
- STPHeuristicScanner scanner = new STPHeuristicScanner(doc);
- int p = c.offset - 3;
-
- // current line
- int line = doc.getLineOfOffset(p);
- int lineOffset = doc.getLineOffset(line);
-
- // make sure we don't have any leading comments etc.
- if (doc.get(lineOffset, p - lineOffset).trim().length() != 0)
- return;
-
- // Line of last C code
- int pos = scanner.findNonWhitespaceBackward(p - 1, STPHeuristicScanner.UNBOUND);
- if (pos == -1)
- return;
- int lastLine = doc.getLineOfOffset(pos);
-
- // Only shift if the last C line is further up and is a braceless block candidate
- if (lastLine < line) {
- STPIndenter indenter = new STPIndenter(doc, scanner, fProject);
- int ref = indenter.findReferencePosition(p, false, MatchMode.MATCH_CASE);
- if (ref == STPHeuristicScanner.NOT_FOUND)
- return;
- int refLine = doc.getLineOfOffset(ref);
- int nextToken = scanner.nextToken(ref, STPHeuristicScanner.UNBOUND);
- String indent;
- if (nextToken == STPSymbols.TokenCASE || nextToken == STPSymbols.TokenDEFAULT)
- indent = getIndentOfLine(doc, refLine);
- else // at the brace of the switch
- indent = indenter.computeIndentation(p).toString();
-
- if (indent != null) {
- c.text = indent.toString() + "case"; //$NON-NLS-1$
- c.length += c.offset - lineOffset;
- c.offset = lineOffset;
- }
- }
-
- return;
- }
- } catch (BadLocationException e) {
- IDEPlugin.log(e);
- }
- }
- /**
- * Computes an insert position for an opening brace if <code>offset</code> maps to a position in
- * <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis.
- *
- * @param document the document being modified
- * @param offset the offset of the caret position, relative to the line start.
- * @param partitioning the document partitioning
- * @param max the max position
- * @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise
- */
- private static int computeAnonymousPosition(IDocument document, int offset, String partitioning, int max) {
- // find the opening parenthesis for every closing parenthesis on the current line after offset
- // return the position behind the closing parenthesis if it looks like a method declaration
- // or an expression for an if, while, for, catch statement
-
- STPHeuristicScanner scanner = new STPHeuristicScanner(document);
- int pos = offset;
- int length = max;
- int scanTo = scanner.scanForward(pos, length, '}');
- if (scanTo == -1)
- scanTo = length;
-
- int closingParen = findClosingParenToLeft(scanner, pos) - 1;
-
- while (true) {
- int startScan = closingParen + 1;
- closingParen = scanner.scanForward(startScan, scanTo, ')');
- if (closingParen == -1)
- break;
-
- int openingParen = scanner.findOpeningPeer(closingParen - 1, '(', ')');
-
- // no way an expression at the beginning of the document can mean anything
- if (openingParen < 1)
- break;
-
- // only select insert positions for parenthesis currently embracing the caret
- if (openingParen > pos)
- continue;
- }
-
- return -1;
- }
-
- /**
- * Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only
- * separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned.
- *
- * @param scanner the C heuristic scanner set up on the document
- * @param position the first character position in <code>document</code> to be considered
- * @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found
- */
- private static int findClosingParenToLeft(STPHeuristicScanner scanner, int position) {
- if (position < 1)
- return position;
-
- if (scanner.previousToken(position - 1, STPHeuristicScanner.UNBOUND) == STPSymbols.TokenRPAREN)
- return scanner.getPosition() + 1;
- return position;
- }
-
- private boolean isClosedBrace(IDocument document, int offset) {
- return getBlockBalance(document, offset, fPartitioning) <= 0;
- }
-
- private void smartIndentOnKeypress(IDocument document, DocumentCommand command) {
- switch (command.text.charAt(0)) {
- case '}':
- smartIndentAfterClosingBracket(document, command);
- break;
- case '{':
- smartIndentAfterOpeningBracket(document, command);
- break;
- case 'e':
- smartIndentUponE(document, command);
- break;
- case '#':
- smartIndentAfterHash(document, command);
- break;
- case '\"':
- smartInsertCloseChar(document, command, '\"');
- break;
- case ')':
- smartInsertCloseChar(document, command, ')');
- break;
- case ']':
- smartInsertCloseChar(document, command, ']');
- break;
- }
- }
-
- /**
- * A closing char (e.g. right paren ')') is being inserted. If one already exists
- * at current location in the document, skip over it and don't do an
- * insert.
- *
- * @param d - document
- * @param c - insert text
- * @param ch - closing char being inserted
- */
- private void smartInsertCloseChar(IDocument d, DocumentCommand c, char ch) {
- if (c.offset < 1 || d.getLength() == 0)
- return;
-
- try {
- if (d.getChar(c.offset) == ch) {
- int backslashCount = 0;
- int prevOffset = c.offset - 1;
- // Look backwards for backslashes. We will ignore if there are even number
- while (prevOffset > 0 && d.getChar(prevOffset) == '\\') {
- --prevOffset;
- ++backslashCount;
- }
- if ((backslashCount & 1) == 0) {
- c.text = ""; //$NON-NLS-1$
- c.offset++;
- }
- }
- } catch (BadLocationException e) {
- IDEPlugin.log(e);
- }
-
- }
-
- private void smartIndentAfterHash(IDocument doc, DocumentCommand c) {
- try {
- ITypedRegion partition= TextUtilities.getPartition(doc, fPartitioning, c.offset, false);
- if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) {
- IRegion startLine= doc.getLineInformationOfOffset(c.offset);
- String indent= doc.get(startLine.getOffset(), c.offset - startLine.getOffset());
- if (indent.trim().length() == 0) {
- c.offset -= indent.length();
- c.length += indent.length();
- }
- }
- } catch (BadLocationException e) {
- IDEPlugin.log(e);
- }
- }
-
- private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) {
- if (c.offset < 1 || d.getLength() == 0)
- return;
-
- int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);
-
- try {
- STPHeuristicScanner scanner= new STPHeuristicScanner(d);
- ITypedRegion partition= TextUtilities.getPartition(d, fPartitioning, p, false);
- if (STPPartitionScanner.STP_CONDITIONAL.equals(partition.getType())) {
- scanner = new STPHeuristicScanner(d, fPartitioning, STPPartitionScanner.STP_CONDITIONAL);
- }
- // current line
- int line = d.getLineOfOffset(c.offset);
- int lineOffset = d.getLineOffset(line);
-
- // make sure we don't have any leading comments etc.
- if (!d.get(lineOffset, c.offset - lineOffset).trim().isEmpty())
- return;
-
- // Line of last C code
- int pos = scanner.findNonWhitespaceBackward(p, STPHeuristicScanner.UNBOUND);
- if (pos == -1)
- return;
- int lastLine = d.getLineOfOffset(pos);
-
- // Only shift if the last C line is further up and is a braceless block candidate
- if (lastLine < line) {
- STPIndenter indenter = new STPIndenter(d, scanner, fProject);
- StringBuilder indent = indenter.computeIndentation(p, true);
- String toDelete = d.get(lineOffset, c.offset - lineOffset);
- if (indent != null && !indent.toString().equals(toDelete)) {
- c.text = indent.append(c.text).toString();
- c.length += c.offset - lineOffset;
- c.offset = lineOffset;
- }
- }
- } catch (BadLocationException e) {
- IDEPlugin.log(e);
- }
- }
-
- private boolean isLineDelimiter(IDocument document, String text) {
- String[] delimiters = document.getLegalLineDelimiters();
- if (delimiters != null)
- return TextUtilities.equals(delimiters, text) > -1;
- return false;
- }
-
- private int getBracketCount(IDocument d, int start, int end, boolean ignoreCloseBrackets) throws BadLocationException {
- int bracketcount = 0;
- while (start < end) {
- char curr = d.getChar(start);
- start++;
- switch (curr) {
- case '#' :
- if (start < end) {
- // '#'-comment: nothing to do anymore on this line
- start = end;
- }
- break;
- case '/' :
- if (start < end) {
- char next = d.getChar(start);
- if (next == '*') {
- // a comment starts, advance to the comment end
- start = getCommentEnd(d, start + 1, end);
- } else if (next == '/') {
- // '//'-comment: nothing to do anymore on this line
- start = end;
- }
- }
- break;
- case '*' :
- if (start < end) {
- char next = d.getChar(start);
- if (next == '/') {
- // we have been in a comment: forget what we read before
- bracketcount = 0;
- start++;
- }
- }
- break;
- case '{' :
- bracketcount++;
- ignoreCloseBrackets = false;
- break;
- case '}' :
- if (!ignoreCloseBrackets) {
- bracketcount--;
- }
- break;
- case '"' :
- case '\'' :
- start = getStringEnd(d, start, end, curr);
- break;
- default :
- }
- }
- return bracketcount;
- }
-
-
- // ----------- bracket counting ------------------------------------------------------
-
- private int getCommentEnd(IDocument d, int pos, int end) throws BadLocationException {
- while (pos < end) {
- char curr = d.getChar(pos);
- pos++;
- if (curr == '*') {
- if (pos < end && d.getChar(pos) == '/') {
- return pos + 1;
- }
- }
- }
- return end;
- }
-
- private String getIndentOfLine(IDocument d, int line) throws BadLocationException {
- if (line > -1) {
- int start = d.getLineOffset(line);
- int end = start + d.getLineLength(line) - 1;
- int whiteend = findEndOfWhiteSpace(d, start, end);
- return d.get(start, whiteend - start);
- }
- return ""; //$NON-NLS-1$
- }
-
- private int getStringEnd(IDocument d, int pos, int end, char ch) throws BadLocationException {
- while (pos < end) {
- char curr = d.getChar(pos);
- pos++;
- if (curr == '\\') {
- // ignore escaped characters
- pos++;
- } else if (curr == ch) {
- return pos;
- }
- }
- return end;
- }
- private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) {
- if (c.offset == -1 || d.getLength() == 0)
- return;
-
- try {
- int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);
- int line = d.getLineOfOffset(p);
- int start = d.getLineOffset(line);
- int whiteend = findEndOfWhiteSpace(d, start, c.offset);
-
- STPHeuristicScanner scanner= new STPHeuristicScanner(d);
- ITypedRegion partition= TextUtilities.getPartition(d, fPartitioning, p, false);
- if (STPPartitionScanner.STP_CONDITIONAL.equals(partition.getType())) {
- scanner = new STPHeuristicScanner(d, fPartitioning, STPPartitionScanner.STP_CONDITIONAL);
- }
- STPIndenter indenter = new STPIndenter(d, scanner, fProject);
-
- // shift only when line does not contain any text up to the closing bracket
- if (whiteend == c.offset) {
- // evaluate the line with the opening bracket that matches out closing bracket
- int reference = indenter.findReferencePosition(c.offset, false, MatchMode.MATCH_BRACE);
- int indLine = d.getLineOfOffset(reference);
- if (indLine != -1 && indLine != line) {
- // take the indent of the found line
- StringBuilder replaceText = new StringBuilder(getIndentOfLine(d, indLine));
- // add the rest of the current line including the just added close bracket
- replaceText.append(d.get(whiteend, c.offset - whiteend));
- replaceText.append(c.text);
- // modify document command
- c.length += c.offset - start;
- c.offset = start;
- c.text = replaceText.toString();
- }
- }
- } catch (BadLocationException e) {
- IDEPlugin.log(e);
- }
- }
-
- /**
- * Installs a C partitioner with <code>document</code>.
- *
- * @param document the document
- */
- private static void installPartitioner(Document document) {
- String[] types= new String[] {
- IDocument.DEFAULT_CONTENT_TYPE,
- STPPartitionScanner.STP_COMMENT,
- STPPartitionScanner.STP_CONDITIONAL,
- };
- FastPartitioner partitioner= new FastPartitioner(new STPPartitionScanner(), types);
- partitioner.connect(document);
- document.setDocumentPartitioner(STPPartitionScanner.STP_PARTITIONING, partitioner);
- }
-
- /**
- * Installs a C partitioner with <code>document</code>.
- *
- * @param document the document
- */
- private static void removePartitioner(Document document) {
- document.setDocumentPartitioner(STPPartitionScanner.STP_PARTITIONING, null);
- }
-
- private void smartPaste(IDocument document, DocumentCommand command) {
- int newOffset= command.offset;
- int newLength= command.length;
- String newText= command.text;
-
- try {
- STPHeuristicScanner scanner= new STPHeuristicScanner(document);
- STPIndenter indenter= new STPIndenter(document, scanner, fProject);
- int offset= newOffset;
-
- // reference position to get the indent from
- int refOffset= indenter.findReferencePosition(offset);
- if (refOffset == STPHeuristicScanner.NOT_FOUND)
- return;
- int peerOffset= getPeerPosition(document, command);
- peerOffset= indenter.findReferencePosition(peerOffset);
- if (peerOffset == STPHeuristicScanner.NOT_FOUND)
- return;
- refOffset= Math.min(refOffset, peerOffset);
-
- // eat any WS before the insertion to the beginning of the line
- int firstLine= 1; // don't format the first line per default, as it has other content before it
- IRegion line= document.getLineInformationOfOffset(offset);
- String notSelected= document.get(line.getOffset(), offset - line.getOffset());
- if (notSelected.trim().length() == 0) {
- newLength += notSelected.length();
- newOffset= line.getOffset();
- firstLine= 0;
- }
-
- // Prefix: the part we need for formatting but won't paste.
- // Take up to 100 previous lines to preserve enough context.
- int firstPrefixLine= Math.max(document.getLineOfOffset(refOffset) - 100, 0);
- int prefixOffset= document.getLineInformation(firstPrefixLine).getOffset();
- String prefix= document.get(prefixOffset, newOffset - prefixOffset);
-
- // Handle the indentation computation inside a temporary document
- Document temp= new Document(prefix + newText);
- DocumentRewriteSession session= temp.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
- scanner= new STPHeuristicScanner(temp);
- indenter= new STPIndenter(temp, scanner, fProject);
- installPartitioner(temp);
-
- // Indent the first and second line
- // compute the relative indentation difference from the second line
- // (as the first might be partially selected) and use the value to
- // indent all other lines.
- boolean isIndentDetected= false;
- StringBuilder addition= new StringBuilder();
- int insertLength= 0;
- int first= document.computeNumberOfLines(prefix) + firstLine; // don't format first line
- int lines= temp.getNumberOfLines();
- boolean changed= false;
- boolean indentInsideLineComments= true;
-
- for (int l= first; l < lines; l++) { // we don't change the number of lines while adding indents
- IRegion r= temp.getLineInformation(l);
- int lineOffset= r.getOffset();
- int lineLength= r.getLength();
-
- if (lineLength == 0) // don't modify empty lines
- continue;
-
- if (!isIndentDetected) {
- // indent the first pasted line
- String current= IndentUtil.getCurrentIndent(temp, l, indentInsideLineComments);
- StringBuilder correct= new StringBuilder(IndentUtil.computeIndent(temp, l, indenter, scanner));
-
- insertLength= subtractIndent(correct, current, addition);
- // workaround for bug 181139
- if (/*l != first && */temp.get(lineOffset, lineLength).trim().length() != 0) {
- isIndentDetected= true;
- if (insertLength == 0) {
- // no adjustment needed, bail out
- if (firstLine == 0) {
- // but we still need to adjust the first line
- command.offset= newOffset;
- command.length= newLength;
- if (changed)
- break; // still need to get the leading indent of the first line
- }
- return;
- }
- removePartitioner(temp);
- } else {
- changed= insertLength != 0;
- }
- }
-
- // relatively indent all pasted lines
- if (insertLength > 0)
- addIndent(temp, l, addition, indentInsideLineComments);
- else if (insertLength < 0)
- cutIndent(temp, l, -insertLength, indentInsideLineComments);
- }
-
- temp.stopRewriteSession(session);
- newText= temp.get(prefix.length(), temp.getLength() - prefix.length());
-
- command.offset= newOffset;
- command.length= newLength;
- command.text= newText;
- } catch (BadLocationException e) {
- IDEPlugin.log(e);
- }
- }
- /**
- * Computes the difference of two indentations and returns the difference in
- * length of current and correct. If the return value is positive, <code>addition</code>
- * is initialized with a substring of that length of <code>correct</code>.
- *
- * @param correct the correct indentation
- * @param current the current indentation (migth contain non-whitespace)
- * @param difference a string buffer - if the return value is positive, it will be cleared and set to the substring of <code>current</code> of that length
- * @return the difference in lenght of <code>correct</code> and <code>current</code>
- */
- private int subtractIndent(CharSequence correct, CharSequence current, StringBuilder difference) {
- int c1= computeVisualLength(correct);
- int c2= computeVisualLength(current);
- int diff= c1 - c2;
- if (diff <= 0)
- return diff;
-
- difference.setLength(0);
- int len= 0, i= 0;
- while (len < diff) {
- char c= correct.charAt(i++);
- difference.append(c);
- len += computeVisualLength(c);
- }
-
- return diff;
- }
-
- /**
- * Indents line <code>line</code> in <code>document</code> with <code>indent</code>.
- * Leaves leading comment signs alone.
- *
- * @param document the document
- * @param line the line
- * @param indent the indentation to insert
- * @param indentInsideLineComments option whether to indent inside line comments starting at column 0
- * @throws BadLocationException on concurrent document modification
- */
- private static void addIndent(Document document, int line, CharSequence indent, boolean indentInsideLineComments) throws BadLocationException {
- IRegion region= document.getLineInformation(line);
- int insert= region.getOffset();
- int endOffset= region.getOffset() + region.getLength();
-
- if (indentInsideLineComments) {
- // go behind line comments
- while (insert < endOffset - 2 && document.get(insert, 2).equals(LINE_COMMENT))
- insert += 2;
- }
-
- // insert indent
- document.replace(insert, 0, indent.toString());
- }
-
- /**
- * Cuts the visual equivalent of <code>toDelete</code> characters out of the
- * indentation of line <code>line</code> in <code>document</code>. Leaves
- * leading comment signs alone.
- *
- * @param document the document
- * @param line the line
- * @param toDelete the number of space equivalents to delete.
- * @param indentInsideLineComments option whether to indent inside line comments starting at column 0
- * @throws BadLocationException on concurrent document modification
- */
- private void cutIndent(Document document, int line, int toDelete, boolean indentInsideLineComments) throws BadLocationException {
- IRegion region= document.getLineInformation(line);
- int from= region.getOffset();
- int endOffset= region.getOffset() + region.getLength();
-
- if (indentInsideLineComments) {
- // go behind line comments
- while (from < endOffset - 2 && document.get(from, 2).equals(LINE_COMMENT))
- from += 2;
- }
-
- int to= from;
- while (toDelete > 0 && to < endOffset) {
- char ch= document.getChar(to);
- if (!Character.isWhitespace(ch))
- break;
- toDelete -= computeVisualLength(ch);
- if (toDelete >= 0)
- to++;
- else
- break;
- }
-
- document.replace(from, to - from, null);
- }
-
- /**
- * Returns the visual length of a given <code>CharSequence</code> taking into
- * account the visual tabulator length.
- *
- * @param seq the string to measure
- * @return the visual length of <code>seq</code>
- */
- private int computeVisualLength(CharSequence seq) {
- int size= 0;
- int tablen= getVisualTabLengthPreference();
-
- for (int i= 0; i < seq.length(); i++) {
- char ch= seq.charAt(i);
- if (ch == '\t') {
- if (tablen != 0)
- size += tablen - size % tablen;
- // else: size stays the same
- } else {
- size++;
- }
- }
- return size;
- }
-
- /**
- * Returns the visual length of a given character taking into
- * account the visual tabulator length.
- *
- * @param ch the character to measure
- * @return the visual length of <code>ch</code>
- */
- private int computeVisualLength(char ch) {
- if (ch == '\t')
- return getVisualTabLengthPreference();
- return 1;
- }
-
- /**
- * The preference setting for the visual tabulator display.
- *
- * @return the number of spaces displayed for a tabulator in the editor
- */
- private int getVisualTabLengthPreference() {
- return CodeFormatterUtil.getTabWidth();
- }
-
- private int getPeerPosition(IDocument document, DocumentCommand command) {
- if (document.getLength() == 0)
- return 0;
- /*
- * Search for scope closers in the pasted text and find their opening peers
- * in the document.
- */
- Document pasted= new Document(command.text);
- installPartitioner(pasted);
- int firstPeer= command.offset;
-
- STPHeuristicScanner pScanner= new STPHeuristicScanner(pasted);
- STPHeuristicScanner dScanner= new STPHeuristicScanner(document);
-
- // add scope relevant after context to peer search
- int afterToken= dScanner.nextToken(command.offset + command.length, STPHeuristicScanner.UNBOUND);
- try {
- switch (afterToken) {
- case STPSymbols.TokenRBRACE:
- pasted.replace(pasted.getLength(), 0, "}"); //$NON-NLS-1$
- break;
- case STPSymbols.TokenRPAREN:
- pasted.replace(pasted.getLength(), 0, ")"); //$NON-NLS-1$
- break;
- case STPSymbols.TokenRBRACKET:
- pasted.replace(pasted.getLength(), 0, "]"); //$NON-NLS-1$
- break;
- }
- } catch (BadLocationException e) {
- // cannot happen
- Assert.isTrue(false);
- }
-
- int pPos= 0; // paste text position (increasing from 0)
- int dPos= Math.max(0, command.offset - 1); // document position (decreasing from paste offset)
- while (true) {
- int token= pScanner.nextToken(pPos, STPHeuristicScanner.UNBOUND);
- pPos= pScanner.getPosition();
- switch (token) {
- case STPSymbols.TokenLBRACE:
- case STPSymbols.TokenLBRACKET:
- case STPSymbols.TokenLPAREN:
- pPos= skipScope(pScanner, pPos, token);
- if (pPos == STPHeuristicScanner.NOT_FOUND)
- return firstPeer;
- break; // closed scope -> keep searching
- case STPSymbols.TokenRBRACE:
- int peer= dScanner.findOpeningPeer(dPos, '{', '}');
- dPos= peer - 1;
- if (peer == STPHeuristicScanner.NOT_FOUND)
- return firstPeer;
- firstPeer= peer;
- break; // keep searching
- case STPSymbols.TokenRBRACKET:
- peer= dScanner.findOpeningPeer(dPos, '[', ']');
- dPos= peer - 1;
- if (peer == STPHeuristicScanner.NOT_FOUND)
- return firstPeer;
- firstPeer= peer;
- break; // keep searching
- case STPSymbols.TokenRPAREN:
- peer= dScanner.findOpeningPeer(dPos, '(', ')');
- dPos= peer - 1;
- if (peer == STPHeuristicScanner.NOT_FOUND)
- return firstPeer;
- firstPeer= peer;
- break; // keep searching
-
- case STPSymbols.TokenCASE:
- case STPSymbols.TokenDEFAULT:
- {
- STPIndenter indenter= new STPIndenter(document, dScanner, fProject);
- peer= indenter.findReferencePosition(dPos, false, MatchMode.MATCH_CASE);
- if (peer == STPHeuristicScanner.NOT_FOUND)
- return firstPeer;
- firstPeer= peer;
- }
- break; // keep searching
-
- case STPSymbols.TokenPUBLIC:
- case STPSymbols.TokenPROTECTED:
- case STPSymbols.TokenPRIVATE:
- {
- STPIndenter indenter= new STPIndenter(document, dScanner, fProject);
- peer= indenter.findReferencePosition(dPos, false, MatchMode.MATCH_ACCESS_SPECIFIER);
- if (peer == STPHeuristicScanner.NOT_FOUND)
- return firstPeer;
- firstPeer= peer;
- }
- break; // keep searching
-
- case STPSymbols.TokenEOF:
- return firstPeer;
- default:
- // keep searching
- }
- }
+ DefaultIndentLineAutoEditStrategy {
+ private static final String LINE_COMMENT= "//"; //$NON-NLS-1$
+ private boolean fCloseBrace = true;
+
+ private String fPartitioning;
+ private IProject fProject;
+
+ public STPAutoEditStrategy(String fPartitioning, IProject project) {
+ this.fPartitioning = fPartitioning;
+ this.fProject = project;
+ }
+
+ /**
+ * Returns the block balance, i.e. zero if the blocks are balanced at
+ * <code>offset</code>, a negative number if there are more closing than opening
+ * braces, and a positive number if there are more opening than closing braces.
+ *
+ * @param document
+ * @param offset
+ * @param partitioning
+ * @return the block balance
+ */
+ private static int getBlockBalance(IDocument document, int offset, String partitioning) {
+ if (offset < 1)
+ return -1;
+ if (offset >= document.getLength())
+ return 1;
+
+ int begin = offset;
+ int end = offset - 1;
+
+ STPHeuristicScanner scanner = new STPHeuristicScanner(document);
+
+ while (true) {
+ begin = scanner.findOpeningPeer(begin - 1, '{', '}');
+ end = scanner.findClosingPeer(end + 1, '{', '}');
+ if (begin == -1 && end == -1)
+ return 0;
+ if (begin == -1)
+ return -1;
+ if (end == -1)
+ return 1;
+ }
+ }
+
+ @Override
+ public void customizeDocumentCommand(IDocument document,
+ DocumentCommand command) {
+ boolean modified = false;
+ boolean isNewLine= command.length == 0 && command.text != null
+ && isLineDelimiter(document, command.text);
+ if (isNewLine) {
+ smartIndentAfterNewLine(document, command);
+ } else if (command.text.length() == 1) {
+ smartIndentOnKeypress(document, command);
+ } else if (command.text.length() > 1
+ && command.text.trim().length() != 0) {
+ smartPaste(document, command); // no smart backspace for paste
+ }
+ if (command.text.equals("\"") && !inStringOrComment(document, command)) { //$NON-NLS-1$
+ command.text = "\"\""; //$NON-NLS-1$
+ modified = true;
+ } else if (command.text.equals("(") && !inStringOrComment(document, command)) { //$NON-NLS-1$
+ command.text = "()"; //$NON-NLS-1$
+ modified = true;
+ } else if (command.text.equals("[") && !inStringOrComment(document, command)) { //$NON-NLS-1$
+ command.text = "[]"; //$NON-NLS-1$
+ modified = true;
+ }
+
+ if (modified) {
+ command.caretOffset = command.offset + 1;
+ command.shiftsCaret = false;
+ }
+
+ super.customizeDocumentCommand(document, command);
+ }
+
+ private boolean inStringOrComment(IDocument d, DocumentCommand c) {
+ int docLength = d.getLength();
+ if (c.offset == -1 || docLength == 0)
+ return false;
+ try {
+ ITypedRegion partition= TextUtilities.getPartition(d, fPartitioning, c.offset, false);
+ String partitionType = partition.getType();
+ if (c.offset > 0 &&
+ (STPPartitionScanner.STP_COMMENT.equals(partitionType)
+ || STPPartitionScanner.STP_MULTILINE_COMMENT.equals(partitionType)
+ || STPPartitionScanner.STP_STRING.equals(partitionType))) {
+ return true;
+ }
+ IRegion lineInfo = d.getLineInformationOfOffset(c.offset);
+ int offset = lineInfo.getOffset();
+ boolean inChar = false;
+ boolean inString = false;
+ boolean inComment = false;
+ for (int i = offset; i < c.offset; ++i) {
+ char ch = d.getChar(i);
+ switch (ch) {
+ case '\"':
+ if (!inChar)
+ inString = !inString;
+ break;
+ case '\'':
+ if (!inString)
+ inChar = !inChar;
+ break;
+ case '\\':
+ ++i;
+ break;
+ case '/':
+ if (!inString && !inChar) {
+ ch = d.getChar(i + 1);
+ if (ch == '/')
+ return true; // We have a line comment
+ else if (ch == '*')
+ inComment = true;
+ }
+ break;
+ case '#':
+ if (!inString && !inChar)
+ return true;
+ break;
+ case '*':
+ if (!inString && !inChar) {
+ if (inComment) {
+ ch = d.getChar(i + 1);
+ if (ch == '/')
+ inComment = false;
+ }
+ }
+ break;
+ }
+ }
+ return inString || inChar || inComment;
+
+ } catch (BadLocationException e) {
+ IDEPlugin.log(e);
+ }
+ return false;
+ }
+
+
+ private void smartIndentAfterNewLine(IDocument d, DocumentCommand c) {
+ int docLength = d.getLength();
+ if (c.offset == -1 || docLength == 0)
+ return;
+
+ int addIndent= 0;
+ STPHeuristicScanner scanner= new STPHeuristicScanner(d);
+ try {
+ ITypedRegion partition= TextUtilities.getPartition(d, fPartitioning, c.offset, false);
+ if (STPPartitionScanner.STP_CONDITIONAL.equals(partition.getType()) && c.offset > 0 && d.getChar(c.offset-1) == '\\') {
+ scanner = new STPHeuristicScanner(d, fPartitioning, STPPartitionScanner.STP_CONDITIONAL);
+ addIndent= 1;
+ }
+
+ int line = d.getLineOfOffset(c.offset);
+ IRegion reg = d.getLineInformation(line);
+ int start = reg.getOffset();
+ int lineEnd = start + reg.getLength();
+
+ StringBuilder indent= null;
+ STPIndenter indenter= new STPIndenter(d, scanner, fProject);
+ indent= indenter.computeIndentation(c.offset);
+ if (indent == null) {
+ indent= new StringBuilder();
+ }
+ if (addIndent > 0 && indent.length() == 0) {
+ indent= indenter.createReusingIndent(indent, addIndent, 0);
+ }
+
+ StringBuilder buf = new StringBuilder(c.text + indent);
+ int contentStart = findEndOfWhiteSpace(d, c.offset, lineEnd);
+ c.length = Math.max(contentStart - c.offset, 0);
+
+ // insert closing brace on new line after an unclosed opening brace
+ if (getBracketCount(d, start, c.offset, true) > 0 && fCloseBrace && !isClosedBrace(d, c.offset)) {
+ c.caretOffset = c.offset + buf.length();
+ c.shiftsCaret = false;
+
+ // copy old content of line behind insertion point to new line
+ // unless we think we are inserting an anonymous type definition
+ if (c.offset == 0 || !(computeAnonymousPosition(d, c.offset - 1, fPartitioning, lineEnd) != -1)) {
+ if (lineEnd - contentStart > 0) {
+ c.length = lineEnd - c.offset;
+ buf.append(d.get(contentStart, lineEnd - contentStart).toCharArray());
+ }
+ }
+
+ buf.append(TextUtilities.getDefaultLineDelimiter(d));
+ StringBuilder reference = null;
+ int nonWS = findEndOfWhiteSpace(d, start, lineEnd);
+ if (nonWS < c.offset && d.getChar(nonWS) == '{')
+ reference = new StringBuilder(d.get(start, nonWS - start));
+ else
+ reference = indenter.getReferenceIndentation(c.offset);
+ if (reference != null)
+ buf.append(reference);
+ buf.append('}');
+ int bound= c.offset > 200 ? c.offset - 200 : STPHeuristicScanner.UNBOUND;
+ int bracePos = scanner.findOpeningPeer(c.offset - 1, bound, '{', '}');
+ if (bracePos != STPHeuristicScanner.NOT_FOUND) {
+ if (scanner.looksLikeCompositeTypeDefinitionBackward(bracePos, bound) ||
+ scanner.previousToken(bracePos - 1, bound) == STPSymbols.TokenEQUAL) {
+ buf.append(';');
+ }
+ }
+ }
+ // insert extra line upon new line between two braces
+ else if (c.offset > start && contentStart < lineEnd && d.getChar(contentStart) == '}') {
+ int firstCharPos = scanner.findNonWhitespaceBackward(c.offset - 1, start);
+ if (firstCharPos != STPHeuristicScanner.NOT_FOUND && d.getChar(firstCharPos) == '{') {
+ c.caretOffset = c.offset + buf.length();
+ c.shiftsCaret = false;
+
+ StringBuilder reference = null;
+ int nonWS = findEndOfWhiteSpace(d, start, lineEnd);
+ if (nonWS < c.offset && d.getChar(nonWS) == '{')
+ reference = new StringBuilder(d.get(start, nonWS - start));
+ else
+ reference = indenter.getReferenceIndentation(c.offset);
+
+ buf.append(TextUtilities.getDefaultLineDelimiter(d));
+
+ if (reference != null)
+ buf.append(reference);
+ }
+ }
+ c.text = buf.toString();
+
+ } catch (BadLocationException e) {
+ IDEPlugin.log(e);
+ }
+ }
+
+ private void smartIndentUponE(IDocument doc, DocumentCommand c) {
+ if (c.offset < 4 || doc.getLength() == 0)
+ return;
+
+ try {
+ String content = doc.get(c.offset - 3, 3);
+ if (content.equals("els")) { //$NON-NLS-1$
+ STPHeuristicScanner scanner = new STPHeuristicScanner(doc);
+ int p = c.offset - 3;
+
+ // current line
+ int line = doc.getLineOfOffset(p);
+ int lineOffset = doc.getLineOffset(line);
+
+ // make sure we don't have any leading comments etc.
+ if (doc.get(lineOffset, p - lineOffset).trim().length() != 0)
+ return;
+
+ // Line of last C code
+ int pos = scanner.findNonWhitespaceBackward(p - 1, STPHeuristicScanner.UNBOUND);
+ if (pos == -1)
+ return;
+ int lastLine = doc.getLineOfOffset(pos);
+
+ // Only shift if the last C line is further up and is a braceless block candidate
+ if (lastLine < line) {
+ STPIndenter indenter = new STPIndenter(doc, scanner, fProject);
+ int ref = indenter.findReferencePosition(p, true, MatchMode.REGULAR);
+ if (ref == STPHeuristicScanner.NOT_FOUND)
+ return;
+ int refLine = doc.getLineOfOffset(ref);
+ String indent = getIndentOfLine(doc, refLine);
+
+ if (indent != null) {
+ c.text = indent + "else"; //$NON-NLS-1$
+ c.length += c.offset - lineOffset;
+ c.offset = lineOffset;
+ }
+ }
+
+ return;
+ }
+
+ if (content.equals("cas")) { //$NON-NLS-1$
+ STPHeuristicScanner scanner = new STPHeuristicScanner(doc);
+ int p = c.offset - 3;
+
+ // current line
+ int line = doc.getLineOfOffset(p);
+ int lineOffset = doc.getLineOffset(line);
+
+ // make sure we don't have any leading comments etc.
+ if (doc.get(lineOffset, p - lineOffset).trim().length() != 0)
+ return;
+
+ // Line of last C code
+ int pos = scanner.findNonWhitespaceBackward(p - 1, STPHeuristicScanner.UNBOUND);
+ if (pos == -1)
+ return;
+ int lastLine = doc.getLineOfOffset(pos);
+
+ // Only shift if the last C line is further up and is a braceless block candidate
+ if (lastLine < line) {
+ STPIndenter indenter = new STPIndenter(doc, scanner, fProject);
+ int ref = indenter.findReferencePosition(p, false, MatchMode.MATCH_CASE);
+ if (ref == STPHeuristicScanner.NOT_FOUND)
+ return;
+ int refLine = doc.getLineOfOffset(ref);
+ int nextToken = scanner.nextToken(ref, STPHeuristicScanner.UNBOUND);
+ String indent;
+ if (nextToken == STPSymbols.TokenCASE || nextToken == STPSymbols.TokenDEFAULT)
+ indent = getIndentOfLine(doc, refLine);
+ else // at the brace of the switch
+ indent = indenter.computeIndentation(p).toString();
+
+ if (indent != null) {
+ c.text = indent.toString() + "case"; //$NON-NLS-1$
+ c.length += c.offset - lineOffset;
+ c.offset = lineOffset;
+ }
+ }
+
+ return;
+ }
+ } catch (BadLocationException e) {
+ IDEPlugin.log(e);
+ }
+ }
+ /**
+ * Computes an insert position for an opening brace if <code>offset</code> maps to a position in
+ * <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis.
+ *
+ * @param document the document being modified
+ * @param offset the offset of the caret position, relative to the line start.
+ * @param partitioning the document partitioning
+ * @param max the max position
+ * @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise
+ */
+ private static int computeAnonymousPosition(IDocument document, int offset, String partitioning, int max) {
+ // find the opening parenthesis for every closing parenthesis on the current line after offset
+ // return the position behind the closing parenthesis if it looks like a method declaration
+ // or an expression for an if, while, for, catch statement
+
+ STPHeuristicScanner scanner = new STPHeuristicScanner(document);
+ int pos = offset;
+ int length = max;
+ int scanTo = scanner.scanForward(pos, length, '}');
+ if (scanTo == -1)
+ scanTo = length;
+
+ int closingParen = findClosingParenToLeft(scanner, pos) - 1;
+
+ while (true) {
+ int startScan = closingParen + 1;
+ closingParen = scanner.scanForward(startScan, scanTo, ')');
+ if (closingParen == -1)
+ break;
+
+ int openingParen = scanner.findOpeningPeer(closingParen - 1, '(', ')');
+
+ // no way an expression at the beginning of the document can mean anything
+ if (openingParen < 1)
+ break;
+
+ // only select insert positions for parenthesis currently embracing the caret
+ if (openingParen > pos)
+ continue;
+ }
+
+ return -1;
+ }
+
+ /**
+ * Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only
+ * separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned.
+ *
+ * @param scanner the C heuristic scanner set up on the document
+ * @param position the first character position in <code>document</code> to be considered
+ * @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found
+ */
+ private static int findClosingParenToLeft(STPHeuristicScanner scanner, int position) {
+ if (position < 1)
+ return position;
+
+ if (scanner.previousToken(position - 1, STPHeuristicScanner.UNBOUND) == STPSymbols.TokenRPAREN)
+ return scanner.getPosition() + 1;
+ return position;
+ }
+
+ private boolean isClosedBrace(IDocument document, int offset) {
+ return getBlockBalance(document, offset, fPartitioning) <= 0;
+ }
+
+ private void smartIndentOnKeypress(IDocument document, DocumentCommand command) {
+ switch (command.text.charAt(0)) {
+ case '}':
+ smartIndentAfterClosingBracket(document, command);
+ break;
+ case '{':
+ smartIndentAfterOpeningBracket(document, command);
+ break;
+ case 'e':
+ smartIndentUponE(document, command);
+ break;
+ case '#':
+ smartIndentAfterHash(document, command);
+ break;
+ case '\"':
+ smartInsertCloseChar(document, command, '\"');
+ break;
+ case ')':
+ smartInsertCloseChar(document, command, ')');
+ break;
+ case ']':
+ smartInsertCloseChar(document, command, ']');
+ break;
+ }
+ }
+
+ /**
+ * A closing char (e.g. right paren ')') is being inserted. If one already exists
+ * at current location in the document, skip over it and don't do an
+ * insert.
+ *
+ * @param d - document
+ * @param c - insert text
+ * @param ch - closing char being inserted
+ */
+ private void smartInsertCloseChar(IDocument d, DocumentCommand c, char ch) {
+ if (c.offset < 1 || d.getLength() == 0)
+ return;
+
+ try {
+ if (d.getChar(c.offset) == ch) {
+ int backslashCount = 0;
+ int prevOffset = c.offset - 1;
+ // Look backwards for backslashes. We will ignore if there are even number
+ while (prevOffset > 0 && d.getChar(prevOffset) == '\\') {
+ --prevOffset;
+ ++backslashCount;
+ }
+ if ((backslashCount & 1) == 0) {
+ c.text = ""; //$NON-NLS-1$
+ c.offset++;
+ }
+ }
+ } catch (BadLocationException e) {
+ IDEPlugin.log(e);
+ }
+
+ }
+
+ private void smartIndentAfterHash(IDocument doc, DocumentCommand c) {
+ try {
+ ITypedRegion partition= TextUtilities.getPartition(doc, fPartitioning, c.offset, false);
+ if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) {
+ IRegion startLine= doc.getLineInformationOfOffset(c.offset);
+ String indent= doc.get(startLine.getOffset(), c.offset - startLine.getOffset());
+ if (indent.trim().length() == 0) {
+ c.offset -= indent.length();
+ c.length += indent.length();
+ }
+ }
+ } catch (BadLocationException e) {
+ IDEPlugin.log(e);
+ }
+ }
+
+ private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) {
+ if (c.offset < 1 || d.getLength() == 0)
+ return;
+
+ int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);
+
+ try {
+ STPHeuristicScanner scanner= new STPHeuristicScanner(d);
+ ITypedRegion partition= TextUtilities.getPartition(d, fPartitioning, p, false);
+ if (STPPartitionScanner.STP_CONDITIONAL.equals(partition.getType())) {
+ scanner = new STPHeuristicScanner(d, fPartitioning, STPPartitionScanner.STP_CONDITIONAL);
+ }
+ // current line
+ int line = d.getLineOfOffset(c.offset);
+ int lineOffset = d.getLineOffset(line);
+
+ // make sure we don't have any leading comments etc.
+ if (!d.get(lineOffset, c.offset - lineOffset).trim().isEmpty())
+ return;
+
+ // Line of last C code
+ int pos = scanner.findNonWhitespaceBackward(p, STPHeuristicScanner.UNBOUND);
+ if (pos == -1)
+ return;
+ int lastLine = d.getLineOfOffset(pos);
+
+ // Only shift if the last C line is further up and is a braceless block candidate
+ if (lastLine < line) {
+ STPIndenter indenter = new STPIndenter(d, scanner, fProject);
+ StringBuilder indent = indenter.computeIndentation(p, true);
+ String toDelete = d.get(lineOffset, c.offset - lineOffset);
+ if (indent != null && !indent.toString().equals(toDelete)) {
+ c.text = indent.append(c.text).toString();
+ c.length += c.offset - lineOffset;
+ c.offset = lineOffset;
+ }
+ }
+ } catch (BadLocationException e) {
+ IDEPlugin.log(e);
+ }
+ }
+
+ private boolean isLineDelimiter(IDocument document, String text) {
+ String[] delimiters = document.getLegalLineDelimiters();
+ if (delimiters != null)
+ return TextUtilities.equals(delimiters, text) > -1;
+ return false;
+ }
+
+ private int getBracketCount(IDocument d, int start, int end, boolean ignoreCloseBrackets) throws BadLocationException {
+ int bracketcount = 0;
+ while (start < end) {
+ char curr = d.getChar(start);
+ start++;
+ switch (curr) {
+ case '#' :
+ if (start < end) {
+ // '#'-comment: nothing to do anymore on this line
+ start = end;
+ }
+ break;
+ case '/' :
+ if (start < end) {
+ char next = d.getChar(start);
+ if (next == '*') {
+ // a comment starts, advance to the comment end
+ start = getCommentEnd(d, start + 1, end);
+ } else if (next == '/') {
+ // '//'-comment: nothing to do anymore on this line
+ start = end;
+ }
+ }
+ break;
+ case '*' :
+ if (start < end) {
+ char next = d.getChar(start);
+ if (next == '/') {
+ // we have been in a comment: forget what we read before
+ bracketcount = 0;
+ start++;
+ }
+ }
+ break;
+ case '{' :
+ bracketcount++;
+ ignoreCloseBrackets = false;
+ break;
+ case '}' :
+ if (!ignoreCloseBrackets) {
+ bracketcount--;
+ }
+ break;
+ case '"' :
+ case '\'' :
+ start = getStringEnd(d, start, end, curr);
+ break;
+ default :
+ }
+ }
+ return bracketcount;
+ }
+
+
+ // ----------- bracket counting ------------------------------------------------------
+
+ private int getCommentEnd(IDocument d, int pos, int end) throws BadLocationException {
+ while (pos < end) {
+ char curr = d.getChar(pos);
+ pos++;
+ if (curr == '*') {
+ if (pos < end && d.getChar(pos) == '/') {
+ return pos + 1;
+ }
+ }
+ }
+ return end;
+ }
+
+ private String getIndentOfLine(IDocument d, int line) throws BadLocationException {
+ if (line > -1) {
+ int start = d.getLineOffset(line);
+ int end = start + d.getLineLength(line) - 1;
+ int whiteend = findEndOfWhiteSpace(d, start, end);
+ return d.get(start, whiteend - start);
+ }
+ return ""; //$NON-NLS-1$
+ }
+
+ private int getStringEnd(IDocument d, int pos, int end, char ch) throws BadLocationException {
+ while (pos < end) {
+ char curr = d.getChar(pos);
+ pos++;
+ if (curr == '\\') {
+ // ignore escaped characters
+ pos++;
+ } else if (curr == ch) {
+ return pos;
+ }
+ }
+ return end;
+ }
+ private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) {
+ if (c.offset == -1 || d.getLength() == 0)
+ return;
+
+ try {
+ int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);
+ int line = d.getLineOfOffset(p);
+ int start = d.getLineOffset(line);
+ int whiteend = findEndOfWhiteSpace(d, start, c.offset);
+
+ STPHeuristicScanner scanner= new STPHeuristicScanner(d);
+ ITypedRegion partition= TextUtilities.getPartition(d, fPartitioning, p, false);
+ if (STPPartitionScanner.STP_CONDITIONAL.equals(partition.getType())) {
+ scanner = new STPHeuristicScanner(d, fPartitioning, STPPartitionScanner.STP_CONDITIONAL);
+ }
+ STPIndenter indenter = new STPIndenter(d, scanner, fProject);
+
+ // shift only when line does not contain any text up to the closing bracket
+ if (whiteend == c.offset) {
+ // evaluate the line with the opening bracket that matches out closing bracket
+ int reference = indenter.findReferencePosition(c.offset, false, MatchMode.MATCH_BRACE);
+ int indLine = d.getLineOfOffset(reference);
+ if (indLine != -1 && indLine != line) {
+ // take the indent of the found line
+ StringBuilder replaceText = new StringBuilder(getIndentOfLine(d, indLine));
+ // add the rest of the current line including the just added close bracket
+ replaceText.append(d.get(whiteend, c.offset - whiteend));
+ replaceText.append(c.text);
+ // modify document command
+ c.length += c.offset - start;
+ c.offset = start;
+ c.text = replaceText.toString();
+ }
+ }
+ } catch (BadLocationException e) {
+ IDEPlugin.log(e);
+ }
+ }
+
+ /**
+ * Installs a C partitioner with <code>document</code>.
+ *
+ * @param document the document
+ */
+ private static void installPartitioner(Document document) {
+ String[] types= new String[] {
+ IDocument.DEFAULT_CONTENT_TYPE,
+ STPPartitionScanner.STP_COMMENT,
+ STPPartitionScanner.STP_CONDITIONAL,
+ };
+ FastPartitioner partitioner= new FastPartitioner(new STPPartitionScanner(), types);
+ partitioner.connect(document);
+ document.setDocumentPartitioner(STPPartitionScanner.STP_PARTITIONING, partitioner);
+ }
+
+ /**
+ * Installs a C partitioner with <code>document</code>.
+ *
+ * @param document the document
+ */
+ private static void removePartitioner(Document document) {
+ document.setDocumentPartitioner(STPPartitionScanner.STP_PARTITIONING, null);
+ }
+
+ private void smartPaste(IDocument document, DocumentCommand command) {
+ int newOffset= command.offset;
+ int newLength= command.length;
+ String newText= command.text;
+
+ try {
+ STPHeuristicScanner scanner= new STPHeuristicScanner(document);
+ STPIndenter indenter= new STPIndenter(document, scanner, fProject);
+ int offset= newOffset;
+
+ // reference position to get the indent from
+ int refOffset= indenter.findReferencePosition(offset);
+ if (refOffset == STPHeuristicScanner.NOT_FOUND)
+ return;
+ int peerOffset= getPeerPosition(document, command);
+ peerOffset= indenter.findReferencePosition(peerOffset);
+ if (peerOffset == STPHeuristicScanner.NOT_FOUND)
+ return;
+ refOffset= Math.min(refOffset, peerOffset);
+
+ // eat any WS before the insertion to the beginning of the line
+ int firstLine= 1; // don't format the first line per default, as it has other content before it
+ IRegion line= document.getLineInformationOfOffset(offset);
+ String notSelected= document.get(line.getOffset(), offset - line.getOffset());
+ if (notSelected.trim().length() == 0) {
+ newLength += notSelected.length();
+ newOffset= line.getOffset();
+ firstLine= 0;
+ }
+
+ // Prefix: the part we need for formatting but won't paste.
+ // Take up to 100 previous lines to preserve enough context.
+ int firstPrefixLine= Math.max(document.getLineOfOffset(refOffset) - 100, 0);
+ int prefixOffset= document.getLineInformation(firstPrefixLine).getOffset();
+ String prefix= document.get(prefixOffset, newOffset - prefixOffset);
+
+ // Handle the indentation computation inside a temporary document
+ Document temp= new Document(prefix + newText);
+ DocumentRewriteSession session= temp.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
+ scanner= new STPHeuristicScanner(temp);
+ indenter= new STPIndenter(temp, scanner, fProject);
+ installPartitioner(temp);
+
+ // Indent the first and second line
+ // compute the relative indentation difference from the second line
+ // (as the first might be partially selected) and use the value to
+ // indent all other lines.
+ boolean isIndentDetected= false;
+ StringBuilder addition= new StringBuilder();
+ int insertLength= 0;
+ int first= document.computeNumberOfLines(prefix) + firstLine; // don't format first line
+ int lines= temp.getNumberOfLines();
+ boolean changed= false;
+ boolean indentInsideLineComments= true;
+
+ for (int l= first; l < lines; l++) { // we don't change the number of lines while adding indents
+ IRegion r= temp.getLineInformation(l);
+ int lineOffset= r.getOffset();
+ int lineLength= r.getLength();
+
+ if (lineLength == 0) // don't modify empty lines
+ continue;
+
+ if (!isIndentDetected) {
+ // indent the first pasted line
+ String current= IndentUtil.getCurrentIndent(temp, l, indentInsideLineComments);
+ StringBuilder correct= new StringBuilder(IndentUtil.computeIndent(temp, l, indenter, scanner));
+
+ insertLength= subtractIndent(correct, current, addition);
+ // workaround for bug 181139
+ if (/*l != first && */temp.get(lineOffset, lineLength).trim().length() != 0) {
+ isIndentDetected= true;
+ if (insertLength == 0) {
+ // no adjustment needed, bail out
+ if (firstLine == 0) {
+ // but we still need to adjust the first line
+ command.offset= newOffset;
+ command.length= newLength;
+ if (changed)
+ break; // still need to get the leading indent of the first line
+ }
+ return;
+ }
+ removePartitioner(temp);
+ } else {
+ changed= insertLength != 0;
+ }
+ }
+
+ // relatively indent all pasted lines
+ if (insertLength > 0)
+ addIndent(temp, l, addition, indentInsideLineComments);
+ else if (insertLength < 0)
+ cutIndent(temp, l, -insertLength, indentInsideLineComments);
+ }
+
+ temp.stopRewriteSession(session);
+ newText= temp.get(prefix.length(), temp.getLength() - prefix.length());
+
+ command.offset= newOffset;
+ command.length= newLength;
+ command.text= newText;
+ } catch (BadLocationException e) {
+ IDEPlugin.log(e);
+ }
+ }
+ /**
+ * Computes the difference of two indentations and returns the difference in
+ * length of current and correct. If the return value is positive, <code>addition</code>
+ * is initialized with a substring of that length of <code>correct</code>.
+ *
+ * @param correct the correct indentation
+ * @param current the current indentation (migth contain non-whitespace)
+ * @param difference a string buffer - if the return value is positive, it will be cleared and set to the substring of <code>current</code> of that length
+ * @return the difference in lenght of <code>correct</code> and <code>current</code>
+ */
+ private int subtractIndent(CharSequence correct, CharSequence current, StringBuilder difference) {
+ int c1= computeVisualLength(correct);
+ int c2= computeVisualLength(current);
+ int diff= c1 - c2;
+ if (diff <= 0)
+ return diff;
+
+ difference.setLength(0);
+ int len= 0, i= 0;
+ while (len < diff) {
+ char c= correct.charAt(i++);
+ difference.append(c);
+ len += computeVisualLength(c);
+ }
+
+ return diff;
+ }
+
+ /**
+ * Indents line <code>line</code> in <code>document</code> with <code>indent</code>.
+ * Leaves leading comment signs alone.
+ *
+ * @param document the document
+ * @param line the line
+ * @param indent the indentation to insert
+ * @param indentInsideLineComments option whether to indent inside line comments starting at column 0
+ * @throws BadLocationException on concurrent document modification
+ */
+ private static void addIndent(Document document, int line, CharSequence indent, boolean indentInsideLineComments) throws BadLocationException {
+ IRegion region= document.getLineInformation(line);
+ int insert= region.getOffset();
+ int endOffset= region.getOffset() + region.getLength();
+
+ if (indentInsideLineComments) {
+ // go behind line comments
+ while (insert < endOffset - 2 && document.get(insert, 2).equals(LINE_COMMENT))
+ insert += 2;
+ }
+
+ // insert indent
+ document.replace(insert, 0, indent.toString());
+ }
+
+ /**
+ * Cuts the visual equivalent of <code>toDelete</code> characters out of the
+ * indentation of line <code>line</code> in <code>document</code>. Leaves
+ * leading comment signs alone.
+ *
+ * @param document the document
+ * @param line the line
+ * @param toDelete the number of space equivalents to delete.
+ * @param indentInsideLineComments option whether to indent inside line comments starting at column 0
+ * @throws BadLocationException on concurrent document modification
+ */
+ private void cutIndent(Document document, int line, int toDelete, boolean indentInsideLineComments) throws BadLocationException {
+ IRegion region= document.getLineInformation(line);
+ int from= region.getOffset();
+ int endOffset= region.getOffset() + region.getLength();
+
+ if (indentInsideLineComments) {
+ // go behind line comments
+ while (from < endOffset - 2 && document.get(from, 2).equals(LINE_COMMENT))
+ from += 2;
+ }
+
+ int to= from;
+ while (toDelete > 0 && to < endOffset) {
+ char ch= document.getChar(to);
+ if (!Character.isWhitespace(ch))
+ break;
+ toDelete -= computeVisualLength(ch);
+ if (toDelete >= 0)
+ to++;
+ else
+ break;
+ }
+
+ document.replace(from, to - from, null);
+ }
+
+ /**
+ * Returns the visual length of a given <code>CharSequence</code> taking into
+ * account the visual tabulator length.
+ *
+ * @param seq the string to measure
+ * @return the visual length of <code>seq</code>
+ */
+ private int computeVisualLength(CharSequence seq) {
+ int size= 0;
+ int tablen= getVisualTabLengthPreference();
+
+ for (int i= 0; i < seq.length(); i++) {
+ char ch= seq.charAt(i);
+ if (ch == '\t') {
+ if (tablen != 0)
+ size += tablen - size % tablen;
+ // else: size stays the same
+ } else {
+ size++;
+ }
+ }
+ return size;
+ }
+
+ /**
+ * Returns the visual length of a given character taking into
+ * account the visual tabulator length.
+ *
+ * @param ch the character to measure
+ * @return the visual length of <code>ch</code>
+ */
+ private int computeVisualLength(char ch) {
+ if (ch == '\t')
+ return getVisualTabLengthPreference();
+ return 1;
+ }
+
+ /**
+ * The preference setting for the visual tabulator display.
+ *
+ * @return the number of spaces displayed for a tabulator in the editor
+ */
+ private int getVisualTabLengthPreference() {
+ return CodeFormatterUtil.getTabWidth();
+ }
+
+ private int getPeerPosition(IDocument document, DocumentCommand command) {
+ if (document.getLength() == 0)
+ return 0;
+ /*
+ * Search for scope closers in the pasted text and find their opening peers
+ * in the document.
+ */
+ Document pasted= new Document(command.text);
+ installPartitioner(pasted);
+ int firstPeer= command.offset;
+
+ STPHeuristicScanner pScanner= new STPHeuristicScanner(pasted);
+ STPHeuristicScanner dScanner= new STPHeuristicScanner(document);
+
+ // add scope relevant after context to peer search
+ int afterToken= dScanner.nextToken(command.offset + command.length, STPHeuristicScanner.UNBOUND);
+ try {
+ switch (afterToken) {
+ case STPSymbols.TokenRBRACE:
+ pasted.replace(pasted.getLength(), 0, "}"); //$NON-NLS-1$
+ break;
+ case STPSymbols.TokenRPAREN:
+ pasted.replace(pasted.getLength(), 0, ")"); //$NON-NLS-1$
+ break;
+ case STPSymbols.TokenRBRACKET:
+ pasted.replace(pasted.getLength(), 0, "]"); //$NON-NLS-1$
+ break;
+ }
+ } catch (BadLocationException e) {
+ // cannot happen
+ Assert.isTrue(false);
+ }
+
+ int pPos= 0; // paste text position (increasing from 0)
+ int dPos= Math.max(0, command.offset - 1); // document position (decreasing from paste offset)
+ while (true) {
+ int token= pScanner.nextToken(pPos, STPHeuristicScanner.UNBOUND);
+ pPos= pScanner.getPosition();
+ switch (token) {
+ case STPSymbols.TokenLBRACE:
+ case STPSymbols.TokenLBRACKET:
+ case STPSymbols.TokenLPAREN:
+ pPos= skipScope(pScanner, pPos, token);
+ if (pPos == STPHeuristicScanner.NOT_FOUND)
+ return firstPeer;
+ break; // closed scope -> keep searching
+ case STPSymbols.TokenRBRACE:
+ int peer= dScanner.findOpeningPeer(dPos, '{', '}');
+ dPos= peer - 1;
+ if (peer == STPHeuristicScanner.NOT_FOUND)
+ return firstPeer;
+ firstPeer= peer;
+ break; // keep searching
+ case STPSymbols.TokenRBRACKET:
+ peer= dScanner.findOpeningPeer(dPos, '[', ']');
+ dPos= peer - 1;
+ if (peer == STPHeuristicScanner.NOT_FOUND)
+ return firstPeer;
+ firstPeer= peer;
+ break; // keep searching
+ case STPSymbols.TokenRPAREN:
+ peer= dScanner.findOpeningPeer(dPos, '(', ')');
+ dPos= peer - 1;
+ if (peer == STPHeuristicScanner.NOT_FOUND)
+ return firstPeer;
+ firstPeer= peer;
+ break; // keep searching
+
+ case STPSymbols.TokenCASE:
+ case STPSymbols.TokenDEFAULT:
+ {
+ STPIndenter indenter= new STPIndenter(document, dScanner, fProject);
+ peer= indenter.findReferencePosition(dPos, false, MatchMode.MATCH_CASE);
+ if (peer == STPHeuristicScanner.NOT_FOUND)
+ return firstPeer;
+ firstPeer= peer;
+ }
+ break; // keep searching
+
+ case STPSymbols.TokenPUBLIC:
+ case STPSymbols.TokenPROTECTED:
+ case STPSymbols.TokenPRIVATE:
+ {
+ STPIndenter indenter= new STPIndenter(document, dScanner, fProject);
+ peer= indenter.findReferencePosition(dPos, false, MatchMode.MATCH_ACCESS_SPECIFIER);
+ if (peer == STPHeuristicScanner.NOT_FOUND)
+ return firstPeer;
+ firstPeer= peer;
+ }
+ break; // keep searching
+
+ case STPSymbols.TokenEOF:
+ return firstPeer;
+ default:
+ // keep searching
+ }
+ }
}
/**
* Skips the scope opened by <code>token</code> in <code>document</code>,
@@ -1047,39 +1047,39 @@ public class STPAutoEditStrategy extends
* @return the position after the scope
*/
private static int skipScope(STPHeuristicScanner scanner, int pos, int token) {
- int openToken= token;
- int closeToken;
- switch (token) {
- case STPSymbols.TokenLPAREN:
- closeToken= STPSymbols.TokenRPAREN;
- break;
- case STPSymbols.TokenLBRACKET:
- closeToken= STPSymbols.TokenRBRACKET;
- break;
- case STPSymbols.TokenLBRACE:
- closeToken= STPSymbols.TokenRBRACE;
- break;
- default:
- Assert.isTrue(false);
- return -1; // dummy
- }
-
- int depth= 1;
- int p= pos;
-
- while (true) {
- int tok= scanner.nextToken(p, STPHeuristicScanner.UNBOUND);
- p= scanner.getPosition();
-
- if (tok == openToken) {
- depth++;
- } else if (tok == closeToken) {
- depth--;
- if (depth == 0)
- return p + 1;
- } else if (tok == STPSymbols.TokenEOF) {
- return STPHeuristicScanner.NOT_FOUND;
- }
- }
+ int openToken= token;
+ int closeToken;
+ switch (token) {
+ case STPSymbols.TokenLPAREN:
+ closeToken= STPSymbols.TokenRPAREN;
+ break;
+ case STPSymbols.TokenLBRACKET:
+ closeToken= STPSymbols.TokenRBRACKET;
+ break;
+ case STPSymbols.TokenLBRACE:
+ closeToken= STPSymbols.TokenRBRACE;
+ break;
+ default:
+ Assert.isTrue(false);
+ return -1; // dummy
+ }
+
+ int depth= 1;
+ int p= pos;
+
+ while (true) {
+ int tok= scanner.nextToken(p, STPHeuristicScanner.UNBOUND);
+ p= scanner.getPosition();
+
+ if (tok == openToken) {
+ depth++;
+ } else if (tok == closeToken) {
+ depth--;
+ if (depth == 0)
+ return p + 1;
+ } else if (tok == STPSymbols.TokenEOF) {
+ return STPHeuristicScanner.NOT_FOUND;
+ }
+ }
}
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPColorConstants.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPColorConstants.java
index 97ca5e873d..e5287a63fd 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPColorConstants.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPColorConstants.java
@@ -1,23 +1,23 @@
/* Copyright (c) 2008 Phil Muldoon <pkmuldoon@picobot.org>.
- *
+ *
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * Phil Muldoon <pkmuldoon@picobot.org> - initial API and implementation.
+ * Phil Muldoon <pkmuldoon@picobot.org> - initial API and implementation.
*******************************************************************************/
package org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp;
import org.eclipse.swt.graphics.RGB;
public interface STPColorConstants {
- RGB KEYWORD = new RGB(127, 0, 85);
- RGB COMMENT = new RGB(63, 127, 95);
- RGB STP_STRING = new RGB(0, 0, 255);
- RGB DEFAULT = new RGB(0, 0, 0);
- RGB EMBEDDED = new RGB (0, 64, 64);
+ RGB KEYWORD = new RGB(127, 0, 85);
+ RGB COMMENT = new RGB(63, 127, 95);
+ RGB STP_STRING = new RGB(0, 0, 255);
+ RGB DEFAULT = new RGB(0, 0, 0);
+ RGB EMBEDDED = new RGB (0, 64, 64);
RGB EMBEDDEDC = new RGB (0, 64, 64);
RGB TYPE= new RGB(0, 0, 128);
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPCompletionProcessor.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPCompletionProcessor.java
index 3d9791b27a..feb2a11635 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPCompletionProcessor.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPCompletionProcessor.java
@@ -32,460 +32,460 @@ import org.eclipse.linuxtools.internal.systemtap.ui.ide.structures.TapsetLibrary
public class STPCompletionProcessor implements IContentAssistProcessor, ITextHover {
- private final IContextInformation[] NO_CONTEXTS = new IContextInformation[0];
- private final char[] PROPOSAL_ACTIVATION_CHARS = new char[] { '.' };
- private ICompletionProposal[] NO_COMPLETIONS = new ICompletionProposal[0];
-
- private static final String GLOBAL_KEYWORD = "global "; //$NON-NLS-1$
- private static final String PROBE_KEYWORD = "probe "; //$NON-NLS-1$
- private static final String FUNCTION_KEYWORD = "function "; //$NON-NLS-1$
-
- private static final String[][] GLOBAL_KEYWORDS = {
- { GLOBAL_KEYWORD, Messages.STPCompletionProcessor_global },
- { PROBE_KEYWORD, Messages.STPCompletionProcessor_probe },
- { FUNCTION_KEYWORD, Messages.STPCompletionProcessor_function } };
-
- private STPMetadataSingleton stpMetadataSingleton;
-
- private static class Token implements IRegion {
- String tokenString;
- int offset;
-
- public Token(String string, int n) {
- this.tokenString = string;
- this.offset = n;
- }
-
- @Override
- public int getLength() {
- return this.tokenString.length();
- }
-
- @Override
- public int getOffset() {
- return this.offset;
- }
- }
-
- public STPCompletionProcessor() {
- this.stpMetadataSingleton = STPMetadataSingleton.getInstance();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
- */
- @Override
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
- int offset) {
- return computeCompletionProposals(viewer.getDocument(), offset);
- }
-
- public ICompletionProposal[] computeCompletionProposals(IDocument document, int offset) {
-
- ITypedRegion partition = null;
- boolean useGlobal = false;
-
- try {
- partition =
- ((IDocumentExtension3) document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING, offset, false);
- if (partition.getOffset() == offset) {
- if (partition.getType() != IDocument.DEFAULT_CONTENT_TYPE && partition.getType() != STPProbeScanner.STP_PROBE) {
- if (offset > 0) {
- ITypedRegion prevPartition =
- ((IDocumentExtension3) document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING, offset - 1, false);
- useGlobal = prevPartition.getType() == IDocument.DEFAULT_CONTENT_TYPE;
- } else {
- useGlobal = true;
- }
- }
- }
- } catch (BadLocationException e1) {
- return NO_COMPLETIONS;
- } catch (BadPartitioningException e) {
- return NO_COMPLETIONS;
- }
-
- String prefix = ""; //$NON-NLS-1$
- String prePrefix = ""; //$NON-NLS-1$
-
- // Get completion hint from document
- try {
- prefix = getPrefix(document, offset);
- Token previousToken = getPrecedingToken(document, offset - prefix.length() - 1);
-
- while (previousToken.tokenString.equals("=") || //$NON-NLS-1$
- previousToken.tokenString.equals(",") ) { //$NON-NLS-1$
- previousToken = getPrecedingToken(document, previousToken.offset - 1);
- previousToken = getPrecedingToken(document, previousToken.offset - 1);
- }
-
- prePrefix = previousToken.tokenString;
-
- } catch (BadLocationException e) {
- return NO_COMPLETIONS;
- }
-
- if (prePrefix.startsWith("probe")) { //$NON-NLS-1$
- return getProbeCompletionList(prefix, offset);
- }
-
- // If inside a probe return probe variable completions and functions
- // which can be called.
- if (partition.getType() == STPProbeScanner.STP_PROBE) {
- ICompletionProposal[] variableCompletions = getProbeVariableCompletions(document, offset, prefix);
- ICompletionProposal[] functionCompletions = getFunctionCompletions(offset, prefix);
-
- ArrayList<ICompletionProposal> completions = new ArrayList<>(
- variableCompletions.length + functionCompletions.length);
- completions.addAll(Arrays.asList(variableCompletions));
- completions.addAll(Arrays.asList(functionCompletions));
-
- return completions.toArray(new ICompletionProposal[0]);
- } else if (partition.getType() == IDocument.DEFAULT_CONTENT_TYPE || useGlobal) {
- // In the global scope return global keyword completion.
- return getGlobalKeywordCompletion(prefix, offset);
- }
-
- return NO_COMPLETIONS;
- }
-
- private ICompletionProposal[] getFunctionCompletions(int offset,
- String prefix) {
- String[] completionData = stpMetadataSingleton.getFunctionCompletions(prefix);
- ICompletionProposal[] result = new ICompletionProposal[completionData.length];
- int prefixLength = prefix.length();
- for (int i = 0; i < completionData.length; i++) {
- result[i] = new CompletionProposal(
- completionData[i].substring(prefixLength) + "()", //$NON-NLS-1$
- offset,
- 0,
- completionData[i].length() - prefixLength + 1,
- null,
- completionData[i] + " - function", //$NON-NLS-1$
- null,
- TapsetLibrary.getAndCacheDocumentation("function::" + completionData[i])); //$NON-NLS-1$
- }
-
- return result;
- }
-
- private ICompletionProposal[] getProbeVariableCompletions(IDocument document, int offset, String prefix) {
- try {
- String probe;
- probe = getProbe(document, offset);
- String[] completionData = stpMetadataSingleton
- .getProbeVariableCompletions(probe, prefix);
- ICompletionProposal[] result = new ICompletionProposal[completionData.length];
-
- int prefixLength = prefix.length();
- for (int i = 0; i < completionData.length; i++) {
- int endIndex = completionData[i].indexOf(':');
- String variableName = completionData[i].substring(0, endIndex);
- result[i] = new CompletionProposal(completionData[i].substring(
- prefixLength, endIndex),
- offset,
- 0,
- endIndex - prefixLength,
- null,
- completionData[i] + " - variable", //$NON-NLS-1$
- null,
- TapsetLibrary.getAndCacheDocumentation("probe::" + probe + "::" + variableName)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return result;
- } catch (BadLocationException e) {
- return NO_COMPLETIONS;
- } catch (BadPartitioningException e) {
- return NO_COMPLETIONS;
- }
- }
-
- /**
- * Returns the full name of the probe surrounding the given
- * offset. This function assumes that the given offset is inside
- * of a {@link STPPartitionScanner#STP_PROBE} section.
- * @param document
- * @param offset
- * @return the probe name
- * @throws BadLocationException
- * @throws BadPartitioningException
- */
- private String getProbe(IDocument document, int offset) throws BadLocationException, BadPartitioningException {
- String probePoint = null;
-
- ITypedRegion partition
- = ((IDocumentExtension3)document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING,
- offset, false);
- String probe = document.get(partition.getOffset(), partition.getLength());
-
- // make sure that we are inside a probe
- if (probe.startsWith(PROBE_KEYWORD)) {
- probePoint = probe.substring(PROBE_KEYWORD.length(), probe.indexOf('{'));
- probePoint = probePoint.trim();
- }
-
- return probePoint;
- }
-
- private ICompletionProposal[] getProbeCompletionList(String prefix, int offset) {
- prefix = canonicalizePrefix(prefix);
- String[] completionData = stpMetadataSingleton.getProbeCompletions(prefix);
-
- ICompletionProposal[] result = new ICompletionProposal[completionData.length];
- for (int i = 0; i < completionData.length; i++) {
- result[i] = new CompletionProposal(
- completionData[i].substring(prefix.length()),
- offset,
- 0,
- completionData[i].length() - prefix.length(),
- null,
- completionData[i],
- null,
- TapsetLibrary.getAndCacheDocumentation("probe::" + completionData[i])); //$NON-NLS-1$
- }
- return result;
-
- }
-
- /**
- * Returns a standardized version of the given prefix so that completion matching
- * can be performed.
- * For example for process("/some/long/path") this returns process(string);
- * @param prefix
- * @return
- */
- private String canonicalizePrefix(String prefix) {
-
- if (prefix.isEmpty()) {
- return ""; //$NON-NLS-1$
- }
- prefix = prefix.replaceAll("(?s)\\(\\s*\".*\"\\s*\\)", "(string)"); //$NON-NLS-1$ //$NON-NLS-2$
- prefix = prefix.replaceAll("(?s)\\(\\s*\\d*\\s*\\)", "(number)"); //$NON-NLS-1$ //$NON-NLS-2$
- return prefix;
- }
-
- private ICompletionProposal[] getGlobalKeywordCompletion(String prefix, int offset) {
-
- ArrayList<ICompletionProposal> completions = new ArrayList<>();
- int prefixLength = prefix.length();
- for (String[] keyword : GLOBAL_KEYWORDS) {
- if (keyword[0].startsWith(prefix)) {
- CompletionProposal proposal = new CompletionProposal(
- keyword[0].substring(prefixLength),
- offset,
- 0,
- keyword[0].length() - prefixLength,
- null,
- keyword[0],
- new ContextInformation("contextDisplayString", "informationDisplayString"), //$NON-NLS-1$ //$NON-NLS-2$
- keyword[1]);
- completions.add(proposal);
- }
- }
- return completions.toArray(new ICompletionProposal[0]);
- }
-
- /**
- * Returns the token preceding the current completion position.
- * @param doc The document for the which the completion is requested.
- * @param prefix The prefix for which the user has requested completion.
- * @param offset Current offset in the document
- * @return The preceding token.
- * @throws BadLocationException
- */
- private Token getPrecedingToken(IDocument doc, int offset) throws BadLocationException {
- // Skip trailing space
- int n = offset;
- while (n >= 0 && Character.isSpaceChar(doc.getChar(n))) {
- n--;
- }
-
- char c = doc.getChar(n);
- if (isTokenDelimiter(c)) {
- return new Token(Character.toString(c), n);
- }
-
- int end = n;
- while (n >= 0 && !isTokenDelimiter((doc.getChar(n)))) {
- n--;
- }
-
- return new Token(doc.get(n+1, end-n), n+1);
- }
-
- private Token getCurrentToken(IDocument doc, int offset) throws BadLocationException {
- char c = doc.getChar(offset);
-
- if (isDelimiter(c)) {
- return new Token(Character.toString(c), offset);
- }
-
- int start = offset;
- while (start >= 0 && !isDelimiter((doc.getChar(start)))) {
- start--;
- }
-
- int end = offset;
- while (end < doc.getLength() && !isDelimiter((doc.getChar(end)))) {
- end++;
- }
-
- start++;
- return new Token(doc.get(start, end-start), start);
- }
-
- /**
- *
- * Return the word the user wants to submit for completion proposals.
- *
- * @param doc - document to insert completion.
- * @param offset - offset of where completion hint was first generated.
- * @return - word to generate completion proposals.
- *
- * @throws BadLocationException
- */
- private String getPrefix(IDocument doc, int offset)
- throws BadLocationException {
-
- for (int n = offset - 1; n >= 0; n--) {
- char c = doc.getChar(n);
- if (isTokenDelimiter(c)) {
- String word = doc.get(n + 1, offset - n - 1);
- return word;
- }
- }
- return ""; //$NON-NLS-1$
- }
-
- private boolean isTokenDelimiter(char c) {
- if (Character.isWhitespace(c)) {
- return true;
- }
-
- switch (c) {
- case '\n':
- case '\0':
- case ',':
- case '{':
- case '}':
- case ']':
- case '[':
- return true;
- }
- return false;
- }
-
- private boolean isDelimiter (char c) {
-
- if (isTokenDelimiter(c)) {
- return true;
- }
-
- switch (c) {
- case '(':
- case ')':
- return true;
- }
- return false;
- }
-
- public void waitForInitialization() {
- this.stpMetadataSingleton.waitForInitialization();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
- */
- @Override
- public IContextInformation[] computeContextInformation(ITextViewer viewer,
- int offset) {
- return NO_CONTEXTS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
- */
- @Override
- public char[] getCompletionProposalAutoActivationCharacters() {
- return PROPOSAL_ACTIVATION_CHARS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
- */
- @Override
- public char[] getContextInformationAutoActivationCharacters() {
- return PROPOSAL_ACTIVATION_CHARS;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
- */
- @Override
- public IContextInformationValidator getContextInformationValidator() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
- */
- @Override
- public String getErrorMessage() {
- // TODO: When does this trigger?
- return "Error."; //$NON-NLS-1$
- }
-
- @Override
- public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
- String documentation = null;
- try {
- String keyword = textViewer.getDocument().get(hoverRegion.getOffset(), hoverRegion.getLength());
-
- documentation = TapsetLibrary.getDocumentation("function::" + keyword); //$NON-NLS-1$
- if (!documentation.startsWith("No manual entry for")) { //$NON-NLS-1$
- return documentation;
- }
-
- documentation = TapsetLibrary.getDocumentation("probe::" + keyword); //$NON-NLS-1$
- if (!documentation.startsWith("No manual entry for")) { //$NON-NLS-1$
- return documentation;
- }
-
- documentation = TapsetLibrary.getDocumentation("tapset::" + keyword); //$NON-NLS-1$
- if (!documentation.startsWith("No manual entry for")) { //$NON-NLS-1$
- return documentation;
- }
-
- if (keyword.indexOf('.') > 0) {
- keyword = keyword.split("\\.")[0]; //$NON-NLS-1$
- documentation = TapsetLibrary.getDocumentation("tapset::" + keyword); //$NON-NLS-1$
- }
-
- IDocument document = textViewer.getDocument();
- ITypedRegion partition =
- ((IDocumentExtension3)document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING,
- hoverRegion.getOffset(), false);
- if (partition.getType() == STPProbeScanner.STP_PROBE) {
- String probe = getProbe(textViewer.getDocument(), hoverRegion.getOffset());
- documentation = TapsetLibrary.getDocumentation("probe::" + probe + "::"+ keyword); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- } catch (BadLocationException e) {
- // Bad hover location; just ignore it.
- } catch (BadPartitioningException e) {
- // Bad hover scenario, just ignore it.
- }
-
- return documentation;
- }
-
- @Override
- public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
- try {
- return getCurrentToken(textViewer.getDocument(), offset);
- } catch (BadLocationException e) {
- // Bad hover location; just ignore it.
- }
-
- return null;
- }
+ private final IContextInformation[] NO_CONTEXTS = new IContextInformation[0];
+ private final char[] PROPOSAL_ACTIVATION_CHARS = new char[] { '.' };
+ private ICompletionProposal[] NO_COMPLETIONS = new ICompletionProposal[0];
+
+ private static final String GLOBAL_KEYWORD = "global "; //$NON-NLS-1$
+ private static final String PROBE_KEYWORD = "probe "; //$NON-NLS-1$
+ private static final String FUNCTION_KEYWORD = "function "; //$NON-NLS-1$
+
+ private static final String[][] GLOBAL_KEYWORDS = {
+ { GLOBAL_KEYWORD, Messages.STPCompletionProcessor_global },
+ { PROBE_KEYWORD, Messages.STPCompletionProcessor_probe },
+ { FUNCTION_KEYWORD, Messages.STPCompletionProcessor_function } };
+
+ private STPMetadataSingleton stpMetadataSingleton;
+
+ private static class Token implements IRegion {
+ String tokenString;
+ int offset;
+
+ public Token(String string, int n) {
+ this.tokenString = string;
+ this.offset = n;
+ }
+
+ @Override
+ public int getLength() {
+ return this.tokenString.length();
+ }
+
+ @Override
+ public int getOffset() {
+ return this.offset;
+ }
+ }
+
+ public STPCompletionProcessor() {
+ this.stpMetadataSingleton = STPMetadataSingleton.getInstance();
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
+ */
+ @Override
+ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
+ int offset) {
+ return computeCompletionProposals(viewer.getDocument(), offset);
+ }
+
+ public ICompletionProposal[] computeCompletionProposals(IDocument document, int offset) {
+
+ ITypedRegion partition = null;
+ boolean useGlobal = false;
+
+ try {
+ partition =
+ ((IDocumentExtension3) document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING, offset, false);
+ if (partition.getOffset() == offset) {
+ if (partition.getType() != IDocument.DEFAULT_CONTENT_TYPE && partition.getType() != STPProbeScanner.STP_PROBE) {
+ if (offset > 0) {
+ ITypedRegion prevPartition =
+ ((IDocumentExtension3) document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING, offset - 1, false);
+ useGlobal = prevPartition.getType() == IDocument.DEFAULT_CONTENT_TYPE;
+ } else {
+ useGlobal = true;
+ }
+ }
+ }
+ } catch (BadLocationException e1) {
+ return NO_COMPLETIONS;
+ } catch (BadPartitioningException e) {
+ return NO_COMPLETIONS;
+ }
+
+ String prefix = ""; //$NON-NLS-1$
+ String prePrefix = ""; //$NON-NLS-1$
+
+ // Get completion hint from document
+ try {
+ prefix = getPrefix(document, offset);
+ Token previousToken = getPrecedingToken(document, offset - prefix.length() - 1);
+
+ while (previousToken.tokenString.equals("=") || //$NON-NLS-1$
+ previousToken.tokenString.equals(",") ) { //$NON-NLS-1$
+ previousToken = getPrecedingToken(document, previousToken.offset - 1);
+ previousToken = getPrecedingToken(document, previousToken.offset - 1);
+ }
+
+ prePrefix = previousToken.tokenString;
+
+ } catch (BadLocationException e) {
+ return NO_COMPLETIONS;
+ }
+
+ if (prePrefix.startsWith("probe")) { //$NON-NLS-1$
+ return getProbeCompletionList(prefix, offset);
+ }
+
+ // If inside a probe return probe variable completions and functions
+ // which can be called.
+ if (partition.getType() == STPProbeScanner.STP_PROBE) {
+ ICompletionProposal[] variableCompletions = getProbeVariableCompletions(document, offset, prefix);
+ ICompletionProposal[] functionCompletions = getFunctionCompletions(offset, prefix);
+
+ ArrayList<ICompletionProposal> completions = new ArrayList<>(
+ variableCompletions.length + functionCompletions.length);
+ completions.addAll(Arrays.asList(variableCompletions));
+ completions.addAll(Arrays.asList(functionCompletions));
+
+ return completions.toArray(new ICompletionProposal[0]);
+ } else if (partition.getType() == IDocument.DEFAULT_CONTENT_TYPE || useGlobal) {
+ // In the global scope return global keyword completion.
+ return getGlobalKeywordCompletion(prefix, offset);
+ }
+
+ return NO_COMPLETIONS;
+ }
+
+ private ICompletionProposal[] getFunctionCompletions(int offset,
+ String prefix) {
+ String[] completionData = stpMetadataSingleton.getFunctionCompletions(prefix);
+ ICompletionProposal[] result = new ICompletionProposal[completionData.length];
+ int prefixLength = prefix.length();
+ for (int i = 0; i < completionData.length; i++) {
+ result[i] = new CompletionProposal(
+ completionData[i].substring(prefixLength) + "()", //$NON-NLS-1$
+ offset,
+ 0,
+ completionData[i].length() - prefixLength + 1,
+ null,
+ completionData[i] + " - function", //$NON-NLS-1$
+ null,
+ TapsetLibrary.getAndCacheDocumentation("function::" + completionData[i])); //$NON-NLS-1$
+ }
+
+ return result;
+ }
+
+ private ICompletionProposal[] getProbeVariableCompletions(IDocument document, int offset, String prefix) {
+ try {
+ String probe;
+ probe = getProbe(document, offset);
+ String[] completionData = stpMetadataSingleton
+ .getProbeVariableCompletions(probe, prefix);
+ ICompletionProposal[] result = new ICompletionProposal[completionData.length];
+
+ int prefixLength = prefix.length();
+ for (int i = 0; i < completionData.length; i++) {
+ int endIndex = completionData[i].indexOf(':');
+ String variableName = completionData[i].substring(0, endIndex);
+ result[i] = new CompletionProposal(completionData[i].substring(
+ prefixLength, endIndex),
+ offset,
+ 0,
+ endIndex - prefixLength,
+ null,
+ completionData[i] + " - variable", //$NON-NLS-1$
+ null,
+ TapsetLibrary.getAndCacheDocumentation("probe::" + probe + "::" + variableName)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return result;
+ } catch (BadLocationException e) {
+ return NO_COMPLETIONS;
+ } catch (BadPartitioningException e) {
+ return NO_COMPLETIONS;
+ }
+ }
+
+ /**
+ * Returns the full name of the probe surrounding the given
+ * offset. This function assumes that the given offset is inside
+ * of a {@link STPPartitionScanner#STP_PROBE} section.
+ * @param document
+ * @param offset
+ * @return the probe name
+ * @throws BadLocationException
+ * @throws BadPartitioningException
+ */
+ private String getProbe(IDocument document, int offset) throws BadLocationException, BadPartitioningException {
+ String probePoint = null;
+
+ ITypedRegion partition
+ = ((IDocumentExtension3)document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING,
+ offset, false);
+ String probe = document.get(partition.getOffset(), partition.getLength());
+
+ // make sure that we are inside a probe
+ if (probe.startsWith(PROBE_KEYWORD)) {
+ probePoint = probe.substring(PROBE_KEYWORD.length(), probe.indexOf('{'));
+ probePoint = probePoint.trim();
+ }
+
+ return probePoint;
+ }
+
+ private ICompletionProposal[] getProbeCompletionList(String prefix, int offset) {
+ prefix = canonicalizePrefix(prefix);
+ String[] completionData = stpMetadataSingleton.getProbeCompletions(prefix);
+
+ ICompletionProposal[] result = new ICompletionProposal[completionData.length];
+ for (int i = 0; i < completionData.length; i++) {
+ result[i] = new CompletionProposal(
+ completionData[i].substring(prefix.length()),
+ offset,
+ 0,
+ completionData[i].length() - prefix.length(),
+ null,
+ completionData[i],
+ null,
+ TapsetLibrary.getAndCacheDocumentation("probe::" + completionData[i])); //$NON-NLS-1$
+ }
+ return result;
+
+ }
+
+ /**
+ * Returns a standardized version of the given prefix so that completion matching
+ * can be performed.
+ * For example for process("/some/long/path") this returns process(string);
+ * @param prefix
+ * @return
+ */
+ private String canonicalizePrefix(String prefix) {
+
+ if (prefix.isEmpty()) {
+ return ""; //$NON-NLS-1$
+ }
+ prefix = prefix.replaceAll("(?s)\\(\\s*\".*\"\\s*\\)", "(string)"); //$NON-NLS-1$ //$NON-NLS-2$
+ prefix = prefix.replaceAll("(?s)\\(\\s*\\d*\\s*\\)", "(number)"); //$NON-NLS-1$ //$NON-NLS-2$
+ return prefix;
+ }
+
+ private ICompletionProposal[] getGlobalKeywordCompletion(String prefix, int offset) {
+
+ ArrayList<ICompletionProposal> completions = new ArrayList<>();
+ int prefixLength = prefix.length();
+ for (String[] keyword : GLOBAL_KEYWORDS) {
+ if (keyword[0].startsWith(prefix)) {
+ CompletionProposal proposal = new CompletionProposal(
+ keyword[0].substring(prefixLength),
+ offset,
+ 0,
+ keyword[0].length() - prefixLength,
+ null,
+ keyword[0],
+ new ContextInformation("contextDisplayString", "informationDisplayString"), //$NON-NLS-1$ //$NON-NLS-2$
+ keyword[1]);
+ completions.add(proposal);
+ }
+ }
+ return completions.toArray(new ICompletionProposal[0]);
+ }
+
+ /**
+ * Returns the token preceding the current completion position.
+ * @param doc The document for the which the completion is requested.
+ * @param prefix The prefix for which the user has requested completion.
+ * @param offset Current offset in the document
+ * @return The preceding token.
+ * @throws BadLocationException
+ */
+ private Token getPrecedingToken(IDocument doc, int offset) throws BadLocationException {
+ // Skip trailing space
+ int n = offset;
+ while (n >= 0 && Character.isSpaceChar(doc.getChar(n))) {
+ n--;
+ }
+
+ char c = doc.getChar(n);
+ if (isTokenDelimiter(c)) {
+ return new Token(Character.toString(c), n);
+ }
+
+ int end = n;
+ while (n >= 0 && !isTokenDelimiter((doc.getChar(n)))) {
+ n--;
+ }
+
+ return new Token(doc.get(n+1, end-n), n+1);
+ }
+
+ private Token getCurrentToken(IDocument doc, int offset) throws BadLocationException {
+ char c = doc.getChar(offset);
+
+ if (isDelimiter(c)) {
+ return new Token(Character.toString(c), offset);
+ }
+
+ int start = offset;
+ while (start >= 0 && !isDelimiter((doc.getChar(start)))) {
+ start--;
+ }
+
+ int end = offset;
+ while (end < doc.getLength() && !isDelimiter((doc.getChar(end)))) {
+ end++;
+ }
+
+ start++;
+ return new Token(doc.get(start, end-start), start);
+ }
+
+ /**
+ *
+ * Return the word the user wants to submit for completion proposals.
+ *
+ * @param doc - document to insert completion.
+ * @param offset - offset of where completion hint was first generated.
+ * @return - word to generate completion proposals.
+ *
+ * @throws BadLocationException
+ */
+ private String getPrefix(IDocument doc, int offset)
+ throws BadLocationException {
+
+ for (int n = offset - 1; n >= 0; n--) {
+ char c = doc.getChar(n);
+ if (isTokenDelimiter(c)) {
+ String word = doc.get(n + 1, offset - n - 1);
+ return word;
+ }
+ }
+ return ""; //$NON-NLS-1$
+ }
+
+ private boolean isTokenDelimiter(char c) {
+ if (Character.isWhitespace(c)) {
+ return true;
+ }
+
+ switch (c) {
+ case '\n':
+ case '\0':
+ case ',':
+ case '{':
+ case '}':
+ case ']':
+ case '[':
+ return true;
+ }
+ return false;
+ }
+
+ private boolean isDelimiter (char c) {
+
+ if (isTokenDelimiter(c)) {
+ return true;
+ }
+
+ switch (c) {
+ case '(':
+ case ')':
+ return true;
+ }
+ return false;
+ }
+
+ public void waitForInitialization() {
+ this.stpMetadataSingleton.waitForInitialization();
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
+ */
+ @Override
+ public IContextInformation[] computeContextInformation(ITextViewer viewer,
+ int offset) {
+ return NO_CONTEXTS;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
+ */
+ @Override
+ public char[] getCompletionProposalAutoActivationCharacters() {
+ return PROPOSAL_ACTIVATION_CHARS;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
+ */
+ @Override
+ public char[] getContextInformationAutoActivationCharacters() {
+ return PROPOSAL_ACTIVATION_CHARS;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
+ */
+ @Override
+ public IContextInformationValidator getContextInformationValidator() {
+ return null;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
+ */
+ @Override
+ public String getErrorMessage() {
+ // TODO: When does this trigger?
+ return "Error."; //$NON-NLS-1$
+ }
+
+ @Override
+ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
+ String documentation = null;
+ try {
+ String keyword = textViewer.getDocument().get(hoverRegion.getOffset(), hoverRegion.getLength());
+
+ documentation = TapsetLibrary.getDocumentation("function::" + keyword); //$NON-NLS-1$
+ if (!documentation.startsWith("No manual entry for")) { //$NON-NLS-1$
+ return documentation;
+ }
+
+ documentation = TapsetLibrary.getDocumentation("probe::" + keyword); //$NON-NLS-1$
+ if (!documentation.startsWith("No manual entry for")) { //$NON-NLS-1$
+ return documentation;
+ }
+
+ documentation = TapsetLibrary.getDocumentation("tapset::" + keyword); //$NON-NLS-1$
+ if (!documentation.startsWith("No manual entry for")) { //$NON-NLS-1$
+ return documentation;
+ }
+
+ if (keyword.indexOf('.') > 0) {
+ keyword = keyword.split("\\.")[0]; //$NON-NLS-1$
+ documentation = TapsetLibrary.getDocumentation("tapset::" + keyword); //$NON-NLS-1$
+ }
+
+ IDocument document = textViewer.getDocument();
+ ITypedRegion partition =
+ ((IDocumentExtension3)document).getPartition(STPProbeScanner.STP_PROBE_PARTITIONING,
+ hoverRegion.getOffset(), false);
+ if (partition.getType() == STPProbeScanner.STP_PROBE) {
+ String probe = getProbe(textViewer.getDocument(), hoverRegion.getOffset());
+ documentation = TapsetLibrary.getDocumentation("probe::" + probe + "::"+ keyword); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ } catch (BadLocationException e) {
+ // Bad hover location; just ignore it.
+ } catch (BadPartitioningException e) {
+ // Bad hover scenario, just ignore it.
+ }
+
+ return documentation;
+ }
+
+ @Override
+ public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
+ try {
+ return getCurrentToken(textViewer.getDocument(), offset);
+ } catch (BadLocationException e) {
+ // Bad hover location; just ignore it.
+ }
+
+ return null;
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPConfiguration.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPConfiguration.java
index 7cd71d53f0..498aa99bbb 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPConfiguration.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPConfiguration.java
@@ -32,70 +32,70 @@ import org.eclipse.linuxtools.systemtap.ui.editor.DoubleClickStrategy;
public class STPConfiguration extends SourceViewerConfiguration {
- private STPElementScanner scanner;
- private ColorManager colorManager;
- private STPEditor editor;
- private DoubleClickStrategy doubleClickStrategy;
- private STPCompletionProcessor processor;
-
- public STPConfiguration(ColorManager colorManager, STPEditor editor) {
- this.colorManager = colorManager;
- this.editor = editor;
- this.processor = new STPCompletionProcessor();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredContentTypes(org.eclipse.jface.text.source.ISourceViewer)
- */
- @Override
- public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
- return new String[] {
- IDocument.DEFAULT_CONTENT_TYPE,
- STPPartitionScanner.STP_COMMENT,
- STPPartitionScanner.STP_CONDITIONAL};
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getContentAssistant(org.eclipse.jface.text.source.ISourceViewer)
- */
- @Override
- public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
- ContentAssistant assistant = new ContentAssistant();
-
- assistant.enableAutoActivation(true);
- assistant.setAutoActivationDelay(500);
- assistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY);
- assistant
- .setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
-
- assistant.setContentAssistProcessor(processor,IDocument.DEFAULT_CONTENT_TYPE);
- assistant.setContentAssistProcessor(processor,STPPartitionScanner.STP_CONDITIONAL);
-
- assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
-
- return assistant;
- }
-
- /**
- * Return the default Element scanner.
- *
- * @return default element scanner.
- */
- private STPElementScanner getSTPScanner() {
- if (scanner == null) {
- scanner = new STPElementScanner(colorManager);
- scanner.setDefaultReturnToken(new Token(new TextAttribute(
- colorManager.getColor(STPColorConstants.DEFAULT))));
- }
- return scanner;
- }
+ private STPElementScanner scanner;
+ private ColorManager colorManager;
+ private STPEditor editor;
+ private DoubleClickStrategy doubleClickStrategy;
+ private STPCompletionProcessor processor;
+
+ public STPConfiguration(ColorManager colorManager, STPEditor editor) {
+ this.colorManager = colorManager;
+ this.editor = editor;
+ this.processor = new STPCompletionProcessor();
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredContentTypes(org.eclipse.jface.text.source.ISourceViewer)
+ */
+ @Override
+ public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
+ return new String[] {
+ IDocument.DEFAULT_CONTENT_TYPE,
+ STPPartitionScanner.STP_COMMENT,
+ STPPartitionScanner.STP_CONDITIONAL};
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getContentAssistant(org.eclipse.jface.text.source.ISourceViewer)
+ */
+ @Override
+ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
+ ContentAssistant assistant = new ContentAssistant();
+
+ assistant.enableAutoActivation(true);
+ assistant.setAutoActivationDelay(500);
+ assistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY);
+ assistant
+ .setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
+
+ assistant.setContentAssistProcessor(processor,IDocument.DEFAULT_CONTENT_TYPE);
+ assistant.setContentAssistProcessor(processor,STPPartitionScanner.STP_CONDITIONAL);
+
+ assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
+
+ return assistant;
+ }
+
+ /**
+ * Return the default Element scanner.
+ *
+ * @return default element scanner.
+ */
+ private STPElementScanner getSTPScanner() {
+ if (scanner == null) {
+ scanner = new STPElementScanner(colorManager);
+ scanner.setDefaultReturnToken(new Token(new TextAttribute(
+ colorManager.getColor(STPColorConstants.DEFAULT))));
+ }
+ return scanner;
+ }
/* (non-Javadoc)
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getReconciler(org.eclipse.jface.text.source.ISourceViewer)
*
* Return the reconciler built on the custom Systemtap reconciling strategy that enables code folding for this editor.
*/
- @Override
+ @Override
public IReconciler getReconciler(ISourceViewer sourceViewer)
{
STPReconcilingStrategy strategy = new STPReconcilingStrategy();
@@ -104,58 +104,58 @@ public class STPConfiguration extends SourceViewerConfiguration {
return reconciler;
}
- /**
- * Instantiates and returns a double click strategy object if one does not exist, and returns the
- * current one if it does.
- */
- @Override
- public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer,String contentType) {
- if (doubleClickStrategy == null) {
- doubleClickStrategy = new DoubleClickStrategy();
- }
- return doubleClickStrategy;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(org.eclipse.jface.text.source.ISourceViewer)
- */
- @Override
- public IPresentationReconciler getPresentationReconciler(
- ISourceViewer sourceViewer) {
-
- PresentationReconciler reconciler = new PresentationReconciler();
-
- DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getSTPScanner());
- reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
- reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
-
- dr = new DefaultDamagerRepairer(getSTPScanner());
- reconciler.setDamager(dr, STPPartitionScanner.STP_COMMENT);
- reconciler.setRepairer(dr, STPPartitionScanner.STP_COMMENT);
-
- dr = new DefaultDamagerRepairer(getSTPScanner());
- reconciler.setDamager(dr, STPPartitionScanner.STP_CONDITIONAL);
- reconciler.setRepairer(dr, STPPartitionScanner.STP_CONDITIONAL);
-
- return reconciler;
- }
-
- @Override
- public IAutoEditStrategy[] getAutoEditStrategies(
- ISourceViewer sourceViewer, String contentType) {
- return new IAutoEditStrategy[] {new STPAutoEditStrategy(STPPartitionScanner.STP_PARTITIONING, null)};
- }
-
- @Override
- public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
- return processor;
- }
-
- @Override
- public String[] getDefaultPrefixes(ISourceViewer sourceViewer,
- String contentType) {
- return new String[] { "//", "" }; //$NON-NLS-1$//$NON-NLS-2$
- }
+ /**
+ * Instantiates and returns a double click strategy object if one does not exist, and returns the
+ * current one if it does.
+ */
+ @Override
+ public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer,String contentType) {
+ if (doubleClickStrategy == null) {
+ doubleClickStrategy = new DoubleClickStrategy();
+ }
+ return doubleClickStrategy;
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getPresentationReconciler(org.eclipse.jface.text.source.ISourceViewer)
+ */
+ @Override
+ public IPresentationReconciler getPresentationReconciler(
+ ISourceViewer sourceViewer) {
+
+ PresentationReconciler reconciler = new PresentationReconciler();
+
+ DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getSTPScanner());
+ reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
+ reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
+
+ dr = new DefaultDamagerRepairer(getSTPScanner());
+ reconciler.setDamager(dr, STPPartitionScanner.STP_COMMENT);
+ reconciler.setRepairer(dr, STPPartitionScanner.STP_COMMENT);
+
+ dr = new DefaultDamagerRepairer(getSTPScanner());
+ reconciler.setDamager(dr, STPPartitionScanner.STP_CONDITIONAL);
+ reconciler.setRepairer(dr, STPPartitionScanner.STP_CONDITIONAL);
+
+ return reconciler;
+ }
+
+ @Override
+ public IAutoEditStrategy[] getAutoEditStrategies(
+ ISourceViewer sourceViewer, String contentType) {
+ return new IAutoEditStrategy[] {new STPAutoEditStrategy(STPPartitionScanner.STP_PARTITIONING, null)};
+ }
+
+ @Override
+ public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
+ return processor;
+ }
+
+ @Override
+ public String[] getDefaultPrefixes(ISourceViewer sourceViewer,
+ String contentType) {
+ return new String[] { "//", "" }; //$NON-NLS-1$//$NON-NLS-2$
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPDefaultCodeFormatterConstants.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPDefaultCodeFormatterConstants.java
index c6b14e41bf..f4255baa81 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPDefaultCodeFormatterConstants.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPDefaultCodeFormatterConstants.java
@@ -25,409 +25,409 @@ import org.eclipse.linuxtools.internal.systemtap.ui.ide.IDEPlugin;
*/
public class STPDefaultCodeFormatterConstants {
- /**
- * <pre>
- * FORMATTER / Value to set an option to false.
- * </pre>
- */
- public static final String FALSE = "false"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Value to set an option to false.
+ * </pre>
+ */
+ public static final String FALSE = "false"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of arguments in method invocation
- * - option id: "org.eclipse.cdt.core.formatter.alignment_for_arguments_in_method_invocation"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- */
- public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION = IDEPlugin.PLUGIN_ID + ".formatter.alignment_for_arguments_in_method_invocation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of expressions in initializer list
- * - option id: "org.eclipse.cdt.core.formatter.alignment_for_expressions_in_array_initializer"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- */
- public static final String FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_INITIALIZER_LIST = IDEPlugin.PLUGIN_ID + ".formatter.alignment_for_expressions_in_array_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option for alignment of parameters in method declaration
- * - option id: "org.eclipse.cdt.core.formatter.alignment_for_parameters_in_method_declaration"
- * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
- * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
- * </pre>
- * @see #createAlignmentValue(boolean, int, int)
- */
- public static final String FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION = IDEPlugin.PLUGIN_ID + ".formatter.alignment_for_parameters_in_method_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of initializer list
- * - option id: "org.eclipse.cdt.core.formatter.brace_position_for_array_initializer"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_INITIALIZER_LIST = IDEPlugin.PLUGIN_ID + ".formatter.brace_position_for_array_initializer"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of a block
- * - option id: "org.eclipse.cdt.core.formatter.brace_position_for_block"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_BLOCK = IDEPlugin.PLUGIN_ID + ".formatter.brace_position_for_block"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of a method declaration
- * - option id: "org.eclipse.cdt.core.formatter.brace_position_for_method_declaration"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION = IDEPlugin.PLUGIN_ID + ".formatter.brace_position_for_method_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of a switch statement
- * - option id: "org.eclipse.cdt.core.formatter.brace_position_for_switch"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_SWITCH = IDEPlugin.PLUGIN_ID + ".formatter.brace_position_for_switch"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to position the braces of a type declaration
- * - option id: "org.eclipse.cdt.core.formatter.brace_position_for_type_declaration"
- * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
- * - default: END_OF_LINE
- * </pre>
- * @see #END_OF_LINE
- * @see #NEXT_LINE
- * @see #NEXT_LINE_SHIFTED
- * @see #NEXT_LINE_ON_WRAP
- */
- public static final String FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION = IDEPlugin.PLUGIN_ID + ".formatter.brace_position_for_type_declaration"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option for alignment of arguments in method invocation
+ * - option id: "org.eclipse.cdt.core.formatter.alignment_for_arguments_in_method_invocation"
+ * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
+ * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
+ * </pre>
+ * @see #createAlignmentValue(boolean, int, int)
+ */
+ public static final String FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION = IDEPlugin.PLUGIN_ID + ".formatter.alignment_for_arguments_in_method_invocation"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option for alignment of expressions in initializer list
+ * - option id: "org.eclipse.cdt.core.formatter.alignment_for_expressions_in_array_initializer"
+ * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
+ * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
+ * </pre>
+ * @see #createAlignmentValue(boolean, int, int)
+ */
+ public static final String FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_INITIALIZER_LIST = IDEPlugin.PLUGIN_ID + ".formatter.alignment_for_expressions_in_array_initializer"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option for alignment of parameters in method declaration
+ * - option id: "org.eclipse.cdt.core.formatter.alignment_for_parameters_in_method_declaration"
+ * - possible values: values returned by <code>createAlignmentValue(boolean, int, int)</code> call
+ * - default: createAlignmentValue(false, WRAP_COMPACT, INDENT_DEFAULT)
+ * </pre>
+ * @see #createAlignmentValue(boolean, int, int)
+ */
+ public static final String FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION = IDEPlugin.PLUGIN_ID + ".formatter.alignment_for_parameters_in_method_declaration"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to position the braces of initializer list
+ * - option id: "org.eclipse.cdt.core.formatter.brace_position_for_array_initializer"
+ * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
+ * - default: END_OF_LINE
+ * </pre>
+ * @see #END_OF_LINE
+ * @see #NEXT_LINE
+ * @see #NEXT_LINE_SHIFTED
+ * @see #NEXT_LINE_ON_WRAP
+ */
+ public static final String FORMATTER_BRACE_POSITION_FOR_INITIALIZER_LIST = IDEPlugin.PLUGIN_ID + ".formatter.brace_position_for_array_initializer"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to position the braces of a block
+ * - option id: "org.eclipse.cdt.core.formatter.brace_position_for_block"
+ * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
+ * - default: END_OF_LINE
+ * </pre>
+ * @see #END_OF_LINE
+ * @see #NEXT_LINE
+ * @see #NEXT_LINE_SHIFTED
+ * @see #NEXT_LINE_ON_WRAP
+ */
+ public static final String FORMATTER_BRACE_POSITION_FOR_BLOCK = IDEPlugin.PLUGIN_ID + ".formatter.brace_position_for_block"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to position the braces of a method declaration
+ * - option id: "org.eclipse.cdt.core.formatter.brace_position_for_method_declaration"
+ * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
+ * - default: END_OF_LINE
+ * </pre>
+ * @see #END_OF_LINE
+ * @see #NEXT_LINE
+ * @see #NEXT_LINE_SHIFTED
+ * @see #NEXT_LINE_ON_WRAP
+ */
+ public static final String FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION = IDEPlugin.PLUGIN_ID + ".formatter.brace_position_for_method_declaration"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to position the braces of a switch statement
+ * - option id: "org.eclipse.cdt.core.formatter.brace_position_for_switch"
+ * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
+ * - default: END_OF_LINE
+ * </pre>
+ * @see #END_OF_LINE
+ * @see #NEXT_LINE
+ * @see #NEXT_LINE_SHIFTED
+ * @see #NEXT_LINE_ON_WRAP
+ */
+ public static final String FORMATTER_BRACE_POSITION_FOR_SWITCH = IDEPlugin.PLUGIN_ID + ".formatter.brace_position_for_switch"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to position the braces of a type declaration
+ * - option id: "org.eclipse.cdt.core.formatter.brace_position_for_type_declaration"
+ * - possible values: { END_OF_LINE, NEXT_LINE, NEXT_LINE_SHIFTED, NEXT_LINE_ON_WRAP }
+ * - default: END_OF_LINE
+ * </pre>
+ * @see #END_OF_LINE
+ * @see #NEXT_LINE
+ * @see #NEXT_LINE_SHIFTED
+ * @see #NEXT_LINE_ON_WRAP
+ */
+ public static final String FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION = IDEPlugin.PLUGIN_ID + ".formatter.brace_position_for_type_declaration"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to set the continuation indentation
- * - option id: "org.eclipse.cdt.core.formatter.continuation_indentation"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "2"
- * </pre>
- */
- public static final String FORMATTER_CONTINUATION_INDENTATION = IDEPlugin.PLUGIN_ID + ".formatter.continuation_indentation"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent 'public:', 'protected:', 'private:' access specifiers relative to class declaration.
- * - option id: "org.eclipse.cdt.core.formatter.indent_access_specifier_compare_to_type_header"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- */
- public static final String FORMATTER_INDENT_ACCESS_SPECIFIER_COMPARE_TO_TYPE_HEADER = IDEPlugin.PLUGIN_ID + ".formatter.indent_access_specifier_compare_to_type_header"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Number of extra spaces in front of 'public:', 'protected:', 'private:' access specifiers.
- * Enables fractional indent of access specifiers. Does not affect indentation of body declarations.
- * - option id: "org.eclipse.cdt.core.formatter.indent_access_specifier_extra_spaces"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "0"
- * </pre>
- * @since 5.2
- */
- public static final String FORMATTER_INDENT_ACCESS_SPECIFIER_EXTRA_SPACES = IDEPlugin.PLUGIN_ID + ".formatter.indent_access_specifier_extra_spaces"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent body declarations relative to access specifiers (visibility labels)
- * - option id: "org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_access_specifier"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- */
- public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ACCESS_SPECIFIER = IDEPlugin.PLUGIN_ID + ".formatter.indent_body_declarations_compare_to_access_specifier"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent body declarations compare to its enclosing namespace header
- * - option id: "org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_namespace_header"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- */
- public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_NAMESPACE_HEADER = IDEPlugin.PLUGIN_ID + ".formatter.indent_body_declarations_compare_to_namespace_header"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent empty lines
- * - option id: "org.eclipse.cdt.core.formatter.indent_empty_lines"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- */
- public static final String FORMATTER_INDENT_EMPTY_LINES = IDEPlugin.PLUGIN_ID + ".formatter.indent_empty_lines"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent inside line comments at column 0
- * - option id: "org.eclipse.cdt.core.formatter.indent_inside_line_comments"
- * - possible values: { TRUE, FALSE }
- * - default: FALSE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- */
- public static final String FORMATTER_INDENT_INSIDE_LINE_COMMENTS = IDEPlugin.PLUGIN_ID + ".formatter.indent_inside_line_comments"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent statements inside a block
- * - option id: "org.eclipse.cdt.core.formatter.indent_statements_compare_to_block"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- */
- public static final String FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK = IDEPlugin.PLUGIN_ID + ".formatter.indent_statements_compare_to_block"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent statements inside the body of a method or a constructor
- * - option id: "org.eclipse.cdt.core.formatter.indent_statements_compare_to_body"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- */
- public static final String FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY = IDEPlugin.PLUGIN_ID + ".formatter.indent_statements_compare_to_body"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent switch statements compare to cases
- * - option id: "org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_cases"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- */
- public static final String FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES = IDEPlugin.PLUGIN_ID + ".formatter.indent_switchstatements_compare_to_cases"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to indent switch statements compare to switch
- * - option id: "org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_switch"
- * - possible values: { TRUE, FALSE }
- * - default: TRUE
- * </pre>
- * @see #TRUE
- * @see #FALSE
- */
- public static final String FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH = IDEPlugin.PLUGIN_ID + ".formatter.indent_switchstatements_compare_to_switch"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to specify the tabulation size
- * - option id: "org.eclipse.cdt.core.formatter.tabulation.char"
- * - possible values: { TAB, SPACE, MIXED }
- * - default: TAB
- * </pre>
- * More values may be added in the future.
- *
- * @see IDEPlugin#TAB
- * @see IDEPlugin#SPACE
- * @see #MIXED
- */
- public static final String FORMATTER_TAB_CHAR = IDEPlugin.PLUGIN_ID + ".formatter.tabulation.char"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Option to specify the equivalent number of spaces that represents one tabulation
- * - option id: "org.eclipse.cdt.core.formatter.tabulation.size"
- * - possible values: "&lt;n&gt;", where n is zero or a positive integer
- * - default: "4"
- * </pre>
- */
- public static final String FORMATTER_TAB_SIZE = IDEPlugin.PLUGIN_ID + ".formatter.tabulation.size"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to set the continuation indentation
+ * - option id: "org.eclipse.cdt.core.formatter.continuation_indentation"
+ * - possible values: "&lt;n&gt;", where n is zero or a positive integer
+ * - default: "2"
+ * </pre>
+ */
+ public static final String FORMATTER_CONTINUATION_INDENTATION = IDEPlugin.PLUGIN_ID + ".formatter.continuation_indentation"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to indent 'public:', 'protected:', 'private:' access specifiers relative to class declaration.
+ * - option id: "org.eclipse.cdt.core.formatter.indent_access_specifier_compare_to_type_header"
+ * - possible values: { TRUE, FALSE }
+ * - default: FALSE
+ * </pre>
+ * @see #TRUE
+ * @see #FALSE
+ */
+ public static final String FORMATTER_INDENT_ACCESS_SPECIFIER_COMPARE_TO_TYPE_HEADER = IDEPlugin.PLUGIN_ID + ".formatter.indent_access_specifier_compare_to_type_header"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Number of extra spaces in front of 'public:', 'protected:', 'private:' access specifiers.
+ * Enables fractional indent of access specifiers. Does not affect indentation of body declarations.
+ * - option id: "org.eclipse.cdt.core.formatter.indent_access_specifier_extra_spaces"
+ * - possible values: "&lt;n&gt;", where n is zero or a positive integer
+ * - default: "0"
+ * </pre>
+ * @since 5.2
+ */
+ public static final String FORMATTER_INDENT_ACCESS_SPECIFIER_EXTRA_SPACES = IDEPlugin.PLUGIN_ID + ".formatter.indent_access_specifier_extra_spaces"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to indent body declarations relative to access specifiers (visibility labels)
+ * - option id: "org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_access_specifier"
+ * - possible values: { TRUE, FALSE }
+ * - default: TRUE
+ * </pre>
+ * @see #TRUE
+ * @see #FALSE
+ */
+ public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ACCESS_SPECIFIER = IDEPlugin.PLUGIN_ID + ".formatter.indent_body_declarations_compare_to_access_specifier"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to indent body declarations compare to its enclosing namespace header
+ * - option id: "org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_namespace_header"
+ * - possible values: { TRUE, FALSE }
+ * - default: TRUE
+ * </pre>
+ * @see #TRUE
+ * @see #FALSE
+ */
+ public static final String FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_NAMESPACE_HEADER = IDEPlugin.PLUGIN_ID + ".formatter.indent_body_declarations_compare_to_namespace_header"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to indent empty lines
+ * - option id: "org.eclipse.cdt.core.formatter.indent_empty_lines"
+ * - possible values: { TRUE, FALSE }
+ * - default: FALSE
+ * </pre>
+ * @see #TRUE
+ * @see #FALSE
+ */
+ public static final String FORMATTER_INDENT_EMPTY_LINES = IDEPlugin.PLUGIN_ID + ".formatter.indent_empty_lines"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to indent inside line comments at column 0
+ * - option id: "org.eclipse.cdt.core.formatter.indent_inside_line_comments"
+ * - possible values: { TRUE, FALSE }
+ * - default: FALSE
+ * </pre>
+ * @see #TRUE
+ * @see #FALSE
+ */
+ public static final String FORMATTER_INDENT_INSIDE_LINE_COMMENTS = IDEPlugin.PLUGIN_ID + ".formatter.indent_inside_line_comments"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to indent statements inside a block
+ * - option id: "org.eclipse.cdt.core.formatter.indent_statements_compare_to_block"
+ * - possible values: { TRUE, FALSE }
+ * - default: TRUE
+ * </pre>
+ * @see #TRUE
+ * @see #FALSE
+ */
+ public static final String FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK = IDEPlugin.PLUGIN_ID + ".formatter.indent_statements_compare_to_block"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to indent statements inside the body of a method or a constructor
+ * - option id: "org.eclipse.cdt.core.formatter.indent_statements_compare_to_body"
+ * - possible values: { TRUE, FALSE }
+ * - default: TRUE
+ * </pre>
+ * @see #TRUE
+ * @see #FALSE
+ */
+ public static final String FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY = IDEPlugin.PLUGIN_ID + ".formatter.indent_statements_compare_to_body"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to indent switch statements compare to cases
+ * - option id: "org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_cases"
+ * - possible values: { TRUE, FALSE }
+ * - default: TRUE
+ * </pre>
+ * @see #TRUE
+ * @see #FALSE
+ */
+ public static final String FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES = IDEPlugin.PLUGIN_ID + ".formatter.indent_switchstatements_compare_to_cases"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to indent switch statements compare to switch
+ * - option id: "org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_switch"
+ * - possible values: { TRUE, FALSE }
+ * - default: TRUE
+ * </pre>
+ * @see #TRUE
+ * @see #FALSE
+ */
+ public static final String FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH = IDEPlugin.PLUGIN_ID + ".formatter.indent_switchstatements_compare_to_switch"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to specify the tabulation size
+ * - option id: "org.eclipse.cdt.core.formatter.tabulation.char"
+ * - possible values: { TAB, SPACE, MIXED }
+ * - default: TAB
+ * </pre>
+ * More values may be added in the future.
+ *
+ * @see IDEPlugin#TAB
+ * @see IDEPlugin#SPACE
+ * @see #MIXED
+ */
+ public static final String FORMATTER_TAB_CHAR = IDEPlugin.PLUGIN_ID + ".formatter.tabulation.char"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Option to specify the equivalent number of spaces that represents one tabulation
+ * - option id: "org.eclipse.cdt.core.formatter.tabulation.size"
+ * - possible values: "&lt;n&gt;", where n is zero or a positive integer
+ * - default: "4"
+ * </pre>
+ */
+ public static final String FORMATTER_TAB_SIZE = IDEPlugin.PLUGIN_ID + ".formatter.tabulation.size"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / The wrapping is done by indenting by one compare to the current indentation.
- * </pre>
- */
- public static final int INDENT_BY_ONE= 2;
+ /**
+ * <pre>
+ * FORMATTER / The wrapping is done by indenting by one compare to the current indentation.
+ * </pre>
+ */
+ public static final int INDENT_BY_ONE= 2;
- /**
- * <pre>
- * FORMATTER / The wrapping is done by using the current indentation.
- * </pre>
- */
- public static final int INDENT_DEFAULT= 0;
- /**
- * <pre>
- * FORMATTER / The wrapping is done by indenting on column under the splitting location.
- * </pre>
- */
- public static final int INDENT_ON_COLUMN = 1;
+ /**
+ * <pre>
+ * FORMATTER / The wrapping is done by using the current indentation.
+ * </pre>
+ */
+ public static final int INDENT_DEFAULT= 0;
+ /**
+ * <pre>
+ * FORMATTER / The wrapping is done by indenting on column under the splitting location.
+ * </pre>
+ */
+ public static final int INDENT_ON_COLUMN = 1;
- /**
- * <pre>
- * FORMATTER / Possible value for the option FORMATTER_TAB_CHAR
- * </pre>
- * @see IDEPlugin#TAB
- * @see IDEPlugin#SPACE
- * @see #FORMATTER_TAB_CHAR
- */
- public static final String MIXED = "mixed"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Value to set a brace location at the start of the next line with
- * an extra indentation.
- * </pre>
- * @see #FORMATTER_BRACE_POSITION_FOR_INITIALIZER_LIST
- * @see #FORMATTER_BRACE_POSITION_FOR_BLOCK
- * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION
- * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH
- * @see #FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION
- */
- public static final String NEXT_LINE_SHIFTED = "next_line_shifted"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / Value to set an option to true.
- * </pre>
- */
- public static final String TRUE = "true"; //$NON-NLS-1$
- /**
- * <pre>
- * FORMATTER / The wrapping is done using as few lines as possible.
- * </pre>
- */
- public static final int WRAP_COMPACT= 1;
- /**
- * <pre>
- * FORMATTER / The wrapping is done putting the first element on a new
- * line and then wrapping next elements using as few lines as possible.
- * </pre>
- */
- public static final int WRAP_COMPACT_FIRST_BREAK= 2;
- /**
- * <pre>
- * FORMATTER / The wrapping is done by putting each element on its own line
- * except the first element.
- * </pre>
- */
- public static final int WRAP_NEXT_PER_LINE= 5;
- /**
- * <pre>
- * FORMATTER / The wrapping is done by putting each element on its own line.
- * All elements are indented by one except the first element.
- * </pre>
- */
- public static final int WRAP_NEXT_SHIFTED= 4;
+ /**
+ * <pre>
+ * FORMATTER / Possible value for the option FORMATTER_TAB_CHAR
+ * </pre>
+ * @see IDEPlugin#TAB
+ * @see IDEPlugin#SPACE
+ * @see #FORMATTER_TAB_CHAR
+ */
+ public static final String MIXED = "mixed"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Value to set a brace location at the start of the next line with
+ * an extra indentation.
+ * </pre>
+ * @see #FORMATTER_BRACE_POSITION_FOR_INITIALIZER_LIST
+ * @see #FORMATTER_BRACE_POSITION_FOR_BLOCK
+ * @see #FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION
+ * @see #FORMATTER_BRACE_POSITION_FOR_SWITCH
+ * @see #FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION
+ */
+ public static final String NEXT_LINE_SHIFTED = "next_line_shifted"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / Value to set an option to true.
+ * </pre>
+ */
+ public static final String TRUE = "true"; //$NON-NLS-1$
+ /**
+ * <pre>
+ * FORMATTER / The wrapping is done using as few lines as possible.
+ * </pre>
+ */
+ public static final int WRAP_COMPACT= 1;
+ /**
+ * <pre>
+ * FORMATTER / The wrapping is done putting the first element on a new
+ * line and then wrapping next elements using as few lines as possible.
+ * </pre>
+ */
+ public static final int WRAP_COMPACT_FIRST_BREAK= 2;
+ /**
+ * <pre>
+ * FORMATTER / The wrapping is done by putting each element on its own line
+ * except the first element.
+ * </pre>
+ */
+ public static final int WRAP_NEXT_PER_LINE= 5;
+ /**
+ * <pre>
+ * FORMATTER / The wrapping is done by putting each element on its own line.
+ * All elements are indented by one except the first element.
+ * </pre>
+ */
+ public static final int WRAP_NEXT_SHIFTED= 4;
- /**
- * <pre>
- * FORMATTER / Value to disable alignment.
- * </pre>
- */
- public static final int WRAP_NO_SPLIT= 0;
- /**
- * <pre>
- * FORMATTER / The wrapping is done by putting each element on its own line.
- * </pre>
- */
- public static final int WRAP_ONE_PER_LINE= 3;
+ /**
+ * <pre>
+ * FORMATTER / Value to disable alignment.
+ * </pre>
+ */
+ public static final int WRAP_NO_SPLIT= 0;
+ /**
+ * <pre>
+ * FORMATTER / The wrapping is done by putting each element on its own line.
+ * </pre>
+ */
+ public static final int WRAP_ONE_PER_LINE= 3;
- /*
- * Private constants.
- */
- private static final IllegalArgumentException WRONG_ARGUMENT = new IllegalArgumentException();
+ /*
+ * Private constants.
+ */
+ private static final IllegalArgumentException WRONG_ARGUMENT = new IllegalArgumentException();
- /**
- * <p>Return the indentation style of the given alignment value.
- * The given alignment value should be created using the <code>createAlignmentValue(boolean, int, int)</code>
- * API.
- * </p>
- *
- * @param value the given alignment value
- * @return the indentation style of the given alignment value
- * @see #createAlignmentValue(boolean, int, int)
- * @exception IllegalArgumentException if the given alignment value is null, or if it
- * doesn't have a valid format.
- */
- public static int getIndentStyle(String value) {
- if (value == null) {
- throw WRONG_ARGUMENT;
- }
- try {
- int existingValue = Integer.parseInt(value);
- if ((existingValue & STPAlignment.M_INDENT_BY_ONE) != 0) {
- return INDENT_BY_ONE;
- } else if ((existingValue & STPAlignment.M_INDENT_ON_COLUMN) != 0) {
- return INDENT_ON_COLUMN;
- } else {
- return INDENT_DEFAULT;
- }
- } catch (NumberFormatException e) {
- throw WRONG_ARGUMENT;
- }
- }
+ /**
+ * <p>Return the indentation style of the given alignment value.
+ * The given alignment value should be created using the <code>createAlignmentValue(boolean, int, int)</code>
+ * API.
+ * </p>
+ *
+ * @param value the given alignment value
+ * @return the indentation style of the given alignment value
+ * @see #createAlignmentValue(boolean, int, int)
+ * @exception IllegalArgumentException if the given alignment value is null, or if it
+ * doesn't have a valid format.
+ */
+ public static int getIndentStyle(String value) {
+ if (value == null) {
+ throw WRONG_ARGUMENT;
+ }
+ try {
+ int existingValue = Integer.parseInt(value);
+ if ((existingValue & STPAlignment.M_INDENT_BY_ONE) != 0) {
+ return INDENT_BY_ONE;
+ } else if ((existingValue & STPAlignment.M_INDENT_ON_COLUMN) != 0) {
+ return INDENT_ON_COLUMN;
+ } else {
+ return INDENT_DEFAULT;
+ }
+ } catch (NumberFormatException e) {
+ throw WRONG_ARGUMENT;
+ }
+ }
- /**
- * <p>Return the wrapping style of the given alignment value.
- * The given alignment value should be created using the <code>createAlignmentValue(boolean, int, int)</code>
- * API.
- * </p>
- *
- * @param value the given alignment value
- * @return the wrapping style of the given alignment value
- * @see #createAlignmentValue(boolean, int, int)
- * @exception IllegalArgumentException if the given alignment value is null, or if it
- * doesn't have a valid format.
- */
- public static int getWrappingStyle(String value) {
- if (value == null) {
- throw WRONG_ARGUMENT;
- }
- try {
- int existingValue = Integer.parseInt(value) & STPAlignment.SPLIT_MASK;
- switch (existingValue) {
- case STPAlignment.M_COMPACT_SPLIT:
- return WRAP_COMPACT;
- case STPAlignment.M_COMPACT_FIRST_BREAK_SPLIT:
- return WRAP_COMPACT_FIRST_BREAK;
- case STPAlignment.M_NEXT_PER_LINE_SPLIT:
- return WRAP_NEXT_PER_LINE;
- case STPAlignment.M_NEXT_SHIFTED_SPLIT:
- return WRAP_NEXT_SHIFTED;
- case STPAlignment.M_ONE_PER_LINE_SPLIT:
- return WRAP_ONE_PER_LINE;
- default:
- return WRAP_NO_SPLIT;
- }
- } catch (NumberFormatException e) {
- throw WRONG_ARGUMENT;
- }
- }
+ /**
+ * <p>Return the wrapping style of the given alignment value.
+ * The given alignment value should be created using the <code>createAlignmentValue(boolean, int, int)</code>
+ * API.
+ * </p>
+ *
+ * @param value the given alignment value
+ * @return the wrapping style of the given alignment value
+ * @see #createAlignmentValue(boolean, int, int)
+ * @exception IllegalArgumentException if the given alignment value is null, or if it
+ * doesn't have a valid format.
+ */
+ public static int getWrappingStyle(String value) {
+ if (value == null) {
+ throw WRONG_ARGUMENT;
+ }
+ try {
+ int existingValue = Integer.parseInt(value) & STPAlignment.SPLIT_MASK;
+ switch (existingValue) {
+ case STPAlignment.M_COMPACT_SPLIT:
+ return WRAP_COMPACT;
+ case STPAlignment.M_COMPACT_FIRST_BREAK_SPLIT:
+ return WRAP_COMPACT_FIRST_BREAK;
+ case STPAlignment.M_NEXT_PER_LINE_SPLIT:
+ return WRAP_NEXT_PER_LINE;
+ case STPAlignment.M_NEXT_SHIFTED_SPLIT:
+ return WRAP_NEXT_SHIFTED;
+ case STPAlignment.M_ONE_PER_LINE_SPLIT:
+ return WRAP_ONE_PER_LINE;
+ default:
+ return WRAP_NO_SPLIT;
+ }
+ } catch (NumberFormatException e) {
+ throw WRONG_ARGUMENT;
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPDocumentProvider.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPDocumentProvider.java
index 1e7feb9970..1a1269398f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPDocumentProvider.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPDocumentProvider.java
@@ -24,31 +24,31 @@ import org.eclipse.ui.editors.text.TextFileDocumentProvider;
public class STPDocumentProvider extends TextFileDocumentProvider {
- @Override
- public void connect(Object element) throws CoreException {
- super.connect(element);
- setupDocument(this.getDocument(element));
- }
+ @Override
+ public void connect(Object element) throws CoreException {
+ super.connect(element);
+ setupDocument(this.getDocument(element));
+ }
- protected void setupDocument(IDocument document) {
- if (document != null) {
- IDocumentPartitioner partitioner = new FastPartitioner(
- new STPPartitionScanner(), STPPartitionScanner.STP_PARTITION_TYPES);
- partitioner.connect(document);
- IDocumentPartitioner partitioner2 = new FastPartitioner(
- new STPProbeScanner(), STPProbeScanner.STP_PROBE_PARTITION_TYPES);
- partitioner2.connect(document);
- ((IDocumentExtension3)document).setDocumentPartitioner(STPPartitionScanner.STP_PARTITIONING, partitioner);
- ((IDocumentExtension3)document).setDocumentPartitioner(STPProbeScanner.STP_PROBE_PARTITIONING, partitioner2);
- }
- }
+ protected void setupDocument(IDocument document) {
+ if (document != null) {
+ IDocumentPartitioner partitioner = new FastPartitioner(
+ new STPPartitionScanner(), STPPartitionScanner.STP_PARTITION_TYPES);
+ partitioner.connect(document);
+ IDocumentPartitioner partitioner2 = new FastPartitioner(
+ new STPProbeScanner(), STPProbeScanner.STP_PROBE_PARTITION_TYPES);
+ partitioner2.connect(document);
+ ((IDocumentExtension3)document).setDocumentPartitioner(STPPartitionScanner.STP_PARTITIONING, partitioner);
+ ((IDocumentExtension3)document).setDocumentPartitioner(STPProbeScanner.STP_PROBE_PARTITIONING, partitioner2);
+ }
+ }
- /**
- * Instantiates and returns a new AnnotationModel object.
- */
- @Override
- protected IAnnotationModel createAnnotationModel(IFile file) {
- return new AnnotationModel();
- }
+ /**
+ * Instantiates and returns a new AnnotationModel object.
+ */
+ @Override
+ protected IAnnotationModel createAnnotationModel(IFile file) {
+ return new AnnotationModel();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPEditor.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPEditor.java
index bdd1744612..045cfd537b 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPEditor.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPEditor.java
@@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008 Phil Muldoon <pkmuldoon@picobot.org>.
- *
+ *
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * Phil Muldoon <pkmuldoon@picobot.org> - initial API.
+ * Phil Muldoon <pkmuldoon@picobot.org> - initial API.
*******************************************************************************/
package org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp;
@@ -36,89 +36,89 @@ import org.eclipse.ui.texteditor.ITextEditorActionConstants;
public class STPEditor extends SimpleEditor {
- private ColorManager colorManager;
-
+ private ColorManager colorManager;
+
private ProjectionSupport stpProjectionSupport;
- private Annotation[] stpOldAnnotations;
- private ProjectionAnnotationModel stpAnnotationModel;
-
- public static final String ID="org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.STPEditor"; //$NON-NLS-1$
-
- public STPEditor() {
- super();
- colorManager = new ColorManager();
- setSourceViewerConfiguration(new STPConfiguration(colorManager,this));
- }
-
- @Override
- protected void internalInit() {
- configureInsertMode(SMART_INSERT, false);
- setDocumentProvider(new STPDocumentProvider());
- }
-
- @Override
- protected void doSetInput(IEditorInput input) throws CoreException {
- if(input instanceof FileStoreEditorInput) {
- input= new PathEditorInput(new Path(((FileStoreEditorInput) input).getURI().getPath()));
- }
- super.doSetInput(input);
- }
-
- @Override
- public void createPartControl(Composite parent)
- {
- super.createPartControl(parent);
- ProjectionViewer viewer =(ProjectionViewer)getSourceViewer();
- stpProjectionSupport = new ProjectionSupport(viewer,getAnnotationAccess(),getSharedColors());
- stpProjectionSupport.install();
- viewer.doOperation(ProjectionViewer.TOGGLE);
- stpAnnotationModel = viewer.getProjectionAnnotationModel();
- }
-
- @Override
- protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
-
- ISourceViewer viewer = new ProjectionViewer(parent, ruler,
- getOverviewRuler(), isOverviewRulerVisible(), styles);
- getSourceViewerDecorationSupport(viewer);
- return viewer;
- }
-
-
- public void updateFoldingStructure(ArrayList<Position> updatedPositions)
- {
- ProjectionAnnotation annotation;
- Annotation[] updatedAnnotations = new Annotation[updatedPositions.size()];
- HashMap<ProjectionAnnotation, Position> newAnnotations = new HashMap<>();
- for(int i =0;i<updatedPositions.size();i++)
- {
- annotation = new ProjectionAnnotation();
- newAnnotations.put(annotation,updatedPositions.get(i));
- updatedAnnotations[i]=annotation;
- }
- stpAnnotationModel.modifyAnnotations(stpOldAnnotations,newAnnotations,null);
- stpOldAnnotations = updatedAnnotations;
- }
-
- public ISourceViewer getMySourceViewer() {
- return this.getSourceViewer();
- }
-
- @Override
- public void dispose() {
- colorManager.dispose();
- super.dispose();
- }
-
- @Override
- protected void editorContextMenuAboutToShow(IMenuManager menu) {
-
- super.editorContextMenuAboutToShow(menu);
- addAction(menu, ITextEditorActionConstants.GROUP_EDIT,
- ITextEditorActionConstants.SHIFT_RIGHT);
- addAction(menu, ITextEditorActionConstants.GROUP_EDIT,
- ITextEditorActionConstants.SHIFT_LEFT);
-
- }
-
+ private Annotation[] stpOldAnnotations;
+ private ProjectionAnnotationModel stpAnnotationModel;
+
+ public static final String ID="org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp.STPEditor"; //$NON-NLS-1$
+
+ public STPEditor() {
+ super();
+ colorManager = new ColorManager();
+ setSourceViewerConfiguration(new STPConfiguration(colorManager,this));
+ }
+
+ @Override
+ protected void internalInit() {
+ configureInsertMode(SMART_INSERT, false);
+ setDocumentProvider(new STPDocumentProvider());
+ }
+
+ @Override
+ protected void doSetInput(IEditorInput input) throws CoreException {
+ if(input instanceof FileStoreEditorInput) {
+ input= new PathEditorInput(new Path(((FileStoreEditorInput) input).getURI().getPath()));
+ }
+ super.doSetInput(input);
+ }
+
+ @Override
+ public void createPartControl(Composite parent)
+ {
+ super.createPartControl(parent);
+ ProjectionViewer viewer =(ProjectionViewer)getSourceViewer();
+ stpProjectionSupport = new ProjectionSupport(viewer,getAnnotationAccess(),getSharedColors());
+ stpProjectionSupport.install();
+ viewer.doOperation(ProjectionViewer.TOGGLE);
+ stpAnnotationModel = viewer.getProjectionAnnotationModel();
+ }
+
+ @Override
+ protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
+
+ ISourceViewer viewer = new ProjectionViewer(parent, ruler,
+ getOverviewRuler(), isOverviewRulerVisible(), styles);
+ getSourceViewerDecorationSupport(viewer);
+ return viewer;
+ }
+
+
+ public void updateFoldingStructure(ArrayList<Position> updatedPositions)
+ {
+ ProjectionAnnotation annotation;
+ Annotation[] updatedAnnotations = new Annotation[updatedPositions.size()];
+ HashMap<ProjectionAnnotation, Position> newAnnotations = new HashMap<>();
+ for(int i =0;i<updatedPositions.size();i++)
+ {
+ annotation = new ProjectionAnnotation();
+ newAnnotations.put(annotation,updatedPositions.get(i));
+ updatedAnnotations[i]=annotation;
+ }
+ stpAnnotationModel.modifyAnnotations(stpOldAnnotations,newAnnotations,null);
+ stpOldAnnotations = updatedAnnotations;
+ }
+
+ public ISourceViewer getMySourceViewer() {
+ return this.getSourceViewer();
+ }
+
+ @Override
+ public void dispose() {
+ colorManager.dispose();
+ super.dispose();
+ }
+
+ @Override
+ protected void editorContextMenuAboutToShow(IMenuManager menu) {
+
+ super.editorContextMenuAboutToShow(menu);
+ addAction(menu, ITextEditorActionConstants.GROUP_EDIT,
+ ITextEditorActionConstants.SHIFT_RIGHT);
+ addAction(menu, ITextEditorActionConstants.GROUP_EDIT,
+ ITextEditorActionConstants.SHIFT_LEFT);
+
+ }
+
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPElementScanner.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPElementScanner.java
index 183678ecde..51ade8b5a9 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPElementScanner.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPElementScanner.java
@@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008 Phil Muldoon <pkmuldoon@picobot.org>.
- *
+ *
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * Phil Muldoon <pkmuldoon@picobot.org> - initial API and implementation.
+ * Phil Muldoon <pkmuldoon@picobot.org> - initial API and implementation.
*******************************************************************************/
package org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp;
@@ -29,80 +29,80 @@ import org.eclipse.swt.SWT;
public class STPElementScanner extends BufferedRuleBasedScanner {
- private String[] keywordList = { "probe", "for", "else", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- "foreach", "exit", "printf", "in", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
- "return", "break", "global", "next", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
- "while", "if", "delete", "#include", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
- "function", "do", "print", "error", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
- "log", "printd", "printdln", "println", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
- "sprint", "sprintf", "system", "warn" }; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
-
- /**
- *
- * Build Element scanner for Syntax Highlighting for Systemtap Editor
- *
- * @param manager ColorManager to source highlighting.
- *
- */
- public STPElementScanner(ColorManager manager) {
- IToken defaultToken = new Token(new TextAttribute(manager
- .getColor(STPColorConstants.DEFAULT)));
-
- IToken keywordToken = new Token(new TextAttribute(manager
- .getColor(STPColorConstants.KEYWORD),null,SWT.BOLD));
-
- IToken commentToken = new Token(new TextAttribute(manager
- .getColor(STPColorConstants.COMMENT)));
-
- IToken stringToken = new Token(new TextAttribute(manager
- .getColor(STPColorConstants.STP_STRING)));
-
-
- // Build keyword scanner
- WordRule keywordsRule = new WordRule(new IWordDetector() {
-
- @Override
- public boolean isWordStart(char c) {
- // probe kernel.function("schedule") is a valid name in
- // Systemtap, but we do not want to highlight the function
- // here as a keyword. Same with foo.return and so on.
- if (c == '.') {
- return true;
- }
-
- return Character.isJavaIdentifierStart(c);
- }
-
- @Override
- public boolean isWordPart(char c) {
- // Set isWordStart for . rule.
- if (c == '.') {
- return true;
- }
-
- return Character.isJavaIdentifierPart(c);
- }
-
- }, defaultToken, true);
-
- for (int i=0; i<keywordList.length; i++)
- keywordsRule.addWord(keywordList[i], keywordToken);
-
- setRules(new IRule[] { new MultiLineRule("/*", "*/", commentToken), //$NON-NLS-1$//$NON-NLS-2$
- new EndOfLineRule("/*", commentToken), //$NON-NLS-1$
- new EndOfLineRule("#", commentToken), //$NON-NLS-1$
- new EndOfLineRule("//", commentToken), //$NON-NLS-1$
- new EndOfLineRule("#if", defaultToken), //$NON-NLS-1$
- new EndOfLineRule("#else", defaultToken), //$NON-NLS-1$
- new EndOfLineRule("#endif", defaultToken), //$NON-NLS-1$
- new EndOfLineRule("#define", defaultToken), //$NON-NLS-1$
- new SingleLineRule("\"", "\"", stringToken, '\\'), //$NON-NLS-1$ //$NON-NLS-2$
- new SingleLineRule("'", "'", stringToken, '\\'), //$NON-NLS-1$//$NON-NLS-2$
- keywordsRule, new WhitespaceRule(new IWhitespaceDetector() {
- @Override
- public boolean isWhitespace(char c) {
- return Character.isWhitespace(c);
- }
- }), });
- }
+ private String[] keywordList = { "probe", "for", "else", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
+ "foreach", "exit", "printf", "in", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
+ "return", "break", "global", "next", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
+ "while", "if", "delete", "#include", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
+ "function", "do", "print", "error", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
+ "log", "printd", "printdln", "println", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
+ "sprint", "sprintf", "system", "warn" }; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
+
+ /**
+ *
+ * Build Element scanner for Syntax Highlighting for Systemtap Editor
+ *
+ * @param manager ColorManager to source highlighting.
+ *
+ */
+ public STPElementScanner(ColorManager manager) {
+ IToken defaultToken = new Token(new TextAttribute(manager
+ .getColor(STPColorConstants.DEFAULT)));
+
+ IToken keywordToken = new Token(new TextAttribute(manager
+ .getColor(STPColorConstants.KEYWORD),null,SWT.BOLD));
+
+ IToken commentToken = new Token(new TextAttribute(manager
+ .getColor(STPColorConstants.COMMENT)));
+
+ IToken stringToken = new Token(new TextAttribute(manager
+ .getColor(STPColorConstants.STP_STRING)));
+
+
+ // Build keyword scanner
+ WordRule keywordsRule = new WordRule(new IWordDetector() {
+
+ @Override
+ public boolean isWordStart(char c) {
+ // probe kernel.function("schedule") is a valid name in
+ // Systemtap, but we do not want to highlight the function
+ // here as a keyword. Same with foo.return and so on.
+ if (c == '.') {
+ return true;
+ }
+
+ return Character.isJavaIdentifierStart(c);
+ }
+
+ @Override
+ public boolean isWordPart(char c) {
+ // Set isWordStart for . rule.
+ if (c == '.') {
+ return true;
+ }
+
+ return Character.isJavaIdentifierPart(c);
+ }
+
+ }, defaultToken, true);
+
+ for (int i=0; i<keywordList.length; i++)
+ keywordsRule.addWord(keywordList[i], keywordToken);
+
+ setRules(new IRule[] { new MultiLineRule("/*", "*/", commentToken), //$NON-NLS-1$//$NON-NLS-2$
+ new EndOfLineRule("/*", commentToken), //$NON-NLS-1$
+ new EndOfLineRule("#", commentToken), //$NON-NLS-1$
+ new EndOfLineRule("//", commentToken), //$NON-NLS-1$
+ new EndOfLineRule("#if", defaultToken), //$NON-NLS-1$
+ new EndOfLineRule("#else", defaultToken), //$NON-NLS-1$
+ new EndOfLineRule("#endif", defaultToken), //$NON-NLS-1$
+ new EndOfLineRule("#define", defaultToken), //$NON-NLS-1$
+ new SingleLineRule("\"", "\"", stringToken, '\\'), //$NON-NLS-1$ //$NON-NLS-2$
+ new SingleLineRule("'", "'", stringToken, '\\'), //$NON-NLS-1$//$NON-NLS-2$
+ keywordsRule, new WhitespaceRule(new IWhitespaceDetector() {
+ @Override
+ public boolean isWhitespace(char c) {
+ return Character.isWhitespace(c);
+ }
+ }), });
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPHeuristicScanner.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPHeuristicScanner.java
index 7237abb757..37d1161e8a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPHeuristicScanner.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPHeuristicScanner.java
@@ -30,1039 +30,1039 @@ import org.eclipse.jface.text.TypedRegion;
* <p>An instance holds some internal position in the document and is therefore not thread-safe.</p>
*/
public final class STPHeuristicScanner implements STPSymbols {
- /**
- * Returned by all methods when the requested position could not be found, or if a
- * {@link BadLocationException} was thrown while scanning.
- */
- public static final int NOT_FOUND= -1;
-
- /**
- * Special bound parameter that means either -1 (backward scanning) or
- * <code>fDocument.getLength()</code> (forward scanning).
- */
- public static final int UNBOUND= -2;
-
-
- /* character constants */
- private static final char LBRACE= '{';
- private static final char RBRACE= '}';
- private static final char LPAREN= '(';
- private static final char RPAREN= ')';
- private static final char SEMICOLON= ';';
- private static final char COLON= ':';
- private static final char COMMA= ',';
- private static final char LBRACKET= '[';
- private static final char RBRACKET= ']';
- private static final char QUESTIONMARK= '?';
- private static final char EQUAL= '=';
- private static final char LANGLE= '<';
- private static final char RANGLE= '>';
- private static final char DOT= '.';
- private static final char MINUS= '-';
- private static final char PLUS= '+';
- private static final char TILDE= '~';
-
- /**
- * Specifies the stop condition, upon which the <code>scanXXX</code> methods will decide whether
- * to keep scanning or not. This interface may implemented by clients.
- */
- private static abstract class StopCondition {
- /**
- * Instructs the scanner to return the current position.
- *
- * @param ch the char at the current position
- * @param position the current position
- * @param forward the iteration direction
- * @return <code>true</code> if the stop condition is met.
- */
- public abstract boolean stop(char ch, int position, boolean forward);
-
- /**
- * Asks the condition to return the next position to query. The default
- * is to return the next/previous position.
- *
- * @return the next position to scan
- */
- public int nextPosition(int position, boolean forward) {
- return forward ? position + 1 : position - 1;
- }
- }
-
- /**
- * Stops upon a non-whitespace (as defined by {@link Character#isWhitespace(char)}) character.
- */
- private static class NonWhitespace extends StopCondition {
- /*
- * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#stop(char)
- */
- @Override
- public boolean stop(char ch, int position, boolean forward) {
- return !Character.isWhitespace(ch);
- }
- }
-
- /**
- * Stops upon a non-whitespace character in the default partition.
- *
- * @see NonWhitespace
- */
- private final class NonWhitespaceDefaultPartition extends NonWhitespace {
- /*
- * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#stop(char)
- */
- @Override
- public boolean stop(char ch, int position, boolean forward) {
- return super.stop(ch, position, true) && isDefaultPartition(position);
- }
-
- /*
- * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#nextPosition(int, boolean)
- */
- @Override
- public int nextPosition(int position, boolean forward) {
- ITypedRegion partition= getPartition(position);
- if (fPartition.equals(partition.getType()))
- return super.nextPosition(position, forward);
-
- if (forward) {
- int end= partition.getOffset() + partition.getLength();
- if (position < end)
- return end;
- } else {
- int offset= partition.getOffset();
- if (position > offset)
- return offset - 1;
- }
- return super.nextPosition(position, forward);
- }
- }
-
- /**
- * Stops upon a non-java identifier (as defined by {@link Character#isJavaIdentifierPart(char)}) character.
- */
- private static class NonJavaIdentifierPart extends StopCondition {
- /*
- * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#stop(char)
- */
- @Override
- public boolean stop(char ch, int position, boolean forward) {
- return !Character.isJavaIdentifierPart(ch);
- }
- }
-
- /**
- * Stops upon a non-java identifier character in the default partition.
- *
- * @see NonJavaIdentifierPart
- */
- private final class NonJavaIdentifierPartDefaultPartition extends NonJavaIdentifierPart {
- /*
- * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#stop(char)
- */
- @Override
- public boolean stop(char ch, int position, boolean forward) {
- return super.stop(ch, position, true) || !isDefaultPartition(position);
- }
-
- /*
- * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#nextPosition(int, boolean)
- */
- @Override
- public int nextPosition(int position, boolean forward) {
- ITypedRegion partition= getPartition(position);
- if (fPartition.equals(partition.getType()))
- return super.nextPosition(position, forward);
-
- if (forward) {
- int end= partition.getOffset() + partition.getLength();
- if (position < end)
- return end;
- } else {
- int offset= partition.getOffset();
- if (position > offset)
- return offset - 1;
- }
- return super.nextPosition(position, forward);
- }
- }
-
- /**
- * Stops upon a character in the default partition that matches the given character list.
- */
- private final class CharacterMatch extends StopCondition {
- private final char[] fChars;
-
- /**
- * Creates a new instance.
- * @param ch the single character to match
- */
- public CharacterMatch(char ch) {
- this(new char[] {ch});
- }
-
- /**
- * Creates a new instance.
- * @param chars the chars to match.
- */
- public CharacterMatch(char[] chars) {
- Assert.isNotNull(chars);
- Assert.isTrue(chars.length > 0);
- fChars= chars;
- Arrays.sort(chars);
- }
-
- /*
- * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#stop(char, int)
- */
- @Override
- public boolean stop(char ch, int position, boolean forward) {
- return Arrays.binarySearch(fChars, ch) >= 0 && isDefaultPartition(position);
- }
-
- /*
- * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#nextPosition(int, boolean)
- */
- @Override
- public int nextPosition(int position, boolean forward) {
- ITypedRegion partition= getPartition(position);
- if (fPartition.equals(partition.getType()))
- return super.nextPosition(position, forward);
-
- if (forward) {
- int end= partition.getOffset() + partition.getLength();
- if (position < end)
- return end;
- } else {
- int offset= partition.getOffset();
- if (position > offset)
- return offset - 1;
- }
- return super.nextPosition(position, forward);
- }
- }
-
- /** The document being scanned. */
- private final IDocument fDocument;
- /** The partitioning being used for scanning. */
- private final String fPartitioning;
- /** The partition to scan in. */
- private final String fPartition;
-
- /* internal scan state */
-
- /** the most recently read character. */
- private char fChar;
- /** the most recently read position. */
- private int fPos;
- /**
- * The most recently used partition.
- */
- private ITypedRegion fCachedPartition= new TypedRegion(-1, 0, "__no_partition_at_all"); //$NON-NLS-1$
-
- /* preset stop conditions */
- private final StopCondition fNonWSDefaultPart= new NonWhitespaceDefaultPartition();
- private static final StopCondition fNonWS= new NonWhitespace();
- private final StopCondition fNonIdent= new NonJavaIdentifierPartDefaultPartition();
-
- /**
- * Creates a new instance.
- *
- * @param document the document to scan
- * @param partitioning the partitioning to use for scanning
- * @param partition the partition to scan in
- */
- public STPHeuristicScanner(IDocument document, String partitioning, String partition) {
- Assert.isLegal(document != null);
- Assert.isLegal(partitioning != null);
- Assert.isLegal(partition != null);
- fDocument= document;
- fPartitioning= partitioning;
- fPartition= partition;
- }
-
- /**
- * Calls <code>this(document, STPPartitionScanner.STP_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE)</code>.
- *
- * @param document the document to scan.
- */
- public STPHeuristicScanner(IDocument document) {
- this(document, STPPartitionScanner.STP_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE);
- }
-
- /**
- * Returns the most recent internal scan position.
- *
- * @return the most recent internal scan position.
- */
- public int getPosition() {
- return fPos;
- }
-
- /**
- * Returns the next token in forward direction, starting at <code>start</code>, and not extending
- * further than <code>bound</code>. The return value is one of the constants defined in {@link STPSymbols}.
- * After a call, {@link #getPosition()} will return the position just after the scanned token
- * (i.e. the next position that will be scanned).
- *
- * @param start the first character position in the document to consider
- * @param bound the first position not to consider any more
- * @return a constant from {@link STPSymbols} describing the next token
- */
- public int nextToken(int start, int bound) {
- int pos= scanForward(start, bound, fNonWS);
- if (pos == NOT_FOUND)
- return TokenEOF;
- try {
- // check for string or char literal
- char ch = fDocument.getChar(pos);
- if (ch == '"' || ch == '\'') {
- fChar= ch;
- fPos= fNonWSDefaultPart.nextPosition(pos, true);
- return TokenOTHER;
- }
- } catch (BadLocationException exc) {
- }
- pos= scanForward(pos, bound, fNonWSDefaultPart);
- if (pos == NOT_FOUND)
- return TokenEOF;
-
- fPos++;
-
- switch (fChar) {
- case LBRACE:
- return TokenLBRACE;
- case RBRACE:
- return TokenRBRACE;
- case LBRACKET:
- return TokenLBRACKET;
- case RBRACKET:
- return TokenRBRACKET;
- case LPAREN:
- return TokenLPAREN;
- case RPAREN:
- return TokenRPAREN;
- case SEMICOLON:
- return TokenSEMICOLON;
- case COLON:
- switch (peekNextChar()) {
- case COLON:
- ++fPos;
- return TokenDOUBLECOLON;
- }
- return TokenCOLON;
- case COMMA:
- return TokenCOMMA;
- case QUESTIONMARK:
- return TokenQUESTIONMARK;
- case EQUAL:
- return TokenEQUAL;
- case LANGLE:
- switch (peekNextChar()) {
- case LANGLE:
- ++fPos;
- if (peekNextChar() == LANGLE) {
- ++fPos;
- return TokenAGGREGATE;
- }
- return TokenSHIFTLEFT;
- case EQUAL:
- ++fPos;
- return TokenOTHER;
- }
- return TokenLESSTHAN;
- case RANGLE:
- switch (peekNextChar()) {
- case RANGLE:
- ++fPos;
- return TokenSHIFTRIGHT;
- case EQUAL:
- ++fPos;
- return TokenOTHER;
- }
- return TokenGREATERTHAN;
- case DOT:
- return TokenDOT;
- case MINUS:
- switch (peekNextChar()) {
- case RANGLE:
- ++fPos;
- return TokenARROW;
- }
- return TokenMINUS;
- case PLUS:
- return TokenPLUS;
- case TILDE:
- return TokenTILDE;
- }
-
- // else
- if (Character.isJavaIdentifierPart(fChar)) {
- // assume an identifier or keyword
- int from= pos, to;
- pos= scanForward(pos + 1, bound, fNonIdent);
- if (pos == NOT_FOUND)
- to= bound == UNBOUND ? fDocument.getLength() : bound;
- else
- to= pos;
-
- String identOrKeyword;
- try {
- identOrKeyword= fDocument.get(from, to - from);
- } catch (BadLocationException e) {
- return TokenEOF;
- }
-
- return getToken(identOrKeyword);
-
-
- }
- // operators, number literals etc
- return TokenOTHER;
- }
-
- /**
- * Returns the next token in backward direction, starting at <code>start</code>, and not extending
- * further than <code>bound</code>. The return value is one of the constants defined in {@link STPSymbols}.
- * After a call, {@link #getPosition()} will return the position just before the scanned token
- * starts (i.e. the next position that will be scanned).
- *
- * @param start the first character position in the document to consider
- * @param bound the first position not to consider any more
- * @return a constant from {@link STPSymbols} describing the previous token
- */
- public int previousToken(int start, int bound) {
- int pos= scanBackward(start, bound, fNonWSDefaultPart);
- if (pos == NOT_FOUND)
- return TokenEOF;
-
- fPos--;
-
- switch (fChar) {
- case LBRACE:
- return TokenLBRACE;
- case RBRACE:
- return TokenRBRACE;
- case LBRACKET:
- return TokenLBRACKET;
- case RBRACKET:
- return TokenRBRACKET;
- case LPAREN:
- return TokenLPAREN;
- case RPAREN:
- return TokenRPAREN;
- case SEMICOLON:
- return TokenSEMICOLON;
- case COLON:
- switch (peekPreviousChar()) {
- case COLON:
- --fPos;
- return TokenDOUBLECOLON;
- }
- return TokenCOLON;
- case COMMA:
- return TokenCOMMA;
- case QUESTIONMARK:
- return TokenQUESTIONMARK;
- case EQUAL:
- switch (peekPreviousChar()) {
- case RANGLE:
- case LANGLE:
- --fPos;
- return TokenOTHER;
- }
- return TokenEQUAL;
- case LANGLE:
- switch (peekPreviousChar()) {
- case LANGLE:
- --fPos;
- return TokenSHIFTLEFT;
- }
- return TokenLESSTHAN;
- case RANGLE:
- switch (peekPreviousChar()) {
- case RANGLE:
- --fPos;
- return TokenSHIFTRIGHT;
- case MINUS:
- --fPos;
- return TokenARROW;
- }
- return TokenGREATERTHAN;
- case DOT:
- return TokenDOT;
- case MINUS:
- return TokenMINUS;
- case PLUS:
- return TokenPLUS;
- case TILDE:
- return TokenTILDE;
- }
-
- // else
- if (Character.isJavaIdentifierPart(fChar)) {
- // assume an ident or keyword
- int from, to= pos + 1;
- pos= scanBackward(pos - 1, bound, fNonIdent);
- if (pos == NOT_FOUND)
- from= bound == UNBOUND ? 0 : bound + 1;
- else
- from= pos + 1;
-
- String identOrKeyword;
- try {
- identOrKeyword= fDocument.get(from, to - from);
- } catch (BadLocationException e) {
- return TokenEOF;
- }
-
- return getToken(identOrKeyword);
- }
- // operators, number literals etc
- return TokenOTHER;
- }
-
- /**
- * @return the next char without shifting the position
- */
- private char peekNextChar() {
- if (fPos + 1 < fDocument.getLength()) {
- try {
- return fDocument.getChar(fPos + 1);
- } catch (BadLocationException exc) {
- }
- }
- return (char)-1;
- }
-
- /**
- * @return the previous char without shifting the position
- */
- private char peekPreviousChar() {
- if (fPos >= 0) {
- try {
- return fDocument.getChar(fPos);
- } catch (BadLocationException e) {
- }
- }
- return (char)-1;
- }
-
- /**
- * Returns one of the keyword constants or <code>TokenIDENT</code> for a scanned identifier.
- *
- * @param s a scanned identifier
- * @return one of the constants defined in {@link STPSymbols}
- */
- private int getToken(String s) {
- Assert.isNotNull(s);
-
- switch (s.length()) {
- case 2:
- if ("if".equals(s)) //$NON-NLS-1$
- return TokenIF;
- if ("do".equals(s)) //$NON-NLS-1$
- return TokenDO;
- break;
- case 3:
- if ("for".equals(s)) //$NON-NLS-1$
- return TokenFOR;
- if ("try".equals(s)) //$NON-NLS-1$
- return TokenTRY;
- if ("new".equals(s)) //$NON-NLS-1$
- return TokenNEW;
- break;
- case 4:
- if ("case".equals(s)) //$NON-NLS-1$
- return TokenCASE;
- if ("else".equals(s)) //$NON-NLS-1$
- return TokenELSE;
- if ("enum".equals(s)) //$NON-NLS-1$
- return TokenENUM;
- if ("goto".equals(s)) //$NON-NLS-1$
- return TokenGOTO;
- break;
- case 5:
- if ("break".equals(s)) //$NON-NLS-1$
- return TokenBREAK;
- if ("catch".equals(s)) //$NON-NLS-1$
- return TokenCATCH;
- if ("class".equals(s)) //$NON-NLS-1$
- return TokenCLASS;
- if ("const".equals(s)) //$NON-NLS-1$
- return TokenCONST;
- if ("while".equals(s)) //$NON-NLS-1$
- return TokenWHILE;
- if ("union".equals(s)) //$NON-NLS-1$
- return TokenUNION;
- if ("using".equals(s)) //$NON-NLS-1$
- return TokenUSING;
- if ("throw".equals(s)) //$NON-NLS-1$
- return TokenTHROW;
- break;
- case 6:
- if ("delete".equals(s)) //$NON-NLS-1$
- return TokenDELETE;
- if ("public".equals(s)) //$NON-NLS-1$
- return TokenPUBLIC;
- if ("return".equals(s)) //$NON-NLS-1$
- return TokenRETURN;
- if ("static".equals(s)) //$NON-NLS-1$
- return TokenSTATIC;
- if ("struct".equals(s)) //$NON-NLS-1$
- return TokenSTRUCT;
- if ("switch".equals(s)) //$NON-NLS-1$
- return TokenSWITCH;
- if ("extern".equals(s)) //$NON-NLS-1$
- return TokenEXTERN;
- break;
- case 7:
- if ("default".equals(s)) //$NON-NLS-1$
- return TokenDEFAULT;
- if ("foreach".equals(s)) //$NON-NLS-1$
- return TokenFOREACH;
- if ("private".equals(s)) //$NON-NLS-1$
- return TokenPRIVATE;
- if ("typedef".equals(s)) //$NON-NLS-1$
- return TokenTYPEDEF;
- if ("virtual".equals(s)) //$NON-NLS-1$
- return TokenVIRTUAL;
- break;
- case 8:
- if ("operator".equals(s)) //$NON-NLS-1$
- return TokenOPERATOR;
- if ("template".equals(s)) //$NON-NLS-1$
- return TokenTEMPLATE;
- if ("typename".equals(s)) //$NON-NLS-1$
- return TokenTYPENAME;
- break;
- case 9:
- if ("namespace".equals(s)) //$NON-NLS-1$
- return TokenNAMESPACE;
- if ("protected".equals(s)) //$NON-NLS-1$
- return TokenPROTECTED;
- }
- return TokenIDENT;
- }
-
- /**
- * Returns the position of the closing peer character (forward search). Any scopes introduced
- * by opening peers are skipped. All peers accounted for must reside in the default partition.
- *
- * <p>Note that <code>start</code> must not point to the opening peer, but to the first
- * character being searched.</p>
- *
- * @param start the start position
- * @param openingPeer the opening peer character (e.g. '{')
- * @param closingPeer the closing peer character (e.g. '}')
- * @return the matching peer character position, or <code>NOT_FOUND</code>
- */
- public int findClosingPeer(int start, final char openingPeer, final char closingPeer) {
- return findClosingPeer(start, UNBOUND, openingPeer, closingPeer);
- }
-
- /**
- * Returns the position of the closing peer character (forward search). Any scopes introduced by opening peers
- * are skipped. All peers accounted for must reside in the default partition.
- *
- * <p>Note that <code>start</code> must not point to the opening peer, but to the first
- * character being searched.</p>
- *
- * @param start the start position
- * @param bound the bound
- * @param openingPeer the opening peer character (e.g. '{')
- * @param closingPeer the closing peer character (e.g. '}')
- * @return the matching peer character position, or <code>NOT_FOUND</code>
- */
- private int findClosingPeer(int start, int bound, final char openingPeer, final char closingPeer) {
- Assert.isLegal(start >= 0);
-
- try {
- int depth= 1;
- start -= 1;
- while (true) {
- start= scanForward(start + 1, bound, new CharacterMatch(new char[] {openingPeer, closingPeer}));
- if (start == NOT_FOUND)
- return NOT_FOUND;
-
- if (fDocument.getChar(start) == openingPeer)
- depth++;
- else
- depth--;
-
- if (depth == 0)
- return start;
- }
-
- } catch (BadLocationException e) {
- return NOT_FOUND;
- }
- }
-
- /**
- * Returns the position of the opening peer character (backward search). Any scopes introduced by closing peers
- * are skipped. All peers accounted for must reside in the default partition.
- *
- * <p>Note that <code>start</code> must not point to the closing peer, but to the first
- * character being searched.</p>
- *
- * @param start the start position
- * @param openingPeer the opening peer character (e.g. '{')
- * @param closingPeer the closing peer character (e.g. '}')
- * @return the matching peer character position, or <code>NOT_FOUND</code>
- */
- public int findOpeningPeer(int start, char openingPeer, char closingPeer) {
- return findOpeningPeer(start, STPHeuristicScanner.UNBOUND, openingPeer, closingPeer);
- }
-
- /**
- * Returns the position of the opening peer character (backward search). Any scopes introduced by closing peers
- * are skipped. All peers accounted for must reside in the default partition.
- *
- * <p>Note that <code>start</code> must not point to the closing peer, but to the first
- * character being searched.</p>
- *
- * @param start the start position
- * @param bound the bound
- * @param openingPeer the opening peer character (e.g. '{')
- * @param closingPeer the closing peer character (e.g. '}')
- * @return the matching peer character position, or <code>NOT_FOUND</code>
- */
- public int findOpeningPeer(int start, int bound, char openingPeer, char closingPeer) {
- Assert.isLegal(start < fDocument.getLength());
-
- try {
- final CharacterMatch match= new CharacterMatch(new char[] {openingPeer, closingPeer});
- int depth= 1;
- start += 1;
- while (true) {
- start= scanBackward(start - 1, bound, match);
- if (start == NOT_FOUND)
- return NOT_FOUND;
-
- if (fDocument.getChar(start) == closingPeer)
- depth++;
- else
- depth--;
-
- if (depth == 0)
- return start;
- }
-
- } catch (BadLocationException e) {
- return NOT_FOUND;
- }
- }
-
- /**
- * Finds the smallest position in <code>fDocument</code> such that the position is &gt;= <code>position</code>
- * and &lt; <code>bound</code> and <code>Character.isWhitespace(fDocument.getChar(pos))</code> evaluates to <code>false</code>.
- *
- * @param position the first character position in <code>fDocument</code> to be considered
- * @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> &gt; <code>position</code>, or <code>UNBOUND</code>
- * @return the smallest position of a non-whitespace character in [<code>position</code>, <code>bound</code>), or <code>NOT_FOUND</code> if none can be found
- */
- public int findNonWhitespaceForwardInAnyPartition(int position, int bound) {
- return scanForward(position, bound, fNonWS);
- }
-
- /**
- * Finds the highest position in <code>fDocument</code> such that the position is &lt;= <code>position</code>
- * and &gt; <code>bound</code> and <code>Character.isWhitespace(fDocument.getChar(pos))</code> evaluates to <code>false</code>
- * and the position is in the default partition.
- *
- * @param position the first character position in <code>fDocument</code> to be considered
- * @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> &lt; <code>position</code>, or <code>UNBOUND</code>
- * @return the highest position of a non-whitespace character in (<code>bound</code>, <code>position</code>] that resides in a C partition, or <code>NOT_FOUND</code> if none can be found
- */
- public int findNonWhitespaceBackward(int position, int bound) {
- return scanBackward(position, bound, fNonWSDefaultPart);
- }
-
- /**
- * Finds the lowest position <code>p</code> in <code>fDocument</code> such that <code>start</code> &lt;= p &lt;
- * <code>bound</code> and <code>condition.stop(fDocument.getChar(p), p)</code> evaluates to <code>true</code>.
- *
- * @param start the first character position in <code>fDocument</code> to be considered
- * @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> &gt; <code>start</code>, or <code>UNBOUND</code>
- * @param condition the <code>StopCondition</code> to check
- * @return the lowest position in [<code>start</code>, <code>bound</code>) for which <code>condition</code> holds, or <code>NOT_FOUND</code> if none can be found
- */
- private int scanForward(int start, int bound, StopCondition condition) {
- Assert.isLegal(start >= 0);
-
- if (bound == UNBOUND)
- bound= fDocument.getLength();
-
- Assert.isLegal(bound <= fDocument.getLength());
-
- try {
- fPos= start;
- while (fPos < bound) {
-
- fChar= fDocument.getChar(fPos);
- if (condition.stop(fChar, fPos, true))
- return fPos;
-
- fPos= condition.nextPosition(fPos, true);
- }
- } catch (BadLocationException e) {
- }
- return NOT_FOUND;
- }
-
-
- /**
- * Finds the lowest position in <code>fDocument</code> such that the position is &gt;= <code>position</code>
- * and &lt; <code>bound</code> and <code>fDocument.getChar(position) == ch</code> evaluates to <code>true</code>
- * and the position is in the default partition.
- *
- * @param position the first character position in <code>fDocument</code> to be considered
- * @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> &gt; <code>position</code>, or <code>UNBOUND</code>
- * @param ch the <code>char</code> to search for
- * @return the lowest position of <code>ch</code> in (<code>bound</code>, <code>position</code>] that resides in a C partition, or <code>NOT_FOUND</code> if none can be found
- */
- public int scanForward(int position, int bound, char ch) {
- return scanForward(position, bound, new CharacterMatch(ch));
- }
-
- /**
- * Finds the highest position <code>p</code> in <code>fDocument</code> such that <code>bound</code> &lt; <code>p</code> &lt;= <code>start</code>
- * and <code>condition.stop(fDocument.getChar(p), p)</code> evaluates to <code>true</code>.
- *
- * @param start the first character position in <code>fDocument</code> to be considered
- * @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> &lt; <code>start</code>, or <code>UNBOUND</code>
- * @param condition the <code>StopCondition</code> to check
- * @return the highest position in (<code>bound</code>, <code>start</code> for which <code>condition</code> holds, or <code>NOT_FOUND</code> if none can be found
- */
- private int scanBackward(int start, int bound, StopCondition condition) {
- if (bound == UNBOUND)
- bound= -1;
-
- Assert.isLegal(bound >= -1);
- Assert.isLegal(start < fDocument.getLength() );
-
- try {
- fPos= start;
- while (fPos > bound) {
-
- fChar= fDocument.getChar(fPos);
- if (condition.stop(fChar, fPos, false))
- return fPos;
-
- fPos= condition.nextPosition(fPos, false);
- }
- } catch (BadLocationException e) {
- }
- return NOT_FOUND;
- }
-
- /**
- * Checks whether <code>position</code> resides in a default (C) partition of <code>fDocument</code>.
- *
- * @param position the position to be checked
- * @return <code>true</code> if <code>position</code> is in the default partition of <code>fDocument</code>, <code>false</code> otherwise
- */
- private boolean isDefaultPartition(int position) {
- String type = getPartition(position).getType();
- return fPartition.equals(type);
- }
-
- /**
- * Returns the partition at <code>position</code>.
- *
- * @param position the position to get the partition for
- * @return the partition at <code>position</code> or a dummy zero-length
- * partition if accessing the document fails
- */
- private ITypedRegion getPartition(int position) {
- if (!contains(fCachedPartition, position)) {
- Assert.isTrue(position >= 0);
- Assert.isTrue(position <= fDocument.getLength());
-
- try {
- fCachedPartition= TextUtilities.getPartition(fDocument, fPartitioning, position, false);
- } catch (BadLocationException e) {
- fCachedPartition= new TypedRegion(position, 0, "__no_partition_at_all"); //$NON-NLS-1$
- }
- }
-
- return fCachedPartition;
- }
-
- /**
- * Returns <code>true</code> if <code>region</code> contains <code>position</code>.
- *
- * @param region a region
- * @param position an offset
- * @return <code>true</code> if <code>region</code> contains <code>position</code>
- */
- private boolean contains(IRegion region, int position) {
- int offset= region.getOffset();
- return offset <= position && position < offset + region.getLength();
- }
-
- /**
- * Checks if the line seems to be an open condition not followed by a block (i.e. an if, while,
- * or for statement with just one following statement, see example below).
- *
- * <pre>
- * if (condition)
- * doStuff();
- * </pre>
- *
- * <p>Algorithm: if the last non-WS, non-Comment code on the line is an if (condition), while (condition),
- * for( expression), do, else, and there is no statement after that </p>
- *
- * @param position the insert position of the new character
- * @param bound the lowest position to consider
- * @return <code>true</code> if the code is a conditional statement or loop without a block, <code>false</code> otherwise
- */
- public boolean isBracelessBlockStart(int position, int bound) {
- if (position < 1)
- return false;
-
- switch (previousToken(position, bound)) {
- case TokenDO:
- case TokenELSE:
- return true;
- case TokenRPAREN:
- position= findOpeningPeer(fPos, STPHeuristicScanner.UNBOUND, LPAREN, RPAREN);
- if (position > 0) {
- switch (previousToken(position - 1, bound)) {
- case TokenIF:
- case TokenFOR:
- case TokenFOREACH:
- case TokenWHILE:
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Returns <code>true</code> if the document, when scanned backwards from <code>start</code>
- * appears to be a composite type (class, struct, union) or enum definition. Examples:
- *
- * <pre>
- * class A {
- * struct A {
- * class A : B {
- * class A : virtual public B, protected C&lt;T&gt; {
- * enum E {
- * </pre>
- *
- * @param start the position of the opening brace.
- * @param bound the first position in <code>fDocument</code> to not consider any more, with
- * <code>bound</code> &lt; <code>start</code>, or <code>UNBOUND</code>
- * @return <code>true</code> if the current position looks like a composite type definition
- */
- public boolean looksLikeCompositeTypeDefinitionBackward(int start, int bound) {
- int token= previousToken(start - 1, bound);
- switch (token) {
- case STPSymbols.TokenSTRUCT:
- case STPSymbols.TokenUNION:
- case STPSymbols.TokenENUM:
- return true; // anonymous
- case STPSymbols.TokenIDENT:
- token= previousToken(getPosition(), bound);
- switch (token) {
- case STPSymbols.TokenCLASS:
- case STPSymbols.TokenSTRUCT:
- case STPSymbols.TokenUNION:
- case STPSymbols.TokenENUM:
- return true; // no base-clause
- default:
- // backtrack
- token= previousToken(start - 1, bound);
- }
- break;
- default:
- // backtrack
- token= previousToken(start - 1, bound);
- break;
- }
- // match base-clause
- if (token == STPSymbols.TokenGREATERTHAN) {
- findOpeningPeer(getPosition(), bound, '<', '>');
- token= previousToken(getPosition(), bound);
- if (token != STPSymbols.TokenLESSTHAN) {
- return false;
- }
- token= previousToken(getPosition(), bound);
- }
- outerWhile: while (token == STPSymbols.TokenIDENT) {// type name or base type
- token= previousToken(getPosition(), bound);
- // match nested-name-specifier
- while (token == STPSymbols.TokenCOLON) { // colon of qualification
- token= previousToken(getPosition(), bound);
- if (token != STPSymbols.TokenCOLON) { // second colon of qualification
- break outerWhile;
- }
- token= previousToken(getPosition(), bound);
- if (token != STPSymbols.TokenIDENT) // qualification name?
- break;
- token= previousToken(getPosition(), bound);
- }
- switch (token) {
- case STPSymbols.TokenVIRTUAL:
- token= previousToken(getPosition(), bound);
- //$FALL-THROUGH$
- case STPSymbols.TokenPUBLIC:
- case STPSymbols.TokenPROTECTED:
- case STPSymbols.TokenPRIVATE:
- token= previousToken(getPosition(), bound);
- if (token == STPSymbols.TokenVIRTUAL) {
- token= previousToken(getPosition(), bound);
- }
- if (token == STPSymbols.TokenCOMMA) {
- token= previousToken(getPosition(), bound);
- if (token == STPSymbols.TokenGREATERTHAN) {
- findOpeningPeer(getPosition(), bound, '<', '>');
- token= previousToken(getPosition(), bound);
- if (token != STPSymbols.TokenLESSTHAN) {
- return false;
- }
- token= previousToken(getPosition(), bound);
- }
- continue; // another base type
- }
- if (token != STPSymbols.TokenCOLON) // colon after class def identifier
- return false;
- //$FALL-THROUGH$
- case STPSymbols.TokenCOLON:
- token= previousToken(getPosition(), bound);
- break outerWhile;
- case STPSymbols.TokenCOMMA:
- token= previousToken(getPosition(), bound);
- if (token == STPSymbols.TokenGREATERTHAN) {
- findOpeningPeer(getPosition(), bound, '<', '>');
- token= previousToken(getPosition(), bound);
- if (token != STPSymbols.TokenLESSTHAN) {
- return false;
- }
- token= previousToken(getPosition(), bound);
- }
- continue; // another base type
- case STPSymbols.TokenIDENT:
- break outerWhile;
- default:
- return false;
- }
- }
- if (token != STPSymbols.TokenIDENT) {
- return false;
- }
- token= previousToken(getPosition(), bound);
- switch (token) {
- case STPSymbols.TokenCLASS:
- case STPSymbols.TokenSTRUCT:
- case STPSymbols.TokenUNION:
- case STPSymbols.TokenENUM: // enum is actually not valid here
- return true;
- default:
- return false;
- }
- }
+ /**
+ * Returned by all methods when the requested position could not be found, or if a
+ * {@link BadLocationException} was thrown while scanning.
+ */
+ public static final int NOT_FOUND= -1;
+
+ /**
+ * Special bound parameter that means either -1 (backward scanning) or
+ * <code>fDocument.getLength()</code> (forward scanning).
+ */
+ public static final int UNBOUND= -2;
+
+
+ /* character constants */
+ private static final char LBRACE= '{';
+ private static final char RBRACE= '}';
+ private static final char LPAREN= '(';
+ private static final char RPAREN= ')';
+ private static final char SEMICOLON= ';';
+ private static final char COLON= ':';
+ private static final char COMMA= ',';
+ private static final char LBRACKET= '[';
+ private static final char RBRACKET= ']';
+ private static final char QUESTIONMARK= '?';
+ private static final char EQUAL= '=';
+ private static final char LANGLE= '<';
+ private static final char RANGLE= '>';
+ private static final char DOT= '.';
+ private static final char MINUS= '-';
+ private static final char PLUS= '+';
+ private static final char TILDE= '~';
+
+ /**
+ * Specifies the stop condition, upon which the <code>scanXXX</code> methods will decide whether
+ * to keep scanning or not. This interface may implemented by clients.
+ */
+ private static abstract class StopCondition {
+ /**
+ * Instructs the scanner to return the current position.
+ *
+ * @param ch the char at the current position
+ * @param position the current position
+ * @param forward the iteration direction
+ * @return <code>true</code> if the stop condition is met.
+ */
+ public abstract boolean stop(char ch, int position, boolean forward);
+
+ /**
+ * Asks the condition to return the next position to query. The default
+ * is to return the next/previous position.
+ *
+ * @return the next position to scan
+ */
+ public int nextPosition(int position, boolean forward) {
+ return forward ? position + 1 : position - 1;
+ }
+ }
+
+ /**
+ * Stops upon a non-whitespace (as defined by {@link Character#isWhitespace(char)}) character.
+ */
+ private static class NonWhitespace extends StopCondition {
+ /*
+ * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#stop(char)
+ */
+ @Override
+ public boolean stop(char ch, int position, boolean forward) {
+ return !Character.isWhitespace(ch);
+ }
+ }
+
+ /**
+ * Stops upon a non-whitespace character in the default partition.
+ *
+ * @see NonWhitespace
+ */
+ private final class NonWhitespaceDefaultPartition extends NonWhitespace {
+ /*
+ * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#stop(char)
+ */
+ @Override
+ public boolean stop(char ch, int position, boolean forward) {
+ return super.stop(ch, position, true) && isDefaultPartition(position);
+ }
+
+ /*
+ * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#nextPosition(int, boolean)
+ */
+ @Override
+ public int nextPosition(int position, boolean forward) {
+ ITypedRegion partition= getPartition(position);
+ if (fPartition.equals(partition.getType()))
+ return super.nextPosition(position, forward);
+
+ if (forward) {
+ int end= partition.getOffset() + partition.getLength();
+ if (position < end)
+ return end;
+ } else {
+ int offset= partition.getOffset();
+ if (position > offset)
+ return offset - 1;
+ }
+ return super.nextPosition(position, forward);
+ }
+ }
+
+ /**
+ * Stops upon a non-java identifier (as defined by {@link Character#isJavaIdentifierPart(char)}) character.
+ */
+ private static class NonJavaIdentifierPart extends StopCondition {
+ /*
+ * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#stop(char)
+ */
+ @Override
+ public boolean stop(char ch, int position, boolean forward) {
+ return !Character.isJavaIdentifierPart(ch);
+ }
+ }
+
+ /**
+ * Stops upon a non-java identifier character in the default partition.
+ *
+ * @see NonJavaIdentifierPart
+ */
+ private final class NonJavaIdentifierPartDefaultPartition extends NonJavaIdentifierPart {
+ /*
+ * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#stop(char)
+ */
+ @Override
+ public boolean stop(char ch, int position, boolean forward) {
+ return super.stop(ch, position, true) || !isDefaultPartition(position);
+ }
+
+ /*
+ * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#nextPosition(int, boolean)
+ */
+ @Override
+ public int nextPosition(int position, boolean forward) {
+ ITypedRegion partition= getPartition(position);
+ if (fPartition.equals(partition.getType()))
+ return super.nextPosition(position, forward);
+
+ if (forward) {
+ int end= partition.getOffset() + partition.getLength();
+ if (position < end)
+ return end;
+ } else {
+ int offset= partition.getOffset();
+ if (position > offset)
+ return offset - 1;
+ }
+ return super.nextPosition(position, forward);
+ }
+ }
+
+ /**
+ * Stops upon a character in the default partition that matches the given character list.
+ */
+ private final class CharacterMatch extends StopCondition {
+ private final char[] fChars;
+
+ /**
+ * Creates a new instance.
+ * @param ch the single character to match
+ */
+ public CharacterMatch(char ch) {
+ this(new char[] {ch});
+ }
+
+ /**
+ * Creates a new instance.
+ * @param chars the chars to match.
+ */
+ public CharacterMatch(char[] chars) {
+ Assert.isNotNull(chars);
+ Assert.isTrue(chars.length > 0);
+ fChars= chars;
+ Arrays.sort(chars);
+ }
+
+ /*
+ * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#stop(char, int)
+ */
+ @Override
+ public boolean stop(char ch, int position, boolean forward) {
+ return Arrays.binarySearch(fChars, ch) >= 0 && isDefaultPartition(position);
+ }
+
+ /*
+ * @see org.eclipse.cdt.internal.ui.text.CHeuristicScanner.StopCondition#nextPosition(int, boolean)
+ */
+ @Override
+ public int nextPosition(int position, boolean forward) {
+ ITypedRegion partition= getPartition(position);
+ if (fPartition.equals(partition.getType()))
+ return super.nextPosition(position, forward);
+
+ if (forward) {
+ int end= partition.getOffset() + partition.getLength();
+ if (position < end)
+ return end;
+ } else {
+ int offset= partition.getOffset();
+ if (position > offset)
+ return offset - 1;
+ }
+ return super.nextPosition(position, forward);
+ }
+ }
+
+ /** The document being scanned. */
+ private final IDocument fDocument;
+ /** The partitioning being used for scanning. */
+ private final String fPartitioning;
+ /** The partition to scan in. */
+ private final String fPartition;
+
+ /* internal scan state */
+
+ /** the most recently read character. */
+ private char fChar;
+ /** the most recently read position. */
+ private int fPos;
+ /**
+ * The most recently used partition.
+ */
+ private ITypedRegion fCachedPartition= new TypedRegion(-1, 0, "__no_partition_at_all"); //$NON-NLS-1$
+
+ /* preset stop conditions */
+ private final StopCondition fNonWSDefaultPart= new NonWhitespaceDefaultPartition();
+ private static final StopCondition fNonWS= new NonWhitespace();
+ private final StopCondition fNonIdent= new NonJavaIdentifierPartDefaultPartition();
+
+ /**
+ * Creates a new instance.
+ *
+ * @param document the document to scan
+ * @param partitioning the partitioning to use for scanning
+ * @param partition the partition to scan in
+ */
+ public STPHeuristicScanner(IDocument document, String partitioning, String partition) {
+ Assert.isLegal(document != null);
+ Assert.isLegal(partitioning != null);
+ Assert.isLegal(partition != null);
+ fDocument= document;
+ fPartitioning= partitioning;
+ fPartition= partition;
+ }
+
+ /**
+ * Calls <code>this(document, STPPartitionScanner.STP_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE)</code>.
+ *
+ * @param document the document to scan.
+ */
+ public STPHeuristicScanner(IDocument document) {
+ this(document, STPPartitionScanner.STP_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE);
+ }
+
+ /**
+ * Returns the most recent internal scan position.
+ *
+ * @return the most recent internal scan position.
+ */
+ public int getPosition() {
+ return fPos;
+ }
+
+ /**
+ * Returns the next token in forward direction, starting at <code>start</code>, and not extending
+ * further than <code>bound</code>. The return value is one of the constants defined in {@link STPSymbols}.
+ * After a call, {@link #getPosition()} will return the position just after the scanned token
+ * (i.e. the next position that will be scanned).
+ *
+ * @param start the first character position in the document to consider
+ * @param bound the first position not to consider any more
+ * @return a constant from {@link STPSymbols} describing the next token
+ */
+ public int nextToken(int start, int bound) {
+ int pos= scanForward(start, bound, fNonWS);
+ if (pos == NOT_FOUND)
+ return TokenEOF;
+ try {
+ // check for string or char literal
+ char ch = fDocument.getChar(pos);
+ if (ch == '"' || ch == '\'') {
+ fChar= ch;
+ fPos= fNonWSDefaultPart.nextPosition(pos, true);
+ return TokenOTHER;
+ }
+ } catch (BadLocationException exc) {
+ }
+ pos= scanForward(pos, bound, fNonWSDefaultPart);
+ if (pos == NOT_FOUND)
+ return TokenEOF;
+
+ fPos++;
+
+ switch (fChar) {
+ case LBRACE:
+ return TokenLBRACE;
+ case RBRACE:
+ return TokenRBRACE;
+ case LBRACKET:
+ return TokenLBRACKET;
+ case RBRACKET:
+ return TokenRBRACKET;
+ case LPAREN:
+ return TokenLPAREN;
+ case RPAREN:
+ return TokenRPAREN;
+ case SEMICOLON:
+ return TokenSEMICOLON;
+ case COLON:
+ switch (peekNextChar()) {
+ case COLON:
+ ++fPos;
+ return TokenDOUBLECOLON;
+ }
+ return TokenCOLON;
+ case COMMA:
+ return TokenCOMMA;
+ case QUESTIONMARK:
+ return TokenQUESTIONMARK;
+ case EQUAL:
+ return TokenEQUAL;
+ case LANGLE:
+ switch (peekNextChar()) {
+ case LANGLE:
+ ++fPos;
+ if (peekNextChar() == LANGLE) {
+ ++fPos;
+ return TokenAGGREGATE;
+ }
+ return TokenSHIFTLEFT;
+ case EQUAL:
+ ++fPos;
+ return TokenOTHER;
+ }
+ return TokenLESSTHAN;
+ case RANGLE:
+ switch (peekNextChar()) {
+ case RANGLE:
+ ++fPos;
+ return TokenSHIFTRIGHT;
+ case EQUAL:
+ ++fPos;
+ return TokenOTHER;
+ }
+ return TokenGREATERTHAN;
+ case DOT:
+ return TokenDOT;
+ case MINUS:
+ switch (peekNextChar()) {
+ case RANGLE:
+ ++fPos;
+ return TokenARROW;
+ }
+ return TokenMINUS;
+ case PLUS:
+ return TokenPLUS;
+ case TILDE:
+ return TokenTILDE;
+ }
+
+ // else
+ if (Character.isJavaIdentifierPart(fChar)) {
+ // assume an identifier or keyword
+ int from= pos, to;
+ pos= scanForward(pos + 1, bound, fNonIdent);
+ if (pos == NOT_FOUND)
+ to= bound == UNBOUND ? fDocument.getLength() : bound;
+ else
+ to= pos;
+
+ String identOrKeyword;
+ try {
+ identOrKeyword= fDocument.get(from, to - from);
+ } catch (BadLocationException e) {
+ return TokenEOF;
+ }
+
+ return getToken(identOrKeyword);
+
+
+ }
+ // operators, number literals etc
+ return TokenOTHER;
+ }
+
+ /**
+ * Returns the next token in backward direction, starting at <code>start</code>, and not extending
+ * further than <code>bound</code>. The return value is one of the constants defined in {@link STPSymbols}.
+ * After a call, {@link #getPosition()} will return the position just before the scanned token
+ * starts (i.e. the next position that will be scanned).
+ *
+ * @param start the first character position in the document to consider
+ * @param bound the first position not to consider any more
+ * @return a constant from {@link STPSymbols} describing the previous token
+ */
+ public int previousToken(int start, int bound) {
+ int pos= scanBackward(start, bound, fNonWSDefaultPart);
+ if (pos == NOT_FOUND)
+ return TokenEOF;
+
+ fPos--;
+
+ switch (fChar) {
+ case LBRACE:
+ return TokenLBRACE;
+ case RBRACE:
+ return TokenRBRACE;
+ case LBRACKET:
+ return TokenLBRACKET;
+ case RBRACKET:
+ return TokenRBRACKET;
+ case LPAREN:
+ return TokenLPAREN;
+ case RPAREN:
+ return TokenRPAREN;
+ case SEMICOLON:
+ return TokenSEMICOLON;
+ case COLON:
+ switch (peekPreviousChar()) {
+ case COLON:
+ --fPos;
+ return TokenDOUBLECOLON;
+ }
+ return TokenCOLON;
+ case COMMA:
+ return TokenCOMMA;
+ case QUESTIONMARK:
+ return TokenQUESTIONMARK;
+ case EQUAL:
+ switch (peekPreviousChar()) {
+ case RANGLE:
+ case LANGLE:
+ --fPos;
+ return TokenOTHER;
+ }
+ return TokenEQUAL;
+ case LANGLE:
+ switch (peekPreviousChar()) {
+ case LANGLE:
+ --fPos;
+ return TokenSHIFTLEFT;
+ }
+ return TokenLESSTHAN;
+ case RANGLE:
+ switch (peekPreviousChar()) {
+ case RANGLE:
+ --fPos;
+ return TokenSHIFTRIGHT;
+ case MINUS:
+ --fPos;
+ return TokenARROW;
+ }
+ return TokenGREATERTHAN;
+ case DOT:
+ return TokenDOT;
+ case MINUS:
+ return TokenMINUS;
+ case PLUS:
+ return TokenPLUS;
+ case TILDE:
+ return TokenTILDE;
+ }
+
+ // else
+ if (Character.isJavaIdentifierPart(fChar)) {
+ // assume an ident or keyword
+ int from, to= pos + 1;
+ pos= scanBackward(pos - 1, bound, fNonIdent);
+ if (pos == NOT_FOUND)
+ from= bound == UNBOUND ? 0 : bound + 1;
+ else
+ from= pos + 1;
+
+ String identOrKeyword;
+ try {
+ identOrKeyword= fDocument.get(from, to - from);
+ } catch (BadLocationException e) {
+ return TokenEOF;
+ }
+
+ return getToken(identOrKeyword);
+ }
+ // operators, number literals etc
+ return TokenOTHER;
+ }
+
+ /**
+ * @return the next char without shifting the position
+ */
+ private char peekNextChar() {
+ if (fPos + 1 < fDocument.getLength()) {
+ try {
+ return fDocument.getChar(fPos + 1);
+ } catch (BadLocationException exc) {
+ }
+ }
+ return (char)-1;
+ }
+
+ /**
+ * @return the previous char without shifting the position
+ */
+ private char peekPreviousChar() {
+ if (fPos >= 0) {
+ try {
+ return fDocument.getChar(fPos);
+ } catch (BadLocationException e) {
+ }
+ }
+ return (char)-1;
+ }
+
+ /**
+ * Returns one of the keyword constants or <code>TokenIDENT</code> for a scanned identifier.
+ *
+ * @param s a scanned identifier
+ * @return one of the constants defined in {@link STPSymbols}
+ */
+ private int getToken(String s) {
+ Assert.isNotNull(s);
+
+ switch (s.length()) {
+ case 2:
+ if ("if".equals(s)) //$NON-NLS-1$
+ return TokenIF;
+ if ("do".equals(s)) //$NON-NLS-1$
+ return TokenDO;
+ break;
+ case 3:
+ if ("for".equals(s)) //$NON-NLS-1$
+ return TokenFOR;
+ if ("try".equals(s)) //$NON-NLS-1$
+ return TokenTRY;
+ if ("new".equals(s)) //$NON-NLS-1$
+ return TokenNEW;
+ break;
+ case 4:
+ if ("case".equals(s)) //$NON-NLS-1$
+ return TokenCASE;
+ if ("else".equals(s)) //$NON-NLS-1$
+ return TokenELSE;
+ if ("enum".equals(s)) //$NON-NLS-1$
+ return TokenENUM;
+ if ("goto".equals(s)) //$NON-NLS-1$
+ return TokenGOTO;
+ break;
+ case 5:
+ if ("break".equals(s)) //$NON-NLS-1$
+ return TokenBREAK;
+ if ("catch".equals(s)) //$NON-NLS-1$
+ return TokenCATCH;
+ if ("class".equals(s)) //$NON-NLS-1$
+ return TokenCLASS;
+ if ("const".equals(s)) //$NON-NLS-1$
+ return TokenCONST;
+ if ("while".equals(s)) //$NON-NLS-1$
+ return TokenWHILE;
+ if ("union".equals(s)) //$NON-NLS-1$
+ return TokenUNION;
+ if ("using".equals(s)) //$NON-NLS-1$
+ return TokenUSING;
+ if ("throw".equals(s)) //$NON-NLS-1$
+ return TokenTHROW;
+ break;
+ case 6:
+ if ("delete".equals(s)) //$NON-NLS-1$
+ return TokenDELETE;
+ if ("public".equals(s)) //$NON-NLS-1$
+ return TokenPUBLIC;
+ if ("return".equals(s)) //$NON-NLS-1$
+ return TokenRETURN;
+ if ("static".equals(s)) //$NON-NLS-1$
+ return TokenSTATIC;
+ if ("struct".equals(s)) //$NON-NLS-1$
+ return TokenSTRUCT;
+ if ("switch".equals(s)) //$NON-NLS-1$
+ return TokenSWITCH;
+ if ("extern".equals(s)) //$NON-NLS-1$
+ return TokenEXTERN;
+ break;
+ case 7:
+ if ("default".equals(s)) //$NON-NLS-1$
+ return TokenDEFAULT;
+ if ("foreach".equals(s)) //$NON-NLS-1$
+ return TokenFOREACH;
+ if ("private".equals(s)) //$NON-NLS-1$
+ return TokenPRIVATE;
+ if ("typedef".equals(s)) //$NON-NLS-1$
+ return TokenTYPEDEF;
+ if ("virtual".equals(s)) //$NON-NLS-1$
+ return TokenVIRTUAL;
+ break;
+ case 8:
+ if ("operator".equals(s)) //$NON-NLS-1$
+ return TokenOPERATOR;
+ if ("template".equals(s)) //$NON-NLS-1$
+ return TokenTEMPLATE;
+ if ("typename".equals(s)) //$NON-NLS-1$
+ return TokenTYPENAME;
+ break;
+ case 9:
+ if ("namespace".equals(s)) //$NON-NLS-1$
+ return TokenNAMESPACE;
+ if ("protected".equals(s)) //$NON-NLS-1$
+ return TokenPROTECTED;
+ }
+ return TokenIDENT;
+ }
+
+ /**
+ * Returns the position of the closing peer character (forward search). Any scopes introduced
+ * by opening peers are skipped. All peers accounted for must reside in the default partition.
+ *
+ * <p>Note that <code>start</code> must not point to the opening peer, but to the first
+ * character being searched.</p>
+ *
+ * @param start the start position
+ * @param openingPeer the opening peer character (e.g. '{')
+ * @param closingPeer the closing peer character (e.g. '}')
+ * @return the matching peer character position, or <code>NOT_FOUND</code>
+ */
+ public int findClosingPeer(int start, final char openingPeer, final char closingPeer) {
+ return findClosingPeer(start, UNBOUND, openingPeer, closingPeer);
+ }
+
+ /**
+ * Returns the position of the closing peer character (forward search). Any scopes introduced by opening peers
+ * are skipped. All peers accounted for must reside in the default partition.
+ *
+ * <p>Note that <code>start</code> must not point to the opening peer, but to the first
+ * character being searched.</p>
+ *
+ * @param start the start position
+ * @param bound the bound
+ * @param openingPeer the opening peer character (e.g. '{')
+ * @param closingPeer the closing peer character (e.g. '}')
+ * @return the matching peer character position, or <code>NOT_FOUND</code>
+ */
+ private int findClosingPeer(int start, int bound, final char openingPeer, final char closingPeer) {
+ Assert.isLegal(start >= 0);
+
+ try {
+ int depth= 1;
+ start -= 1;
+ while (true) {
+ start= scanForward(start + 1, bound, new CharacterMatch(new char[] {openingPeer, closingPeer}));
+ if (start == NOT_FOUND)
+ return NOT_FOUND;
+
+ if (fDocument.getChar(start) == openingPeer)
+ depth++;
+ else
+ depth--;
+
+ if (depth == 0)
+ return start;
+ }
+
+ } catch (BadLocationException e) {
+ return NOT_FOUND;
+ }
+ }
+
+ /**
+ * Returns the position of the opening peer character (backward search). Any scopes introduced by closing peers
+ * are skipped. All peers accounted for must reside in the default partition.
+ *
+ * <p>Note that <code>start</code> must not point to the closing peer, but to the first
+ * character being searched.</p>
+ *
+ * @param start the start position
+ * @param openingPeer the opening peer character (e.g. '{')
+ * @param closingPeer the closing peer character (e.g. '}')
+ * @return the matching peer character position, or <code>NOT_FOUND</code>
+ */
+ public int findOpeningPeer(int start, char openingPeer, char closingPeer) {
+ return findOpeningPeer(start, STPHeuristicScanner.UNBOUND, openingPeer, closingPeer);
+ }
+
+ /**
+ * Returns the position of the opening peer character (backward search). Any scopes introduced by closing peers
+ * are skipped. All peers accounted for must reside in the default partition.
+ *
+ * <p>Note that <code>start</code> must not point to the closing peer, but to the first
+ * character being searched.</p>
+ *
+ * @param start the start position
+ * @param bound the bound
+ * @param openingPeer the opening peer character (e.g. '{')
+ * @param closingPeer the closing peer character (e.g. '}')
+ * @return the matching peer character position, or <code>NOT_FOUND</code>
+ */
+ public int findOpeningPeer(int start, int bound, char openingPeer, char closingPeer) {
+ Assert.isLegal(start < fDocument.getLength());
+
+ try {
+ final CharacterMatch match= new CharacterMatch(new char[] {openingPeer, closingPeer});
+ int depth= 1;
+ start += 1;
+ while (true) {
+ start= scanBackward(start - 1, bound, match);
+ if (start == NOT_FOUND)
+ return NOT_FOUND;
+
+ if (fDocument.getChar(start) == closingPeer)
+ depth++;
+ else
+ depth--;
+
+ if (depth == 0)
+ return start;
+ }
+
+ } catch (BadLocationException e) {
+ return NOT_FOUND;
+ }
+ }
+
+ /**
+ * Finds the smallest position in <code>fDocument</code> such that the position is &gt;= <code>position</code>
+ * and &lt; <code>bound</code> and <code>Character.isWhitespace(fDocument.getChar(pos))</code> evaluates to <code>false</code>.
+ *
+ * @param position the first character position in <code>fDocument</code> to be considered
+ * @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> &gt; <code>position</code>, or <code>UNBOUND</code>
+ * @return the smallest position of a non-whitespace character in [<code>position</code>, <code>bound</code>), or <code>NOT_FOUND</code> if none can be found
+ */
+ public int findNonWhitespaceForwardInAnyPartition(int position, int bound) {
+ return scanForward(position, bound, fNonWS);
+ }
+
+ /**
+ * Finds the highest position in <code>fDocument</code> such that the position is &lt;= <code>position</code>
+ * and &gt; <code>bound</code> and <code>Character.isWhitespace(fDocument.getChar(pos))</code> evaluates to <code>false</code>
+ * and the position is in the default partition.
+ *
+ * @param position the first character position in <code>fDocument</code> to be considered
+ * @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> &lt; <code>position</code>, or <code>UNBOUND</code>
+ * @return the highest position of a non-whitespace character in (<code>bound</code>, <code>position</code>] that resides in a C partition, or <code>NOT_FOUND</code> if none can be found
+ */
+ public int findNonWhitespaceBackward(int position, int bound) {
+ return scanBackward(position, bound, fNonWSDefaultPart);
+ }
+
+ /**
+ * Finds the lowest position <code>p</code> in <code>fDocument</code> such that <code>start</code> &lt;= p &lt;
+ * <code>bound</code> and <code>condition.stop(fDocument.getChar(p), p)</code> evaluates to <code>true</code>.
+ *
+ * @param start the first character position in <code>fDocument</code> to be considered
+ * @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> &gt; <code>start</code>, or <code>UNBOUND</code>
+ * @param condition the <code>StopCondition</code> to check
+ * @return the lowest position in [<code>start</code>, <code>bound</code>) for which <code>condition</code> holds, or <code>NOT_FOUND</code> if none can be found
+ */
+ private int scanForward(int start, int bound, StopCondition condition) {
+ Assert.isLegal(start >= 0);
+
+ if (bound == UNBOUND)
+ bound= fDocument.getLength();
+
+ Assert.isLegal(bound <= fDocument.getLength());
+
+ try {
+ fPos= start;
+ while (fPos < bound) {
+
+ fChar= fDocument.getChar(fPos);
+ if (condition.stop(fChar, fPos, true))
+ return fPos;
+
+ fPos= condition.nextPosition(fPos, true);
+ }
+ } catch (BadLocationException e) {
+ }
+ return NOT_FOUND;
+ }
+
+
+ /**
+ * Finds the lowest position in <code>fDocument</code> such that the position is &gt;= <code>position</code>
+ * and &lt; <code>bound</code> and <code>fDocument.getChar(position) == ch</code> evaluates to <code>true</code>
+ * and the position is in the default partition.
+ *
+ * @param position the first character position in <code>fDocument</code> to be considered
+ * @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> &gt; <code>position</code>, or <code>UNBOUND</code>
+ * @param ch the <code>char</code> to search for
+ * @return the lowest position of <code>ch</code> in (<code>bound</code>, <code>position</code>] that resides in a C partition, or <code>NOT_FOUND</code> if none can be found
+ */
+ public int scanForward(int position, int bound, char ch) {
+ return scanForward(position, bound, new CharacterMatch(ch));
+ }
+
+ /**
+ * Finds the highest position <code>p</code> in <code>fDocument</code> such that <code>bound</code> &lt; <code>p</code> &lt;= <code>start</code>
+ * and <code>condition.stop(fDocument.getChar(p), p)</code> evaluates to <code>true</code>.
+ *
+ * @param start the first character position in <code>fDocument</code> to be considered
+ * @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> &lt; <code>start</code>, or <code>UNBOUND</code>
+ * @param condition the <code>StopCondition</code> to check
+ * @return the highest position in (<code>bound</code>, <code>start</code> for which <code>condition</code> holds, or <code>NOT_FOUND</code> if none can be found
+ */
+ private int scanBackward(int start, int bound, StopCondition condition) {
+ if (bound == UNBOUND)
+ bound= -1;
+
+ Assert.isLegal(bound >= -1);
+ Assert.isLegal(start < fDocument.getLength() );
+
+ try {
+ fPos= start;
+ while (fPos > bound) {
+
+ fChar= fDocument.getChar(fPos);
+ if (condition.stop(fChar, fPos, false))
+ return fPos;
+
+ fPos= condition.nextPosition(fPos, false);
+ }
+ } catch (BadLocationException e) {
+ }
+ return NOT_FOUND;
+ }
+
+ /**
+ * Checks whether <code>position</code> resides in a default (C) partition of <code>fDocument</code>.
+ *
+ * @param position the position to be checked
+ * @return <code>true</code> if <code>position</code> is in the default partition of <code>fDocument</code>, <code>false</code> otherwise
+ */
+ private boolean isDefaultPartition(int position) {
+ String type = getPartition(position).getType();
+ return fPartition.equals(type);
+ }
+
+ /**
+ * Returns the partition at <code>position</code>.
+ *
+ * @param position the position to get the partition for
+ * @return the partition at <code>position</code> or a dummy zero-length
+ * partition if accessing the document fails
+ */
+ private ITypedRegion getPartition(int position) {
+ if (!contains(fCachedPartition, position)) {
+ Assert.isTrue(position >= 0);
+ Assert.isTrue(position <= fDocument.getLength());
+
+ try {
+ fCachedPartition= TextUtilities.getPartition(fDocument, fPartitioning, position, false);
+ } catch (BadLocationException e) {
+ fCachedPartition= new TypedRegion(position, 0, "__no_partition_at_all"); //$NON-NLS-1$
+ }
+ }
+
+ return fCachedPartition;
+ }
+
+ /**
+ * Returns <code>true</code> if <code>region</code> contains <code>position</code>.
+ *
+ * @param region a region
+ * @param position an offset
+ * @return <code>true</code> if <code>region</code> contains <code>position</code>
+ */
+ private boolean contains(IRegion region, int position) {
+ int offset= region.getOffset();
+ return offset <= position && position < offset + region.getLength();
+ }
+
+ /**
+ * Checks if the line seems to be an open condition not followed by a block (i.e. an if, while,
+ * or for statement with just one following statement, see example below).
+ *
+ * <pre>
+ * if (condition)
+ * doStuff();
+ * </pre>
+ *
+ * <p>Algorithm: if the last non-WS, non-Comment code on the line is an if (condition), while (condition),
+ * for( expression), do, else, and there is no statement after that </p>
+ *
+ * @param position the insert position of the new character
+ * @param bound the lowest position to consider
+ * @return <code>true</code> if the code is a conditional statement or loop without a block, <code>false</code> otherwise
+ */
+ public boolean isBracelessBlockStart(int position, int bound) {
+ if (position < 1)
+ return false;
+
+ switch (previousToken(position, bound)) {
+ case TokenDO:
+ case TokenELSE:
+ return true;
+ case TokenRPAREN:
+ position= findOpeningPeer(fPos, STPHeuristicScanner.UNBOUND, LPAREN, RPAREN);
+ if (position > 0) {
+ switch (previousToken(position - 1, bound)) {
+ case TokenIF:
+ case TokenFOR:
+ case TokenFOREACH:
+ case TokenWHILE:
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Returns <code>true</code> if the document, when scanned backwards from <code>start</code>
+ * appears to be a composite type (class, struct, union) or enum definition. Examples:
+ *
+ * <pre>
+ * class A {
+ * struct A {
+ * class A : B {
+ * class A : virtual public B, protected C&lt;T&gt; {
+ * enum E {
+ * </pre>
+ *
+ * @param start the position of the opening brace.
+ * @param bound the first position in <code>fDocument</code> to not consider any more, with
+ * <code>bound</code> &lt; <code>start</code>, or <code>UNBOUND</code>
+ * @return <code>true</code> if the current position looks like a composite type definition
+ */
+ public boolean looksLikeCompositeTypeDefinitionBackward(int start, int bound) {
+ int token= previousToken(start - 1, bound);
+ switch (token) {
+ case STPSymbols.TokenSTRUCT:
+ case STPSymbols.TokenUNION:
+ case STPSymbols.TokenENUM:
+ return true; // anonymous
+ case STPSymbols.TokenIDENT:
+ token= previousToken(getPosition(), bound);
+ switch (token) {
+ case STPSymbols.TokenCLASS:
+ case STPSymbols.TokenSTRUCT:
+ case STPSymbols.TokenUNION:
+ case STPSymbols.TokenENUM:
+ return true; // no base-clause
+ default:
+ // backtrack
+ token= previousToken(start - 1, bound);
+ }
+ break;
+ default:
+ // backtrack
+ token= previousToken(start - 1, bound);
+ break;
+ }
+ // match base-clause
+ if (token == STPSymbols.TokenGREATERTHAN) {
+ findOpeningPeer(getPosition(), bound, '<', '>');
+ token= previousToken(getPosition(), bound);
+ if (token != STPSymbols.TokenLESSTHAN) {
+ return false;
+ }
+ token= previousToken(getPosition(), bound);
+ }
+ outerWhile: while (token == STPSymbols.TokenIDENT) {// type name or base type
+ token= previousToken(getPosition(), bound);
+ // match nested-name-specifier
+ while (token == STPSymbols.TokenCOLON) { // colon of qualification
+ token= previousToken(getPosition(), bound);
+ if (token != STPSymbols.TokenCOLON) { // second colon of qualification
+ break outerWhile;
+ }
+ token= previousToken(getPosition(), bound);
+ if (token != STPSymbols.TokenIDENT) // qualification name?
+ break;
+ token= previousToken(getPosition(), bound);
+ }
+ switch (token) {
+ case STPSymbols.TokenVIRTUAL:
+ token= previousToken(getPosition(), bound);
+ //$FALL-THROUGH$
+ case STPSymbols.TokenPUBLIC:
+ case STPSymbols.TokenPROTECTED:
+ case STPSymbols.TokenPRIVATE:
+ token= previousToken(getPosition(), bound);
+ if (token == STPSymbols.TokenVIRTUAL) {
+ token= previousToken(getPosition(), bound);
+ }
+ if (token == STPSymbols.TokenCOMMA) {
+ token= previousToken(getPosition(), bound);
+ if (token == STPSymbols.TokenGREATERTHAN) {
+ findOpeningPeer(getPosition(), bound, '<', '>');
+ token= previousToken(getPosition(), bound);
+ if (token != STPSymbols.TokenLESSTHAN) {
+ return false;
+ }
+ token= previousToken(getPosition(), bound);
+ }
+ continue; // another base type
+ }
+ if (token != STPSymbols.TokenCOLON) // colon after class def identifier
+ return false;
+ //$FALL-THROUGH$
+ case STPSymbols.TokenCOLON:
+ token= previousToken(getPosition(), bound);
+ break outerWhile;
+ case STPSymbols.TokenCOMMA:
+ token= previousToken(getPosition(), bound);
+ if (token == STPSymbols.TokenGREATERTHAN) {
+ findOpeningPeer(getPosition(), bound, '<', '>');
+ token= previousToken(getPosition(), bound);
+ if (token != STPSymbols.TokenLESSTHAN) {
+ return false;
+ }
+ token= previousToken(getPosition(), bound);
+ }
+ continue; // another base type
+ case STPSymbols.TokenIDENT:
+ break outerWhile;
+ default:
+ return false;
+ }
+ }
+ if (token != STPSymbols.TokenIDENT) {
+ return false;
+ }
+ token= previousToken(getPosition(), bound);
+ switch (token) {
+ case STPSymbols.TokenCLASS:
+ case STPSymbols.TokenSTRUCT:
+ case STPSymbols.TokenUNION:
+ case STPSymbols.TokenENUM: // enum is actually not valid here
+ return true;
+ default:
+ return false;
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPIndenter.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPIndenter.java
index 537dd24d91..743a5adc17 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPIndenter.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPIndenter.java
@@ -41,2298 +41,2298 @@ import org.eclipse.linuxtools.internal.systemtap.ui.ide.IDEPlugin;
* </p>
*/
public final class STPIndenter {
- /**
- * The CDT Core preferences.
- */
- private final class CorePrefs {
- private final boolean prefUseTabs;
- private final boolean prefArrayDimensionsDeepIndent;
- private final int prefArrayIndent;
- private final boolean prefArrayDeepIndent;
- private final boolean prefTernaryDeepAlign;
- private final int prefTernaryIndent;
- private final int prefCaseIndent;
- private final int prefCaseBlockIndent;
- private final int prefAssignmentIndent;
- private final int prefSimpleIndent;
- private final int prefBracketIndent;
- private final boolean prefMethodDeclDeepIndent;
- private final boolean prefMethodDeclFirstParameterDeepIndent;
- private final int prefMethodDeclIndent;
- private final boolean prefMethodCallDeepIndent;
- private final boolean prefMethodCallFirstParameterDeepIndent;
- private final int prefMethodCallIndent;
- private final boolean prefParenthesisDeepIndent;
- private final int prefParenthesisIndent;
- private final int prefBlockIndent;
- private final int prefMethodBodyIndent;
- private final int prefTypeIndent;
- private final int prefAccessSpecifierIndent;
- private final int prefAccessSpecifierExtraSpaces;
- private final int prefNamespaceBodyIndent;
- private final boolean prefIndentBracesForBlocks;
- private final boolean prefIndentBracesForArrays;
- private final boolean prefIndentBracesForMethods;
- private final boolean prefIndentBracesForTypes;
- private final int prefContinuationIndent;
- private final boolean prefHasTemplates;
- private final String prefTabChar;
-
- private final IPreferencesService preferenceService;
- private final IScopeContext[] preferenceContexts;
-
- /**
- * Returns the possibly project-specific core preference defined under <code>key</code>.
- *
- * @param key the key of the preference
- * @return the value of the preference
- */
- private String getCoreFormatterOption(String key) {
- return getCoreFormatterOption(key, null);
- }
-
- private String getCoreFormatterOption(String key, String defaultValue) {
- return preferenceService.getString(IDEPlugin.PLUGIN_ID, key, defaultValue, preferenceContexts);
- }
-
- private int getCoreFormatterOption(String key, int defaultValue) {
- return preferenceService.getInt(IDEPlugin.PLUGIN_ID, key, defaultValue, preferenceContexts);
- }
-
- CorePrefs(IProject project) {
- preferenceService = Platform.getPreferencesService();
- preferenceContexts = project != null ?
- new IScopeContext[] { new ProjectScope(project.getProject()),
- InstanceScope.INSTANCE, DefaultScope.INSTANCE } :
- new IScopeContext[] { InstanceScope.INSTANCE, DefaultScope.INSTANCE };
- prefUseTabs= prefUseTabs();
- prefArrayDimensionsDeepIndent= prefArrayDimensionsDeepIndent();
- prefContinuationIndent= prefContinuationIndent();
- prefBlockIndent= prefBlockIndent();
- prefArrayIndent= prefArrayIndent();
- prefArrayDeepIndent= prefArrayDeepIndent();
- prefTernaryDeepAlign= false;
- prefTernaryIndent= prefContinuationIndent();
- prefCaseIndent= prefCaseIndent();
- prefCaseBlockIndent= prefCaseBlockIndent();
- prefAssignmentIndent= prefAssignmentIndent();
- prefIndentBracesForBlocks= prefIndentBracesForBlocks();
- prefSimpleIndent= prefSimpleIndent();
- prefBracketIndent= prefBracketIndent();
- prefMethodDeclDeepIndent= prefMethodDeclDeepIndent();
- prefMethodDeclFirstParameterDeepIndent= prefMethodDeclFirstParameterDeepIndent();
- prefMethodDeclIndent= prefMethodDeclIndent();
- prefMethodCallDeepIndent= prefMethodCallDeepIndent();
- prefMethodCallFirstParameterDeepIndent= prefMethodCallFirstParameterDeepIndent();
- prefMethodCallIndent= prefMethodCallIndent();
- prefParenthesisDeepIndent= prefParenthesisDeepIndent();
- prefParenthesisIndent= prefParenthesisIndent();
- prefMethodBodyIndent= prefMethodBodyIndent();
- prefTypeIndent= prefTypeIndent();
- prefAccessSpecifierIndent= prefAccessSpecifierIndent();
- prefAccessSpecifierExtraSpaces= prefAccessSpecifierExtraSpaces();
- prefNamespaceBodyIndent= prefNamespaceBodyIndent();
- prefIndentBracesForArrays= prefIndentBracesForArrays();
- prefIndentBracesForMethods= prefIndentBracesForMethods();
- prefIndentBracesForTypes= prefIndentBracesForTypes();
- prefHasTemplates= hasTemplates();
- prefTabChar= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
- }
-
- private boolean prefUseTabs() {
- return !IDEPlugin.SPACE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_TAB_CHAR));
- }
-
- private boolean prefArrayDimensionsDeepIndent() {
- return true; // sensible default, no formatter setting
- }
-
- private int prefArrayIndent() {
- String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_INITIALIZER_LIST);
- try {
- if (STPDefaultCodeFormatterConstants.getIndentStyle(option) == STPDefaultCodeFormatterConstants.INDENT_BY_ONE)
- return 1;
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
-
- return prefContinuationIndent(); // default
- }
-
- private boolean prefArrayDeepIndent() {
- String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_INITIALIZER_LIST);
- try {
- return STPDefaultCodeFormatterConstants.getIndentStyle(option) == STPDefaultCodeFormatterConstants.INDENT_ON_COLUMN;
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
-
- return true;
- }
-
- private int prefCaseIndent() {
- if (STPDefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH)))
- return 1;
- else
- return 0;
- }
-
- private int prefCaseBlockIndent() {
- if (STPDefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES)))
- return 1;
- else
- return 0;
- }
-
- private int prefAssignmentIndent() {
- return prefContinuationIndent();
- }
-
- private int prefSimpleIndent() {
- if (prefIndentBracesForBlocks() && prefBlockIndent() == 0)
- return 1;
- else
- return prefBlockIndent();
- }
-
- private int prefBracketIndent() {
- return prefBlockIndent();
- }
-
- private boolean prefMethodDeclDeepIndent() {
- String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
- try {
- int indentStyle = STPDefaultCodeFormatterConstants.getIndentStyle(option);
- return indentStyle == STPDefaultCodeFormatterConstants.INDENT_ON_COLUMN;
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
-
- return false;
- }
-
- private boolean prefMethodDeclFirstParameterDeepIndent() {
- String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
- try {
- int indentStyle = STPDefaultCodeFormatterConstants.getIndentStyle(option);
- int wrappingStyle = STPDefaultCodeFormatterConstants.getWrappingStyle(option);
- return indentStyle == STPDefaultCodeFormatterConstants.INDENT_ON_COLUMN &&
- (wrappingStyle == STPDefaultCodeFormatterConstants.WRAP_COMPACT_FIRST_BREAK ||
- wrappingStyle == STPDefaultCodeFormatterConstants.WRAP_ONE_PER_LINE);
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
-
- return false;
- }
-
- private int prefMethodDeclIndent() {
- String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
- try {
- if (STPDefaultCodeFormatterConstants.getIndentStyle(option) == STPDefaultCodeFormatterConstants.INDENT_BY_ONE)
- return 1;
- else
- return prefContinuationIndent();
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
- return 1;
- }
-
- private boolean prefMethodCallDeepIndent() {
- String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
- try {
- int indentStyle = STPDefaultCodeFormatterConstants.getIndentStyle(option);
- return indentStyle == STPDefaultCodeFormatterConstants.INDENT_ON_COLUMN;
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
- return false; // sensible default
- }
-
- private boolean prefMethodCallFirstParameterDeepIndent() {
- String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
- try {
- int indentStyle = STPDefaultCodeFormatterConstants.getIndentStyle(option);
- int wrappingStyle = STPDefaultCodeFormatterConstants.getWrappingStyle(option);
- return indentStyle == STPDefaultCodeFormatterConstants.INDENT_ON_COLUMN &&
- (wrappingStyle == STPDefaultCodeFormatterConstants.WRAP_COMPACT_FIRST_BREAK ||
- wrappingStyle == STPDefaultCodeFormatterConstants.WRAP_ONE_PER_LINE);
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
- return false; // sensible default
- }
-
- private int prefMethodCallIndent() {
- String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
- try {
- if (STPDefaultCodeFormatterConstants.getIndentStyle(option) == STPDefaultCodeFormatterConstants.INDENT_BY_ONE)
- return 1;
- else
- return prefContinuationIndent();
- } catch (IllegalArgumentException e) {
- // ignore and return default
- }
-
- return 1; // sensible default
- }
-
- private boolean prefParenthesisDeepIndent() {
- return false;
- }
-
- private int prefParenthesisIndent() {
- return prefContinuationIndent();
- }
-
- private int prefBlockIndent() {
- String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK);
- if (STPDefaultCodeFormatterConstants.FALSE.equals(option))
- return 0;
-
- return 1; // sensible default
- }
-
- private int prefMethodBodyIndent() {
- if (STPDefaultCodeFormatterConstants.FALSE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY)))
- return 0;
-
- return 1; // sensible default
- }
-
- private int prefTypeIndent() {
- String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ACCESS_SPECIFIER);
- if (STPDefaultCodeFormatterConstants.FALSE.equals(option))
- return 0;
-
- return 1; // sensible default
- }
-
- private int prefAccessSpecifierIndent() {
- if (STPDefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_ACCESS_SPECIFIER_COMPARE_TO_TYPE_HEADER)))
- return 1;
- else
- return 0;
- }
-
- private int prefAccessSpecifierExtraSpaces() {
- return getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_ACCESS_SPECIFIER_EXTRA_SPACES, 0);
- }
-
- private int prefNamespaceBodyIndent() {
- if (STPDefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_NAMESPACE_HEADER)))
- return prefBlockIndent();
- else
- return 0;
- }
-
- private boolean prefIndentBracesForBlocks() {
- return STPDefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK));
- }
-
- private boolean prefIndentBracesForArrays() {
- return STPDefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_INITIALIZER_LIST));
- }
-
- private boolean prefIndentBracesForMethods() {
- return STPDefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION));
- }
-
- private boolean prefIndentBracesForTypes() {
- return STPDefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION));
- }
-
- private int prefContinuationIndent() {
- try {
- return Integer.parseInt(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION));
- } catch (NumberFormatException e) {
- // ignore and return default
- }
-
- return 2; // sensible default
- }
-
- private boolean hasTemplates() {
- return true;
- }
- }
-
- /** The document being scanned. */
- private final IDocument fDocument;
- /** The indentation accumulated by <code>findReferencePosition</code>. */
- private int fIndent;
- /** Extra spaces to add on top of fIndent */
- private int fExtraSpaces;
- /**
- * The absolute (character-counted) indentation offset for special cases
- * (method definitions, array initializers)
- */
- private int fAlign;
- /** The stateful scan position for the indentation methods. */
- private int fPosition;
- /** The previous position. */
- private int fPreviousPos;
- /** The most recent token. */
- private int fToken;
- /** The line of <code>fPosition</code>. */
- private int fLine;
- /**
- * The scanner we will use to scan the document. It has to be installed
- * on the same document as the one we get.
- */
- private final STPHeuristicScanner fScanner;
- /**
- * The CDT Core preferences.
- */
- private final CorePrefs fPrefs;
-
- /**
- * Creates a new instance.
- *
- * @param document the document to scan
- * @param scanner the {@link STPHeuristicScanner} to be used for scanning
- * the document. It must be installed on the same <code>IDocument</code>.
- */
- public STPIndenter(IDocument document, STPHeuristicScanner scanner) {
- this(document, scanner, null);
- }
-
- /**
- * Creates a new instance.
- *
- * @param document the document to scan
- * @param scanner the {@link STPHeuristicScanner} to be used for scanning
- * the document. It must be installed on the same
- * <code>IDocument</code>.
- * @param project the C/C++ project to get the formatter preferences from, or
- * <code>null</code> to use the workspace settings
- */
- public STPIndenter(IDocument document, STPHeuristicScanner scanner, IProject project) {
- Assert.isNotNull(document);
- Assert.isNotNull(scanner);
- fDocument= document;
- fScanner= scanner;
- fPrefs= new CorePrefs(project);
- }
-
- /**
- * Computes the indentation at the reference point of <code>position</code>.
- *
- * @param offset the offset in the document
- * @return a String which reflects the indentation at the line in which the
- * reference position to <code>offset</code> resides, or <code>null</code>
- * if it cannot be determined
- */
- public StringBuilder getReferenceIndentation(int offset) {
- return getReferenceIndentation(offset, false);
- }
-
- /**
- * Computes the indentation at the reference point of <code>position</code>.
- *
- * @param offset the offset in the document
- * @param assumeOpeningBrace <code>true</code> if an opening brace should be assumed
- * @return a String which reflects the indentation at the line in which the
- * reference position to <code>offset</code> resides, or <code>null</code>
- * if it cannot be determined
- */
- private StringBuilder getReferenceIndentation(int offset, boolean assumeOpeningBrace) {
- int unit= findReferencePosition(offset,
- assumeOpeningBrace ? STPSymbols.TokenLBRACE : peekToken(offset));
-
- // if we were unable to find anything, return null
- if (unit == NOT_FOUND)
- return null;
-
- return getLeadingWhitespace(unit);
- }
-
- /**
- * Computes the indentation at <code>offset</code>.
- *
- * @param offset the offset in the document
- * @return a String which reflects the correct indentation for the line in
- * which offset resides, or <code>null</code> if it cannot be
- * determined
- */
- public StringBuilder computeIndentation(int offset) {
- return computeIndentation(offset, false);
- }
-
- /**
- * Computes the indentation at <code>offset</code>.
- *
- * @param offset the offset in the document
- * @param assumeOpeningBrace <code>true</code> if an opening brace should be assumed
- * @return a String which reflects the correct indentation for the line in
- * which offset resides, or <code>null</code> if it cannot be
- * determined
- */
- public StringBuilder computeIndentation(int offset, boolean assumeOpeningBrace) {
- StringBuilder reference= getReferenceIndentation(offset, assumeOpeningBrace);
-
- // handle special alignment
- if (fAlign != NOT_FOUND) {
- try {
- // a special case has been detected.
- IRegion line= fDocument.getLineInformationOfOffset(fAlign);
- int lineOffset= line.getOffset();
- return createIndent(lineOffset, fAlign, false);
- } catch (BadLocationException e) {
- return null;
- }
- }
-
- if (reference == null)
- return null;
-
- // Add additional indent
- return createReusingIndent(reference, fIndent, fExtraSpaces);
- }
-
- /**
- * Computes the length of a <code>CharacterSequence</code>, counting
- * a tab character as the size until the next tab stop and every other
- * character as one.
- *
- * @param indent the string to measure
- * @return the visual length in characters
- */
- private int computeVisualLength(CharSequence indent) {
- final int tabSize= CodeFormatterUtil.getTabWidth();
- int length= 0;
- for (int i= 0; i < indent.length(); i++) {
- char ch= indent.charAt(i);
- switch (ch) {
- case '\t':
- if (tabSize > 0) {
- int reminder= length % tabSize;
- length += tabSize - reminder;
- }
- break;
- case ' ':
- length++;
- break;
- }
- }
- return length;
- }
-
- /**
- * Strips any characters off the end of <code>reference</code> that exceed
- * <code>indentLength</code>.
- *
- * @param reference the string to measure
- * @param indentLength the maximum visual indentation length
- * @return the stripped <code>reference</code>
- */
- private StringBuilder stripExceedingChars(StringBuilder reference, int indentLength) {
- final int tabSize= CodeFormatterUtil.getTabWidth();
- int measured= 0;
- int chars= reference.length();
- int i= 0;
- for (; measured < indentLength && i < chars; i++) {
- char ch= reference.charAt(i);
- switch (ch) {
- case '\t':
- if (tabSize > 0) {
- int reminder= measured % tabSize;
- measured += tabSize - reminder;
- }
- break;
- case ' ':
- measured++;
- break;
- }
- }
- int deleteFrom= measured > indentLength ? i - 1 : i;
-
- return reference.delete(deleteFrom, chars);
- }
-
- /**
- * Returns the indentation of the line at <code>offset</code> as a
- * <code>StringBuilder</code>. If the offset is not valid, the empty string
- * is returned.
- *
- * @param offset the offset in the document
- * @return the indentation (leading whitespace) of the line in which
- * <code>offset</code> is located
- */
- private StringBuilder getLeadingWhitespace(int offset) {
- StringBuilder indent= new StringBuilder();
- try {
- IRegion line= fDocument.getLineInformationOfOffset(offset);
- int lineOffset= line.getOffset();
- int nonWS= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, lineOffset + line.getLength());
- indent.append(fDocument.get(lineOffset, nonWS - lineOffset));
- return indent;
- } catch (BadLocationException e) {
- return indent;
- }
- }
-
- /**
- * Creates an indentation string of the length indent - start, consisting of
- * the content in <code>fDocument</code> in the range [start, indent),
- * with every character replaced by a space except for tabs, which are kept
- * as such.
- * <p>
- * If <code>convertSpaceRunsToTabs</code> is <code>true</code>, every
- * run of the number of spaces that make up a tab are replaced by a tab
- * character. If it is not set, no conversion takes place, but tabs in the
- * original range are still copied verbatim.
- * </p>
- *
- * @param start the start of the document region to copy the indent from
- * @param indent the exclusive end of the document region to copy the indent
- * from
- * @param convertSpaceRunsToTabs whether to convert consecutive runs of
- * spaces to tabs
- * @return the indentation corresponding to the document content specified
- * by <code>start</code> and <code>indent</code>
- */
- private StringBuilder createIndent(int start, final int indent, final boolean convertSpaceRunsToTabs) {
- final boolean convertTabs= fPrefs.prefUseTabs && convertSpaceRunsToTabs;
- final int tabLen= CodeFormatterUtil.getTabWidth();
- final StringBuilder ret= new StringBuilder();
- try {
- int spaces= 0;
- while (start < indent) {
- char ch= fDocument.getChar(start);
- if (ch == '\t') {
- ret.append('\t');
- spaces= 0;
- } else if (convertTabs) {
- spaces++;
- if (spaces == tabLen) {
- ret.append('\t');
- spaces= 0;
- }
- } else {
- ret.append(' ');
- }
-
- start++;
- }
- // remainder
- while (spaces-- > 0)
- ret.append(' ');
- } catch (BadLocationException e) {
- }
-
- return ret;
- }
-
- /**
- * Creates a string with a visual length of the given
- * <code>indentationSize</code>.
- *
- * @param buffer the original indent to reuse if possible
- * @param additional the additional indentation units to add or subtract to
- * reference
- * @param extraSpaces additional spaces to add to indentation.
- * @return the modified <code>buffer</code> reflecting the indentation
- * adapted to <code>additional</code>
- */
- public StringBuilder createReusingIndent(StringBuilder buffer, int additional, int extraSpaces) {
- int refLength= computeVisualLength(buffer);
- int addLength= CodeFormatterUtil.getIndentWidth() * additional + extraSpaces; // may be < 0
- int totalLength= Math.max(0, refLength + addLength);
-
- // copy the reference indentation for the indent up to the last tab
- // stop within the maxCopy area
- int minLength= Math.min(totalLength, refLength);
- int tabSize= CodeFormatterUtil.getTabWidth();
- int maxCopyLength= tabSize > 0 ? minLength - minLength % tabSize : minLength; // maximum indent to copy
- stripExceedingChars(buffer, maxCopyLength);
-
- // add additional indent
- int missing= totalLength - maxCopyLength;
- int tabs, spaces;
- if (IDEPlugin.SPACE.equals(fPrefs.prefTabChar)) {
- tabs= 0;
- spaces= missing;
- } else {
- tabs= tabSize > 0 ? missing / tabSize : 0;
- spaces= tabSize > 0 ? missing % tabSize : missing;
- }
- for (int i= 0; i < tabs; i++)
- buffer.append('\t');
- for (int i= 0; i < spaces; i++)
- buffer.append(' ');
- return buffer;
- }
-
- /**
- * Returns relative indent of continuation lines.
- * @return a number of indentation units.
- */
- public int getContinuationLineIndent() {
- return fPrefs.prefContinuationIndent;
- }
-
- /**
- * Returns the reference position regarding to indentation for <code>offset</code>,
- * or {@link STPHeuristicScanner#NOT_FOUND NOT_FOUND}. This method calls
- * {@link #findReferencePosition(int, int) findReferencePosition(offset, nextChar)} where
- * <code>nextChar</code> is the next character after <code>offset</code>.
- *
- * @param offset the offset for which the reference is computed
- * @return the reference statement relative to which <code>offset</code>
- * should be indented, or {@link STPHeuristicScanner#NOT_FOUND NOT_FOUND}
- */
- public int findReferencePosition(int offset) {
- return findReferencePosition(offset, peekToken(offset));
- }
-
- /**
- * Peeks the next token in the document that comes after <code>offset</code>
- * on the same line as <code>offset</code>.
- *
- * @param offset the offset into document
- * @return the token symbol of the next element, or TokenEOF if there is none
- */
- private int peekToken(int offset) {
- if (offset < fDocument.getLength()) {
- try {
- IRegion line= fDocument.getLineInformationOfOffset(offset);
- int lineEnd= line.getOffset() + line.getLength();
- int next= fScanner.nextToken(offset, lineEnd);
- return next;
- } catch (BadLocationException e) {
- }
- }
- return STPSymbols.TokenEOF;
- }
-
- /**
- * Peeks the second next token in the document that comes after <code>offset</code>
- * on the same line as <code>offset</code>.
- *
- * @param offset the offset into document
- * @return the token symbol of the second next element, or TokenEOF if there is none
- */
- private int peekSecondToken(int offset) {
- if (offset < fDocument.getLength()) {
- try {
- IRegion line= fDocument.getLineInformationOfOffset(offset);
- int lineEnd= line.getOffset() + line.getLength();
- fScanner.nextToken(offset, lineEnd);
- int next = fScanner.nextToken(fScanner.getPosition(), lineEnd);
- return next;
- } catch (BadLocationException e) {
- }
- }
- return STPSymbols.TokenEOF;
- }
-
- /**
- * Returns the reference position regarding to indentation for <code>position</code>,
- * or {@link STPHeuristicScanner#NOT_FOUND NOT_FOUND}.
- *
- * <p>If <code>peekNextChar</code> is <code>true</code>, the next token after
- * <code>offset</code> is read and taken into account when computing the
- * indentation. Currently, if the next token is the first token on the line
- * (i.e. only preceded by whitespace), the following tokens are specially
- * handled:
- * <ul>
- * <li><code>switch</code> labels are indented relative to the switch block</li>
- * <li>opening curly braces are aligned correctly with the introducing code</li>
- * <li>closing curly braces are aligned properly with the introducing code of
- * the matching opening brace</li>
- * <li>closing parenthesis' are aligned with their opening peer</li>
- * <li>the <code>else</code> keyword is aligned with its <code>if</code>, anything
- * else is aligned normally (i.e. with the base of any introducing statements).</li>
- * <li>if there is no token on the same line after <code>offset</code>, the indentation
- * is the same as for an <code>else</code> keyword</li>
- * </ul>
- *
- * @param offset the offset for which the reference is computed
- * @param nextToken the next token to assume in the document
- * @return the reference statement relative to which <code>offset</code>
- * should be indented, or {@link STPHeuristicScanner#NOT_FOUND NOT_FOUND}
- */
- private int findReferencePosition(int offset, int nextToken) {
- boolean danglingElse= false;
- boolean cancelIndent= false; // If set to true, fIndent is ignored.
- int extraIndent= 0; // Can be either positive or negative.
- MatchMode matchMode = MatchMode.REGULAR;
-
- // Account for un-indentation characters already typed in, but after position.
- // If they are on a line by themselves, the indentation gets adjusted accordingly.
- //
- // Also account for a dangling else.
- if (offset < fDocument.getLength()) {
- try {
- IRegion line= fDocument.getLineInformationOfOffset(offset);
- int lineOffset= line.getOffset();
- int prevPos= Math.max(offset - 1, 0);
- boolean isFirstTokenOnLine=
- fDocument.get(lineOffset, prevPos + 1 - lineOffset).trim().length() == 0;
- int prevToken= fScanner.previousToken(prevPos, STPHeuristicScanner.UNBOUND);
- boolean bracelessBlockStart= fScanner.isBracelessBlockStart(prevPos, STPHeuristicScanner.UNBOUND);
-
- switch (nextToken) {
- case STPSymbols.TokenELSE:
- danglingElse= true;
- break;
-
- case STPSymbols.TokenCASE:
- case STPSymbols.TokenDEFAULT:
- if (isFirstTokenOnLine)
- matchMode = MatchMode.MATCH_CASE;
- break;
-
- case STPSymbols.TokenPUBLIC:
- case STPSymbols.TokenPROTECTED:
- case STPSymbols.TokenPRIVATE:
- if (isFirstTokenOnLine && peekSecondToken(offset) != STPSymbols.TokenIDENT)
- matchMode = MatchMode.MATCH_ACCESS_SPECIFIER;
- break;
-
- case STPSymbols.TokenLBRACE: // for opening-brace-on-new-line style
- if (bracelessBlockStart) {
- extraIndent= fPrefs.prefIndentBracesForBlocks ? 0 : -1;
- } else if (prevToken == STPSymbols.TokenCOLON && !fPrefs.prefIndentBracesForBlocks) {
- extraIndent= -1;
- } else if ((prevToken == STPSymbols.TokenEQUAL || prevToken == STPSymbols.TokenRBRACKET) &&
- !fPrefs.prefIndentBracesForArrays) {
- cancelIndent= true;
- } else if ((prevToken == STPSymbols.TokenRPAREN || prevToken == STPSymbols.TokenCONST) && fPrefs.prefIndentBracesForMethods) {
- extraIndent= 1;
- } else if (prevToken == STPSymbols.TokenIDENT) {
- if (fPrefs.prefIndentBracesForTypes) {
- extraIndent= 1;
- }
- int pos = fPosition;
- fPosition = offset;
- if (matchTypeDeclaration() != NOT_FOUND) {
- matchMode = MatchMode.MATCH_TYPE_DECLARATION;
- }
- fPosition = pos;
- }
- break;
-
- case STPSymbols.TokenRBRACE: // closing braces get unindented
- if (isFirstTokenOnLine || prevToken != STPSymbols.TokenLBRACE)
- matchMode = MatchMode.MATCH_BRACE;
- break;
-
- case STPSymbols.TokenRPAREN:
- if (isFirstTokenOnLine)
- matchMode = MatchMode.MATCH_PAREN;
- break;
- }
- } catch (BadLocationException e) {
- }
- } else {
- // Don't assume an else could come if we are at the end of file.
- danglingElse= false;
- }
-
- int ref= findReferencePosition(offset, danglingElse, matchMode);
- if (cancelIndent) {
- fIndent = 0;
- } else if (extraIndent > 0) {
- fAlign= NOT_FOUND;
- fIndent += extraIndent;
- } else {
- fIndent += extraIndent;
- }
- return ref;
- }
-
- /**
- * Enumeration used by {@link #findReferencePosition(int, boolean, MatchMode)} method.
- */
- public enum MatchMode {
- /**
- * The reference position should be returned based on the regular code analysis.
- */
- REGULAR,
- /**
- * The position of the matching brace should be returned instead of doing code analysis.
- */
- MATCH_BRACE,
- /**
- * The position of the matching parenthesis should be returned instead of doing code
- * analysis.
- */
- MATCH_PAREN,
- /**
- * The position of a switch statement reference should be returned (either an earlier case
- * statement or the switch block brace).
- */
- MATCH_CASE,
- /**
- * The position of a class body reference should be returned (either an earlier
- * public/protected/private or the class body brace).
- */
- MATCH_ACCESS_SPECIFIER,
- /**
- * The position of a class declaration should be returned.
- */
- MATCH_TYPE_DECLARATION
- }
-
- /**
- * Returns the reference position regarding to indentation for <code>position</code>,
- * or {@link STPHeuristicScanner#NOT_FOUND NOT_FOUND}. <code>fIndent</code> will contain
- * the relative indentation (in indentation units, not characters) after the call. If there is
- * a special alignment (e.g. for a method declaration where parameters should be aligned),
- * <code>fAlign</code> will contain the absolute position of the alignment reference
- * in <code>fDocument</code>, otherwise <code>fAlign</code> is set to
- * {@link STPHeuristicScanner#NOT_FOUND}.
- *
- * @param offset the offset for which the reference is computed
- * @param danglingElse whether a dangling else should be assumed at <code>position</code>
- * @param matchMode determines what kind of reference position should be returned.
- * See {@link MatchMode}.
- * @return the reference statement relative to which <code>position</code>
- * should be indented, or {@link STPHeuristicScanner#NOT_FOUND}
- */
- public int findReferencePosition(int offset, boolean danglingElse, MatchMode matchMode) {
- fIndent= 0; // The indentation modification
- fExtraSpaces= 0;
- fAlign= NOT_FOUND;
- fPosition= offset;
-
- // Forward cases.
- // An unindentation happens sometimes if the next token is special, namely on braces,
- // parens and case labels align braces, but handle the case where we align with the method
- // declaration start instead of the opening brace.
- switch (matchMode) {
- case MATCH_BRACE:
- if (skipScope(STPSymbols.TokenLBRACE, STPSymbols.TokenRBRACE)) {
- try {
- // Align with the opening brace that is on a line by its own
- int lineOffset= fDocument.getLineOffset(fLine);
- if (lineOffset <= fPosition &&
- fDocument.get(lineOffset, fPosition - lineOffset).trim().isEmpty()) {
- return fPosition;
- }
- } catch (BadLocationException e) {
- // Concurrent modification - walk default path
- }
- // If the opening brace is not on the start of the line, skip to the start.
- int pos= skipToStatementStart(true, true);
- fIndent= 0; // indent is aligned with reference position
- return pos;
- } else {
- // If we can't find the matching brace, the heuristic is to unindent
- // by one against the normal position
- int pos= findReferencePosition(offset, danglingElse, MatchMode.REGULAR);
- fIndent--;
- return pos;
- }
-
- case MATCH_PAREN:
- // Align parentheses.
- if (skipScope(STPSymbols.TokenLPAREN, STPSymbols.TokenRPAREN)) {
- return fPosition;
- } else {
- // If we can't find the matching paren, the heuristic is to unindent by one
- // against the normal position.
- int pos= findReferencePosition(offset, danglingElse, MatchMode.REGULAR);
- fIndent--;
- return pos;
- }
-
- case MATCH_CASE:
- // The only reliable way to get case labels aligned (due to many different styles of
- // using braces in a block) is to go for another case statement, or the scope opening
- // brace.
- return matchCaseAlignment();
-
- case MATCH_ACCESS_SPECIFIER:
- // The only reliable way to get access specifiers aligned (due to many different styles
- // of using braces in a block) is to go for another access specifier, or the scope
- // opening brace.
- return matchAccessSpecifierAlignment();
-
- case MATCH_TYPE_DECLARATION:
- return matchTypeDeclaration();
-
- case REGULAR:
- break;
- }
-
- if (peekToken(offset) == STPSymbols.TokenCOLON) {
- int pos= fPosition;
- if (looksLikeTypeInheritanceDecl()) {
- fIndent = fPrefs.prefContinuationIndent;
- return fPosition;
- }
- fPosition = pos;
- }
-
- nextToken();
- // Skip access specifiers
- while (fToken == STPSymbols.TokenCOLON && isAccessSpecifier()) {
- nextToken();
- }
-
- int line= fLine;
- switch (fToken) {
- case STPSymbols.TokenGREATERTHAN:
- case STPSymbols.TokenRBRACE:
- // Skip the block and fall through.
- // If we can't complete the scope, reset the scan position
- int pos= fPosition;
- if (!skipScope())
- fPosition= pos;
- return skipToStatementStart(danglingElse, false);
-
- case STPSymbols.TokenSEMICOLON:
- // This is the 90% case: after a statement block
- // the end of the previous statement / block previous.end
- // search to the end of the statement / block before the previous;
- // the token just after that is previous.start
- return skipToStatementStart(danglingElse, false);
-
- // Scope introduction: special treat who special is
- case STPSymbols.TokenLPAREN:
- case STPSymbols.TokenLBRACE:
- case STPSymbols.TokenLBRACKET:
- return handleScopeIntroduction(Math.min(offset + 1, fDocument.getLength()), true);
-
- case STPSymbols.TokenEOF:
- // trap when hitting start of document
- return NOT_FOUND;
-
- case STPSymbols.TokenEQUAL:
- // indent assignments, but don't do so if there is a String
- // after the assignment because SystemTap doesn't require
- // semi-colons to end lines and so this should be treated as
- // a complete assignment.
- pos = fPosition;
- while (pos < offset) {
- try {
- ITypedRegion partition = ((IDocumentExtension3)fDocument).getPartition(STPPartitionScanner.STP_PARTITIONING, pos, danglingElse);
- if (STPPartitionScanner.STP_STRING.equals(partition.getType()))
- return skipToStatementStart(danglingElse, false);
- pos = partition.getOffset() + partition.getLength();
- } catch (BadLocationException e) {
- break;
- } catch (BadPartitioningException e) {
- break;
- }
- }
- fIndent= fPrefs.prefAssignmentIndent;
- return fPosition;
- case STPSymbols.TokenCOLON:
- pos= fPosition;
- if (looksLikeCaseStatement()) {
- fIndent= fPrefs.prefCaseBlockIndent;
- return pos;
- }
- fPosition= pos;
- if (looksLikeTypeInheritanceDecl()) {
- fIndent= fPrefs.prefContinuationIndent;
- return pos;
- }
- fPosition= pos;
- if (looksLikeConstructorInitializer()) {
- fIndent= fPrefs.prefBlockIndent;
- return pos;
- }
- fPosition= pos;
- if (isConditional()) {
- fPosition= offset;
- fLine= line;
- return skipToPreviousListItemOrListStart();
- }
- fPosition= pos;
- return skipToPreviousListItemOrListStart();
-
- case STPSymbols.TokenQUESTIONMARK:
- if (fPrefs.prefTernaryDeepAlign) {
- setFirstElementAlignment(fPosition, offset + 1);
- } else {
- fIndent= fPrefs.prefTernaryIndent;
- }
- return fPosition;
-
- // Indentation for blockless introducers:
- case STPSymbols.TokenDO:
- case STPSymbols.TokenWHILE:
- case STPSymbols.TokenELSE:
- fIndent= fPrefs.prefSimpleIndent;
- return fPosition;
-
- case STPSymbols.TokenTRY:
- return skipToStatementStart(danglingElse, false);
-
- case STPSymbols.TokenRETURN:
- case STPSymbols.TokenTYPEDEF:
- case STPSymbols.TokenUSING:
- fIndent = fPrefs.prefContinuationIndent;
- return fPosition;
-
- case STPSymbols.TokenCONST:
- nextToken();
- if (fToken != STPSymbols.TokenRPAREN) {
- return skipToPreviousListItemOrListStart();
- }
- // could be const method decl
- //$FALL-THROUGH$
- case STPSymbols.TokenRPAREN:
- if (skipScope(STPSymbols.TokenLPAREN, STPSymbols.TokenRPAREN)) {
- int scope= fPosition;
- nextToken();
- if (fToken == STPSymbols.TokenIF || fToken == STPSymbols.TokenWHILE || fToken == STPSymbols.TokenFOR
- || fToken == STPSymbols.TokenFOREACH) {
- fIndent= fPrefs.prefSimpleIndent;
- return fPosition;
- }
- if (fToken == STPSymbols.TokenSWITCH) {
- return fPosition;
- }
- fPosition= scope;
- if (looksLikeMethodDecl()) {
- return skipToStatementStart(danglingElse, false);
- }
- if (fToken == STPSymbols.TokenCATCH) {
- return skipToStatementStart(danglingElse, false);
- }
- fPosition= scope;
- if (looksLikeAnonymousTypeDecl()) {
- return skipToStatementStart(danglingElse, false);
- }
- }
- // restore
- fPosition= offset;
- fLine= line;
- // else: fall through to default
- return skipToPreviousListItemOrListStart();
-
- case STPSymbols.TokenCOMMA:
- // Inside a list of some type.
- // Easy if there is already a list item before with its own indentation - we just align.
- // If not: take the start of the list (LPAREN, LBRACE, LBRACKET) and either align or
- // indent by list-indent.
- return skipToPreviousListItemOrListStart();
-
- case STPSymbols.TokenPLUS:
- case STPSymbols.TokenMINUS:
- case STPSymbols.TokenLESSTHAN:
- case STPSymbols.TokenAGGREGATE:
- case STPSymbols.TokenSHIFTRIGHT:
- case STPSymbols.TokenSHIFTLEFT:
- case STPSymbols.TokenOTHER:
- // Math symbol, use skipToPreviousListItemOrListStart.
- return skipToPreviousListItemOrListStart();
- // Otherwise, fall-through
- default:
- // Inside whatever we don't know about:
- // C would treat this as a list, but in SystemTap we might just have a line that doesn't
- // end in a semi-colon. We want to indent to the same level as the statement.
- return skipToStatementStart(danglingElse, false);
- }
- }
-
- /**
- * Test whether an identifier encountered during scanning is part of
- * a type declaration, by scanning backward and ignoring any identifiers, commas,
- * and colons until we hit <code>class</code>, <code>struct</code>, <code>union</code>,
- * or <code>enum</code>. If any braces, semicolons, or parentheses are encountered,
- * this is not a type declaration.
- * @return the reference offset of the start of the statement
- */
- private int matchTypeDeclaration() {
- while (true) {
- nextToken();
- if (fToken == STPSymbols.TokenIDENT
- || fToken == STPSymbols.TokenCOMMA
- || fToken == STPSymbols.TokenCOLON
- || fToken == STPSymbols.TokenPUBLIC
- || fToken == STPSymbols.TokenPROTECTED
- || fToken == STPSymbols.TokenPRIVATE) {
- continue;
- }
- if (fToken == STPSymbols.TokenCLASS
- || fToken == STPSymbols.TokenSTRUCT
- || fToken == STPSymbols.TokenUNION) {
- // inside a type declaration? Only so if not preceded by '(' or ',' as in
- // a parameter list. To be safe, only accept ';' or EOF
- int pos= fPosition;
- nextToken();
- if (fToken == STPSymbols.TokenSEMICOLON || fToken == STPSymbols.TokenEOF) {
- return pos;
- } else {
- return NOT_FOUND;
- }
- } else {
- return NOT_FOUND;
- }
- }
- }
-
- /**
- * Test whether the colon at the current position marks a case statement
- *
- * @return <code>true</code> if this looks like a case statement
- */
- private boolean looksLikeCaseStatement() {
- nextToken();
- switch (fToken) {
- case STPSymbols.TokenCASE:
- // char literal got skipped
- return true;
- case STPSymbols.TokenIDENT:
- nextToken();
- while (skipQualifiers()) {
- nextToken();
- }
- while (fToken == STPSymbols.TokenMINUS || fToken == STPSymbols.TokenPLUS) {
- nextToken();
- }
- if (fToken == STPSymbols.TokenCASE) {
- return true;
- }
- break;
- case STPSymbols.TokenOTHER:
- nextToken();
- if (fToken == STPSymbols.TokenCASE) {
- return true;
- }
- break;
- case STPSymbols.TokenDEFAULT:
- return true;
- }
- return false;
- }
-
- /**
- * Test whether the colon at the current position marks a type inheritance decl.
- *
- * @return <code>true</code> if this looks like a type inheritance decl.
- */
- private boolean looksLikeTypeInheritanceDecl() {
- nextToken();
- switch (fToken) {
- case STPSymbols.TokenIDENT:
- nextToken();
- while (skipQualifiers()) {
- nextToken();
- }
- switch (fToken) {
- case STPSymbols.TokenCLASS:
- case STPSymbols.TokenSTRUCT:
- case STPSymbols.TokenUNION:
- return true;
- }
- break;
- }
- return false;
- }
-
- /**
- * Test whether the colon at the current position marks a constructor initializer list.
- *
- * @return <code>true</code> if this looks like a constructor initializer list.
- */
- private boolean looksLikeConstructorInitializer() {
- nextToken();
- if (fToken != STPSymbols.TokenRPAREN) {
- return false;
- }
- if (!skipScope()) {
- return false;
- }
- nextToken();
- if (fToken == STPSymbols.TokenTHROW) {
- nextToken();
- if (fToken != STPSymbols.TokenRPAREN) {
- return false;
- }
- if (!skipScope()) {
- return false;
- }
- nextToken();
- }
- if (fToken != STPSymbols.TokenIDENT) {
- return false;
- }
- nextToken();
- switch (fToken) {
- case STPSymbols.TokenCOLON:
- nextToken();
- switch (fToken) {
- case STPSymbols.TokenCOLON: // A::A() :
- case STPSymbols.TokenPUBLIC: // public: A() :
- case STPSymbols.TokenPROTECTED:
- case STPSymbols.TokenPRIVATE:
- return true;
- }
- return false;
-
- case STPSymbols.TokenLBRACE: // class A { A() :
- case STPSymbols.TokenRBRACE:
- case STPSymbols.TokenSEMICOLON:
- return true;
- }
- return false;
- }
-
- /**
- * Test whether the left brace at the current position marks an enum decl.
- *
- * @return <code>true</code> if this looks like an enum decl.
- */
- private boolean looksLikeEnumDeclaration() {
- int pos = fPosition;
- nextToken();
- if (fToken == STPSymbols.TokenIDENT) {
- nextToken();
- while (skipQualifiers()) {
- nextToken();
- }
- }
- if (fToken == STPSymbols.TokenENUM) {
- fPosition = pos;
- return true;
- }
- fPosition = pos;
- return false;
- }
-
-
- /**
- * Test whether the colon at the current position marks an access specifier.
- *
- * @return <code>true</code> if current position marks an access specifier
- */
- private boolean isAccessSpecifier() {
- int pos= fPosition;
- int token = fToken;
- nextToken();
- switch (fToken) {
- case STPSymbols.TokenPUBLIC:
- case STPSymbols.TokenPROTECTED:
- case STPSymbols.TokenPRIVATE:
- return true;
- }
- fToken = token;
- fPosition= pos;
- return false;
- }
-
- /**
- * Skips to the start of a statement that ends at the current position.
- *
- * @param danglingElse whether to indent aligned with the last <code>if</code>
- * @param isInBlock whether the current position is inside a block, which limits the search scope to
- * the next scope introducer
- * @return the reference offset of the start of the statement
- */
- private int skipToStatementStart(boolean danglingElse, boolean isInBlock) {
- final int NOTHING= 0;
- final int READ_PARENS= 1;
- final int READ_IDENT= 2;
- int mayBeMethodBody= NOTHING;
- boolean isTypeBody= false;
- int startLine = fLine;
- while (true) {
- int prevToken= fToken;
- nextToken();
-
- if (isInBlock) {
- switch (fToken) {
- // exit on all block introducers
- case STPSymbols.TokenIF:
- case STPSymbols.TokenELSE:
- case STPSymbols.TokenCATCH:
- case STPSymbols.TokenDO:
- case STPSymbols.TokenWHILE:
- case STPSymbols.TokenFOR:
- case STPSymbols.TokenFOREACH:
- case STPSymbols.TokenTRY:
- fIndent += fPrefs.prefIndentBracesForBlocks ? 1 : 0;
- return fPosition;
- case STPSymbols.TokenCLASS:
- case STPSymbols.TokenSTRUCT:
- case STPSymbols.TokenUNION:
- isTypeBody= true;
- break;
-
- case STPSymbols.TokenSWITCH:
- fIndent= fPrefs.prefCaseIndent;
- return fPosition;
- }
- }
-
- if (fToken == STPSymbols.TokenSEMICOLON && fLine == startLine) {
- // Skip semicolons on the same line. Otherwise we may never reach beginning of a 'for'
- // statement.
- continue;
- }
-
- switch (fToken) {
- // scope introduction through: LPAREN, LBRACE, LBRACKET
- // search stop on SEMICOLON, RBRACE, COLON, EOF
- // -> the next token is the start of the statement (i.e. previousPos when backward scanning)
- case STPSymbols.TokenLPAREN:
- if (peekToken() == STPSymbols.TokenFOR) {
- nextToken(); // Consume 'for'
- fIndent = fPrefs.prefContinuationIndent;
- return fPosition;
- }
- break;
-
- case STPSymbols.TokenLBRACE:
- case STPSymbols.TokenSEMICOLON:
- case STPSymbols.TokenEOF:
- if (isInBlock)
- fIndent= getBlockIndent(mayBeMethodBody == READ_IDENT, isTypeBody);
- return fPreviousPos;
-
- case STPSymbols.TokenCOLON:
- switch (prevToken) {
- case STPSymbols.TokenPRIVATE:
- case STPSymbols.TokenPROTECTED:
- case STPSymbols.TokenPUBLIC:
- continue; // Don't stop at colon in a class declaration
-
- case STPSymbols.TokenVIRTUAL:
- switch (peekToken()) {
- case STPSymbols.TokenPRIVATE:
- case STPSymbols.TokenPROTECTED:
- case STPSymbols.TokenPUBLIC:
- break;
- default:
- continue;
- }
- }
- int pos= fPreviousPos;
- if (!isConditional())
- return pos;
- break;
-
- case STPSymbols.TokenRBRACE:
- // RBRACE is a little tricky: it can be the end of an array definition, but
- // usually it is the end of a previous block
- pos= fPreviousPos; // store state
- if (skipScope()) {
- if (looksLikeArrayInitializerIntro()) {
- continue; // it's an array
- }
- if (prevToken == STPSymbols.TokenSEMICOLON) {
- // end of type def
- continue;
- }
- }
- if (isInBlock)
- fIndent= getBlockIndent(mayBeMethodBody == READ_IDENT, isTypeBody);
- return pos; // it's not - do as with all the above
-
- // scopes: skip them
- case STPSymbols.TokenRPAREN:
- if (isInBlock)
- mayBeMethodBody= READ_PARENS;
- // fall thru
- pos= fPreviousPos;
- if (skipScope())
- break;
- else
- return pos;
- case STPSymbols.TokenRBRACKET:
- pos= fPreviousPos;
- if (skipScope())
- break;
- else
- return pos;
-
- // IF / ELSE: align the position after the conditional block with the if
- // so we are ready for an else, except if danglingElse is false
- // in order for this to work, we must skip an else to its if
- case STPSymbols.TokenIF:
- if (danglingElse)
- return fPosition;
- else
- break;
- case STPSymbols.TokenELSE:
- // skip behind the next if, as we have that one covered
- pos= fPosition;
- if (skipNextIF())
- break;
- else
- return pos;
-
- case STPSymbols.TokenDO:
- // align the WHILE position with its do
- return fPosition;
-
- case STPSymbols.TokenWHILE:
- // this one is tricky: while can be the start of a while loop
- // or the end of a do - while
- pos= fPosition;
- if (hasMatchingDo()) {
- // continue searching from the DO on
- break;
- } else {
- // continue searching from the WHILE on
- fPosition= pos;
- break;
- }
- case STPSymbols.TokenIDENT:
- if (mayBeMethodBody == READ_PARENS)
- mayBeMethodBody= READ_IDENT;
- break;
-
- default:
- // keep searching
- }
- }
- }
-
- private int getBlockIndent(boolean isMethodBody, boolean isTypeBody) {
- if (isTypeBody) {
- return fPrefs.prefTypeIndent + fPrefs.prefAccessSpecifierIndent;
- } else if (isMethodBody) {
- return fPrefs.prefMethodBodyIndent + (fPrefs.prefIndentBracesForMethods ? 1 : 0);
- } else {
- return fIndent;
- }
- }
-
- /**
- * Returns <code>true</code> if the colon at the current position is part of a conditional
- * (ternary) expression, <code>false</code> otherwise.
- *
- * @return <code>true</code> if the colon at the current position is part of a conditional
- */
- private boolean isConditional() {
- while (true) {
- int previous= fToken;
- nextToken();
- switch (fToken) {
- // search for case labels, which consist of (possibly qualified) identifiers or numbers
- case STPSymbols.TokenIDENT:
- if (previous == STPSymbols.TokenIDENT) {
- return false;
- }
- // fall thru
- continue;
- case STPSymbols.TokenDOUBLECOLON:
- case STPSymbols.TokenOTHER:
- case STPSymbols.TokenMINUS:
- case STPSymbols.TokenPLUS:
- continue;
-
- case STPSymbols.TokenQUESTIONMARK:
- return true;
-
- case STPSymbols.TokenSEMICOLON:
- case STPSymbols.TokenLBRACE:
- case STPSymbols.TokenRBRACE:
- case STPSymbols.TokenCASE:
- case STPSymbols.TokenDEFAULT:
- case STPSymbols.TokenPUBLIC:
- case STPSymbols.TokenPROTECTED:
- case STPSymbols.TokenPRIVATE:
- case STPSymbols.TokenCLASS:
- case STPSymbols.TokenSTRUCT:
- case STPSymbols.TokenUNION:
- return false;
-
- default:
- return true;
- }
- }
- }
-
- /**
- * Returns as a reference any previous <code>switch</code> labels (<code>case</code>
- * or <code>default</code>) or the offset of the brace that scopes the switch
- * statement. Sets <code>fIndent</code> to <code>prefCaseIndent</code> upon
- * a match.
- *
- * @return the reference offset for a <code>switch</code> label
- */
- private int matchCaseAlignment() {
- while (true) {
- nextToken();
- switch (fToken) {
- // invalid cases: another case label or an LBRACE must come before a case
- // -> bail out with the current position
- case STPSymbols.TokenLPAREN:
- case STPSymbols.TokenLBRACKET:
- case STPSymbols.TokenEOF:
- return fPosition;
-
- case STPSymbols.TokenSWITCH:
- // start of switch statement
- fIndent= fPrefs.prefCaseIndent;
- return fPosition;
-
- case STPSymbols.TokenCASE:
- case STPSymbols.TokenDEFAULT:
- // align with previous label
- fIndent= 0;
- return fPosition;
-
- // scopes: skip them
- case STPSymbols.TokenRPAREN:
- case STPSymbols.TokenRBRACKET:
- case STPSymbols.TokenRBRACE:
- skipScope();
- break;
-
- default:
- // keep searching
- continue;
- }
- }
- }
-
- /**
- * Returns as a reference any previous access specifiers (<code>public</code>,
- * <code>protected</code> or <code>default</code>) or the offset of the brace that
- * scopes the class body.
- * Sets <code>fIndent</code> to <code>prefAccessSpecifierIndent</code> upon
- * a match.
- *
- * @return the reference offset for an access specifier (public/protected/private)
- */
- private int matchAccessSpecifierAlignment() {
- while (true) {
- nextToken();
- switch (fToken) {
- // invalid cases: another access specifier or an LBRACE must come before an access specifier
- // -> bail out with the current position
- case STPSymbols.TokenLPAREN:
- case STPSymbols.TokenLBRACKET:
- case STPSymbols.TokenEOF:
- return fPosition;
-
- case STPSymbols.TokenLBRACE:
- // opening brace of class body
- int pos= fPosition;
- int typeDeclPos= matchTypeDeclaration();
- fIndent= fPrefs.prefAccessSpecifierIndent;
- fExtraSpaces = fPrefs.prefAccessSpecifierExtraSpaces;
- if (typeDeclPos != NOT_FOUND) {
- return typeDeclPos;
- }
- return pos;
- case STPSymbols.TokenPUBLIC:
- case STPSymbols.TokenPROTECTED:
- case STPSymbols.TokenPRIVATE:
- // align with previous access specifier
- fIndent= 0;
- return fPosition;
-
- // scopes: skip them
- case STPSymbols.TokenRPAREN:
- case STPSymbols.TokenRBRACKET:
- case STPSymbols.TokenRBRACE:
- skipScope();
- break;
-
- default:
- // keep searching
- continue;
- }
- }
- }
-
- /**
- * Returns the reference position for a list element. The algorithm
- * tries to match any previous indentation on the same list. If there is none,
- * the reference position returned is determined depending on the type of list:
- * The indentation will either match the list scope introducer (e.g. for
- * method declarations), so called deep indents, or simply increase the
- * indentation by a number of standard indents. See also {@link #handleScopeIntroduction(int, boolean)}.
- * @return the reference position for a list item: either a previous list item
- * that has its own indentation, or the list introduction start.
- */
- private int skipToPreviousListItemOrListStart() {
- int startLine= fLine;
- int startPosition= fPosition;
- int linesSkippedInsideScopes = 0;
- boolean continuationLineCandidate =
- fToken == STPSymbols.TokenEQUAL || fToken == STPSymbols.TokenSHIFTLEFT ||
- fToken == STPSymbols.TokenRPAREN;
- while (true) {
- int previous = fToken;
- nextToken();
-
- // If any line item comes with its own indentation, adapt to it
- if (fLine < startLine - linesSkippedInsideScopes) {
- try {
- int lineOffset= fDocument.getLineOffset(startLine);
- int bound= Math.min(fDocument.getLength(), startPosition + 1);
- if ((fToken == STPSymbols.TokenSEMICOLON || fToken == STPSymbols.TokenRBRACE || fToken == STPSymbols.TokenIDENT ||
- fToken == STPSymbols.TokenLBRACE && !looksLikeArrayInitializerIntro() && !looksLikeEnumDeclaration()) &&
- continuationLineCandidate) {
- fIndent = fPrefs.prefContinuationIndent;
- } else {
- fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, bound);
- // If the reference line starts with a colon, skip the colon.
- if (peekToken(fAlign) == STPSymbols.TokenCOLON) {
- fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(fAlign + 1, bound);
- }
- }
- } catch (BadLocationException e) {
- // Ignore and return just the position
- }
- return startPosition;
- }
-
- int line = fLine;
- switch (fToken) {
- // scopes: skip them
- case STPSymbols.TokenRPAREN:
- continuationLineCandidate = true;
- //$FALL-THROUGH$
- case STPSymbols.TokenRBRACKET:
- case STPSymbols.TokenRBRACE:
- skipScope();
- linesSkippedInsideScopes = line - fLine;
- break;
-
- // scope introduction: special treat who special is
- case STPSymbols.TokenLPAREN:
- case STPSymbols.TokenLBRACE:
- case STPSymbols.TokenLBRACKET:
- return handleScopeIntroduction(startPosition + 1, false);
-
- case STPSymbols.TokenSEMICOLON:
- return fPosition;
-
- case STPSymbols.TokenQUESTIONMARK:
- if (fPrefs.prefTernaryDeepAlign) {
- setFirstElementAlignment(fPosition - 1, fPosition + 1);
- } else {
- fIndent= fPrefs.prefTernaryIndent;
- }
- return fPosition;
-
- case STPSymbols.TokenEQUAL:
- case STPSymbols.TokenSHIFTLEFT:
- continuationLineCandidate = true;
- break;
-
- case STPSymbols.TokenRETURN:
- case STPSymbols.TokenUSING:
- fIndent = fPrefs.prefContinuationIndent;
- return fPosition;
-
- case STPSymbols.TokenTYPEDEF:
- switch (previous) {
- case STPSymbols.TokenSTRUCT:
- case STPSymbols.TokenUNION:
- case STPSymbols.TokenCLASS:
- case STPSymbols.TokenENUM:
- break;
- default:
- fIndent = fPrefs.prefContinuationIndent;
- }
- return fPosition;
-
- case STPSymbols.TokenEOF:
- if (continuationLineCandidate) {
- fIndent = fPrefs.prefContinuationIndent;
- }
- return 0;
- }
- }
- }
-
- /**
- * Skips a scope and positions the cursor (<code>fPosition</code>) on the
- * token that opens the scope. Returns <code>true</code> if a matching peer
- * could be found, <code>false</code> otherwise. The current token when calling
- * must be one out of <code>STPSymbols.TokenRPAREN</code>, <code>STPSymbols.TokenRBRACE</code>,
- * and <code>STPSymbols.TokenRBRACKET</code>.
- *
- * @return <code>true</code> if a matching peer was found, <code>false</code> otherwise
- */
- private boolean skipScope() {
- switch (fToken) {
- case STPSymbols.TokenRPAREN:
- return skipScope(STPSymbols.TokenLPAREN, STPSymbols.TokenRPAREN);
- case STPSymbols.TokenRBRACKET:
- return skipScope(STPSymbols.TokenLBRACKET, STPSymbols.TokenRBRACKET);
- case STPSymbols.TokenRBRACE:
- return skipScope(STPSymbols.TokenLBRACE, STPSymbols.TokenRBRACE);
- case STPSymbols.TokenGREATERTHAN:
- if (!fPrefs.prefHasTemplates)
- return false;
- int storedPosition= fPosition;
- int storedToken= fToken;
- nextToken();
- switch (fToken) {
- case STPSymbols.TokenIDENT:
- fPosition = storedPosition;
- if (skipScope(STPSymbols.TokenLESSTHAN, STPSymbols.TokenGREATERTHAN))
- return true;
- break;
- case STPSymbols.TokenQUESTIONMARK:
- case STPSymbols.TokenGREATERTHAN:
- fPosition = storedPosition;
- if (skipScope(STPSymbols.TokenLESSTHAN, STPSymbols.TokenGREATERTHAN))
- return true;
- break;
- }
- // <> are harder to detect - restore the position if we fail
- fPosition= storedPosition;
- fToken= storedToken;
- return false;
-
- default:
- // programming error
- Assert.isTrue(false);
- return false;
- }
- }
-
- /**
- * Returns the contents of the current token.
- *
- * @return the contents of the current token
- */
- private CharSequence getTokenContent() {
- return new DocumentCharacterIterator(fDocument, fPosition, fPreviousPos);
- }
-
- /**
- * Handles the introduction of a new scope. The current token must be one out
- * of <code>STPSymbols.TokenLPAREN</code>, <code>STPSymbols.TokenLBRACE</code>,
- * and <code>STPSymbols.TokenLBRACKET</code>. Returns as the reference position
- * either the token introducing the scope or - if available - the first
- * token after that.
- *
- * <p>Depending on the type of scope introduction, the indentation will align
- * (deep indenting) with the reference position (<code>fAlign</code> will be
- * set to the reference position) or <code>fIndent</code> will be set to
- * the number of indentation units.
- * </p>
- *
- * @param bound the bound for the search for the first token after the scope
- * introduction.
- * @param firstToken <code>true</code> if we are dealing with the first token after
- * the opening parenthesis.
- * @return the indent
- */
- private int handleScopeIntroduction(int bound, boolean firstToken) {
- int pos= fPosition; // store
-
- switch (fToken) {
- // scope introduction: special treat who special is
- case STPSymbols.TokenLPAREN:
- // special: method declaration deep indentation
- if (looksLikeMethodDecl()) {
- if (firstToken ? fPrefs.prefMethodDeclFirstParameterDeepIndent : fPrefs.prefMethodDeclDeepIndent) {
- return setFirstElementAlignment(pos, bound);
- } else {
- fIndent= fPrefs.prefMethodDeclIndent;
- return pos;
- }
- } else {
- fPosition= pos;
- if (looksLikeMethodCall()) {
- if (firstToken ? fPrefs.prefMethodCallFirstParameterDeepIndent : fPrefs.prefMethodCallDeepIndent) {
- return setFirstElementAlignment(pos, bound);
- } else {
- fIndent= fPrefs.prefMethodCallIndent;
- return pos;
- }
- } else if (fPrefs.prefParenthesisDeepIndent) {
- return setFirstElementAlignment(pos, bound);
- }
- }
-
- // normal: return the parenthesis as reference
- fIndent= fPrefs.prefParenthesisIndent;
- return pos;
-
- case STPSymbols.TokenLBRACE:
- final boolean looksLikeArrayInitializerIntro= looksLikeArrayInitializerIntro();
- // special: array initializer
- if (looksLikeArrayInitializerIntro) {
- if (fPrefs.prefArrayDeepIndent)
- return setFirstElementAlignment(pos, bound);
- else
- fIndent= fPrefs.prefArrayIndent;
- } else if (isNamespace() || isLinkageSpec()) {
- fIndent= fPrefs.prefNamespaceBodyIndent;
- } else if (looksLikeEnumDeclaration()) {
- fIndent = fPrefs.prefTypeIndent;
- } else {
- int typeDeclPos = matchTypeDeclaration();
- if (typeDeclPos == NOT_FOUND) {
- fIndent= fPrefs.prefBlockIndent;
- } else {
- fIndent= fPrefs.prefAccessSpecifierIndent + fPrefs.prefTypeIndent;
- }
- }
-
- // normal: skip to the statement start before the scope introducer
- // opening braces are often on differently ending indents than e.g. a method definition
- if (!looksLikeArrayInitializerIntro) {
- fPosition= pos; // restore
- return skipToStatementStart(true, true); // set to true to match the first if
- } else {
- return pos;
- }
-
- case STPSymbols.TokenLBRACKET:
- // special: method declaration deep indentation
- if (fPrefs.prefArrayDimensionsDeepIndent) {
- return setFirstElementAlignment(pos, bound);
- }
-
- // normal: return the bracket as reference
- fIndent= fPrefs.prefBracketIndent;
- return pos; // restore
-
- default:
- // programming error
- Assert.isTrue(false);
- return -1; // dummy
- }
- }
-
- /**
- * Sets the deep indent offset (<code>fAlign</code>) to either the offset
- * right after <code>scopeIntroducerOffset</code> or - if available - the
- * first C token after <code>scopeIntroducerOffset</code>, but before
- * <code>bound</code>.
- *
- * @param scopeIntroducerOffset the offset of the scope introducer
- * @param bound the bound for the search for another element
- * @return the reference position
- */
- private int setFirstElementAlignment(int scopeIntroducerOffset, int bound) {
- int firstPossible= scopeIntroducerOffset + 1; // align with the first position after the scope intro
- fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(firstPossible, bound);
- if (fAlign == NOT_FOUND) {
- fAlign= firstPossible;
- } else {
- try {
- IRegion lineRegion = fDocument.getLineInformationOfOffset(scopeIntroducerOffset);
- if (fAlign > lineRegion.getOffset() + lineRegion.getLength()) {
- fAlign= firstPossible;
- }
- } catch (BadLocationException e) {
- // Ignore.
- }
- }
- return fAlign;
- }
-
- /**
- * Returns <code>true</code> if the next token received after calling
- * <code>nextToken</code> is either an equal sign, an opening brace,
- * a comma or an array designator ('[]').
- *
- * @return <code>true</code> if the next elements look like the start of an array definition
- */
- private boolean looksLikeArrayInitializerIntro() {
- int pos= fPosition;
- nextToken();
- switch (fToken) {
- case STPSymbols.TokenEQUAL:
- return true;
- case STPSymbols.TokenRBRACKET:
- return skipBrackets();
- case STPSymbols.TokenLBRACE:
- if (looksLikeArrayInitializerIntro()) {
- fPosition= pos;
- return true;
- }
- return false;
- case STPSymbols.TokenCOMMA:
- fPosition= pos;
- return true;
- }
- fPosition= pos;
- return false;
- }
-
- /**
- * Returns <code>true</code> if the the current token is "namespace", or the current token
- * is an identifier and the previous token is "namespace".
- *
- * @return <code>true</code> if the next elements look like the start of a namespace declaration.
- */
- private boolean isNamespace() {
- int pos = fPosition;
- nextToken();
- if (fToken == STPSymbols.TokenNAMESPACE) {
- fPosition = pos;
- return true; // Anonymous namespace
- } else if (fToken == STPSymbols.TokenIDENT) {
- nextToken(); // Get previous token
- if (fToken == STPSymbols.TokenNAMESPACE) {
- fPosition = pos;
- return true; // Named namespace
- }
- }
- fPosition = pos;
- return false;
- }
-
- /**
- * Returns <code>true</code> if the current token is keyword "extern".
- *
- * @return <code>true</code> if the next elements look like the start of a linkage spec.
- */
- private boolean isLinkageSpec() {
- int pos = fPosition;
- nextToken();
- if (fToken == STPSymbols.TokenEXTERN) {
- fPosition = pos;
- return true;
- }
- fPosition = pos;
- return false;
- }
-
- /**
- * Skips over the next <code>if</code> keyword. The current token when calling
- * this method must be an <code>else</code> keyword. Returns <code>true</code>
- * if a matching <code>if</code> could be found, <code>false</code> otherwise.
- * The cursor (<code>fPosition</code>) is set to the offset of the <code>if</code>
- * token.
- *
- * @return <code>true</code> if a matching <code>if</code> token was found, <code>false</code> otherwise
- */
- private boolean skipNextIF() {
- Assert.isTrue(fToken == STPSymbols.TokenELSE);
-
- while (true) {
- nextToken();
- switch (fToken) {
- // scopes: skip them
- case STPSymbols.TokenRPAREN:
- case STPSymbols.TokenRBRACKET:
- case STPSymbols.TokenRBRACE:
- skipScope();
- break;
-
- case STPSymbols.TokenIF:
- // found it, return
- return true;
- case STPSymbols.TokenELSE:
- // recursively skip else-if blocks
- skipNextIF();
- break;
-
- // shortcut scope starts
- case STPSymbols.TokenLPAREN:
- case STPSymbols.TokenLBRACE:
- case STPSymbols.TokenLBRACKET:
- case STPSymbols.TokenEOF:
- return false;
- }
- }
- }
-
- /**
- * while(condition); is ambiguous when parsed backwardly, as it is a valid
- * statement by its own, so we have to check whether there is a matching
- * do. A <code>do</code> can either be separated from the while by a
- * block, or by a single statement, which limits our search distance.
- *
- * @return <code>true</code> if the <code>while</code> currently in
- * <code>fToken</code> has a matching <code>do</code>.
- */
- private boolean hasMatchingDo() {
- Assert.isTrue(fToken == STPSymbols.TokenWHILE);
- nextToken();
- switch (fToken) {
- case STPSymbols.TokenRBRACE:
- skipScope(); // and fall thru
- skipToStatementStart(false, false);
- return fToken == STPSymbols.TokenDO;
-
- case STPSymbols.TokenSEMICOLON:
- skipToStatementStart(false, false);
- return fToken == STPSymbols.TokenDO;
- }
- return false;
- }
-
- /**
- * Skips pointer operators if the current token is a pointer operator.
- *
- * @return <code>true</code> if a <code>*</code> or <code>&amp;</code> could be scanned, the
- * current token is left at the operator.
- */
- private boolean skipPointerOperators() {
- if (fToken == STPSymbols.TokenOTHER) {
- CharSequence token= getTokenContent().toString().trim();
- if (token.length() == 1 && token.charAt(0) == '*' || token.charAt(0) == '&') {
- return true;
- }
- } else if (fToken == STPSymbols.TokenCONST) {
- return true;
- }
- return false;
- }
-
- /**
- * Skips brackets if the current token is a RBRACKET. There can be nothing
- * but whitespace in between, this is only to be used for <code>[]</code> elements.
- *
- * @return <code>true</code> if a <code>[]</code> could be scanned, the
- * current token is left at the LBRACKET.
- */
- private boolean skipBrackets() {
- if (fToken == STPSymbols.TokenRBRACKET) {
- nextToken();
- if (fToken == STPSymbols.TokenLBRACKET) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Skips scope qualifiers of identifiers.
- *
- * @return <code>true</code> if a qualifier was encountered, the last token
- * will be an IDENT.
- */
- private boolean skipQualifiers() {
- if (fToken == STPSymbols.TokenDOUBLECOLON) {
- nextToken();
- if (fToken == STPSymbols.TokenIDENT) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Reads the next token in backward direction from the heuristic scanner
- * and sets the fields <code>fToken, fPreviousPosition</code> and <code>fPosition</code>
- * accordingly.
- */
- private void nextToken() {
- nextToken(fPosition);
- }
-
- /**
- * Reads the next token in backward direction of <code>start</code> from
- * the heuristic scanner and sets the fields <code>fToken, fPreviousPosition</code>
- * and <code>fPosition</code> accordingly.
- *
- * @param start the start offset from which to scan backwards
- */
- private void nextToken(int start) {
- fToken= fScanner.previousToken(start - 1, STPHeuristicScanner.UNBOUND);
- fPreviousPos= start;
- fPosition= fScanner.getPosition() + 1;
- try {
- fLine= fDocument.getLineOfOffset(fPosition);
- } catch (BadLocationException e) {
- fLine= -1;
- }
- }
-
- /**
- * Reads the next token in backward direction from the heuristic scanner
- * and returns that token without changing the current position.
- */
- private int peekToken() {
- return fScanner.previousToken(fPosition - 1, STPHeuristicScanner.UNBOUND);
- }
-
- /**
- * Returns <code>true</code> if the current tokens look like a method
- * declaration header (i.e. only the return type and method name). The
- * heuristic calls <code>nextToken</code> and expects an identifier
- * (method name) and an optional return type declaration.
- *
- * @return <code>true</code> if the current position looks like a method
- * declaration header.
- */
- private boolean looksLikeMethodDecl() {
- nextToken();
- switch (fToken) {
- case STPSymbols.TokenIDENT: // method name
- int pos= fPosition;
- nextToken();
- // check destructor tilde
- if (fToken == STPSymbols.TokenTILDE) {
- return true;
- }
- if (skipQualifiers()) {
- return true;
- }
- // optional brackets for array valued return types
- while (skipBrackets()) {
- nextToken();
- }
- while (skipPointerOperators()) {
- nextToken();
- }
- switch (fToken) {
- case STPSymbols.TokenIDENT:
- return true;
- case STPSymbols.TokenSEMICOLON:
- case STPSymbols.TokenRBRACE:
- fPosition= pos;
- return true;
- case STPSymbols.TokenLBRACE:
- if (fScanner.looksLikeCompositeTypeDefinitionBackward(fPosition, STPHeuristicScanner.UNBOUND)) {
- fPosition= pos;
- return true;
- }
- break;
- case STPSymbols.TokenCOMMA:
- nextToken();
- if (fToken == STPSymbols.TokenRPAREN) {
- // field initializer
- if (skipScope()) {
- return looksLikeMethodDecl();
- }
- }
- break;
- case STPSymbols.TokenCOLON:
- nextToken();
- switch (fToken) {
- case STPSymbols.TokenPUBLIC:
- case STPSymbols.TokenPROTECTED:
- case STPSymbols.TokenPRIVATE:
- fPosition= pos;
- return true;
- case STPSymbols.TokenRPAREN:
- // constructor initializer
- if (skipScope()) {
- pos = fPosition;
- nextToken();
- // optional throw
- if (fToken == STPSymbols.TokenTHROW) {
- nextToken();
- if (fToken != STPSymbols.TokenRPAREN || !skipScope()) {
- return false;
- }
- } else {
- fPosition = pos;
- }
- return looksLikeMethodDecl();
- }
- break;
- }
- }
- break;
- case STPSymbols.TokenARROW:
- case STPSymbols.TokenCOMMA:
- case STPSymbols.TokenEQUAL:
- case STPSymbols.TokenGREATERTHAN:
- case STPSymbols.TokenLESSTHAN:
- case STPSymbols.TokenMINUS:
- case STPSymbols.TokenPLUS:
- case STPSymbols.TokenSHIFTRIGHT:
- case STPSymbols.TokenSHIFTLEFT:
- case STPSymbols.TokenDELETE:
- case STPSymbols.TokenNEW:
- nextToken();
- return fToken == STPSymbols.TokenOPERATOR;
- case STPSymbols.TokenRPAREN:
- nextToken();
- if (fToken != STPSymbols.TokenLPAREN)
- return false;
- nextToken();
- return fToken == STPSymbols.TokenOPERATOR;
- case STPSymbols.TokenRBRACKET:
- nextToken();
- if (fToken != STPSymbols.TokenLBRACKET)
- return false;
- nextToken();
- if (fToken == STPSymbols.TokenNEW || fToken == STPSymbols.TokenDELETE)
- nextToken();
- return fToken == STPSymbols.TokenOPERATOR;
- case STPSymbols.TokenOTHER:
- if (getTokenContent().length() == 1) {
- nextToken();
- if (fToken == STPSymbols.TokenOPERATOR)
- return true;
- }
- if (getTokenContent().length() == 1) {
- nextToken();
- if (fToken == STPSymbols.TokenOPERATOR)
- return true;
- }
- }
- return false;
- }
-
- /**
- * Returns <code>true</code> if the current tokens look like an anonymous type declaration
- * header (i.e. a type name (potentially qualified) and a new keyword). The heuristic calls
- * <code>nextToken</code> and expects a possibly qualified identifier (type name) and a new
- * keyword
- *
- * @return <code>true</code> if the current position looks like a anonymous type declaration
- * header.
- */
- private boolean looksLikeAnonymousTypeDecl() {
- nextToken();
- if (fToken == STPSymbols.TokenIDENT) { // type name
- nextToken();
- while (fToken == STPSymbols.TokenOTHER) { // dot of qualification
- nextToken();
- if (fToken != STPSymbols.TokenIDENT) // qualifying name
- return false;
- nextToken();
- }
- return fToken == STPSymbols.TokenNEW;
- }
- return false;
- }
-
- /**
- * Returns <code>true</code> if the current tokens look like beginning of a method
- * call (i.e. an identifier as opposed to a keyword taking parenthesized parameters
- * such as <code>if</code>).
- * <p>The heuristic calls <code>nextToken</code> and expects an identifier
- * (method name).
- *
- * @return <code>true</code> if the current position looks like a method call
- * header.
- */
- private boolean looksLikeMethodCall() {
- nextToken();
- if (fToken == STPSymbols.TokenGREATERTHAN) {
- if (!skipScope())
- return false;
- nextToken();
- }
- return fToken == STPSymbols.TokenIDENT; // method name
- }
-
- /**
- * Scans tokens for the matching opening peer. The internal cursor
- * (<code>fPosition</code>) is set to the offset of the opening peer if found.
- *
- * @param openToken the opening peer token
- * @param closeToken the closing peer token
- * @return <code>true</code> if a matching token was found, <code>false</code>
- * otherwise
- */
- private boolean skipScope(int openToken, int closeToken) {
- int depth= 1;
-
- while (true) {
- nextToken();
-
- if (fToken == closeToken) {
- depth++;
- } else if (fToken == openToken) {
- depth--;
- if (depth == 0)
- return true;
- } else if (fToken == STPSymbols.TokenEOF) {
- return false;
- }
- }
- }
+ /**
+ * The CDT Core preferences.
+ */
+ private final class CorePrefs {
+ private final boolean prefUseTabs;
+ private final boolean prefArrayDimensionsDeepIndent;
+ private final int prefArrayIndent;
+ private final boolean prefArrayDeepIndent;
+ private final boolean prefTernaryDeepAlign;
+ private final int prefTernaryIndent;
+ private final int prefCaseIndent;
+ private final int prefCaseBlockIndent;
+ private final int prefAssignmentIndent;
+ private final int prefSimpleIndent;
+ private final int prefBracketIndent;
+ private final boolean prefMethodDeclDeepIndent;
+ private final boolean prefMethodDeclFirstParameterDeepIndent;
+ private final int prefMethodDeclIndent;
+ private final boolean prefMethodCallDeepIndent;
+ private final boolean prefMethodCallFirstParameterDeepIndent;
+ private final int prefMethodCallIndent;
+ private final boolean prefParenthesisDeepIndent;
+ private final int prefParenthesisIndent;
+ private final int prefBlockIndent;
+ private final int prefMethodBodyIndent;
+ private final int prefTypeIndent;
+ private final int prefAccessSpecifierIndent;
+ private final int prefAccessSpecifierExtraSpaces;
+ private final int prefNamespaceBodyIndent;
+ private final boolean prefIndentBracesForBlocks;
+ private final boolean prefIndentBracesForArrays;
+ private final boolean prefIndentBracesForMethods;
+ private final boolean prefIndentBracesForTypes;
+ private final int prefContinuationIndent;
+ private final boolean prefHasTemplates;
+ private final String prefTabChar;
+
+ private final IPreferencesService preferenceService;
+ private final IScopeContext[] preferenceContexts;
+
+ /**
+ * Returns the possibly project-specific core preference defined under <code>key</code>.
+ *
+ * @param key the key of the preference
+ * @return the value of the preference
+ */
+ private String getCoreFormatterOption(String key) {
+ return getCoreFormatterOption(key, null);
+ }
+
+ private String getCoreFormatterOption(String key, String defaultValue) {
+ return preferenceService.getString(IDEPlugin.PLUGIN_ID, key, defaultValue, preferenceContexts);
+ }
+
+ private int getCoreFormatterOption(String key, int defaultValue) {
+ return preferenceService.getInt(IDEPlugin.PLUGIN_ID, key, defaultValue, preferenceContexts);
+ }
+
+ CorePrefs(IProject project) {
+ preferenceService = Platform.getPreferencesService();
+ preferenceContexts = project != null ?
+ new IScopeContext[] { new ProjectScope(project.getProject()),
+ InstanceScope.INSTANCE, DefaultScope.INSTANCE } :
+ new IScopeContext[] { InstanceScope.INSTANCE, DefaultScope.INSTANCE };
+ prefUseTabs= prefUseTabs();
+ prefArrayDimensionsDeepIndent= prefArrayDimensionsDeepIndent();
+ prefContinuationIndent= prefContinuationIndent();
+ prefBlockIndent= prefBlockIndent();
+ prefArrayIndent= prefArrayIndent();
+ prefArrayDeepIndent= prefArrayDeepIndent();
+ prefTernaryDeepAlign= false;
+ prefTernaryIndent= prefContinuationIndent();
+ prefCaseIndent= prefCaseIndent();
+ prefCaseBlockIndent= prefCaseBlockIndent();
+ prefAssignmentIndent= prefAssignmentIndent();
+ prefIndentBracesForBlocks= prefIndentBracesForBlocks();
+ prefSimpleIndent= prefSimpleIndent();
+ prefBracketIndent= prefBracketIndent();
+ prefMethodDeclDeepIndent= prefMethodDeclDeepIndent();
+ prefMethodDeclFirstParameterDeepIndent= prefMethodDeclFirstParameterDeepIndent();
+ prefMethodDeclIndent= prefMethodDeclIndent();
+ prefMethodCallDeepIndent= prefMethodCallDeepIndent();
+ prefMethodCallFirstParameterDeepIndent= prefMethodCallFirstParameterDeepIndent();
+ prefMethodCallIndent= prefMethodCallIndent();
+ prefParenthesisDeepIndent= prefParenthesisDeepIndent();
+ prefParenthesisIndent= prefParenthesisIndent();
+ prefMethodBodyIndent= prefMethodBodyIndent();
+ prefTypeIndent= prefTypeIndent();
+ prefAccessSpecifierIndent= prefAccessSpecifierIndent();
+ prefAccessSpecifierExtraSpaces= prefAccessSpecifierExtraSpaces();
+ prefNamespaceBodyIndent= prefNamespaceBodyIndent();
+ prefIndentBracesForArrays= prefIndentBracesForArrays();
+ prefIndentBracesForMethods= prefIndentBracesForMethods();
+ prefIndentBracesForTypes= prefIndentBracesForTypes();
+ prefHasTemplates= hasTemplates();
+ prefTabChar= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_TAB_CHAR);
+ }
+
+ private boolean prefUseTabs() {
+ return !IDEPlugin.SPACE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_TAB_CHAR));
+ }
+
+ private boolean prefArrayDimensionsDeepIndent() {
+ return true; // sensible default, no formatter setting
+ }
+
+ private int prefArrayIndent() {
+ String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_INITIALIZER_LIST);
+ try {
+ if (STPDefaultCodeFormatterConstants.getIndentStyle(option) == STPDefaultCodeFormatterConstants.INDENT_BY_ONE)
+ return 1;
+ } catch (IllegalArgumentException e) {
+ // ignore and return default
+ }
+
+ return prefContinuationIndent(); // default
+ }
+
+ private boolean prefArrayDeepIndent() {
+ String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_INITIALIZER_LIST);
+ try {
+ return STPDefaultCodeFormatterConstants.getIndentStyle(option) == STPDefaultCodeFormatterConstants.INDENT_ON_COLUMN;
+ } catch (IllegalArgumentException e) {
+ // ignore and return default
+ }
+
+ return true;
+ }
+
+ private int prefCaseIndent() {
+ if (STPDefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH)))
+ return 1;
+ else
+ return 0;
+ }
+
+ private int prefCaseBlockIndent() {
+ if (STPDefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES)))
+ return 1;
+ else
+ return 0;
+ }
+
+ private int prefAssignmentIndent() {
+ return prefContinuationIndent();
+ }
+
+ private int prefSimpleIndent() {
+ if (prefIndentBracesForBlocks() && prefBlockIndent() == 0)
+ return 1;
+ else
+ return prefBlockIndent();
+ }
+
+ private int prefBracketIndent() {
+ return prefBlockIndent();
+ }
+
+ private boolean prefMethodDeclDeepIndent() {
+ String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
+ try {
+ int indentStyle = STPDefaultCodeFormatterConstants.getIndentStyle(option);
+ return indentStyle == STPDefaultCodeFormatterConstants.INDENT_ON_COLUMN;
+ } catch (IllegalArgumentException e) {
+ // ignore and return default
+ }
+
+ return false;
+ }
+
+ private boolean prefMethodDeclFirstParameterDeepIndent() {
+ String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
+ try {
+ int indentStyle = STPDefaultCodeFormatterConstants.getIndentStyle(option);
+ int wrappingStyle = STPDefaultCodeFormatterConstants.getWrappingStyle(option);
+ return indentStyle == STPDefaultCodeFormatterConstants.INDENT_ON_COLUMN &&
+ (wrappingStyle == STPDefaultCodeFormatterConstants.WRAP_COMPACT_FIRST_BREAK ||
+ wrappingStyle == STPDefaultCodeFormatterConstants.WRAP_ONE_PER_LINE);
+ } catch (IllegalArgumentException e) {
+ // ignore and return default
+ }
+
+ return false;
+ }
+
+ private int prefMethodDeclIndent() {
+ String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION);
+ try {
+ if (STPDefaultCodeFormatterConstants.getIndentStyle(option) == STPDefaultCodeFormatterConstants.INDENT_BY_ONE)
+ return 1;
+ else
+ return prefContinuationIndent();
+ } catch (IllegalArgumentException e) {
+ // ignore and return default
+ }
+ return 1;
+ }
+
+ private boolean prefMethodCallDeepIndent() {
+ String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
+ try {
+ int indentStyle = STPDefaultCodeFormatterConstants.getIndentStyle(option);
+ return indentStyle == STPDefaultCodeFormatterConstants.INDENT_ON_COLUMN;
+ } catch (IllegalArgumentException e) {
+ // ignore and return default
+ }
+ return false; // sensible default
+ }
+
+ private boolean prefMethodCallFirstParameterDeepIndent() {
+ String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
+ try {
+ int indentStyle = STPDefaultCodeFormatterConstants.getIndentStyle(option);
+ int wrappingStyle = STPDefaultCodeFormatterConstants.getWrappingStyle(option);
+ return indentStyle == STPDefaultCodeFormatterConstants.INDENT_ON_COLUMN &&
+ (wrappingStyle == STPDefaultCodeFormatterConstants.WRAP_COMPACT_FIRST_BREAK ||
+ wrappingStyle == STPDefaultCodeFormatterConstants.WRAP_ONE_PER_LINE);
+ } catch (IllegalArgumentException e) {
+ // ignore and return default
+ }
+ return false; // sensible default
+ }
+
+ private int prefMethodCallIndent() {
+ String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION);
+ try {
+ if (STPDefaultCodeFormatterConstants.getIndentStyle(option) == STPDefaultCodeFormatterConstants.INDENT_BY_ONE)
+ return 1;
+ else
+ return prefContinuationIndent();
+ } catch (IllegalArgumentException e) {
+ // ignore and return default
+ }
+
+ return 1; // sensible default
+ }
+
+ private boolean prefParenthesisDeepIndent() {
+ return false;
+ }
+
+ private int prefParenthesisIndent() {
+ return prefContinuationIndent();
+ }
+
+ private int prefBlockIndent() {
+ String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK);
+ if (STPDefaultCodeFormatterConstants.FALSE.equals(option))
+ return 0;
+
+ return 1; // sensible default
+ }
+
+ private int prefMethodBodyIndent() {
+ if (STPDefaultCodeFormatterConstants.FALSE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BODY)))
+ return 0;
+
+ return 1; // sensible default
+ }
+
+ private int prefTypeIndent() {
+ String option= getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_ACCESS_SPECIFIER);
+ if (STPDefaultCodeFormatterConstants.FALSE.equals(option))
+ return 0;
+
+ return 1; // sensible default
+ }
+
+ private int prefAccessSpecifierIndent() {
+ if (STPDefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_ACCESS_SPECIFIER_COMPARE_TO_TYPE_HEADER)))
+ return 1;
+ else
+ return 0;
+ }
+
+ private int prefAccessSpecifierExtraSpaces() {
+ return getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_ACCESS_SPECIFIER_EXTRA_SPACES, 0);
+ }
+
+ private int prefNamespaceBodyIndent() {
+ if (STPDefaultCodeFormatterConstants.TRUE.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_NAMESPACE_HEADER)))
+ return prefBlockIndent();
+ else
+ return 0;
+ }
+
+ private boolean prefIndentBracesForBlocks() {
+ return STPDefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK));
+ }
+
+ private boolean prefIndentBracesForArrays() {
+ return STPDefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_INITIALIZER_LIST));
+ }
+
+ private boolean prefIndentBracesForMethods() {
+ return STPDefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION));
+ }
+
+ private boolean prefIndentBracesForTypes() {
+ return STPDefaultCodeFormatterConstants.NEXT_LINE_SHIFTED.equals(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION));
+ }
+
+ private int prefContinuationIndent() {
+ try {
+ return Integer.parseInt(getCoreFormatterOption(STPDefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION));
+ } catch (NumberFormatException e) {
+ // ignore and return default
+ }
+
+ return 2; // sensible default
+ }
+
+ private boolean hasTemplates() {
+ return true;
+ }
+ }
+
+ /** The document being scanned. */
+ private final IDocument fDocument;
+ /** The indentation accumulated by <code>findReferencePosition</code>. */
+ private int fIndent;
+ /** Extra spaces to add on top of fIndent */
+ private int fExtraSpaces;
+ /**
+ * The absolute (character-counted) indentation offset for special cases
+ * (method definitions, array initializers)
+ */
+ private int fAlign;
+ /** The stateful scan position for the indentation methods. */
+ private int fPosition;
+ /** The previous position. */
+ private int fPreviousPos;
+ /** The most recent token. */
+ private int fToken;
+ /** The line of <code>fPosition</code>. */
+ private int fLine;
+ /**
+ * The scanner we will use to scan the document. It has to be installed
+ * on the same document as the one we get.
+ */
+ private final STPHeuristicScanner fScanner;
+ /**
+ * The CDT Core preferences.
+ */
+ private final CorePrefs fPrefs;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param document the document to scan
+ * @param scanner the {@link STPHeuristicScanner} to be used for scanning
+ * the document. It must be installed on the same <code>IDocument</code>.
+ */
+ public STPIndenter(IDocument document, STPHeuristicScanner scanner) {
+ this(document, scanner, null);
+ }
+
+ /**
+ * Creates a new instance.
+ *
+ * @param document the document to scan
+ * @param scanner the {@link STPHeuristicScanner} to be used for scanning
+ * the document. It must be installed on the same
+ * <code>IDocument</code>.
+ * @param project the C/C++ project to get the formatter preferences from, or
+ * <code>null</code> to use the workspace settings
+ */
+ public STPIndenter(IDocument document, STPHeuristicScanner scanner, IProject project) {
+ Assert.isNotNull(document);
+ Assert.isNotNull(scanner);
+ fDocument= document;
+ fScanner= scanner;
+ fPrefs= new CorePrefs(project);
+ }
+
+ /**
+ * Computes the indentation at the reference point of <code>position</code>.
+ *
+ * @param offset the offset in the document
+ * @return a String which reflects the indentation at the line in which the
+ * reference position to <code>offset</code> resides, or <code>null</code>
+ * if it cannot be determined
+ */
+ public StringBuilder getReferenceIndentation(int offset) {
+ return getReferenceIndentation(offset, false);
+ }
+
+ /**
+ * Computes the indentation at the reference point of <code>position</code>.
+ *
+ * @param offset the offset in the document
+ * @param assumeOpeningBrace <code>true</code> if an opening brace should be assumed
+ * @return a String which reflects the indentation at the line in which the
+ * reference position to <code>offset</code> resides, or <code>null</code>
+ * if it cannot be determined
+ */
+ private StringBuilder getReferenceIndentation(int offset, boolean assumeOpeningBrace) {
+ int unit= findReferencePosition(offset,
+ assumeOpeningBrace ? STPSymbols.TokenLBRACE : peekToken(offset));
+
+ // if we were unable to find anything, return null
+ if (unit == NOT_FOUND)
+ return null;
+
+ return getLeadingWhitespace(unit);
+ }
+
+ /**
+ * Computes the indentation at <code>offset</code>.
+ *
+ * @param offset the offset in the document
+ * @return a String which reflects the correct indentation for the line in
+ * which offset resides, or <code>null</code> if it cannot be
+ * determined
+ */
+ public StringBuilder computeIndentation(int offset) {
+ return computeIndentation(offset, false);
+ }
+
+ /**
+ * Computes the indentation at <code>offset</code>.
+ *
+ * @param offset the offset in the document
+ * @param assumeOpeningBrace <code>true</code> if an opening brace should be assumed
+ * @return a String which reflects the correct indentation for the line in
+ * which offset resides, or <code>null</code> if it cannot be
+ * determined
+ */
+ public StringBuilder computeIndentation(int offset, boolean assumeOpeningBrace) {
+ StringBuilder reference= getReferenceIndentation(offset, assumeOpeningBrace);
+
+ // handle special alignment
+ if (fAlign != NOT_FOUND) {
+ try {
+ // a special case has been detected.
+ IRegion line= fDocument.getLineInformationOfOffset(fAlign);
+ int lineOffset= line.getOffset();
+ return createIndent(lineOffset, fAlign, false);
+ } catch (BadLocationException e) {
+ return null;
+ }
+ }
+
+ if (reference == null)
+ return null;
+
+ // Add additional indent
+ return createReusingIndent(reference, fIndent, fExtraSpaces);
+ }
+
+ /**
+ * Computes the length of a <code>CharacterSequence</code>, counting
+ * a tab character as the size until the next tab stop and every other
+ * character as one.
+ *
+ * @param indent the string to measure
+ * @return the visual length in characters
+ */
+ private int computeVisualLength(CharSequence indent) {
+ final int tabSize= CodeFormatterUtil.getTabWidth();
+ int length= 0;
+ for (int i= 0; i < indent.length(); i++) {
+ char ch= indent.charAt(i);
+ switch (ch) {
+ case '\t':
+ if (tabSize > 0) {
+ int reminder= length % tabSize;
+ length += tabSize - reminder;
+ }
+ break;
+ case ' ':
+ length++;
+ break;
+ }
+ }
+ return length;
+ }
+
+ /**
+ * Strips any characters off the end of <code>reference</code> that exceed
+ * <code>indentLength</code>.
+ *
+ * @param reference the string to measure
+ * @param indentLength the maximum visual indentation length
+ * @return the stripped <code>reference</code>
+ */
+ private StringBuilder stripExceedingChars(StringBuilder reference, int indentLength) {
+ final int tabSize= CodeFormatterUtil.getTabWidth();
+ int measured= 0;
+ int chars= reference.length();
+ int i= 0;
+ for (; measured < indentLength && i < chars; i++) {
+ char ch= reference.charAt(i);
+ switch (ch) {
+ case '\t':
+ if (tabSize > 0) {
+ int reminder= measured % tabSize;
+ measured += tabSize - reminder;
+ }
+ break;
+ case ' ':
+ measured++;
+ break;
+ }
+ }
+ int deleteFrom= measured > indentLength ? i - 1 : i;
+
+ return reference.delete(deleteFrom, chars);
+ }
+
+ /**
+ * Returns the indentation of the line at <code>offset</code> as a
+ * <code>StringBuilder</code>. If the offset is not valid, the empty string
+ * is returned.
+ *
+ * @param offset the offset in the document
+ * @return the indentation (leading whitespace) of the line in which
+ * <code>offset</code> is located
+ */
+ private StringBuilder getLeadingWhitespace(int offset) {
+ StringBuilder indent= new StringBuilder();
+ try {
+ IRegion line= fDocument.getLineInformationOfOffset(offset);
+ int lineOffset= line.getOffset();
+ int nonWS= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, lineOffset + line.getLength());
+ indent.append(fDocument.get(lineOffset, nonWS - lineOffset));
+ return indent;
+ } catch (BadLocationException e) {
+ return indent;
+ }
+ }
+
+ /**
+ * Creates an indentation string of the length indent - start, consisting of
+ * the content in <code>fDocument</code> in the range [start, indent),
+ * with every character replaced by a space except for tabs, which are kept
+ * as such.
+ * <p>
+ * If <code>convertSpaceRunsToTabs</code> is <code>true</code>, every
+ * run of the number of spaces that make up a tab are replaced by a tab
+ * character. If it is not set, no conversion takes place, but tabs in the
+ * original range are still copied verbatim.
+ * </p>
+ *
+ * @param start the start of the document region to copy the indent from
+ * @param indent the exclusive end of the document region to copy the indent
+ * from
+ * @param convertSpaceRunsToTabs whether to convert consecutive runs of
+ * spaces to tabs
+ * @return the indentation corresponding to the document content specified
+ * by <code>start</code> and <code>indent</code>
+ */
+ private StringBuilder createIndent(int start, final int indent, final boolean convertSpaceRunsToTabs) {
+ final boolean convertTabs= fPrefs.prefUseTabs && convertSpaceRunsToTabs;
+ final int tabLen= CodeFormatterUtil.getTabWidth();
+ final StringBuilder ret= new StringBuilder();
+ try {
+ int spaces= 0;
+ while (start < indent) {
+ char ch= fDocument.getChar(start);
+ if (ch == '\t') {
+ ret.append('\t');
+ spaces= 0;
+ } else if (convertTabs) {
+ spaces++;
+ if (spaces == tabLen) {
+ ret.append('\t');
+ spaces= 0;
+ }
+ } else {
+ ret.append(' ');
+ }
+
+ start++;
+ }
+ // remainder
+ while (spaces-- > 0)
+ ret.append(' ');
+ } catch (BadLocationException e) {
+ }
+
+ return ret;
+ }
+
+ /**
+ * Creates a string with a visual length of the given
+ * <code>indentationSize</code>.
+ *
+ * @param buffer the original indent to reuse if possible
+ * @param additional the additional indentation units to add or subtract to
+ * reference
+ * @param extraSpaces additional spaces to add to indentation.
+ * @return the modified <code>buffer</code> reflecting the indentation
+ * adapted to <code>additional</code>
+ */
+ public StringBuilder createReusingIndent(StringBuilder buffer, int additional, int extraSpaces) {
+ int refLength= computeVisualLength(buffer);
+ int addLength= CodeFormatterUtil.getIndentWidth() * additional + extraSpaces; // may be < 0
+ int totalLength= Math.max(0, refLength + addLength);
+
+ // copy the reference indentation for the indent up to the last tab
+ // stop within the maxCopy area
+ int minLength= Math.min(totalLength, refLength);
+ int tabSize= CodeFormatterUtil.getTabWidth();
+ int maxCopyLength= tabSize > 0 ? minLength - minLength % tabSize : minLength; // maximum indent to copy
+ stripExceedingChars(buffer, maxCopyLength);
+
+ // add additional indent
+ int missing= totalLength - maxCopyLength;
+ int tabs, spaces;
+ if (IDEPlugin.SPACE.equals(fPrefs.prefTabChar)) {
+ tabs= 0;
+ spaces= missing;
+ } else {
+ tabs= tabSize > 0 ? missing / tabSize : 0;
+ spaces= tabSize > 0 ? missing % tabSize : missing;
+ }
+ for (int i= 0; i < tabs; i++)
+ buffer.append('\t');
+ for (int i= 0; i < spaces; i++)
+ buffer.append(' ');
+ return buffer;
+ }
+
+ /**
+ * Returns relative indent of continuation lines.
+ * @return a number of indentation units.
+ */
+ public int getContinuationLineIndent() {
+ return fPrefs.prefContinuationIndent;
+ }
+
+ /**
+ * Returns the reference position regarding to indentation for <code>offset</code>,
+ * or {@link STPHeuristicScanner#NOT_FOUND NOT_FOUND}. This method calls
+ * {@link #findReferencePosition(int, int) findReferencePosition(offset, nextChar)} where
+ * <code>nextChar</code> is the next character after <code>offset</code>.
+ *
+ * @param offset the offset for which the reference is computed
+ * @return the reference statement relative to which <code>offset</code>
+ * should be indented, or {@link STPHeuristicScanner#NOT_FOUND NOT_FOUND}
+ */
+ public int findReferencePosition(int offset) {
+ return findReferencePosition(offset, peekToken(offset));
+ }
+
+ /**
+ * Peeks the next token in the document that comes after <code>offset</code>
+ * on the same line as <code>offset</code>.
+ *
+ * @param offset the offset into document
+ * @return the token symbol of the next element, or TokenEOF if there is none
+ */
+ private int peekToken(int offset) {
+ if (offset < fDocument.getLength()) {
+ try {
+ IRegion line= fDocument.getLineInformationOfOffset(offset);
+ int lineEnd= line.getOffset() + line.getLength();
+ int next= fScanner.nextToken(offset, lineEnd);
+ return next;
+ } catch (BadLocationException e) {
+ }
+ }
+ return STPSymbols.TokenEOF;
+ }
+
+ /**
+ * Peeks the second next token in the document that comes after <code>offset</code>
+ * on the same line as <code>offset</code>.
+ *
+ * @param offset the offset into document
+ * @return the token symbol of the second next element, or TokenEOF if there is none
+ */
+ private int peekSecondToken(int offset) {
+ if (offset < fDocument.getLength()) {
+ try {
+ IRegion line= fDocument.getLineInformationOfOffset(offset);
+ int lineEnd= line.getOffset() + line.getLength();
+ fScanner.nextToken(offset, lineEnd);
+ int next = fScanner.nextToken(fScanner.getPosition(), lineEnd);
+ return next;
+ } catch (BadLocationException e) {
+ }
+ }
+ return STPSymbols.TokenEOF;
+ }
+
+ /**
+ * Returns the reference position regarding to indentation for <code>position</code>,
+ * or {@link STPHeuristicScanner#NOT_FOUND NOT_FOUND}.
+ *
+ * <p>If <code>peekNextChar</code> is <code>true</code>, the next token after
+ * <code>offset</code> is read and taken into account when computing the
+ * indentation. Currently, if the next token is the first token on the line
+ * (i.e. only preceded by whitespace), the following tokens are specially
+ * handled:
+ * <ul>
+ * <li><code>switch</code> labels are indented relative to the switch block</li>
+ * <li>opening curly braces are aligned correctly with the introducing code</li>
+ * <li>closing curly braces are aligned properly with the introducing code of
+ * the matching opening brace</li>
+ * <li>closing parenthesis' are aligned with their opening peer</li>
+ * <li>the <code>else</code> keyword is aligned with its <code>if</code>, anything
+ * else is aligned normally (i.e. with the base of any introducing statements).</li>
+ * <li>if there is no token on the same line after <code>offset</code>, the indentation
+ * is the same as for an <code>else</code> keyword</li>
+ * </ul>
+ *
+ * @param offset the offset for which the reference is computed
+ * @param nextToken the next token to assume in the document
+ * @return the reference statement relative to which <code>offset</code>
+ * should be indented, or {@link STPHeuristicScanner#NOT_FOUND NOT_FOUND}
+ */
+ private int findReferencePosition(int offset, int nextToken) {
+ boolean danglingElse= false;
+ boolean cancelIndent= false; // If set to true, fIndent is ignored.
+ int extraIndent= 0; // Can be either positive or negative.
+ MatchMode matchMode = MatchMode.REGULAR;
+
+ // Account for un-indentation characters already typed in, but after position.
+ // If they are on a line by themselves, the indentation gets adjusted accordingly.
+ //
+ // Also account for a dangling else.
+ if (offset < fDocument.getLength()) {
+ try {
+ IRegion line= fDocument.getLineInformationOfOffset(offset);
+ int lineOffset= line.getOffset();
+ int prevPos= Math.max(offset - 1, 0);
+ boolean isFirstTokenOnLine=
+ fDocument.get(lineOffset, prevPos + 1 - lineOffset).trim().length() == 0;
+ int prevToken= fScanner.previousToken(prevPos, STPHeuristicScanner.UNBOUND);
+ boolean bracelessBlockStart= fScanner.isBracelessBlockStart(prevPos, STPHeuristicScanner.UNBOUND);
+
+ switch (nextToken) {
+ case STPSymbols.TokenELSE:
+ danglingElse= true;
+ break;
+
+ case STPSymbols.TokenCASE:
+ case STPSymbols.TokenDEFAULT:
+ if (isFirstTokenOnLine)
+ matchMode = MatchMode.MATCH_CASE;
+ break;
+
+ case STPSymbols.TokenPUBLIC:
+ case STPSymbols.TokenPROTECTED:
+ case STPSymbols.TokenPRIVATE:
+ if (isFirstTokenOnLine && peekSecondToken(offset) != STPSymbols.TokenIDENT)
+ matchMode = MatchMode.MATCH_ACCESS_SPECIFIER;
+ break;
+
+ case STPSymbols.TokenLBRACE: // for opening-brace-on-new-line style
+ if (bracelessBlockStart) {
+ extraIndent= fPrefs.prefIndentBracesForBlocks ? 0 : -1;
+ } else if (prevToken == STPSymbols.TokenCOLON && !fPrefs.prefIndentBracesForBlocks) {
+ extraIndent= -1;
+ } else if ((prevToken == STPSymbols.TokenEQUAL || prevToken == STPSymbols.TokenRBRACKET) &&
+ !fPrefs.prefIndentBracesForArrays) {
+ cancelIndent= true;
+ } else if ((prevToken == STPSymbols.TokenRPAREN || prevToken == STPSymbols.TokenCONST) && fPrefs.prefIndentBracesForMethods) {
+ extraIndent= 1;
+ } else if (prevToken == STPSymbols.TokenIDENT) {
+ if (fPrefs.prefIndentBracesForTypes) {
+ extraIndent= 1;
+ }
+ int pos = fPosition;
+ fPosition = offset;
+ if (matchTypeDeclaration() != NOT_FOUND) {
+ matchMode = MatchMode.MATCH_TYPE_DECLARATION;
+ }
+ fPosition = pos;
+ }
+ break;
+
+ case STPSymbols.TokenRBRACE: // closing braces get unindented
+ if (isFirstTokenOnLine || prevToken != STPSymbols.TokenLBRACE)
+ matchMode = MatchMode.MATCH_BRACE;
+ break;
+
+ case STPSymbols.TokenRPAREN:
+ if (isFirstTokenOnLine)
+ matchMode = MatchMode.MATCH_PAREN;
+ break;
+ }
+ } catch (BadLocationException e) {
+ }
+ } else {
+ // Don't assume an else could come if we are at the end of file.
+ danglingElse= false;
+ }
+
+ int ref= findReferencePosition(offset, danglingElse, matchMode);
+ if (cancelIndent) {
+ fIndent = 0;
+ } else if (extraIndent > 0) {
+ fAlign= NOT_FOUND;
+ fIndent += extraIndent;
+ } else {
+ fIndent += extraIndent;
+ }
+ return ref;
+ }
+
+ /**
+ * Enumeration used by {@link #findReferencePosition(int, boolean, MatchMode)} method.
+ */
+ public enum MatchMode {
+ /**
+ * The reference position should be returned based on the regular code analysis.
+ */
+ REGULAR,
+ /**
+ * The position of the matching brace should be returned instead of doing code analysis.
+ */
+ MATCH_BRACE,
+ /**
+ * The position of the matching parenthesis should be returned instead of doing code
+ * analysis.
+ */
+ MATCH_PAREN,
+ /**
+ * The position of a switch statement reference should be returned (either an earlier case
+ * statement or the switch block brace).
+ */
+ MATCH_CASE,
+ /**
+ * The position of a class body reference should be returned (either an earlier
+ * public/protected/private or the class body brace).
+ */
+ MATCH_ACCESS_SPECIFIER,
+ /**
+ * The position of a class declaration should be returned.
+ */
+ MATCH_TYPE_DECLARATION
+ }
+
+ /**
+ * Returns the reference position regarding to indentation for <code>position</code>,
+ * or {@link STPHeuristicScanner#NOT_FOUND NOT_FOUND}. <code>fIndent</code> will contain
+ * the relative indentation (in indentation units, not characters) after the call. If there is
+ * a special alignment (e.g. for a method declaration where parameters should be aligned),
+ * <code>fAlign</code> will contain the absolute position of the alignment reference
+ * in <code>fDocument</code>, otherwise <code>fAlign</code> is set to
+ * {@link STPHeuristicScanner#NOT_FOUND}.
+ *
+ * @param offset the offset for which the reference is computed
+ * @param danglingElse whether a dangling else should be assumed at <code>position</code>
+ * @param matchMode determines what kind of reference position should be returned.
+ * See {@link MatchMode}.
+ * @return the reference statement relative to which <code>position</code>
+ * should be indented, or {@link STPHeuristicScanner#NOT_FOUND}
+ */
+ public int findReferencePosition(int offset, boolean danglingElse, MatchMode matchMode) {
+ fIndent= 0; // The indentation modification
+ fExtraSpaces= 0;
+ fAlign= NOT_FOUND;
+ fPosition= offset;
+
+ // Forward cases.
+ // An unindentation happens sometimes if the next token is special, namely on braces,
+ // parens and case labels align braces, but handle the case where we align with the method
+ // declaration start instead of the opening brace.
+ switch (matchMode) {
+ case MATCH_BRACE:
+ if (skipScope(STPSymbols.TokenLBRACE, STPSymbols.TokenRBRACE)) {
+ try {
+ // Align with the opening brace that is on a line by its own
+ int lineOffset= fDocument.getLineOffset(fLine);
+ if (lineOffset <= fPosition &&
+ fDocument.get(lineOffset, fPosition - lineOffset).trim().isEmpty()) {
+ return fPosition;
+ }
+ } catch (BadLocationException e) {
+ // Concurrent modification - walk default path
+ }
+ // If the opening brace is not on the start of the line, skip to the start.
+ int pos= skipToStatementStart(true, true);
+ fIndent= 0; // indent is aligned with reference position
+ return pos;
+ } else {
+ // If we can't find the matching brace, the heuristic is to unindent
+ // by one against the normal position
+ int pos= findReferencePosition(offset, danglingElse, MatchMode.REGULAR);
+ fIndent--;
+ return pos;
+ }
+
+ case MATCH_PAREN:
+ // Align parentheses.
+ if (skipScope(STPSymbols.TokenLPAREN, STPSymbols.TokenRPAREN)) {
+ return fPosition;
+ } else {
+ // If we can't find the matching paren, the heuristic is to unindent by one
+ // against the normal position.
+ int pos= findReferencePosition(offset, danglingElse, MatchMode.REGULAR);
+ fIndent--;
+ return pos;
+ }
+
+ case MATCH_CASE:
+ // The only reliable way to get case labels aligned (due to many different styles of
+ // using braces in a block) is to go for another case statement, or the scope opening
+ // brace.
+ return matchCaseAlignment();
+
+ case MATCH_ACCESS_SPECIFIER:
+ // The only reliable way to get access specifiers aligned (due to many different styles
+ // of using braces in a block) is to go for another access specifier, or the scope
+ // opening brace.
+ return matchAccessSpecifierAlignment();
+
+ case MATCH_TYPE_DECLARATION:
+ return matchTypeDeclaration();
+
+ case REGULAR:
+ break;
+ }
+
+ if (peekToken(offset) == STPSymbols.TokenCOLON) {
+ int pos= fPosition;
+ if (looksLikeTypeInheritanceDecl()) {
+ fIndent = fPrefs.prefContinuationIndent;
+ return fPosition;
+ }
+ fPosition = pos;
+ }
+
+ nextToken();
+ // Skip access specifiers
+ while (fToken == STPSymbols.TokenCOLON && isAccessSpecifier()) {
+ nextToken();
+ }
+
+ int line= fLine;
+ switch (fToken) {
+ case STPSymbols.TokenGREATERTHAN:
+ case STPSymbols.TokenRBRACE:
+ // Skip the block and fall through.
+ // If we can't complete the scope, reset the scan position
+ int pos= fPosition;
+ if (!skipScope())
+ fPosition= pos;
+ return skipToStatementStart(danglingElse, false);
+
+ case STPSymbols.TokenSEMICOLON:
+ // This is the 90% case: after a statement block
+ // the end of the previous statement / block previous.end
+ // search to the end of the statement / block before the previous;
+ // the token just after that is previous.start
+ return skipToStatementStart(danglingElse, false);
+
+ // Scope introduction: special treat who special is
+ case STPSymbols.TokenLPAREN:
+ case STPSymbols.TokenLBRACE:
+ case STPSymbols.TokenLBRACKET:
+ return handleScopeIntroduction(Math.min(offset + 1, fDocument.getLength()), true);
+
+ case STPSymbols.TokenEOF:
+ // trap when hitting start of document
+ return NOT_FOUND;
+
+ case STPSymbols.TokenEQUAL:
+ // indent assignments, but don't do so if there is a String
+ // after the assignment because SystemTap doesn't require
+ // semi-colons to end lines and so this should be treated as
+ // a complete assignment.
+ pos = fPosition;
+ while (pos < offset) {
+ try {
+ ITypedRegion partition = ((IDocumentExtension3)fDocument).getPartition(STPPartitionScanner.STP_PARTITIONING, pos, danglingElse);
+ if (STPPartitionScanner.STP_STRING.equals(partition.getType()))
+ return skipToStatementStart(danglingElse, false);
+ pos = partition.getOffset() + partition.getLength();
+ } catch (BadLocationException e) {
+ break;
+ } catch (BadPartitioningException e) {
+ break;
+ }
+ }
+ fIndent= fPrefs.prefAssignmentIndent;
+ return fPosition;
+ case STPSymbols.TokenCOLON:
+ pos= fPosition;
+ if (looksLikeCaseStatement()) {
+ fIndent= fPrefs.prefCaseBlockIndent;
+ return pos;
+ }
+ fPosition= pos;
+ if (looksLikeTypeInheritanceDecl()) {
+ fIndent= fPrefs.prefContinuationIndent;
+ return pos;
+ }
+ fPosition= pos;
+ if (looksLikeConstructorInitializer()) {
+ fIndent= fPrefs.prefBlockIndent;
+ return pos;
+ }
+ fPosition= pos;
+ if (isConditional()) {
+ fPosition= offset;
+ fLine= line;
+ return skipToPreviousListItemOrListStart();
+ }
+ fPosition= pos;
+ return skipToPreviousListItemOrListStart();
+
+ case STPSymbols.TokenQUESTIONMARK:
+ if (fPrefs.prefTernaryDeepAlign) {
+ setFirstElementAlignment(fPosition, offset + 1);
+ } else {
+ fIndent= fPrefs.prefTernaryIndent;
+ }
+ return fPosition;
+
+ // Indentation for blockless introducers:
+ case STPSymbols.TokenDO:
+ case STPSymbols.TokenWHILE:
+ case STPSymbols.TokenELSE:
+ fIndent= fPrefs.prefSimpleIndent;
+ return fPosition;
+
+ case STPSymbols.TokenTRY:
+ return skipToStatementStart(danglingElse, false);
+
+ case STPSymbols.TokenRETURN:
+ case STPSymbols.TokenTYPEDEF:
+ case STPSymbols.TokenUSING:
+ fIndent = fPrefs.prefContinuationIndent;
+ return fPosition;
+
+ case STPSymbols.TokenCONST:
+ nextToken();
+ if (fToken != STPSymbols.TokenRPAREN) {
+ return skipToPreviousListItemOrListStart();
+ }
+ // could be const method decl
+ //$FALL-THROUGH$
+ case STPSymbols.TokenRPAREN:
+ if (skipScope(STPSymbols.TokenLPAREN, STPSymbols.TokenRPAREN)) {
+ int scope= fPosition;
+ nextToken();
+ if (fToken == STPSymbols.TokenIF || fToken == STPSymbols.TokenWHILE || fToken == STPSymbols.TokenFOR
+ || fToken == STPSymbols.TokenFOREACH) {
+ fIndent= fPrefs.prefSimpleIndent;
+ return fPosition;
+ }
+ if (fToken == STPSymbols.TokenSWITCH) {
+ return fPosition;
+ }
+ fPosition= scope;
+ if (looksLikeMethodDecl()) {
+ return skipToStatementStart(danglingElse, false);
+ }
+ if (fToken == STPSymbols.TokenCATCH) {
+ return skipToStatementStart(danglingElse, false);
+ }
+ fPosition= scope;
+ if (looksLikeAnonymousTypeDecl()) {
+ return skipToStatementStart(danglingElse, false);
+ }
+ }
+ // restore
+ fPosition= offset;
+ fLine= line;
+ // else: fall through to default
+ return skipToPreviousListItemOrListStart();
+
+ case STPSymbols.TokenCOMMA:
+ // Inside a list of some type.
+ // Easy if there is already a list item before with its own indentation - we just align.
+ // If not: take the start of the list (LPAREN, LBRACE, LBRACKET) and either align or
+ // indent by list-indent.
+ return skipToPreviousListItemOrListStart();
+
+ case STPSymbols.TokenPLUS:
+ case STPSymbols.TokenMINUS:
+ case STPSymbols.TokenLESSTHAN:
+ case STPSymbols.TokenAGGREGATE:
+ case STPSymbols.TokenSHIFTRIGHT:
+ case STPSymbols.TokenSHIFTLEFT:
+ case STPSymbols.TokenOTHER:
+ // Math symbol, use skipToPreviousListItemOrListStart.
+ return skipToPreviousListItemOrListStart();
+ // Otherwise, fall-through
+ default:
+ // Inside whatever we don't know about:
+ // C would treat this as a list, but in SystemTap we might just have a line that doesn't
+ // end in a semi-colon. We want to indent to the same level as the statement.
+ return skipToStatementStart(danglingElse, false);
+ }
+ }
+
+ /**
+ * Test whether an identifier encountered during scanning is part of
+ * a type declaration, by scanning backward and ignoring any identifiers, commas,
+ * and colons until we hit <code>class</code>, <code>struct</code>, <code>union</code>,
+ * or <code>enum</code>. If any braces, semicolons, or parentheses are encountered,
+ * this is not a type declaration.
+ * @return the reference offset of the start of the statement
+ */
+ private int matchTypeDeclaration() {
+ while (true) {
+ nextToken();
+ if (fToken == STPSymbols.TokenIDENT
+ || fToken == STPSymbols.TokenCOMMA
+ || fToken == STPSymbols.TokenCOLON
+ || fToken == STPSymbols.TokenPUBLIC
+ || fToken == STPSymbols.TokenPROTECTED
+ || fToken == STPSymbols.TokenPRIVATE) {
+ continue;
+ }
+ if (fToken == STPSymbols.TokenCLASS
+ || fToken == STPSymbols.TokenSTRUCT
+ || fToken == STPSymbols.TokenUNION) {
+ // inside a type declaration? Only so if not preceded by '(' or ',' as in
+ // a parameter list. To be safe, only accept ';' or EOF
+ int pos= fPosition;
+ nextToken();
+ if (fToken == STPSymbols.TokenSEMICOLON || fToken == STPSymbols.TokenEOF) {
+ return pos;
+ } else {
+ return NOT_FOUND;
+ }
+ } else {
+ return NOT_FOUND;
+ }
+ }
+ }
+
+ /**
+ * Test whether the colon at the current position marks a case statement
+ *
+ * @return <code>true</code> if this looks like a case statement
+ */
+ private boolean looksLikeCaseStatement() {
+ nextToken();
+ switch (fToken) {
+ case STPSymbols.TokenCASE:
+ // char literal got skipped
+ return true;
+ case STPSymbols.TokenIDENT:
+ nextToken();
+ while (skipQualifiers()) {
+ nextToken();
+ }
+ while (fToken == STPSymbols.TokenMINUS || fToken == STPSymbols.TokenPLUS) {
+ nextToken();
+ }
+ if (fToken == STPSymbols.TokenCASE) {
+ return true;
+ }
+ break;
+ case STPSymbols.TokenOTHER:
+ nextToken();
+ if (fToken == STPSymbols.TokenCASE) {
+ return true;
+ }
+ break;
+ case STPSymbols.TokenDEFAULT:
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Test whether the colon at the current position marks a type inheritance decl.
+ *
+ * @return <code>true</code> if this looks like a type inheritance decl.
+ */
+ private boolean looksLikeTypeInheritanceDecl() {
+ nextToken();
+ switch (fToken) {
+ case STPSymbols.TokenIDENT:
+ nextToken();
+ while (skipQualifiers()) {
+ nextToken();
+ }
+ switch (fToken) {
+ case STPSymbols.TokenCLASS:
+ case STPSymbols.TokenSTRUCT:
+ case STPSymbols.TokenUNION:
+ return true;
+ }
+ break;
+ }
+ return false;
+ }
+
+ /**
+ * Test whether the colon at the current position marks a constructor initializer list.
+ *
+ * @return <code>true</code> if this looks like a constructor initializer list.
+ */
+ private boolean looksLikeConstructorInitializer() {
+ nextToken();
+ if (fToken != STPSymbols.TokenRPAREN) {
+ return false;
+ }
+ if (!skipScope()) {
+ return false;
+ }
+ nextToken();
+ if (fToken == STPSymbols.TokenTHROW) {
+ nextToken();
+ if (fToken != STPSymbols.TokenRPAREN) {
+ return false;
+ }
+ if (!skipScope()) {
+ return false;
+ }
+ nextToken();
+ }
+ if (fToken != STPSymbols.TokenIDENT) {
+ return false;
+ }
+ nextToken();
+ switch (fToken) {
+ case STPSymbols.TokenCOLON:
+ nextToken();
+ switch (fToken) {
+ case STPSymbols.TokenCOLON: // A::A() :
+ case STPSymbols.TokenPUBLIC: // public: A() :
+ case STPSymbols.TokenPROTECTED:
+ case STPSymbols.TokenPRIVATE:
+ return true;
+ }
+ return false;
+
+ case STPSymbols.TokenLBRACE: // class A { A() :
+ case STPSymbols.TokenRBRACE:
+ case STPSymbols.TokenSEMICOLON:
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Test whether the left brace at the current position marks an enum decl.
+ *
+ * @return <code>true</code> if this looks like an enum decl.
+ */
+ private boolean looksLikeEnumDeclaration() {
+ int pos = fPosition;
+ nextToken();
+ if (fToken == STPSymbols.TokenIDENT) {
+ nextToken();
+ while (skipQualifiers()) {
+ nextToken();
+ }
+ }
+ if (fToken == STPSymbols.TokenENUM) {
+ fPosition = pos;
+ return true;
+ }
+ fPosition = pos;
+ return false;
+ }
+
+
+ /**
+ * Test whether the colon at the current position marks an access specifier.
+ *
+ * @return <code>true</code> if current position marks an access specifier
+ */
+ private boolean isAccessSpecifier() {
+ int pos= fPosition;
+ int token = fToken;
+ nextToken();
+ switch (fToken) {
+ case STPSymbols.TokenPUBLIC:
+ case STPSymbols.TokenPROTECTED:
+ case STPSymbols.TokenPRIVATE:
+ return true;
+ }
+ fToken = token;
+ fPosition= pos;
+ return false;
+ }
+
+ /**
+ * Skips to the start of a statement that ends at the current position.
+ *
+ * @param danglingElse whether to indent aligned with the last <code>if</code>
+ * @param isInBlock whether the current position is inside a block, which limits the search scope to
+ * the next scope introducer
+ * @return the reference offset of the start of the statement
+ */
+ private int skipToStatementStart(boolean danglingElse, boolean isInBlock) {
+ final int NOTHING= 0;
+ final int READ_PARENS= 1;
+ final int READ_IDENT= 2;
+ int mayBeMethodBody= NOTHING;
+ boolean isTypeBody= false;
+ int startLine = fLine;
+ while (true) {
+ int prevToken= fToken;
+ nextToken();
+
+ if (isInBlock) {
+ switch (fToken) {
+ // exit on all block introducers
+ case STPSymbols.TokenIF:
+ case STPSymbols.TokenELSE:
+ case STPSymbols.TokenCATCH:
+ case STPSymbols.TokenDO:
+ case STPSymbols.TokenWHILE:
+ case STPSymbols.TokenFOR:
+ case STPSymbols.TokenFOREACH:
+ case STPSymbols.TokenTRY:
+ fIndent += fPrefs.prefIndentBracesForBlocks ? 1 : 0;
+ return fPosition;
+ case STPSymbols.TokenCLASS:
+ case STPSymbols.TokenSTRUCT:
+ case STPSymbols.TokenUNION:
+ isTypeBody= true;
+ break;
+
+ case STPSymbols.TokenSWITCH:
+ fIndent= fPrefs.prefCaseIndent;
+ return fPosition;
+ }
+ }
+
+ if (fToken == STPSymbols.TokenSEMICOLON && fLine == startLine) {
+ // Skip semicolons on the same line. Otherwise we may never reach beginning of a 'for'
+ // statement.
+ continue;
+ }
+
+ switch (fToken) {
+ // scope introduction through: LPAREN, LBRACE, LBRACKET
+ // search stop on SEMICOLON, RBRACE, COLON, EOF
+ // -> the next token is the start of the statement (i.e. previousPos when backward scanning)
+ case STPSymbols.TokenLPAREN:
+ if (peekToken() == STPSymbols.TokenFOR) {
+ nextToken(); // Consume 'for'
+ fIndent = fPrefs.prefContinuationIndent;
+ return fPosition;
+ }
+ break;
+
+ case STPSymbols.TokenLBRACE:
+ case STPSymbols.TokenSEMICOLON:
+ case STPSymbols.TokenEOF:
+ if (isInBlock)
+ fIndent= getBlockIndent(mayBeMethodBody == READ_IDENT, isTypeBody);
+ return fPreviousPos;
+
+ case STPSymbols.TokenCOLON:
+ switch (prevToken) {
+ case STPSymbols.TokenPRIVATE:
+ case STPSymbols.TokenPROTECTED:
+ case STPSymbols.TokenPUBLIC:
+ continue; // Don't stop at colon in a class declaration
+
+ case STPSymbols.TokenVIRTUAL:
+ switch (peekToken()) {
+ case STPSymbols.TokenPRIVATE:
+ case STPSymbols.TokenPROTECTED:
+ case STPSymbols.TokenPUBLIC:
+ break;
+ default:
+ continue;
+ }
+ }
+ int pos= fPreviousPos;
+ if (!isConditional())
+ return pos;
+ break;
+
+ case STPSymbols.TokenRBRACE:
+ // RBRACE is a little tricky: it can be the end of an array definition, but
+ // usually it is the end of a previous block
+ pos= fPreviousPos; // store state
+ if (skipScope()) {
+ if (looksLikeArrayInitializerIntro()) {
+ continue; // it's an array
+ }
+ if (prevToken == STPSymbols.TokenSEMICOLON) {
+ // end of type def
+ continue;
+ }
+ }
+ if (isInBlock)
+ fIndent= getBlockIndent(mayBeMethodBody == READ_IDENT, isTypeBody);
+ return pos; // it's not - do as with all the above
+
+ // scopes: skip them
+ case STPSymbols.TokenRPAREN:
+ if (isInBlock)
+ mayBeMethodBody= READ_PARENS;
+ // fall thru
+ pos= fPreviousPos;
+ if (skipScope())
+ break;
+ else
+ return pos;
+ case STPSymbols.TokenRBRACKET:
+ pos= fPreviousPos;
+ if (skipScope())
+ break;
+ else
+ return pos;
+
+ // IF / ELSE: align the position after the conditional block with the if
+ // so we are ready for an else, except if danglingElse is false
+ // in order for this to work, we must skip an else to its if
+ case STPSymbols.TokenIF:
+ if (danglingElse)
+ return fPosition;
+ else
+ break;
+ case STPSymbols.TokenELSE:
+ // skip behind the next if, as we have that one covered
+ pos= fPosition;
+ if (skipNextIF())
+ break;
+ else
+ return pos;
+
+ case STPSymbols.TokenDO:
+ // align the WHILE position with its do
+ return fPosition;
+
+ case STPSymbols.TokenWHILE:
+ // this one is tricky: while can be the start of a while loop
+ // or the end of a do - while
+ pos= fPosition;
+ if (hasMatchingDo()) {
+ // continue searching from the DO on
+ break;
+ } else {
+ // continue searching from the WHILE on
+ fPosition= pos;
+ break;
+ }
+ case STPSymbols.TokenIDENT:
+ if (mayBeMethodBody == READ_PARENS)
+ mayBeMethodBody= READ_IDENT;
+ break;
+
+ default:
+ // keep searching
+ }
+ }
+ }
+
+ private int getBlockIndent(boolean isMethodBody, boolean isTypeBody) {
+ if (isTypeBody) {
+ return fPrefs.prefTypeIndent + fPrefs.prefAccessSpecifierIndent;
+ } else if (isMethodBody) {
+ return fPrefs.prefMethodBodyIndent + (fPrefs.prefIndentBracesForMethods ? 1 : 0);
+ } else {
+ return fIndent;
+ }
+ }
+
+ /**
+ * Returns <code>true</code> if the colon at the current position is part of a conditional
+ * (ternary) expression, <code>false</code> otherwise.
+ *
+ * @return <code>true</code> if the colon at the current position is part of a conditional
+ */
+ private boolean isConditional() {
+ while (true) {
+ int previous= fToken;
+ nextToken();
+ switch (fToken) {
+ // search for case labels, which consist of (possibly qualified) identifiers or numbers
+ case STPSymbols.TokenIDENT:
+ if (previous == STPSymbols.TokenIDENT) {
+ return false;
+ }
+ // fall thru
+ continue;
+ case STPSymbols.TokenDOUBLECOLON:
+ case STPSymbols.TokenOTHER:
+ case STPSymbols.TokenMINUS:
+ case STPSymbols.TokenPLUS:
+ continue;
+
+ case STPSymbols.TokenQUESTIONMARK:
+ return true;
+
+ case STPSymbols.TokenSEMICOLON:
+ case STPSymbols.TokenLBRACE:
+ case STPSymbols.TokenRBRACE:
+ case STPSymbols.TokenCASE:
+ case STPSymbols.TokenDEFAULT:
+ case STPSymbols.TokenPUBLIC:
+ case STPSymbols.TokenPROTECTED:
+ case STPSymbols.TokenPRIVATE:
+ case STPSymbols.TokenCLASS:
+ case STPSymbols.TokenSTRUCT:
+ case STPSymbols.TokenUNION:
+ return false;
+
+ default:
+ return true;
+ }
+ }
+ }
+
+ /**
+ * Returns as a reference any previous <code>switch</code> labels (<code>case</code>
+ * or <code>default</code>) or the offset of the brace that scopes the switch
+ * statement. Sets <code>fIndent</code> to <code>prefCaseIndent</code> upon
+ * a match.
+ *
+ * @return the reference offset for a <code>switch</code> label
+ */
+ private int matchCaseAlignment() {
+ while (true) {
+ nextToken();
+ switch (fToken) {
+ // invalid cases: another case label or an LBRACE must come before a case
+ // -> bail out with the current position
+ case STPSymbols.TokenLPAREN:
+ case STPSymbols.TokenLBRACKET:
+ case STPSymbols.TokenEOF:
+ return fPosition;
+
+ case STPSymbols.TokenSWITCH:
+ // start of switch statement
+ fIndent= fPrefs.prefCaseIndent;
+ return fPosition;
+
+ case STPSymbols.TokenCASE:
+ case STPSymbols.TokenDEFAULT:
+ // align with previous label
+ fIndent= 0;
+ return fPosition;
+
+ // scopes: skip them
+ case STPSymbols.TokenRPAREN:
+ case STPSymbols.TokenRBRACKET:
+ case STPSymbols.TokenRBRACE:
+ skipScope();
+ break;
+
+ default:
+ // keep searching
+ continue;
+ }
+ }
+ }
+
+ /**
+ * Returns as a reference any previous access specifiers (<code>public</code>,
+ * <code>protected</code> or <code>default</code>) or the offset of the brace that
+ * scopes the class body.
+ * Sets <code>fIndent</code> to <code>prefAccessSpecifierIndent</code> upon
+ * a match.
+ *
+ * @return the reference offset for an access specifier (public/protected/private)
+ */
+ private int matchAccessSpecifierAlignment() {
+ while (true) {
+ nextToken();
+ switch (fToken) {
+ // invalid cases: another access specifier or an LBRACE must come before an access specifier
+ // -> bail out with the current position
+ case STPSymbols.TokenLPAREN:
+ case STPSymbols.TokenLBRACKET:
+ case STPSymbols.TokenEOF:
+ return fPosition;
+
+ case STPSymbols.TokenLBRACE:
+ // opening brace of class body
+ int pos= fPosition;
+ int typeDeclPos= matchTypeDeclaration();
+ fIndent= fPrefs.prefAccessSpecifierIndent;
+ fExtraSpaces = fPrefs.prefAccessSpecifierExtraSpaces;
+ if (typeDeclPos != NOT_FOUND) {
+ return typeDeclPos;
+ }
+ return pos;
+ case STPSymbols.TokenPUBLIC:
+ case STPSymbols.TokenPROTECTED:
+ case STPSymbols.TokenPRIVATE:
+ // align with previous access specifier
+ fIndent= 0;
+ return fPosition;
+
+ // scopes: skip them
+ case STPSymbols.TokenRPAREN:
+ case STPSymbols.TokenRBRACKET:
+ case STPSymbols.TokenRBRACE:
+ skipScope();
+ break;
+
+ default:
+ // keep searching
+ continue;
+ }
+ }
+ }
+
+ /**
+ * Returns the reference position for a list element. The algorithm
+ * tries to match any previous indentation on the same list. If there is none,
+ * the reference position returned is determined depending on the type of list:
+ * The indentation will either match the list scope introducer (e.g. for
+ * method declarations), so called deep indents, or simply increase the
+ * indentation by a number of standard indents. See also {@link #handleScopeIntroduction(int, boolean)}.
+ * @return the reference position for a list item: either a previous list item
+ * that has its own indentation, or the list introduction start.
+ */
+ private int skipToPreviousListItemOrListStart() {
+ int startLine= fLine;
+ int startPosition= fPosition;
+ int linesSkippedInsideScopes = 0;
+ boolean continuationLineCandidate =
+ fToken == STPSymbols.TokenEQUAL || fToken == STPSymbols.TokenSHIFTLEFT ||
+ fToken == STPSymbols.TokenRPAREN;
+ while (true) {
+ int previous = fToken;
+ nextToken();
+
+ // If any line item comes with its own indentation, adapt to it
+ if (fLine < startLine - linesSkippedInsideScopes) {
+ try {
+ int lineOffset= fDocument.getLineOffset(startLine);
+ int bound= Math.min(fDocument.getLength(), startPosition + 1);
+ if ((fToken == STPSymbols.TokenSEMICOLON || fToken == STPSymbols.TokenRBRACE || fToken == STPSymbols.TokenIDENT ||
+ fToken == STPSymbols.TokenLBRACE && !looksLikeArrayInitializerIntro() && !looksLikeEnumDeclaration()) &&
+ continuationLineCandidate) {
+ fIndent = fPrefs.prefContinuationIndent;
+ } else {
+ fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, bound);
+ // If the reference line starts with a colon, skip the colon.
+ if (peekToken(fAlign) == STPSymbols.TokenCOLON) {
+ fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(fAlign + 1, bound);
+ }
+ }
+ } catch (BadLocationException e) {
+ // Ignore and return just the position
+ }
+ return startPosition;
+ }
+
+ int line = fLine;
+ switch (fToken) {
+ // scopes: skip them
+ case STPSymbols.TokenRPAREN:
+ continuationLineCandidate = true;
+ //$FALL-THROUGH$
+ case STPSymbols.TokenRBRACKET:
+ case STPSymbols.TokenRBRACE:
+ skipScope();
+ linesSkippedInsideScopes = line - fLine;
+ break;
+
+ // scope introduction: special treat who special is
+ case STPSymbols.TokenLPAREN:
+ case STPSymbols.TokenLBRACE:
+ case STPSymbols.TokenLBRACKET:
+ return handleScopeIntroduction(startPosition + 1, false);
+
+ case STPSymbols.TokenSEMICOLON:
+ return fPosition;
+
+ case STPSymbols.TokenQUESTIONMARK:
+ if (fPrefs.prefTernaryDeepAlign) {
+ setFirstElementAlignment(fPosition - 1, fPosition + 1);
+ } else {
+ fIndent= fPrefs.prefTernaryIndent;
+ }
+ return fPosition;
+
+ case STPSymbols.TokenEQUAL:
+ case STPSymbols.TokenSHIFTLEFT:
+ continuationLineCandidate = true;
+ break;
+
+ case STPSymbols.TokenRETURN:
+ case STPSymbols.TokenUSING:
+ fIndent = fPrefs.prefContinuationIndent;
+ return fPosition;
+
+ case STPSymbols.TokenTYPEDEF:
+ switch (previous) {
+ case STPSymbols.TokenSTRUCT:
+ case STPSymbols.TokenUNION:
+ case STPSymbols.TokenCLASS:
+ case STPSymbols.TokenENUM:
+ break;
+ default:
+ fIndent = fPrefs.prefContinuationIndent;
+ }
+ return fPosition;
+
+ case STPSymbols.TokenEOF:
+ if (continuationLineCandidate) {
+ fIndent = fPrefs.prefContinuationIndent;
+ }
+ return 0;
+ }
+ }
+ }
+
+ /**
+ * Skips a scope and positions the cursor (<code>fPosition</code>) on the
+ * token that opens the scope. Returns <code>true</code> if a matching peer
+ * could be found, <code>false</code> otherwise. The current token when calling
+ * must be one out of <code>STPSymbols.TokenRPAREN</code>, <code>STPSymbols.TokenRBRACE</code>,
+ * and <code>STPSymbols.TokenRBRACKET</code>.
+ *
+ * @return <code>true</code> if a matching peer was found, <code>false</code> otherwise
+ */
+ private boolean skipScope() {
+ switch (fToken) {
+ case STPSymbols.TokenRPAREN:
+ return skipScope(STPSymbols.TokenLPAREN, STPSymbols.TokenRPAREN);
+ case STPSymbols.TokenRBRACKET:
+ return skipScope(STPSymbols.TokenLBRACKET, STPSymbols.TokenRBRACKET);
+ case STPSymbols.TokenRBRACE:
+ return skipScope(STPSymbols.TokenLBRACE, STPSymbols.TokenRBRACE);
+ case STPSymbols.TokenGREATERTHAN:
+ if (!fPrefs.prefHasTemplates)
+ return false;
+ int storedPosition= fPosition;
+ int storedToken= fToken;
+ nextToken();
+ switch (fToken) {
+ case STPSymbols.TokenIDENT:
+ fPosition = storedPosition;
+ if (skipScope(STPSymbols.TokenLESSTHAN, STPSymbols.TokenGREATERTHAN))
+ return true;
+ break;
+ case STPSymbols.TokenQUESTIONMARK:
+ case STPSymbols.TokenGREATERTHAN:
+ fPosition = storedPosition;
+ if (skipScope(STPSymbols.TokenLESSTHAN, STPSymbols.TokenGREATERTHAN))
+ return true;
+ break;
+ }
+ // <> are harder to detect - restore the position if we fail
+ fPosition= storedPosition;
+ fToken= storedToken;
+ return false;
+
+ default:
+ // programming error
+ Assert.isTrue(false);
+ return false;
+ }
+ }
+
+ /**
+ * Returns the contents of the current token.
+ *
+ * @return the contents of the current token
+ */
+ private CharSequence getTokenContent() {
+ return new DocumentCharacterIterator(fDocument, fPosition, fPreviousPos);
+ }
+
+ /**
+ * Handles the introduction of a new scope. The current token must be one out
+ * of <code>STPSymbols.TokenLPAREN</code>, <code>STPSymbols.TokenLBRACE</code>,
+ * and <code>STPSymbols.TokenLBRACKET</code>. Returns as the reference position
+ * either the token introducing the scope or - if available - the first
+ * token after that.
+ *
+ * <p>Depending on the type of scope introduction, the indentation will align
+ * (deep indenting) with the reference position (<code>fAlign</code> will be
+ * set to the reference position) or <code>fIndent</code> will be set to
+ * the number of indentation units.
+ * </p>
+ *
+ * @param bound the bound for the search for the first token after the scope
+ * introduction.
+ * @param firstToken <code>true</code> if we are dealing with the first token after
+ * the opening parenthesis.
+ * @return the indent
+ */
+ private int handleScopeIntroduction(int bound, boolean firstToken) {
+ int pos= fPosition; // store
+
+ switch (fToken) {
+ // scope introduction: special treat who special is
+ case STPSymbols.TokenLPAREN:
+ // special: method declaration deep indentation
+ if (looksLikeMethodDecl()) {
+ if (firstToken ? fPrefs.prefMethodDeclFirstParameterDeepIndent : fPrefs.prefMethodDeclDeepIndent) {
+ return setFirstElementAlignment(pos, bound);
+ } else {
+ fIndent= fPrefs.prefMethodDeclIndent;
+ return pos;
+ }
+ } else {
+ fPosition= pos;
+ if (looksLikeMethodCall()) {
+ if (firstToken ? fPrefs.prefMethodCallFirstParameterDeepIndent : fPrefs.prefMethodCallDeepIndent) {
+ return setFirstElementAlignment(pos, bound);
+ } else {
+ fIndent= fPrefs.prefMethodCallIndent;
+ return pos;
+ }
+ } else if (fPrefs.prefParenthesisDeepIndent) {
+ return setFirstElementAlignment(pos, bound);
+ }
+ }
+
+ // normal: return the parenthesis as reference
+ fIndent= fPrefs.prefParenthesisIndent;
+ return pos;
+
+ case STPSymbols.TokenLBRACE:
+ final boolean looksLikeArrayInitializerIntro= looksLikeArrayInitializerIntro();
+ // special: array initializer
+ if (looksLikeArrayInitializerIntro) {
+ if (fPrefs.prefArrayDeepIndent)
+ return setFirstElementAlignment(pos, bound);
+ else
+ fIndent= fPrefs.prefArrayIndent;
+ } else if (isNamespace() || isLinkageSpec()) {
+ fIndent= fPrefs.prefNamespaceBodyIndent;
+ } else if (looksLikeEnumDeclaration()) {
+ fIndent = fPrefs.prefTypeIndent;
+ } else {
+ int typeDeclPos = matchTypeDeclaration();
+ if (typeDeclPos == NOT_FOUND) {
+ fIndent= fPrefs.prefBlockIndent;
+ } else {
+ fIndent= fPrefs.prefAccessSpecifierIndent + fPrefs.prefTypeIndent;
+ }
+ }
+
+ // normal: skip to the statement start before the scope introducer
+ // opening braces are often on differently ending indents than e.g. a method definition
+ if (!looksLikeArrayInitializerIntro) {
+ fPosition= pos; // restore
+ return skipToStatementStart(true, true); // set to true to match the first if
+ } else {
+ return pos;
+ }
+
+ case STPSymbols.TokenLBRACKET:
+ // special: method declaration deep indentation
+ if (fPrefs.prefArrayDimensionsDeepIndent) {
+ return setFirstElementAlignment(pos, bound);
+ }
+
+ // normal: return the bracket as reference
+ fIndent= fPrefs.prefBracketIndent;
+ return pos; // restore
+
+ default:
+ // programming error
+ Assert.isTrue(false);
+ return -1; // dummy
+ }
+ }
+
+ /**
+ * Sets the deep indent offset (<code>fAlign</code>) to either the offset
+ * right after <code>scopeIntroducerOffset</code> or - if available - the
+ * first C token after <code>scopeIntroducerOffset</code>, but before
+ * <code>bound</code>.
+ *
+ * @param scopeIntroducerOffset the offset of the scope introducer
+ * @param bound the bound for the search for another element
+ * @return the reference position
+ */
+ private int setFirstElementAlignment(int scopeIntroducerOffset, int bound) {
+ int firstPossible= scopeIntroducerOffset + 1; // align with the first position after the scope intro
+ fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(firstPossible, bound);
+ if (fAlign == NOT_FOUND) {
+ fAlign= firstPossible;
+ } else {
+ try {
+ IRegion lineRegion = fDocument.getLineInformationOfOffset(scopeIntroducerOffset);
+ if (fAlign > lineRegion.getOffset() + lineRegion.getLength()) {
+ fAlign= firstPossible;
+ }
+ } catch (BadLocationException e) {
+ // Ignore.
+ }
+ }
+ return fAlign;
+ }
+
+ /**
+ * Returns <code>true</code> if the next token received after calling
+ * <code>nextToken</code> is either an equal sign, an opening brace,
+ * a comma or an array designator ('[]').
+ *
+ * @return <code>true</code> if the next elements look like the start of an array definition
+ */
+ private boolean looksLikeArrayInitializerIntro() {
+ int pos= fPosition;
+ nextToken();
+ switch (fToken) {
+ case STPSymbols.TokenEQUAL:
+ return true;
+ case STPSymbols.TokenRBRACKET:
+ return skipBrackets();
+ case STPSymbols.TokenLBRACE:
+ if (looksLikeArrayInitializerIntro()) {
+ fPosition= pos;
+ return true;
+ }
+ return false;
+ case STPSymbols.TokenCOMMA:
+ fPosition= pos;
+ return true;
+ }
+ fPosition= pos;
+ return false;
+ }
+
+ /**
+ * Returns <code>true</code> if the the current token is "namespace", or the current token
+ * is an identifier and the previous token is "namespace".
+ *
+ * @return <code>true</code> if the next elements look like the start of a namespace declaration.
+ */
+ private boolean isNamespace() {
+ int pos = fPosition;
+ nextToken();
+ if (fToken == STPSymbols.TokenNAMESPACE) {
+ fPosition = pos;
+ return true; // Anonymous namespace
+ } else if (fToken == STPSymbols.TokenIDENT) {
+ nextToken(); // Get previous token
+ if (fToken == STPSymbols.TokenNAMESPACE) {
+ fPosition = pos;
+ return true; // Named namespace
+ }
+ }
+ fPosition = pos;
+ return false;
+ }
+
+ /**
+ * Returns <code>true</code> if the current token is keyword "extern".
+ *
+ * @return <code>true</code> if the next elements look like the start of a linkage spec.
+ */
+ private boolean isLinkageSpec() {
+ int pos = fPosition;
+ nextToken();
+ if (fToken == STPSymbols.TokenEXTERN) {
+ fPosition = pos;
+ return true;
+ }
+ fPosition = pos;
+ return false;
+ }
+
+ /**
+ * Skips over the next <code>if</code> keyword. The current token when calling
+ * this method must be an <code>else</code> keyword. Returns <code>true</code>
+ * if a matching <code>if</code> could be found, <code>false</code> otherwise.
+ * The cursor (<code>fPosition</code>) is set to the offset of the <code>if</code>
+ * token.
+ *
+ * @return <code>true</code> if a matching <code>if</code> token was found, <code>false</code> otherwise
+ */
+ private boolean skipNextIF() {
+ Assert.isTrue(fToken == STPSymbols.TokenELSE);
+
+ while (true) {
+ nextToken();
+ switch (fToken) {
+ // scopes: skip them
+ case STPSymbols.TokenRPAREN:
+ case STPSymbols.TokenRBRACKET:
+ case STPSymbols.TokenRBRACE:
+ skipScope();
+ break;
+
+ case STPSymbols.TokenIF:
+ // found it, return
+ return true;
+ case STPSymbols.TokenELSE:
+ // recursively skip else-if blocks
+ skipNextIF();
+ break;
+
+ // shortcut scope starts
+ case STPSymbols.TokenLPAREN:
+ case STPSymbols.TokenLBRACE:
+ case STPSymbols.TokenLBRACKET:
+ case STPSymbols.TokenEOF:
+ return false;
+ }
+ }
+ }
+
+ /**
+ * while(condition); is ambiguous when parsed backwardly, as it is a valid
+ * statement by its own, so we have to check whether there is a matching
+ * do. A <code>do</code> can either be separated from the while by a
+ * block, or by a single statement, which limits our search distance.
+ *
+ * @return <code>true</code> if the <code>while</code> currently in
+ * <code>fToken</code> has a matching <code>do</code>.
+ */
+ private boolean hasMatchingDo() {
+ Assert.isTrue(fToken == STPSymbols.TokenWHILE);
+ nextToken();
+ switch (fToken) {
+ case STPSymbols.TokenRBRACE:
+ skipScope(); // and fall thru
+ skipToStatementStart(false, false);
+ return fToken == STPSymbols.TokenDO;
+
+ case STPSymbols.TokenSEMICOLON:
+ skipToStatementStart(false, false);
+ return fToken == STPSymbols.TokenDO;
+ }
+ return false;
+ }
+
+ /**
+ * Skips pointer operators if the current token is a pointer operator.
+ *
+ * @return <code>true</code> if a <code>*</code> or <code>&amp;</code> could be scanned, the
+ * current token is left at the operator.
+ */
+ private boolean skipPointerOperators() {
+ if (fToken == STPSymbols.TokenOTHER) {
+ CharSequence token= getTokenContent().toString().trim();
+ if (token.length() == 1 && token.charAt(0) == '*' || token.charAt(0) == '&') {
+ return true;
+ }
+ } else if (fToken == STPSymbols.TokenCONST) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Skips brackets if the current token is a RBRACKET. There can be nothing
+ * but whitespace in between, this is only to be used for <code>[]</code> elements.
+ *
+ * @return <code>true</code> if a <code>[]</code> could be scanned, the
+ * current token is left at the LBRACKET.
+ */
+ private boolean skipBrackets() {
+ if (fToken == STPSymbols.TokenRBRACKET) {
+ nextToken();
+ if (fToken == STPSymbols.TokenLBRACKET) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Skips scope qualifiers of identifiers.
+ *
+ * @return <code>true</code> if a qualifier was encountered, the last token
+ * will be an IDENT.
+ */
+ private boolean skipQualifiers() {
+ if (fToken == STPSymbols.TokenDOUBLECOLON) {
+ nextToken();
+ if (fToken == STPSymbols.TokenIDENT) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Reads the next token in backward direction from the heuristic scanner
+ * and sets the fields <code>fToken, fPreviousPosition</code> and <code>fPosition</code>
+ * accordingly.
+ */
+ private void nextToken() {
+ nextToken(fPosition);
+ }
+
+ /**
+ * Reads the next token in backward direction of <code>start</code> from
+ * the heuristic scanner and sets the fields <code>fToken, fPreviousPosition</code>
+ * and <code>fPosition</code> accordingly.
+ *
+ * @param start the start offset from which to scan backwards
+ */
+ private void nextToken(int start) {
+ fToken= fScanner.previousToken(start - 1, STPHeuristicScanner.UNBOUND);
+ fPreviousPos= start;
+ fPosition= fScanner.getPosition() + 1;
+ try {
+ fLine= fDocument.getLineOfOffset(fPosition);
+ } catch (BadLocationException e) {
+ fLine= -1;
+ }
+ }
+
+ /**
+ * Reads the next token in backward direction from the heuristic scanner
+ * and returns that token without changing the current position.
+ */
+ private int peekToken() {
+ return fScanner.previousToken(fPosition - 1, STPHeuristicScanner.UNBOUND);
+ }
+
+ /**
+ * Returns <code>true</code> if the current tokens look like a method
+ * declaration header (i.e. only the return type and method name). The
+ * heuristic calls <code>nextToken</code> and expects an identifier
+ * (method name) and an optional return type declaration.
+ *
+ * @return <code>true</code> if the current position looks like a method
+ * declaration header.
+ */
+ private boolean looksLikeMethodDecl() {
+ nextToken();
+ switch (fToken) {
+ case STPSymbols.TokenIDENT: // method name
+ int pos= fPosition;
+ nextToken();
+ // check destructor tilde
+ if (fToken == STPSymbols.TokenTILDE) {
+ return true;
+ }
+ if (skipQualifiers()) {
+ return true;
+ }
+ // optional brackets for array valued return types
+ while (skipBrackets()) {
+ nextToken();
+ }
+ while (skipPointerOperators()) {
+ nextToken();
+ }
+ switch (fToken) {
+ case STPSymbols.TokenIDENT:
+ return true;
+ case STPSymbols.TokenSEMICOLON:
+ case STPSymbols.TokenRBRACE:
+ fPosition= pos;
+ return true;
+ case STPSymbols.TokenLBRACE:
+ if (fScanner.looksLikeCompositeTypeDefinitionBackward(fPosition, STPHeuristicScanner.UNBOUND)) {
+ fPosition= pos;
+ return true;
+ }
+ break;
+ case STPSymbols.TokenCOMMA:
+ nextToken();
+ if (fToken == STPSymbols.TokenRPAREN) {
+ // field initializer
+ if (skipScope()) {
+ return looksLikeMethodDecl();
+ }
+ }
+ break;
+ case STPSymbols.TokenCOLON:
+ nextToken();
+ switch (fToken) {
+ case STPSymbols.TokenPUBLIC:
+ case STPSymbols.TokenPROTECTED:
+ case STPSymbols.TokenPRIVATE:
+ fPosition= pos;
+ return true;
+ case STPSymbols.TokenRPAREN:
+ // constructor initializer
+ if (skipScope()) {
+ pos = fPosition;
+ nextToken();
+ // optional throw
+ if (fToken == STPSymbols.TokenTHROW) {
+ nextToken();
+ if (fToken != STPSymbols.TokenRPAREN || !skipScope()) {
+ return false;
+ }
+ } else {
+ fPosition = pos;
+ }
+ return looksLikeMethodDecl();
+ }
+ break;
+ }
+ }
+ break;
+ case STPSymbols.TokenARROW:
+ case STPSymbols.TokenCOMMA:
+ case STPSymbols.TokenEQUAL:
+ case STPSymbols.TokenGREATERTHAN:
+ case STPSymbols.TokenLESSTHAN:
+ case STPSymbols.TokenMINUS:
+ case STPSymbols.TokenPLUS:
+ case STPSymbols.TokenSHIFTRIGHT:
+ case STPSymbols.TokenSHIFTLEFT:
+ case STPSymbols.TokenDELETE:
+ case STPSymbols.TokenNEW:
+ nextToken();
+ return fToken == STPSymbols.TokenOPERATOR;
+ case STPSymbols.TokenRPAREN:
+ nextToken();
+ if (fToken != STPSymbols.TokenLPAREN)
+ return false;
+ nextToken();
+ return fToken == STPSymbols.TokenOPERATOR;
+ case STPSymbols.TokenRBRACKET:
+ nextToken();
+ if (fToken != STPSymbols.TokenLBRACKET)
+ return false;
+ nextToken();
+ if (fToken == STPSymbols.TokenNEW || fToken == STPSymbols.TokenDELETE)
+ nextToken();
+ return fToken == STPSymbols.TokenOPERATOR;
+ case STPSymbols.TokenOTHER:
+ if (getTokenContent().length() == 1) {
+ nextToken();
+ if (fToken == STPSymbols.TokenOPERATOR)
+ return true;
+ }
+ if (getTokenContent().length() == 1) {
+ nextToken();
+ if (fToken == STPSymbols.TokenOPERATOR)
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Returns <code>true</code> if the current tokens look like an anonymous type declaration
+ * header (i.e. a type name (potentially qualified) and a new keyword). The heuristic calls
+ * <code>nextToken</code> and expects a possibly qualified identifier (type name) and a new
+ * keyword
+ *
+ * @return <code>true</code> if the current position looks like a anonymous type declaration
+ * header.
+ */
+ private boolean looksLikeAnonymousTypeDecl() {
+ nextToken();
+ if (fToken == STPSymbols.TokenIDENT) { // type name
+ nextToken();
+ while (fToken == STPSymbols.TokenOTHER) { // dot of qualification
+ nextToken();
+ if (fToken != STPSymbols.TokenIDENT) // qualifying name
+ return false;
+ nextToken();
+ }
+ return fToken == STPSymbols.TokenNEW;
+ }
+ return false;
+ }
+
+ /**
+ * Returns <code>true</code> if the current tokens look like beginning of a method
+ * call (i.e. an identifier as opposed to a keyword taking parenthesized parameters
+ * such as <code>if</code>).
+ * <p>The heuristic calls <code>nextToken</code> and expects an identifier
+ * (method name).
+ *
+ * @return <code>true</code> if the current position looks like a method call
+ * header.
+ */
+ private boolean looksLikeMethodCall() {
+ nextToken();
+ if (fToken == STPSymbols.TokenGREATERTHAN) {
+ if (!skipScope())
+ return false;
+ nextToken();
+ }
+ return fToken == STPSymbols.TokenIDENT; // method name
+ }
+
+ /**
+ * Scans tokens for the matching opening peer. The internal cursor
+ * (<code>fPosition</code>) is set to the offset of the opening peer if found.
+ *
+ * @param openToken the opening peer token
+ * @param closeToken the closing peer token
+ * @return <code>true</code> if a matching token was found, <code>false</code>
+ * otherwise
+ */
+ private boolean skipScope(int openToken, int closeToken) {
+ int depth= 1;
+
+ while (true) {
+ nextToken();
+
+ if (fToken == closeToken) {
+ depth++;
+ } else if (fToken == openToken) {
+ depth--;
+ if (depth == 0)
+ return true;
+ } else if (fToken == STPSymbols.TokenEOF) {
+ return false;
+ }
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPMetadataSingleton.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPMetadataSingleton.java
index c91f2d3226..347521bcb6 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPMetadataSingleton.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPMetadataSingleton.java
@@ -29,106 +29,106 @@ import org.eclipse.linuxtools.systemtap.structures.TreeNode;
*/
public final class STPMetadataSingleton {
- public static String[] NO_MATCHES = new String[0];
-
- private static STPMetadataSingleton instance = null;
-
- private STPMetadataSingleton() {
- TapsetLibrary.init();
- }
-
- public static STPMetadataSingleton getInstance() {
- if (instance == null) {
- instance = new STPMetadataSingleton();
- }
- return instance;
- }
-
- public void waitForInitialization() {
- TapsetLibrary.waitForInitialization();
- }
-
- public String[] getFunctionCompletions(String prefix) {
- TreeNode node = TapsetLibrary.getFunctions();
- return getMatchingChildren(node, prefix);
- }
-
- public String[] getProbeCompletions(String prefix) {
- List<String> matches = new LinkedList<>();
- String groupName = extractProbeGroupName(prefix);
-
- for (TreeNode node : getEachProbeCategoryNode()) {
- if (node == null) {
- continue;
- }
-
- TreeNode groupNode = node.getChildByName(groupName);
- if (groupNode != null) {
- node = groupNode;
- }
-
- matches.addAll(Arrays.asList(getMatchingChildren(node, prefix)));
- }
-
- return !matches.isEmpty() ? matches.toArray(new String[matches.size()]) : NO_MATCHES;
- }
-
- /**
- * Returns a list of variables available in the given probe.
- * @param probe The probe for which to find variables
- * @param prefix The prefix to complete.
- * @return a list of variables matching the prefix.
- */
- public String[] getProbeVariableCompletions(String probe, String prefix) {
- // The only probes that may have avilable variables are non-static ones.
- TreeNode node = TapsetLibrary.getProbeAliases();
- if (node == null) {
- return NO_MATCHES;
- }
-
- node = node.getChildByName(extractProbeGroupName(probe));
- if (node == null) {
- return NO_MATCHES;
- }
-
- node = node.getChildByName(probe);
- if (node == null) {
- return NO_MATCHES;
- }
-
- return getMatchingChildren(node, prefix);
- }
-
- private TreeNode[] getEachProbeCategoryNode() {
- return new TreeNode[]{TapsetLibrary.getStaticProbes(), TapsetLibrary.getProbeAliases()};
- }
-
- private String[] getMatchingChildren(TreeNode node, String prefix) {
- ArrayList<String> matches = new ArrayList<>();
-
- int n = node.getChildCount();
- for (int i = 0; i < n; i++) {
- if (node.getChildAt(i).toString().startsWith(prefix)) {
- matches.add(node.getChildAt(i).toString());
- }
- }
-
- return matches.toArray(new String[0]);
- }
-
- private String extractProbeGroupName(String probeName) {
- int dotIndex = probeName.indexOf('.');
- int parenIndex = probeName.indexOf('(');
- if (dotIndex > 0 && parenIndex > 0) {
- return probeName.substring(0, Math.min(dotIndex, parenIndex));
- }
- if (dotIndex > 0) {
- return probeName.substring(0, dotIndex);
- }
- if (parenIndex > 0) {
- return probeName.substring(0, parenIndex);
- }
- return probeName;
- }
+ public static String[] NO_MATCHES = new String[0];
+
+ private static STPMetadataSingleton instance = null;
+
+ private STPMetadataSingleton() {
+ TapsetLibrary.init();
+ }
+
+ public static STPMetadataSingleton getInstance() {
+ if (instance == null) {
+ instance = new STPMetadataSingleton();
+ }
+ return instance;
+ }
+
+ public void waitForInitialization() {
+ TapsetLibrary.waitForInitialization();
+ }
+
+ public String[] getFunctionCompletions(String prefix) {
+ TreeNode node = TapsetLibrary.getFunctions();
+ return getMatchingChildren(node, prefix);
+ }
+
+ public String[] getProbeCompletions(String prefix) {
+ List<String> matches = new LinkedList<>();
+ String groupName = extractProbeGroupName(prefix);
+
+ for (TreeNode node : getEachProbeCategoryNode()) {
+ if (node == null) {
+ continue;
+ }
+
+ TreeNode groupNode = node.getChildByName(groupName);
+ if (groupNode != null) {
+ node = groupNode;
+ }
+
+ matches.addAll(Arrays.asList(getMatchingChildren(node, prefix)));
+ }
+
+ return !matches.isEmpty() ? matches.toArray(new String[matches.size()]) : NO_MATCHES;
+ }
+
+ /**
+ * Returns a list of variables available in the given probe.
+ * @param probe The probe for which to find variables
+ * @param prefix The prefix to complete.
+ * @return a list of variables matching the prefix.
+ */
+ public String[] getProbeVariableCompletions(String probe, String prefix) {
+ // The only probes that may have avilable variables are non-static ones.
+ TreeNode node = TapsetLibrary.getProbeAliases();
+ if (node == null) {
+ return NO_MATCHES;
+ }
+
+ node = node.getChildByName(extractProbeGroupName(probe));
+ if (node == null) {
+ return NO_MATCHES;
+ }
+
+ node = node.getChildByName(probe);
+ if (node == null) {
+ return NO_MATCHES;
+ }
+
+ return getMatchingChildren(node, prefix);
+ }
+
+ private TreeNode[] getEachProbeCategoryNode() {
+ return new TreeNode[]{TapsetLibrary.getStaticProbes(), TapsetLibrary.getProbeAliases()};
+ }
+
+ private String[] getMatchingChildren(TreeNode node, String prefix) {
+ ArrayList<String> matches = new ArrayList<>();
+
+ int n = node.getChildCount();
+ for (int i = 0; i < n; i++) {
+ if (node.getChildAt(i).toString().startsWith(prefix)) {
+ matches.add(node.getChildAt(i).toString());
+ }
+ }
+
+ return matches.toArray(new String[0]);
+ }
+
+ private String extractProbeGroupName(String probeName) {
+ int dotIndex = probeName.indexOf('.');
+ int parenIndex = probeName.indexOf('(');
+ if (dotIndex > 0 && parenIndex > 0) {
+ return probeName.substring(0, Math.min(dotIndex, parenIndex));
+ }
+ if (dotIndex > 0) {
+ return probeName.substring(0, dotIndex);
+ }
+ if (parenIndex > 0) {
+ return probeName.substring(0, parenIndex);
+ }
+ return probeName;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPPartitionScanner.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPPartitionScanner.java
index dec239de04..de959ce0e8 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPPartitionScanner.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPPartitionScanner.java
@@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008 Phil Muldoon <pkmuldoon@picobot.org>.
- *
+ *
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * Phil Muldoon <pkmuldoon@picobot.org> - initial API and implementation.
+ * Phil Muldoon <pkmuldoon@picobot.org> - initial API and implementation.
*******************************************************************************/
package org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp;
@@ -24,73 +24,73 @@ import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.rules.WordRule;
public class STPPartitionScanner extends RuleBasedPartitionScanner {
- public final static String STP_PARTITIONING = "__stp_partitioning"; //$NON-NLS-1$
-
- public final static String STP_STRING = "__stp_string"; //$NON-NLS-1$
- public final static String STP_COMMENT = "__stp_comment"; //$NON-NLS-1$
- public final static String STP_CONDITIONAL = "__stp_conditional"; //$NON-NLS-1$
- public final static String STP_MULTILINE_COMMENT = "__stp_multiline_comment"; //$NON-NLS-1$
-
- public static String[] STP_PARTITION_TYPES = { IDocument.DEFAULT_CONTENT_TYPE,
- STP_COMMENT, STP_MULTILINE_COMMENT, STP_STRING, STP_CONDITIONAL};
-
- /**
- * Detect empty comments
- */
- private static class EmptyCommentDetector implements IWordDetector {
- @Override
- public boolean isWordStart(char c) {
- return (c == '/');
- }
-
- @Override
- public boolean isWordPart(char c) {
- return (c == '*' || c == '/');
- }
- }
-
- /**
- * Cope with the empty comment issue.
- */
- private static class EmptyCommentRule extends WordRule implements IPredicateRule {
-
- private IToken fSuccessToken;
-
- public EmptyCommentRule(IToken successToken) {
- super(new EmptyCommentDetector());
- fSuccessToken= successToken;
- addWord("/**/", fSuccessToken); //$NON-NLS-1$
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner, boolean resume) {
- return evaluate(scanner);
- }
-
- @Override
- public IToken getSuccessToken() {
- return fSuccessToken;
- }
- }
-
- public STPPartitionScanner() {
-
- IToken stpComment = new Token(STP_COMMENT);
- IToken stpMultilineComment = new Token(STP_MULTILINE_COMMENT);
- IToken stpConditional = new Token(STP_CONDITIONAL);
- IToken stpString = new Token(STP_STRING);
-
- // Add special case word rule.
- EmptyCommentRule emptyCommentRule= new EmptyCommentRule(stpComment);
+ public final static String STP_PARTITIONING = "__stp_partitioning"; //$NON-NLS-1$
+
+ public final static String STP_STRING = "__stp_string"; //$NON-NLS-1$
+ public final static String STP_COMMENT = "__stp_comment"; //$NON-NLS-1$
+ public final static String STP_CONDITIONAL = "__stp_conditional"; //$NON-NLS-1$
+ public final static String STP_MULTILINE_COMMENT = "__stp_multiline_comment"; //$NON-NLS-1$
+
+ public static String[] STP_PARTITION_TYPES = { IDocument.DEFAULT_CONTENT_TYPE,
+ STP_COMMENT, STP_MULTILINE_COMMENT, STP_STRING, STP_CONDITIONAL};
+
+ /**
+ * Detect empty comments
+ */
+ private static class EmptyCommentDetector implements IWordDetector {
+ @Override
+ public boolean isWordStart(char c) {
+ return (c == '/');
+ }
+
+ @Override
+ public boolean isWordPart(char c) {
+ return (c == '*' || c == '/');
+ }
+ }
+
+ /**
+ * Cope with the empty comment issue.
+ */
+ private static class EmptyCommentRule extends WordRule implements IPredicateRule {
+
+ private IToken fSuccessToken;
+
+ public EmptyCommentRule(IToken successToken) {
+ super(new EmptyCommentDetector());
+ fSuccessToken= successToken;
+ addWord("/**/", fSuccessToken); //$NON-NLS-1$
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner, boolean resume) {
+ return evaluate(scanner);
+ }
+
+ @Override
+ public IToken getSuccessToken() {
+ return fSuccessToken;
+ }
+ }
+
+ public STPPartitionScanner() {
+
+ IToken stpComment = new Token(STP_COMMENT);
+ IToken stpMultilineComment = new Token(STP_MULTILINE_COMMENT);
+ IToken stpConditional = new Token(STP_CONDITIONAL);
+ IToken stpString = new Token(STP_STRING);
+
+ // Add special case word rule.
+ EmptyCommentRule emptyCommentRule= new EmptyCommentRule(stpComment);
setPredicateRules(new IPredicateRule[] {
- new EndOfLineRule("//", stpComment), //$NON-NLS-1$
- new MultiLineRule("/*", "*/", stpMultilineComment), //$NON-NLS-1$//$NON-NLS-2$
+ new EndOfLineRule("//", stpComment), //$NON-NLS-1$
+ new MultiLineRule("/*", "*/", stpMultilineComment), //$NON-NLS-1$//$NON-NLS-2$
new EndOfLineRule("#", stpComment), //$NON-NLS-1$
- emptyCommentRule,
- new SingleLineRule("\"", "\"", stpString, '\\', false, true), //$NON-NLS-1$ //$NON-NLS-2$
+ emptyCommentRule,
+ new SingleLineRule("\"", "\"", stpString, '\\', false, true), //$NON-NLS-1$ //$NON-NLS-2$
new MultiLineRule("%(", "%)", stpConditional), //$NON-NLS-1$ //$NON-NLS-2$
});
- }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPPartitioner.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPPartitioner.java
index 5ed8a3344b..41643489f6 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPPartitioner.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPPartitioner.java
@@ -15,17 +15,17 @@ import org.eclipse.jface.text.rules.IPartitionTokenScanner;
public class STPPartitioner extends FastPartitioner {
- /**
- * Straight forward FastPartitioner, with debug output.
- *
- * Taken directly from org.eclipse.linuxtools.rpm.ui.editor.SpecFilePartitioner.
- * No noteworthy alterations so Copyright header and license text untouched.
- *
- * @param scanner
- * @param legalContentTypes
- */
- public STPPartitioner(IPartitionTokenScanner scanner, String[] legalContentTypes) {
- super(scanner, legalContentTypes);
- }
+ /**
+ * Straight forward FastPartitioner, with debug output.
+ *
+ * Taken directly from org.eclipse.linuxtools.rpm.ui.editor.SpecFilePartitioner.
+ * No noteworthy alterations so Copyright header and license text untouched.
+ *
+ * @param scanner
+ * @param legalContentTypes
+ */
+ public STPPartitioner(IPartitionTokenScanner scanner, String[] legalContentTypes) {
+ super(scanner, legalContentTypes);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPProbeScanner.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPProbeScanner.java
index fcd4358843..7e96af4e25 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPProbeScanner.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPProbeScanner.java
@@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008, 2013 Phil Muldoon <pkmuldoon@picobot.org>.
- *
+ *
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * Phil Muldoon <pkmuldoon@picobot.org> - initial API and implementation.
+ * Phil Muldoon <pkmuldoon@picobot.org> - initial API and implementation.
* Red Hat Inc. - modification for use in probe scanning
*******************************************************************************/
package org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp;
@@ -22,35 +22,35 @@ import org.eclipse.jface.text.rules.SingleLineRule;
import org.eclipse.jface.text.rules.Token;
public class STPProbeScanner extends RuleBasedPartitionScanner {
- public final static String STP_STRING = "__stp_string"; //$NON-NLS-1$
- public final static String STP_PROBE = "__stp_probe"; //$NON-NLS-1$
- public final static String STP_CONDITIONAL = "__stp_conditional"; //$NON-NLS-1$
- public final static String STP_COMMENT = "__stp_comment"; //$NON-NLS-1$
-
- public final static String STP_PROBE_PARTITIONING = "__stp_probe_partitioning"; //$NON-NLS-1$
-
- public static String[] STP_PROBE_PARTITION_TYPES = { IDocument.DEFAULT_CONTENT_TYPE,
- STP_COMMENT, STP_STRING, STP_PROBE, STP_CONDITIONAL};
-
- public STPProbeScanner() {
-
- IToken stpString = new Token(STP_STRING);
- IToken stpProbe = new Token(STP_PROBE);
- IToken stpComment = new Token(STP_COMMENT);
- IToken stpConditional = new Token(STP_CONDITIONAL);
+ public final static String STP_STRING = "__stp_string"; //$NON-NLS-1$
+ public final static String STP_PROBE = "__stp_probe"; //$NON-NLS-1$
+ public final static String STP_CONDITIONAL = "__stp_conditional"; //$NON-NLS-1$
+ public final static String STP_COMMENT = "__stp_comment"; //$NON-NLS-1$
+
+ public final static String STP_PROBE_PARTITIONING = "__stp_probe_partitioning"; //$NON-NLS-1$
+
+ public static String[] STP_PROBE_PARTITION_TYPES = { IDocument.DEFAULT_CONTENT_TYPE,
+ STP_COMMENT, STP_STRING, STP_PROBE, STP_CONDITIONAL};
+
+ public STPProbeScanner() {
+
+ IToken stpString = new Token(STP_STRING);
+ IToken stpProbe = new Token(STP_PROBE);
+ IToken stpComment = new Token(STP_COMMENT);
+ IToken stpConditional = new Token(STP_CONDITIONAL);
setPredicateRules(new IPredicateRule[] {
- new EndOfLineRule("//", stpComment), //$NON-NLS-1$
- new MultiLineRule("/*", "*/", stpComment), //$NON-NLS-1$//$NON-NLS-2$
- new EndOfLineRule("#", stpComment), //$NON-NLS-1$
+ new EndOfLineRule("//", stpComment), //$NON-NLS-1$
+ new MultiLineRule("/*", "*/", stpComment), //$NON-NLS-1$//$NON-NLS-2$
+ new EndOfLineRule("#", stpComment), //$NON-NLS-1$
new EndOfLineRule("#if", stpConditional), //$NON-NLS-1$
new EndOfLineRule("#else", stpConditional), //$NON-NLS-1$
new EndOfLineRule("#endif", stpConditional), //$NON-NLS-1$
new EndOfLineRule("#define", stpConditional), //$NON-NLS-1$
- new SingleLineRule("\"", "\"", stpString, '\\', false, true), //$NON-NLS-1$ //$NON-NLS-2$
- new SingleLineRule("'", "'", stpString, '\\'), //$NON-NLS-1$ //$NON-NLS-2$
+ new SingleLineRule("\"", "\"", stpString, '\\', false, true), //$NON-NLS-1$ //$NON-NLS-2$
+ new SingleLineRule("'", "'", stpString, '\\'), //$NON-NLS-1$ //$NON-NLS-2$
new MultiLineRule("probe", "}", stpProbe), //$NON-NLS-1$ //$NON-NLS-2$
});
- }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPReconcilingStrategy.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPReconcilingStrategy.java
index f4a536f826..f3b3383a3b 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPReconcilingStrategy.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPReconcilingStrategy.java
@@ -33,7 +33,7 @@ import org.eclipse.swt.widgets.Display;
public class STPReconcilingStrategy implements IReconcilingStrategy,
IReconcilingStrategyExtension {
- // Constants
+ // Constants
protected static final int STP_NO_TAG = 0;
protected static final int STP_MULTILINE_COMMENT_TAG = 1;
protected static final int STP_PROBE = 2;
@@ -48,8 +48,8 @@ public class STPReconcilingStrategy implements IReconcilingStrategy,
// Current tag end
protected int currentTagEnd = 0;
- // List of positions
- protected final ArrayList<Position> documentPositionList = new ArrayList<>();
+ // List of positions
+ protected final ArrayList<Position> documentPositionList = new ArrayList<>();
// The end offset of the range to be scanned *//*
protected int endOfDocumentPostion;
@@ -61,67 +61,67 @@ public class STPReconcilingStrategy implements IReconcilingStrategy,
* Sets the current editor.
*/
public void setEditor(STPEditor editor) {
- this.currentEditor = editor;
+ this.currentEditor = editor;
}
/**
* Sets the current (ie working) document.
*/
@Override
- public void setDocument(IDocument document) {
- this.currentDocument = document;
+ public void setDocument(IDocument document) {
+ this.currentDocument = document;
}
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.IRegion)
- */
- @Override
- public void reconcile(IRegion partition) {
- // Just rebuild the whole document
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.IRegion)
+ */
+ @Override
+ public void reconcile(IRegion partition) {
+ // Just rebuild the whole document
initialReconcile();
- }
+ }
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion, org.eclipse.jface.text.IRegion)
- */
- @Override
- public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
- //Just rebuild the whole document
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion, org.eclipse.jface.text.IRegion)
+ */
+ @Override
+ public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
+ //Just rebuild the whole document
initialReconcile();
- }
+ }
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension#initialReconcile()
- */
- @Override
- public void initialReconcile() {
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension#initialReconcile()
+ */
+ @Override
+ public void initialReconcile() {
endOfDocumentPostion = currentDocument.getLength();
try {
- calculatePositions();
- } catch (BadLocationException e) {
- // Cannot reconcile, return
- return;
- }
- }
+ calculatePositions();
+ } catch (BadLocationException e) {
+ // Cannot reconcile, return
+ return;
+ }
+ }
- /* (non-Javadoc)
- * @see org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension#setProgressMonitor(org.eclipse.core.runtime.IProgressMonitor)
- */
- @Override
- public void setProgressMonitor(IProgressMonitor monitor) {
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension#setProgressMonitor(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ @Override
+ public void setProgressMonitor(IProgressMonitor monitor) {
- }
+ }
- /**
- *
- * From currentDocument, calculate beginning of document
- * to endOfDocumentPostion to build positions for code folding.
- *
- * @throws BadLocationException
- */
- private void calculatePositions() throws BadLocationException {
- // Clear old positions and reset to beginning of document
- documentPositionList.clear();
+ /**
+ *
+ * From currentDocument, calculate beginning of document
+ * to endOfDocumentPostion to build positions for code folding.
+ *
+ * @throws BadLocationException
+ */
+ private void calculatePositions() throws BadLocationException {
+ // Clear old positions and reset to beginning of document
+ documentPositionList.clear();
nextCharPosition = 0;
// Build the actual document positions
@@ -130,87 +130,87 @@ public class STPReconcilingStrategy implements IReconcilingStrategy,
// Paint the folding annotations in the background.
Display.getDefault().asyncExec(new Runnable() {
@Override
- public void run() {
- currentEditor.updateFoldingStructure(documentPositionList);
+ public void run() {
+ currentEditor.updateFoldingStructure(documentPositionList);
}
});
- }
+ }
- /**
- *
- * Start trying to guess if given char z, what - if any - tag this
- * begins.
- *
- * @param location - location of current position
- * @return - tag type, if any
- *
- * @throws BadLocationException
- */
- private int classifyComponent(int location) throws BadLocationException {
+ /**
+ *
+ * Start trying to guess if given char z, what - if any - tag this
+ * begins.
+ *
+ * @param location - location of current position
+ * @return - tag type, if any
+ *
+ * @throws BadLocationException
+ */
+ private int classifyComponent(int location) throws BadLocationException {
int deltaLocation = location;
- char ch = currentDocument.getChar(deltaLocation);
+ char ch = currentDocument.getChar(deltaLocation);
switch (ch) {
- // The 'comment' case.
- case '/':
- deltaLocation++;
- ch = currentDocument.getChar(deltaLocation);
- if (ch == '*') {
- currentTagStart = location;
- deltaLocation++;
- nextCharPosition = deltaLocation;
- return STP_MULTILINE_COMMENT_TAG;
- }
- break;
- // The 'probe' case.
- case 'p':
- if (isProbe()) {
- currentTagStart = location;
- return STP_PROBE;
- }
+ // The 'comment' case.
+ case '/':
+ deltaLocation++;
+ ch = currentDocument.getChar(deltaLocation);
+ if (ch == '*') {
+ currentTagStart = location;
+ deltaLocation++;
+ nextCharPosition = deltaLocation;
+ return STP_MULTILINE_COMMENT_TAG;
+ }
+ break;
+ // The 'probe' case.
+ case 'p':
+ if (isProbe()) {
+ currentTagStart = location;
+ return STP_PROBE;
+ }
- // The 'function' case.
- case 'f':
- if (isFunction()) {
- currentTagStart = location;
- return STP_FUNCTION;
- }
- // No tag, don't fold region.
- default:
- break;
+ // The 'function' case.
+ case 'f':
+ if (isFunction()) {
+ currentTagStart = location;
+ return STP_FUNCTION;
+ }
+ // No tag, don't fold region.
+ default:
+ break;
}
return STP_NO_TAG;
- }
+ }
- /**
- *
- * Build a list of locations to mark beginning and end of folding regions.
- *
- * @throws BadLocationException
- */
- private void buildPositions() throws BadLocationException {
+ /**
+ *
+ * Build a list of locations to mark beginning and end of folding regions.
+ *
+ * @throws BadLocationException
+ */
+ private void buildPositions() throws BadLocationException {
while (nextCharPosition < endOfDocumentPostion) {
- switch (classifyComponent(nextCharPosition))
- {
- // All of these cases have found the beginning of a tag
- // to start folding. Each element must now be find
- // the end of the region it represents.
- case STP_MULTILINE_COMMENT_TAG:
- currentTagEnd = findEndOfComment();
- writePosition(currentTagStart,currentTagEnd);
- nextCharPosition = currentTagStart + currentTagEnd;
- break;
- case STP_PROBE:
- case STP_FUNCTION:
- currentTagEnd = findEndOfProbeOrFunction();
- writePosition(currentTagStart,currentTagEnd);
- nextCharPosition = currentTagStart + currentTagEnd;
- break;
- default:
- nextCharPosition++;
- break;
+ switch (classifyComponent(nextCharPosition))
+ {
+ // All of these cases have found the beginning of a tag
+ // to start folding. Each element must now be find
+ // the end of the region it represents.
+ case STP_MULTILINE_COMMENT_TAG:
+ currentTagEnd = findEndOfComment();
+ writePosition(currentTagStart,currentTagEnd);
+ nextCharPosition = currentTagStart + currentTagEnd;
+ break;
+ case STP_PROBE:
+ case STP_FUNCTION:
+ currentTagEnd = findEndOfProbeOrFunction();
+ writePosition(currentTagStart,currentTagEnd);
+ nextCharPosition = currentTagStart + currentTagEnd;
+ break;
+ default:
+ nextCharPosition++;
+ break;
}
}
- }
+ }
/**
*
@@ -221,65 +221,65 @@ public class STPReconcilingStrategy implements IReconcilingStrategy,
*
*/
private void writePosition(int startOffset, int length) {
- if (length > 0)
- documentPositionList.add(new Position(startOffset, length));
+ if (length > 0)
+ documentPositionList.add(new Position(startOffset, length));
}
private boolean isProbe() throws BadLocationException {
- return matchKeyWord("probe"); //$NON-NLS-1$
+ return matchKeyWord("probe"); //$NON-NLS-1$
}
private boolean isFunction() throws BadLocationException {
- return matchKeyWord("function"); //$NON-NLS-1$
+ return matchKeyWord("function"); //$NON-NLS-1$
}
private boolean matchKeyWord(String word) throws BadLocationException {
- StringBuffer keyWord = new StringBuffer();
- int location = nextCharPosition;
- while (location < endOfDocumentPostion) {
- char ch = currentDocument.getChar(location);
- if ((ch == ' ') || (!Character.isLetter(ch)))
- break;
- else
- keyWord.append(ch);
- location++;
- }
- if (keyWord.toString().compareTo(word) == 0)
- return true;
- return false;
+ StringBuffer keyWord = new StringBuffer();
+ int location = nextCharPosition;
+ while (location < endOfDocumentPostion) {
+ char ch = currentDocument.getChar(location);
+ if ((ch == ' ') || (!Character.isLetter(ch)))
+ break;
+ else
+ keyWord.append(ch);
+ location++;
+ }
+ if (keyWord.toString().compareTo(word) == 0)
+ return true;
+ return false;
}
private int findEndOfProbeOrFunction() throws BadLocationException {
- int bracketCount = 0;
- boolean firstBracket = false;
- char ch;
+ int bracketCount = 0;
+ boolean firstBracket = false;
+ char ch;
- while (nextCharPosition < endOfDocumentPostion) {
- ch = currentDocument.getChar(nextCharPosition);
- if (ch == '{') {
- firstBracket = true;
- bracketCount++;
- }
- if (ch == '}')
- bracketCount--;
- if ((bracketCount == 0) && (firstBracket))
- return (nextCharPosition-currentTagStart)+2;
- nextCharPosition++;
- }
- return -1;
+ while (nextCharPosition < endOfDocumentPostion) {
+ ch = currentDocument.getChar(nextCharPosition);
+ if (ch == '{') {
+ firstBracket = true;
+ bracketCount++;
+ }
+ if (ch == '}')
+ bracketCount--;
+ if ((bracketCount == 0) && (firstBracket))
+ return (nextCharPosition-currentTagStart)+2;
+ nextCharPosition++;
+ }
+ return -1;
}
private int findEndOfComment() throws BadLocationException {
- while (nextCharPosition < endOfDocumentPostion) {
- char ch = currentDocument.getChar(nextCharPosition);
- if (ch == '*') {
- nextCharPosition++;
- ch = currentDocument.getChar(nextCharPosition);
- if (ch == '/')
- return (nextCharPosition-currentTagStart)+2;
- }
- nextCharPosition++;
- }
- return -1;
+ while (nextCharPosition < endOfDocumentPostion) {
+ char ch = currentDocument.getChar(nextCharPosition);
+ if (ch == '*') {
+ nextCharPosition++;
+ ch = currentDocument.getChar(nextCharPosition);
+ if (ch == '/')
+ return (nextCharPosition-currentTagStart)+2;
+ }
+ nextCharPosition++;
+ }
+ return -1;
}
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPSymbols.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPSymbols.java
index a506cef9a3..2113ba3e4a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPSymbols.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/editors/stp/STPSymbols.java
@@ -17,63 +17,63 @@ package org.eclipse.linuxtools.internal.systemtap.ui.ide.editors.stp;
* Symbols for the heuristic STP scanner.
*/
public interface STPSymbols {
- int TokenEOF= -1;
- int TokenLBRACE= 1;
- int TokenRBRACE= 2;
- int TokenLBRACKET= 3;
- int TokenRBRACKET= 4;
- int TokenLPAREN= 5;
- int TokenRPAREN= 6;
- int TokenSEMICOLON= 7;
- int TokenOTHER= 8;
- int TokenCOLON= 9;
- int TokenQUESTIONMARK= 10;
- int TokenCOMMA= 11;
- int TokenEQUAL= 12;
- int TokenLESSTHAN= 13;
- int TokenGREATERTHAN= 14;
- int TokenDOT= 15;
- int TokenMINUS= 16;
- int TokenTILDE= 17;
- int TokenSHIFTRIGHT= 18;
- int TokenARROW= 19;
- int TokenDOUBLECOLON= 20;
- int TokenSHIFTLEFT= 21;
- int TokenPLUS= 22;
- int TokenAGGREGATE= 23;
- int TokenIF= 109;
- int TokenDO= 1010;
- int TokenFOR= 1011;
- int TokenTRY= 1012;
- int TokenCASE= 1013;
- int TokenELSE= 1014;
- int TokenBREAK= 1015;
- int TokenCATCH= 1016;
- int TokenWHILE= 1017;
- int TokenRETURN= 1018;
- int TokenSTATIC= 1019;
- int TokenSWITCH= 1020;
- int TokenGOTO= 1021;
- int TokenDEFAULT= 1022;
- int TokenPRIVATE= 1023;
- int TokenPROTECTED= 1024;
- int TokenPUBLIC= 1025;
- int TokenNEW= 1026;
- int TokenDELETE= 1027;
- int TokenCLASS= 1028;
- int TokenSTRUCT= 1029;
- int TokenUNION= 1030;
- int TokenENUM= 1031;
- int TokenVIRTUAL= 1032;
- int TokenNAMESPACE= 1033;
- int TokenOPERATOR= 1034;
- int TokenTHROW= 1035;
- int TokenCONST= 1036;
- int TokenEXTERN= 1037;
- int TokenTYPEDEF= 1038;
- int TokenUSING= 1039;
- int TokenTEMPLATE= 1040;
- int TokenTYPENAME= 1041;
- int TokenFOREACH= 1042;
- int TokenIDENT= 2000;
+ int TokenEOF= -1;
+ int TokenLBRACE= 1;
+ int TokenRBRACE= 2;
+ int TokenLBRACKET= 3;
+ int TokenRBRACKET= 4;
+ int TokenLPAREN= 5;
+ int TokenRPAREN= 6;
+ int TokenSEMICOLON= 7;
+ int TokenOTHER= 8;
+ int TokenCOLON= 9;
+ int TokenQUESTIONMARK= 10;
+ int TokenCOMMA= 11;
+ int TokenEQUAL= 12;
+ int TokenLESSTHAN= 13;
+ int TokenGREATERTHAN= 14;
+ int TokenDOT= 15;
+ int TokenMINUS= 16;
+ int TokenTILDE= 17;
+ int TokenSHIFTRIGHT= 18;
+ int TokenARROW= 19;
+ int TokenDOUBLECOLON= 20;
+ int TokenSHIFTLEFT= 21;
+ int TokenPLUS= 22;
+ int TokenAGGREGATE= 23;
+ int TokenIF= 109;
+ int TokenDO= 1010;
+ int TokenFOR= 1011;
+ int TokenTRY= 1012;
+ int TokenCASE= 1013;
+ int TokenELSE= 1014;
+ int TokenBREAK= 1015;
+ int TokenCATCH= 1016;
+ int TokenWHILE= 1017;
+ int TokenRETURN= 1018;
+ int TokenSTATIC= 1019;
+ int TokenSWITCH= 1020;
+ int TokenGOTO= 1021;
+ int TokenDEFAULT= 1022;
+ int TokenPRIVATE= 1023;
+ int TokenPROTECTED= 1024;
+ int TokenPUBLIC= 1025;
+ int TokenNEW= 1026;
+ int TokenDELETE= 1027;
+ int TokenCLASS= 1028;
+ int TokenSTRUCT= 1029;
+ int TokenUNION= 1030;
+ int TokenENUM= 1031;
+ int TokenVIRTUAL= 1032;
+ int TokenNAMESPACE= 1033;
+ int TokenOPERATOR= 1034;
+ int TokenTHROW= 1035;
+ int TokenCONST= 1036;
+ int TokenEXTERN= 1037;
+ int TokenTYPEDEF= 1038;
+ int TokenUSING= 1039;
+ int TokenTEMPLATE= 1040;
+ int TokenTYPENAME= 1041;
+ int TokenFOREACH= 1042;
+ int TokenIDENT= 2000;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/AddStapProbeHandler.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/AddStapProbeHandler.java
index d4af4ae9fd..1f92e17abd 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/AddStapProbeHandler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/AddStapProbeHandler.java
@@ -25,107 +25,107 @@ import org.eclipse.ui.texteditor.ITextEditor;
public class AddStapProbeHandler extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ITextEditor editor;
- try {
- editor = (ITextEditor) HandlerUtil.getActiveEditor(event);
- } catch (ClassCastException e) {
- throw new ExecutionException(Messages.AddStapProbe_editorError, e);
- }
- IVerticalRulerInfo rulerInfo = (IVerticalRulerInfo) editor.getAdapter(IVerticalRulerInfo.class);
-
- Shell shell = editor.getSite().getShell();
- shell.setCursor(shell.getDisplay().getSystemCursor(
- SWT.CURSOR_WAIT));
- int lineno = rulerInfo.getLineOfLastMouseButtonActivity();
- IDocument document = editor.getDocumentProvider().getDocument(
- editor.getEditorInput());
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ITextEditor editor;
+ try {
+ editor = (ITextEditor) HandlerUtil.getActiveEditor(event);
+ } catch (ClassCastException e) {
+ throw new ExecutionException(Messages.AddStapProbe_editorError, e);
+ }
+ IVerticalRulerInfo rulerInfo = (IVerticalRulerInfo) editor.getAdapter(IVerticalRulerInfo.class);
- String s = document.get();
- String[] lines = s.split("\n"); //$NON-NLS-1$
- String line = lines[lineno].trim();
- boolean die = false;
- if (line.isEmpty()) {//eat blank lines
- die = true;
- }
- if (line.startsWith("#")) {//eat preprocessor directives //$NON-NLS-1$
- die = true;
- }
- if (line.startsWith("//")) {//eat C99 comments //$NON-NLS-1$
- die = true;
- }
- if (line.startsWith("/*") && !line.contains("*/") && !line.endsWith("*/")) {//try to eat single-line C comments //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- die = true;
- }
+ Shell shell = editor.getSite().getShell();
+ shell.setCursor(shell.getDisplay().getSystemCursor(
+ SWT.CURSOR_WAIT));
+ int lineno = rulerInfo.getLineOfLastMouseButtonActivity();
+ IDocument document = editor.getDocumentProvider().getDocument(
+ editor.getEditorInput());
- // gogo find comment segments
- try {
- ArrayList<Integer> commentChunks = new ArrayList<>();
- char[] chars = s.toCharArray();
- int needle = 1;
- int offset = document.getLineOffset(lineno);
- while (needle < chars.length) {
- if (chars[needle - 1] == '/' && chars[needle] == '*') {
- commentChunks.add(needle);
- while (needle < chars.length) {
- if (chars[needle - 1] == '*'
- && chars[needle] == '/') {
- commentChunks.add(needle);
- needle++;
- break;
- }
- needle++;
- }
- }
- needle++;
- }
- for (int i = 0, pair, start, end; i < commentChunks.size(); i++) {
- if (!(commentChunks.get(i).intValue() < offset)) {
- pair = i - i % 2;
- start = commentChunks.get(pair).intValue();
- end = commentChunks.get(pair + 1).intValue();
- if (offset >= start && offset <= end) {
- die = true;
- }
- }
- }
- } catch (BadLocationException excp) {
- ExceptionErrorDialog.openError(Messages.AddStapProbe_unableToInsertProbe, excp);
- }
- if (die) {
- MessageDialog
- .openError(
- PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow()
- .getShell(),
- Messages.CEditor_probeInsertFailed, Messages.CEditor_canNotProbeLine);
- } else {
- IEditorInput in = editor.getEditorInput();
- if (in instanceof FileStoreEditorInput) {
- FileStoreEditorInput input = (FileStoreEditorInput) in;
+ String s = document.get();
+ String[] lines = s.split("\n"); //$NON-NLS-1$
+ String line = lines[lineno].trim();
+ boolean die = false;
+ if (line.isEmpty()) {//eat blank lines
+ die = true;
+ }
+ if (line.startsWith("#")) {//eat preprocessor directives //$NON-NLS-1$
+ die = true;
+ }
+ if (line.startsWith("//")) {//eat C99 comments //$NON-NLS-1$
+ die = true;
+ }
+ if (line.startsWith("/*") && !line.contains("*/") && !line.endsWith("*/")) {//try to eat single-line C comments //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ die = true;
+ }
- IPreferenceStore p = IDEPlugin.getDefault()
- .getPreferenceStore();
- String kernroot = p
- .getString(IDEPreferenceConstants.P_KERNEL_SOURCE);
+ // gogo find comment segments
+ try {
+ ArrayList<Integer> commentChunks = new ArrayList<>();
+ char[] chars = s.toCharArray();
+ int needle = 1;
+ int offset = document.getLineOffset(lineno);
+ while (needle < chars.length) {
+ if (chars[needle - 1] == '/' && chars[needle] == '*') {
+ commentChunks.add(needle);
+ while (needle < chars.length) {
+ if (chars[needle - 1] == '*'
+ && chars[needle] == '/') {
+ commentChunks.add(needle);
+ needle++;
+ break;
+ }
+ needle++;
+ }
+ }
+ needle++;
+ }
+ for (int i = 0, pair, start, end; i < commentChunks.size(); i++) {
+ if (!(commentChunks.get(i).intValue() < offset)) {
+ pair = i - i % 2;
+ start = commentChunks.get(pair).intValue();
+ end = commentChunks.get(pair + 1).intValue();
+ if (offset >= start && offset <= end) {
+ die = true;
+ }
+ }
+ }
+ } catch (BadLocationException excp) {
+ ExceptionErrorDialog.openError(Messages.AddStapProbe_unableToInsertProbe, excp);
+ }
+ if (die) {
+ MessageDialog
+ .openError(
+ PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow()
+ .getShell(),
+ Messages.CEditor_probeInsertFailed, Messages.CEditor_canNotProbeLine);
+ } else {
+ IEditorInput in = editor.getEditorInput();
+ if (in instanceof FileStoreEditorInput) {
+ FileStoreEditorInput input = (FileStoreEditorInput) in;
- String filepath = input.getURI().getPath();
- String kernrelative = filepath.substring(
- kernroot.length() + 1, filepath.length());
- StringBuffer sb = new StringBuffer();
+ IPreferenceStore p = IDEPlugin.getDefault()
+ .getPreferenceStore();
+ String kernroot = p
+ .getString(IDEPreferenceConstants.P_KERNEL_SOURCE);
- sb.append("probe kernel.statement(\"*@" + kernrelative + ":" + (lineno + 1) + "\")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ String filepath = input.getURI().getPath();
+ String kernrelative = filepath.substring(
+ kernroot.length() + 1, filepath.length());
+ StringBuffer sb = new StringBuffer();
- sb.append("\n{\n\t\n}\n"); //$NON-NLS-1$
- STPEditor activeSTPEditor = IDESessionSettings.getOrAskForActiveSTPEditor(false);
- if (null != activeSTPEditor) {
- activeSTPEditor.insertText(sb.toString());
- }
- }
- }
- shell.setCursor(null); // Return the cursor to normal
- return null;
- }
+ sb.append("probe kernel.statement(\"*@" + kernrelative + ":" + (lineno + 1) + "\")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ sb.append("\n{\n\t\n}\n"); //$NON-NLS-1$
+ STPEditor activeSTPEditor = IDESessionSettings.getOrAskForActiveSTPEditor(false);
+ if (null != activeSTPEditor) {
+ activeSTPEditor.insertText(sb.toString());
+ }
+ }
+ }
+ shell.setCursor(null); // Return the cursor to normal
+ return null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/DefinitionHandler.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/DefinitionHandler.java
index bf1a52d35c..c279ea24e4 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/DefinitionHandler.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/DefinitionHandler.java
@@ -30,54 +30,54 @@ import org.eclipse.ui.handlers.HandlerUtil;
public class DefinitionHandler extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) {
- TreeDefinitionNode t = getSelection(event);
- if(t == null) {
- return null;
- }
- String filename = t.getDefinition();
- if (filename == null) {
- return null;
- }
- File file = new File(filename);
- OpenFileAction open = new OpenFileAction();
- open.run(file);
- if (open.isSuccessful() && t.getData() instanceof ISearchableNode) {
- IEditorPart editorPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- STPEditor editor = (STPEditor)editorPart;
- editor.jumpToLocation(findDefinitionLine((ISearchableNode) t.getData(), editor) + 1, 0);
- }
- return null;
- }
+ @Override
+ public Object execute(ExecutionEvent event) {
+ TreeDefinitionNode t = getSelection(event);
+ if(t == null) {
+ return null;
+ }
+ String filename = t.getDefinition();
+ if (filename == null) {
+ return null;
+ }
+ File file = new File(filename);
+ OpenFileAction open = new OpenFileAction();
+ open.run(file);
+ if (open.isSuccessful() && t.getData() instanceof ISearchableNode) {
+ IEditorPart editorPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
+ STPEditor editor = (STPEditor)editorPart;
+ editor.jumpToLocation(findDefinitionLine((ISearchableNode) t.getData(), editor) + 1, 0);
+ }
+ return null;
+ }
- private TreeDefinitionNode getSelection(ExecutionEvent event) {
- ISelection selection = HandlerUtil.getCurrentSelection(event);
- if (selection instanceof StructuredSelection) {
- Object[] selections = ((StructuredSelection) selection).toArray();
- return (selections.length == 1 && selections[0] instanceof TreeDefinitionNode)
- ? (TreeDefinitionNode) selections[0] : null;
- }
- return null;
- }
+ private TreeDefinitionNode getSelection(ExecutionEvent event) {
+ ISelection selection = HandlerUtil.getCurrentSelection(event);
+ if (selection instanceof StructuredSelection) {
+ Object[] selections = ((StructuredSelection) selection).toArray();
+ return (selections.length == 1 && selections[0] instanceof TreeDefinitionNode)
+ ? (TreeDefinitionNode) selections[0] : null;
+ }
+ return null;
+ }
- private int findDefinitionLine(ISearchableNode data, STPEditor editor) {
- int locationIndex;
- String contents = CommentRemover.exec(editor.getDocumentProvider().getDocument(editor.getEditorInput()).get());
- if (data.isRegexSearch()) {
- Pattern pattern = Pattern.compile(data.getSearchToken());
- Matcher matcher = pattern.matcher(contents);
- locationIndex = matcher.find() ? matcher.start() : -1;
- } else {
- locationIndex = contents.indexOf(data.getSearchToken());
- }
- if (locationIndex != -1) {
- // Get the line of the match by counting newlines.
- contents = contents.substring(0, locationIndex);
- return contents.length() - contents.replaceAll("\n", "").length(); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- return 0;
- }
- }
+ private int findDefinitionLine(ISearchableNode data, STPEditor editor) {
+ int locationIndex;
+ String contents = CommentRemover.exec(editor.getDocumentProvider().getDocument(editor.getEditorInput()).get());
+ if (data.isRegexSearch()) {
+ Pattern pattern = Pattern.compile(data.getSearchToken());
+ Matcher matcher = pattern.matcher(contents);
+ locationIndex = matcher.find() ? matcher.start() : -1;
+ } else {
+ locationIndex = contents.indexOf(data.getSearchToken());
+ }
+ if (locationIndex != -1) {
+ // Get the line of the match by counting newlines.
+ contents = contents.substring(0, locationIndex);
+ return contents.length() - contents.replaceAll("\n", "").length(); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ return 0;
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/DefinitionMenuTester.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/DefinitionMenuTester.java
index 904a982fd0..35ea8c98a5 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/DefinitionMenuTester.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/DefinitionMenuTester.java
@@ -16,12 +16,12 @@ import org.eclipse.linuxtools.systemtap.structures.TreeDefinitionNode;
public class DefinitionMenuTester extends PropertyTester {
- @Override
- public boolean test(Object receiver, String property, Object[] args,
- Object expectedValue) {
- return receiver instanceof TreeDefinitionNode
- ? ((TreeDefinitionNode) receiver).getDefinition() != null
- : false;
- }
+ @Override
+ public boolean test(Object receiver, String property, Object[] args,
+ Object expectedValue) {
+ return receiver instanceof TreeDefinitionNode
+ ? ((TreeDefinitionNode) receiver).getDefinition() != null
+ : false;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/Messages.java
index 92c22977ec..e8a4c102ed 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/handlers/Messages.java
@@ -16,16 +16,16 @@ import org.eclipse.osgi.util.NLS;
* @since 2.0
*/
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.handlers.messages"; //$NON-NLS-1$
- public static String AddStapProbe_editorError;
- public static String AddStapProbe_unableToInsertProbe;
- public static String CEditor_probeInsertFailed;
- public static String CEditor_canNotProbeLine;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.handlers.messages"; //$NON-NLS-1$
+ public static String AddStapProbe_editorError;
+ public static String AddStapProbe_unableToInsertProbe;
+ public static String CEditor_probeInsertFailed;
+ public static String CEditor_canNotProbeLine;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/Messages.java
index 0f98eec25e..ca6b379793 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/Messages.java
@@ -15,98 +15,98 @@ import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.launcher.messages"; //$NON-NLS-1$
-
- public static String SystemTapScriptGraphOptionsTab_cantInitializeTab;
- public static String SystemTapScriptGraphOptionsTab_graphOutputRun;
- public static String SystemTapScriptGraphOptionsTab_graphOutput;
- public static String SystemTapScriptGraphOptionsTab_outputLabel;
- public static String SystemTapScriptGraphOptionsTab_emptyGroup;
- public static String SystemTapScriptGraphOptionsTab_graphingTitle;
- public static String SystemTapScriptGraphOptionsTab_deletedGraphData;
- public static String SystemTapScriptGraphOptionsTab_noGroups;
- public static String SystemTapScriptGraphOptionsTab_badGraphID;
-
- public static String SystemTapScriptGraphOptionsTab_AddGraphButton;
- public static String SystemTapScriptGraphOptionsTab_AddGraphButtonToolTip;
- public static String SystemTapScriptGraphOptionsTab_DuplicateGraphButton;
- public static String SystemTapScriptGraphOptionsTab_DuplicateGraphButtonToolTip;
- public static String SystemTapScriptGraphOptionsTab_EditGraphButton;
- public static String SystemTapScriptGraphOptionsTab_EditGraphButtonToolTip;
-
- public static String SystemTapScriptGraphOptionsTab_columnTitle;
- public static String SystemTapScriptGraphOptionsTab_extractedValueLabel;
- public static String SystemTapScriptGraphOptionsTab_columnShiftUp;
- public static String SystemTapScriptGraphOptionsTab_columnShiftDown;
- public static String SystemTapScriptGraphOptionsTab_defaultColumnTitleBase;
- public static String SystemTapScriptGraphOptionsTab_RemoveGraphButton;
- public static String SystemTapScriptGraphOptionsTab_RemoveGraphButtonToolTip;
- public static String SystemTapScriptGraphOptionsTab_invalidGraph;
- public static String SystemTapScriptGraphOptionsTab_invalidGraphID;
-
- public static String SystemTapScriptGraphOptionsTab_regexErrorMsgFormat;
- public static String SystemTapScriptGraphOptionsTab_regexLabel;
- public static String SystemTapScriptGraphOptionsTab_regexTooltip;
- public static String SystemTapScriptGraphOptionsTab_regexAddNew;
- public static String SystemTapScriptGraphOptionsTab_regexRemove;
- public static String SystemTapScriptGraphOptionsTab_graphSetTitleBase;
-
- public static String SystemTapScriptGraphOptionsTab_removeRegexTitle;
- public static String SystemTapScriptGraphOptionsTab_removeRegexAsk;
-
- public static String SystemTapScriptGraphOptionsTab_sampleOutputLabel;
- public static String SystemTapScriptGraphOptionsTab_sampleOutputTooltip;
- public static String SystemTapScriptGraphOptionsTab_sampleOutputNoMatch;
- public static String SystemTapScriptGraphOptionsTab_sampleOutputIsEmpty;
-
- public static String SystemTapScriptGraphOptionsTab_generateFromPrintsButton;
- public static String SystemTapScriptGraphOptionsTab_generateFromPrintsTooltip;
- public static String SystemTapScriptGraphOptionsTab_generateFromPrintsTitle;
- public static String SystemTapScriptGraphOptionsTab_generateFromPrintsMessage;
- public static String SystemTapScriptGraphOptionsTab_generateFromPrintsErrorTitle;
- public static String SystemTapScriptGraphOptionsTab_generateFromPrintsError;
- public static String SystemTapScriptGraphOptionsTab_generateFromPrintsEmpty;
-
- public static String SystemTapScriptLaunchConfigurationTab_script;
- public static String SystemTapScriptLaunchConfigurationTab_browse;
- public static String SystemTapScriptLaunchConfigurationTab_currentUser;
- public static String SystemTapScriptLaunchConfigurationTab_username;
- public static String SystemTapScriptLaunchConfigurationTab_password;
- public static String SystemTapScriptLaunchConfigurationTab_user;
- public static String SystemTapScriptLaunchConfigurationTab_host;
- public static String SystemTapScriptLaunchConfigurationTab_runLocally;
- public static String SystemTapScriptLaunchConfigurationTab_hostname;
- public static String SystemTapScriptLaunchConfigurationTab_general;
- public static String SystemTapScriptLaunchConfigurationTab_tabName;
- public static String SystemTapScriptLaunchConfigurationTab_selectScript;
-
- public static String SystemTapScriptLaunchConfigurationTab_errorInitializingTab;
- public static String SystemTapScriptLaunchConfigurationTab_options;
- public static String SystemTapScriptLaunchConfigurationTab_runWithChart;
- public static String SystemTapScriptLaunchShortcut_couldNotFindConfig;
- public static String SystemTapScriptLaunchShortcut_couldNotLaunchScript;
- public static String SystemTapScriptLaunchConfigurationTab_fileNotFound;
- public static String SystemTapScriptLaunchConfigurationTab_fileNotStp;
-
- public static String SystemTapScriptOptionsTab_selectExec;
- public static String SystemTapScriptOptionsTab_targetExec;
- public static String SystemTapScriptOptionsTab_otherOptions;
- public static String SystemTapScriptOptionsTab_dyninst;
- public static String SystemTapScriptOptionsTab_dyninstError;
- public static String SystemTapScriptOptionsTab_pidError;
- public static String SystemTapScriptOptionsTab_initializeConfigurationFailed;
- public static String SystemTapScriptOptionsTab_targetToolTip;
-
- public static String SystemTapScriptLaunchError_graph;
- public static String SystemTapScriptLaunchError_fileNotFound;
- public static String SystemTapScriptLaunchError_fileNotStp;
- public static String SystemTapScriptLaunchError_waitForConsoles;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.launcher.messages"; //$NON-NLS-1$
+
+ public static String SystemTapScriptGraphOptionsTab_cantInitializeTab;
+ public static String SystemTapScriptGraphOptionsTab_graphOutputRun;
+ public static String SystemTapScriptGraphOptionsTab_graphOutput;
+ public static String SystemTapScriptGraphOptionsTab_outputLabel;
+ public static String SystemTapScriptGraphOptionsTab_emptyGroup;
+ public static String SystemTapScriptGraphOptionsTab_graphingTitle;
+ public static String SystemTapScriptGraphOptionsTab_deletedGraphData;
+ public static String SystemTapScriptGraphOptionsTab_noGroups;
+ public static String SystemTapScriptGraphOptionsTab_badGraphID;
+
+ public static String SystemTapScriptGraphOptionsTab_AddGraphButton;
+ public static String SystemTapScriptGraphOptionsTab_AddGraphButtonToolTip;
+ public static String SystemTapScriptGraphOptionsTab_DuplicateGraphButton;
+ public static String SystemTapScriptGraphOptionsTab_DuplicateGraphButtonToolTip;
+ public static String SystemTapScriptGraphOptionsTab_EditGraphButton;
+ public static String SystemTapScriptGraphOptionsTab_EditGraphButtonToolTip;
+
+ public static String SystemTapScriptGraphOptionsTab_columnTitle;
+ public static String SystemTapScriptGraphOptionsTab_extractedValueLabel;
+ public static String SystemTapScriptGraphOptionsTab_columnShiftUp;
+ public static String SystemTapScriptGraphOptionsTab_columnShiftDown;
+ public static String SystemTapScriptGraphOptionsTab_defaultColumnTitleBase;
+ public static String SystemTapScriptGraphOptionsTab_RemoveGraphButton;
+ public static String SystemTapScriptGraphOptionsTab_RemoveGraphButtonToolTip;
+ public static String SystemTapScriptGraphOptionsTab_invalidGraph;
+ public static String SystemTapScriptGraphOptionsTab_invalidGraphID;
+
+ public static String SystemTapScriptGraphOptionsTab_regexErrorMsgFormat;
+ public static String SystemTapScriptGraphOptionsTab_regexLabel;
+ public static String SystemTapScriptGraphOptionsTab_regexTooltip;
+ public static String SystemTapScriptGraphOptionsTab_regexAddNew;
+ public static String SystemTapScriptGraphOptionsTab_regexRemove;
+ public static String SystemTapScriptGraphOptionsTab_graphSetTitleBase;
+
+ public static String SystemTapScriptGraphOptionsTab_removeRegexTitle;
+ public static String SystemTapScriptGraphOptionsTab_removeRegexAsk;
+
+ public static String SystemTapScriptGraphOptionsTab_sampleOutputLabel;
+ public static String SystemTapScriptGraphOptionsTab_sampleOutputTooltip;
+ public static String SystemTapScriptGraphOptionsTab_sampleOutputNoMatch;
+ public static String SystemTapScriptGraphOptionsTab_sampleOutputIsEmpty;
+
+ public static String SystemTapScriptGraphOptionsTab_generateFromPrintsButton;
+ public static String SystemTapScriptGraphOptionsTab_generateFromPrintsTooltip;
+ public static String SystemTapScriptGraphOptionsTab_generateFromPrintsTitle;
+ public static String SystemTapScriptGraphOptionsTab_generateFromPrintsMessage;
+ public static String SystemTapScriptGraphOptionsTab_generateFromPrintsErrorTitle;
+ public static String SystemTapScriptGraphOptionsTab_generateFromPrintsError;
+ public static String SystemTapScriptGraphOptionsTab_generateFromPrintsEmpty;
+
+ public static String SystemTapScriptLaunchConfigurationTab_script;
+ public static String SystemTapScriptLaunchConfigurationTab_browse;
+ public static String SystemTapScriptLaunchConfigurationTab_currentUser;
+ public static String SystemTapScriptLaunchConfigurationTab_username;
+ public static String SystemTapScriptLaunchConfigurationTab_password;
+ public static String SystemTapScriptLaunchConfigurationTab_user;
+ public static String SystemTapScriptLaunchConfigurationTab_host;
+ public static String SystemTapScriptLaunchConfigurationTab_runLocally;
+ public static String SystemTapScriptLaunchConfigurationTab_hostname;
+ public static String SystemTapScriptLaunchConfigurationTab_general;
+ public static String SystemTapScriptLaunchConfigurationTab_tabName;
+ public static String SystemTapScriptLaunchConfigurationTab_selectScript;
+
+ public static String SystemTapScriptLaunchConfigurationTab_errorInitializingTab;
+ public static String SystemTapScriptLaunchConfigurationTab_options;
+ public static String SystemTapScriptLaunchConfigurationTab_runWithChart;
+ public static String SystemTapScriptLaunchShortcut_couldNotFindConfig;
+ public static String SystemTapScriptLaunchShortcut_couldNotLaunchScript;
+ public static String SystemTapScriptLaunchConfigurationTab_fileNotFound;
+ public static String SystemTapScriptLaunchConfigurationTab_fileNotStp;
+
+ public static String SystemTapScriptOptionsTab_selectExec;
+ public static String SystemTapScriptOptionsTab_targetExec;
+ public static String SystemTapScriptOptionsTab_otherOptions;
+ public static String SystemTapScriptOptionsTab_dyninst;
+ public static String SystemTapScriptOptionsTab_dyninstError;
+ public static String SystemTapScriptOptionsTab_pidError;
+ public static String SystemTapScriptOptionsTab_initializeConfigurationFailed;
+ public static String SystemTapScriptOptionsTab_targetToolTip;
+
+ public static String SystemTapScriptLaunchError_graph;
+ public static String SystemTapScriptLaunchError_fileNotFound;
+ public static String SystemTapScriptLaunchError_fileNotStp;
+ public static String SystemTapScriptLaunchError_waitForConsoles;
+
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
+
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptGraphOptionsTab.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptGraphOptionsTab.java
index 80d66f9ae4..05321a2374 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptGraphOptionsTab.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptGraphOptionsTab.java
@@ -76,1571 +76,1571 @@ import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;
public class SystemTapScriptGraphOptionsTab extends
- AbstractLaunchConfigurationTab {
-
- /**
- * The maximum number of regular expressions that can be stored in a configuration.
- */
- static final int MAX_NUMBER_OF_REGEXS = 20;
-
- /**
- * The maximum length of an output-parsing regular expression.
- */
- static final int MAX_REGEX_LENGTH = 200;
-
- // Note: any non-private String key with a trailing underscore is to be appended with an integer when looking up values.
- static final String RUN_WITH_CHART = "runWithChart"; //$NON-NLS-1$
- static final String NUMBER_OF_REGEXS = "numberOfRegexs"; //$NON-NLS-1$
- static final String NUMBER_OF_COLUMNS = "numberOfColumns_"; //$NON-NLS-1$
- static final String REGEX_BOX = "regexBox_"; //$NON-NLS-1$
- static final String NUMBER_OF_EXTRAS = "numberOfExtras_"; //$NON-NLS-1$
- static final String EXTRA_BOX = "extraBox_"; //$NON-NLS-1$
- static final String REGULAR_EXPRESSION = "regularExpression_"; //$NON-NLS-1$
- static final String SAMPLE_OUTPUT = "sampleOutput_"; //$NON-NLS-1$
-
- // Note: all graph-related keys point to 2D lists (regular expression & graph number),
- // except for GRAPH_Y_SERIES (which is a 3D list).
- private static final String NUMBER_OF_GRAPHS = "numberOfGraphs"; //$NON-NLS-1$
- private static final String GRAPH_TITLE = "graphTitle"; //$NON-NLS-1$
- private static final String GRAPH_KEY = "graphKey"; //$NON-NLS-1$
- private static final String GRAPH_X_SERIES = "graphXSeries"; //$NON-NLS-1$
- private static final String GRAPH_ID = "graphID"; //$NON-NLS-1$
- private static final String GRAPH_Y_SERIES_LENGTH = "graphYSeriesLength"; //$NON-NLS-1$
- private static final String GRAPH_Y_SERIES = "graphYSeries"; //$NON-NLS-1$
- protected Pattern pattern;
- protected Matcher matcher;
-
- private Combo regularExpressionCombo;
- private Button removeRegexButton;
- private Button generateExpsButton;
-
- private Text sampleOutputText;
- private Composite textFieldsComposite;
-
- /**
- * This value controls whether or not the ModifyListeners associated with
- * the Texts will perform when dispatched. Sometimes the listeners should
- * be disabled to prevent needless/unsafe operations.
- */
- private boolean textListenersEnabled = true;
-
- private ScrolledComposite regexTextScrolledComposite;
- private Group outputParsingGroup;
- private Button runWithChartCheckButton;
-
- private Table graphsTable;
- private Button addGraphButton, duplicateGraphButton, editGraphButton, removeGraphButton;
- private TableItem selectedTableItem;
- private Group graphsGroup;
- private int numberOfVisibleColumns = 0;
- private boolean graphingEnabled = true;
-
- /**
- * A list of error messages, each entry corresponding to an entered regular expression.
- */
- private List<String> regexErrorMessages = new ArrayList<>();
-
- /**
- * The index of the selected regular expression.
- */
- private int selectedRegex = -1;
-
- /**
- * A list containing the user-defined sample outputs associated with the regex of every index.
- */
- private List<String> outputList = new ArrayList<>();
-
- /**
- * A name is given to each group captured by a regular expression. This stack contains
- * the names of all of a regex's groups that have been deleted, so each name may be
- * restored (without having to retype it) when a group is added again.
- */
- private Stack<String> cachedNames;
-
- /**
- * A list of cachedNames stacks, containing one entry for each regular expression stored.
- */
- private List<Stack<String>> cachedNamesList = new ArrayList<>();
-
- /**
- * A two-dimensional list that holds references to the names given to each regular expression's captured groups.
- */
- private List<ArrayList<String>> columnNamesList = new ArrayList<>();
-
- /**
- * A list holding the data of every graph for the selected regular expression.
- */
- private List<GraphData> graphsData = new LinkedList<>();
-
- /**
- * A list of graphsData lists. This is needed because each regular expression has its own set of graphs.
- */
- private List<LinkedList<GraphData>> graphsDataList = new ArrayList<>();
-
- /**
- * A list of GraphDatas that rely on series information that has been deleted from their relying regex.
- */
- private List<GraphData> badGraphs = new LinkedList<>();
-
- private ModifyListener regexListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent event) {
- if (!textListenersEnabled || regularExpressionCombo.getSelectionIndex() != -1) {
- return;
- }
- regularExpressionCombo.setItem(selectedRegex, regularExpressionCombo.getText());
- regularExpressionCombo.select(selectedRegex);
- refreshRegexRows();
- updateLaunchConfigurationDialog();
- }
- };
-
- private ModifyListener sampleOutputListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent event) {
- if (!textListenersEnabled) {
- return;
- }
- outputList.set(selectedRegex, sampleOutputText.getText());
- refreshRegexRows();
- updateLaunchConfigurationDialog();
- }
- };
-
- private ModifyListener columnNameListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent event) {
- if (!textListenersEnabled) {
- return;
- }
-
- ArrayList<String> columnNames = new ArrayList<>();
- Control[] children = textFieldsComposite.getChildren();
- for (int i = 0; i < numberOfVisibleColumns; i++) {
- columnNames.add(((Text)children[i*4 + 2]).getText());
- }
- columnNamesList.set(selectedRegex, columnNames);
- updateLaunchConfigurationDialog();
- }
- };
-
- private SelectionAdapter regexGenerator = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- MessageDialog dialog;
- IWorkbench workbench = PlatformUI.getWorkbench();
- IPath scriptPath = null;
- for (ILaunchConfigurationTab tab : getLaunchConfigurationDialog().getTabs()) {
- if (tab instanceof SystemTapScriptLaunchConfigurationTab) {
- scriptPath = ((SystemTapScriptLaunchConfigurationTab) tab).getScriptPath();
- break;
- }
- }
- if (scriptPath == null) {
- dialog = new MessageDialog(workbench
- .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsErrorTitle, null,
- Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsError,
- MessageDialog.ERROR, new String[]{"OK"}, 0); //$NON-NLS-1$
- dialog.open();
- return;
- }
-
- dialog = new MessageDialog(workbench
- .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsTitle, null,
- Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsMessage,
- MessageDialog.QUESTION, new String[]{"Yes", "Cancel"}, 0); //$NON-NLS-1$ //$NON-NLS-2$
- int result = dialog.open();
- if (result != 0) { // Cancel
- return;
- }
-
- textListenersEnabled = false;
- // If editor of this file is open, take current file contents.
- String contents = null;
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IEditorPart editor = ResourceUtil.findEditor(workbench.getActiveWorkbenchWindow().getActivePage(), root.getFile(scriptPath.makeRelativeTo(root.getLocation())));
- if (editor != null) {
- ITextEditor tEditor = (ITextEditor) editor.getAdapter(ITextEditor.class);
- if (tEditor != null) {
- IDocumentProvider provider = tEditor.getDocumentProvider();
- IDocument document = provider.getDocument(tEditor.getEditorInput());
- contents = document.get();
- }
- }
-
- // If chosen file is not being edited or is outside of the workspace, use the saved contents of the file itself.
- if (contents == null) {
- File scriptFile = scriptPath.toFile();
- try (FileInputStream f = new FileInputStream(scriptFile)) {
- byte[] data = new byte[(int)scriptFile.length()];
- f.read(data);
- f.close();
- contents = new String(data, Charset.defaultCharset());
- } catch (IOException e1) {
- dialog = new MessageDialog(workbench
- .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsErrorTitle, null,
- Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsError,
- MessageDialog.ERROR, new String[]{"OK"}, 0); //$NON-NLS-1$
- dialog.open();
- return;
- }
- }
-
- // Delete comments from the file contents. Ignore comment markers between quotes.
- contents = CommentRemover.exec(contents);
-
- // Now actually search the contents for "printf(...)" statements. (^|[\s({;])printf\("(.+?)",.+\)
- Pattern pattern = Pattern.compile("(?<=[^\\w])printf\\(\"(.+?)\",.+?\\)"); //$NON-NLS-1$
- Matcher matcher = pattern.matcher(contents);
- boolean firstfound = false;
- while (matcher.find() && (!firstfound || getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS)) {
- String regex = null;
-
- // Note: allow optional "long" modifier 'l'. Not captured because it doesn't impact output format.
- // Also, don't support variable width/precision modifiers (*).
- // TODO: Consider %m & %M support.
- Pattern format = Pattern.compile("%([-\\+ \\#0])?(\\d+)?(\\.\\d*)?l?([bcdiopsuxX%])"); //$NON-NLS-1$
-
- // Only capture until newlines to preserve the "column" format.
- // Don't try gluing together output from multiple printfs
- // since asynchronous prints would make things messy.
- String[] printls = matcher.group(1).split("\\\\n"); //$NON-NLS-1$
- for (int i = 0; i < printls.length; i++) {
- String printl = printls[i];
- // Ignore newlines if they are escaped ("\\n").
- if (printl.endsWith("\\")) { //$NON-NLS-1$
- printls[i+1] = printl.concat("\\n" + printls[i+1]); //$NON-NLS-1$
- continue;
- }
-
- Matcher fmatch = format.matcher(printl);
- int lastend = 0;
- ArrayList<String> columnNames = new ArrayList<>();
- int r = 0;
-
- while (fmatch.find()) {
- char chr = fmatch.group(4) == null ? '\0' : fmatch.group(4).charAt(0);
- if (chr == '\0') {
- // Skip this statement if an invalid regex is found.
- regex = null;
- break;
- }
- char flag = fmatch.group(1) == null ? '\0' : fmatch.group(1).charAt(0);
- int width = fmatch.group(2) == null ? 0 : Integer.parseInt(fmatch.group(2));
- String precision = fmatch.group(3) == null ? null : fmatch.group(3).substring(1);
-
- // First, add any non-capturing characters.
- String pre = addRegexEscapes(printl.substring(lastend, fmatch.start()));
- regex = lastend > 0 ? regex.concat(pre) : pre;
- lastend = fmatch.end();
-
- // Now add what will be captured.
- String target = "("; //$NON-NLS-1$
- if (chr == 'u' || (flag != '#' && chr == 'o')) {
- target = target.concat("\\d+"); //$NON-NLS-1$
- }
- else if (chr == 'd' || chr == 'i') {
- if (flag == '+') {
- target = target.concat("\\+|"); //$NON-NLS-1$
- } else if (flag == ' ') {
- target = target.concat(" |"); //$NON-NLS-1$
- }
- target = target.concat("-?\\d+"); //$NON-NLS-1$
- }
- else if (flag == '#' && chr == 'o') {
- target = target.concat("0\\d+"); //$NON-NLS-1$
- }
- else if (chr == 'p') {
- target = target.concat("0x[a-f0-9]+"); //$NON-NLS-1$
- }
- else if (chr == 'x') {
- if (flag == '#') {
- target = target.concat("0x"); //$NON-NLS-1$
- }
- target = target.concat("[a-f0-9]+"); //$NON-NLS-1$
- }
- else if (chr == 'X') {
- if (flag == '#') {
- target = target.concat("0X"); //$NON-NLS-1$
- }
- target = target.concat("[A-F0-9]+"); //$NON-NLS-1$
- }
- else if (chr == 'b') {
- target = target.concat("."); //$NON-NLS-1$
- }
- else if (chr == 'c') {
- if (flag != '#') {
- target = target.concat("."); //$NON-NLS-1$
- } else {
- target = target.concat("\\([a-z]|[0-9]{3})|.|\\\\"); //$NON-NLS-1$
- }
- }
- else if (chr == 's') {
- if (precision != null) {
- target = target.concat(".{" + precision + "}"); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- target = target.concat(".+"); //$NON-NLS-1$
- }
- }
- else {
- // Invalid or unhandled format specifier. Skip this regex.
- regex = null;
- break;
- }
-
- target = target.concat(")"); //$NON-NLS-1$
-
- // Handle the optional width specifier.
- // Ignore it for %b, which uses the width value in a different way.
- if (chr != 'b' && --width > 0) {
- if (flag == '-') {
- target = target.concat(" {0," + width + "}"); //$NON-NLS-1$ //$NON-NLS-2$
- } else if (flag != '0' || chr == 's' || chr == 'c') {
- target = " {0," + width + "}".concat(target); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- regex = regex.concat(target);
- columnNames.add(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase, ++r));
- }
- if (regex != null) {
- if (!firstfound) {
- // Since script output has been found, reset the configuration's regexs.
- // Only reset once/if something is found, and do it only one time.
- regularExpressionCombo.removeAll();
- outputList.clear();
- regexErrorMessages.clear();
- columnNamesList.clear();
- cachedNamesList.clear();
- graphsTable.removeAll();
- graphsDataList.clear();
- badGraphs.clear();
- firstfound = true;
- }
- // Finally, add the uncaptured remainder of the print statement to the regex.
- regex = regex.concat(addRegexEscapes(printl.substring(lastend)));
-
- regularExpressionCombo.add(regex);
- outputList.add(""); //$NON-NLS-1$ //For empty "sample output" entry.
- regexErrorMessages.add(null);
- columnNamesList.add(columnNames);
- cachedNamesList.add(new Stack<String>());
- graphsDataList.add(new LinkedList<GraphData>());
- }
- }
- }
- textListenersEnabled = true;
-
- if (!firstfound) {
- dialog = new MessageDialog(workbench
- .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsErrorTitle, null,
- Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsEmpty,
- MessageDialog.ERROR, new String[]{"OK"}, 0); //$NON-NLS-1$
- dialog.open();
- return;
- }
-
- if (getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
- regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
- }
-
- removeRegexButton.setEnabled(getNumberOfRegexs() > 1);
- regularExpressionCombo.select(0);
- updateRegexSelection(0, true);
- checkAllOtherErrors(); // Check for errors in case there was a problem with regex generation
- updateLaunchConfigurationDialog();
- }
-
- /**
- * This escapes all special regex characters in a string. Escapes must be added
- * to the generated regexs to capture printf output that doesn't
- * come from format specifiers (aka literal strings).
- * @param s The string to add escapes to.
- * @return The same string, after it has been modified with escapes.
- */
- private String addRegexEscapes(String s) {
- String schars = "[^$.|?*+(){}"; //$NON-NLS-1$
- for (int i = 0; i < schars.length(); i++) {
- s = s.replaceAll("(\\" + schars.substring(i,i+1) + ")", "\\\\$1"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return s;
- }
- };
-
- /**
- * Returns the list of the names given to reach regular expression.
- * @param configuration
- * @return
- */
- public static List<String> createDatasetNames(ILaunchConfiguration configuration) {
- try {
- int numberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
- ArrayList<String> names = new ArrayList<>(numberOfRegexs);
- for (int r = 0; r < numberOfRegexs; r++) {
- names.add(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, r + 1));
- }
- return names;
- } catch (CoreException e) {
- ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
- }
- return null;
- }
-
- /**
- * Creates a list of parsers, one for each regular expression created, that will be used
- * to parse the output of a running script.
- * @param configuration The desired run configuration.
- * @return A list of parsers.
- */
- public static List<IDataSetParser> createDatasetParsers(ILaunchConfiguration configuration) {
- try {
- int numberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
- ArrayList<IDataSetParser> parsers = new ArrayList<>(numberOfRegexs);
- for (int r = 0; r < numberOfRegexs; r++) {
- parsers.add(new LineParser("^" + configuration.getAttribute(REGULAR_EXPRESSION + r, "") + "$")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return parsers;
- } catch (CoreException e) {
- ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
- }
- return null;
- }
-
- /**
- * Creates a data set corresponding to the titles given to each output column
- * from each of a run configuration's regular expressions.
- * @param configuration
- * @return
- */
- public static List<IFilteredDataSet> createDataset(ILaunchConfiguration configuration) {
- try {
- int numberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
- ArrayList<IFilteredDataSet> datasets = new ArrayList<>(numberOfRegexs);
-
- for (int r = 0; r < numberOfRegexs; r++) {
- int numberOfColumns = configuration.getAttribute(NUMBER_OF_COLUMNS + r, 0);
- ArrayList<String> labels = new ArrayList<>(numberOfColumns);
-
- for (int c = 0; c < numberOfColumns; c++) {
- labels.add(configuration.getAttribute(get2DConfigData(REGEX_BOX, r, c), "")); //$NON-NLS-1$
- }
- datasets.add(DataSetFactory.createFilteredDataSet(RowDataSet.ID, labels.toArray(new String[] {})));
- }
-
- return datasets;
- } catch (CoreException e) {
- ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
- }
- return null;
- }
-
- /**
- * Creates graph data corresponding to the graphs that will plot a script's parsed output data.
- * @param configuration The desired run configuration.
- * @return A data set.
- */
- public static List<LinkedList<GraphData>> createGraphsFromConfiguration (ILaunchConfiguration configuration)
- throws CoreException {
- // Restrict number of regexs to at least one, so at least
- // one inner list will exist in the return value.
- int numberOfRegexs = Math.max(configuration.getAttribute(NUMBER_OF_REGEXS, 1), 1);
- ArrayList<LinkedList<GraphData>> graphsList = new ArrayList<>(numberOfRegexs);
-
- for (int r = 0; r < numberOfRegexs; r++) {
- int numberOfGraphs = configuration.getAttribute(NUMBER_OF_GRAPHS + r, 0);
- LinkedList<GraphData> graphs = new LinkedList<>();
- for (int i = 0; i < numberOfGraphs; i++) {
- GraphData graphData = new GraphData();
- graphData.title = configuration.getAttribute(get2DConfigData(GRAPH_TITLE, r, i), (String) null);
-
- graphData.key = configuration.getAttribute(get2DConfigData(GRAPH_KEY, r, i), (String) null);
- graphData.xSeries = configuration.getAttribute(get2DConfigData(GRAPH_X_SERIES, r, i), 0);
- graphData.graphID = configuration.getAttribute(get2DConfigData(GRAPH_ID, r, i), (String) null);
-
- int ySeriesLength = configuration.getAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, r, i), 0);
- if (ySeriesLength == 0) {
- graphData.ySeries = null;
- } else {
- int[] ySeries = new int[ySeriesLength];
- for (int j = 0; j < ySeriesLength; j++) {
- ySeries[j] = configuration.getAttribute(get2DConfigData(GRAPH_Y_SERIES, r, i + "_" + j), 0); //$NON-NLS-1$
- }
- graphData.ySeries = ySeries;
- }
-
- graphs.add(graphData);
- }
- graphsList.add(graphs);
- }
-
- return graphsList;
- }
-
- /**
- * Returns the key associated with the i'th data item of the r'th regular expression.
- * @param configDataName The type of data to access from the configuration.
- * @param r The index of the regular expression.
- * @param i The index of the data item to access.
- */
- private static String get2DConfigData(String configDataName, int r, int i) {
- return configDataName + r + "_" + i; //$NON-NLS-1$
- }
-
- /**
- * Returns the key associated with the data item of the r'th regular expression, tagged by string s.
- * @param configDataName The type of data to access from the configuration.
- * @param r The index of the regular expression.
- * @param s The string to put at the end of the key.
- */
- private static String get2DConfigData(String configDataName, int r, String s) {
- return configDataName + r + "_" + s; //$NON-NLS-1$
- }
-
- /**
- * Returns the total number of regular expressions of the current configuration.
- */
- private int getNumberOfRegexs() {
- return outputList.size();
- }
-
- @Override
- public void createControl(Composite parent) {
- GridLayout layout = new GridLayout();
- Composite top = new Composite(parent, SWT.NONE);
- setControl(top);
- top.setLayout(layout);
- top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- this.runWithChartCheckButton = new Button(top, SWT.CHECK);
- runWithChartCheckButton.setText(Messages.SystemTapScriptGraphOptionsTab_graphOutputRun);
- runWithChartCheckButton.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- setGraphingEnabled(runWithChartCheckButton.getSelection());
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- setGraphingEnabled(runWithChartCheckButton.getSelection());
- }
- });
-
- runWithChartCheckButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_graphOutput);
-
- this.outputParsingGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
- outputParsingGroup.setText(Messages.SystemTapScriptGraphOptionsTab_outputLabel);
- outputParsingGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- this.createColumnSelector(outputParsingGroup);
-
- this.graphsGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
- // Set the text here just to allow proper sizing.
- graphsGroup.setText(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, 1));
- graphsGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- createGraphCreateArea(graphsGroup);
-
- setGraphingEnabled(false);
- runWithChartCheckButton.setSelection(false);
- }
-
- private void createColumnSelector(Composite parent) {
-
- GridLayout layout = new GridLayout();
- parent.setLayout(layout);
-
- Composite topLayout = new Composite(parent, SWT.NONE);
- topLayout.setLayout(new GridLayout(1, false));
- topLayout.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
-
- generateExpsButton = new Button(topLayout, SWT.PUSH);
- generateExpsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- generateExpsButton.setText(Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsButton);
- generateExpsButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsTooltip);
- generateExpsButton.addSelectionListener(regexGenerator);
-
- Composite regexButtonLayout = new Composite(parent, SWT.NONE);
- regexButtonLayout.setLayout(new GridLayout(3, false));
- regexButtonLayout.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-
- Label selectedRegexLabel = new Label(regexButtonLayout, SWT.NONE);
- selectedRegexLabel.setText(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
- selectedRegexLabel.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_regexTooltip);
- regularExpressionCombo = new Combo(regexButtonLayout, SWT.DROP_DOWN);
- regularExpressionCombo.setTextLimit(MAX_REGEX_LENGTH);
- regularExpressionCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- regularExpressionCombo.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int selected = regularExpressionCombo.getSelectionIndex();
- if (selected == selectedRegex) {
- return;
- }
-
- // If deselecting an empty regular expression, delete it automatically.
- if (regularExpressionCombo.getItem(selectedRegex).isEmpty()
- && graphsDataList.get(selectedRegex).size() == 0
- && outputList.get(selectedRegex).isEmpty()) {
-
- // If the deselected regex is the last one in the combo, just quit.
- // Otherwise, the deleted blank entry would be replaced by another blank entry.
- if (selected == regularExpressionCombo.getItemCount() - 1) {
- regularExpressionCombo.select(selectedRegex); // To keep the text blank.
- return;
- }
- removeRegex(false);
- if (selected > selectedRegex) {
- selected--;
- }
- }
-
- // When selecting the "Add New Regex" item in the combo (which is always the last item),
- // update all appropriate values to make room for a new regular expression.
- if (selected == regularExpressionCombo.getItemCount() - 1 && getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
- outputList.add(""); //$NON-NLS-1$
- regexErrorMessages.add(null);
- columnNamesList.add(new ArrayList<String>());
- cachedNamesList.add(new Stack<String>());
- graphsDataList.add(new LinkedList<GraphData>());
-
- // Remove "Add New Regex" from the selected combo item; make it blank.
- regularExpressionCombo.setItem(selected, ""); //$NON-NLS-1$
- regularExpressionCombo.select(selected);
- updateRegexSelection(selected, false);
- updateLaunchConfigurationDialog();
-
- // Enable the "remove" button if only one item was present before.
- // (Don't do this _every_ time something is added.)
- if (getNumberOfRegexs() == 2) {
- removeRegexButton.setEnabled(true);
- }
- if (getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
- regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
- }
- } else {
- updateRegexSelection(selected, false);
- }
- }
- });
- regularExpressionCombo.addModifyListener(regexListener);
-
- removeRegexButton = new Button(regexButtonLayout, SWT.PUSH);
- removeRegexButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
- removeRegexButton.setText(Messages.SystemTapScriptGraphOptionsTab_regexRemove);
- removeRegexButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- IWorkbench workbench = PlatformUI.getWorkbench();
- MessageDialog dialog = new MessageDialog(workbench
- .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_removeRegexTitle, null,
- MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_removeRegexAsk,
- regularExpressionCombo.getItem(selectedRegex)),
- MessageDialog.QUESTION, new String[]{"Yes", "No"}, 0); //$NON-NLS-1$ //$NON-NLS-2$
- int result = dialog.open();
- if (result == 0) { //Yes
- removeRegex(true);
- }
- }
- });
-
- GridLayout twoColumns = new GridLayout(2, false);
-
- Composite regexSummaryComposite = new Composite(parent, SWT.NONE);
- regexSummaryComposite.setLayout(twoColumns);
- regexSummaryComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- Label sampleOutputLabel = new Label(regexSummaryComposite, SWT.NONE);
- sampleOutputLabel.setText(Messages.SystemTapScriptGraphOptionsTab_sampleOutputLabel);
- sampleOutputLabel.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_sampleOutputTooltip);
- this.sampleOutputText = new Text(regexSummaryComposite, SWT.BORDER);
- this.sampleOutputText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- this.sampleOutputText.addModifyListener(sampleOutputListener);
- sampleOutputText.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_sampleOutputTooltip);
-
-
- Composite expressionTableLabels = new Composite(parent, SWT.NONE);
- expressionTableLabels.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
- expressionTableLabels.setLayout(twoColumns);
-
- Label label = new Label(expressionTableLabels, SWT.NONE);
- label.setText(Messages.SystemTapScriptGraphOptionsTab_columnTitle);
- label.setAlignment(SWT.LEFT);
-
- Label label2 = new Label(expressionTableLabels, SWT.NONE);
- label2.setAlignment(SWT.LEFT);
- label2.setText(Messages.SystemTapScriptGraphOptionsTab_extractedValueLabel);
-
- this.regexTextScrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.BORDER);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, false);
- data.heightHint = 200;
- regexTextScrolledComposite.setLayoutData(data);
-
- textFieldsComposite = new Composite(regexTextScrolledComposite, SWT.NONE);
- textFieldsComposite.setLayout(new GridLayout(4, false));
- regexTextScrolledComposite.setContent(textFieldsComposite);
- regexTextScrolledComposite.setExpandHorizontal(true);
-
- // To position the column labels properly, add a dummy column and use its children's sizes for reference.
- // This is necessary since expressionTableLabels can't share a layout with textFieldsComposite.
- textListenersEnabled = false;
- addColumn(""); //$NON-NLS-1$
- data = new GridData(SWT.FILL, SWT.FILL, false, false);
- data.horizontalIndent = textFieldsComposite.getChildren()[2].getLocation().x;
- data.widthHint = textFieldsComposite.getChildren()[2].getSize().x;
- label.setLayoutData(data);
- label2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
- removeColumn(false);
- textListenersEnabled = true;
- }
-
- private IDataSet getCurrentDataset() {
- return DataSetFactory.createDataSet(RowDataSet.ID, columnNamesList.get(selectedRegex).toArray(new String[] {}));
- }
-
- private void createGraphCreateArea(Composite comp) {
- comp.setLayout(new GridLayout(2, false));
-
- graphsTable = new Table(comp, SWT.SINGLE | SWT.BORDER);
- GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
- graphsTable.setLayoutData(layoutData);
-
- // Button to add another graph
- Composite buttonComposite = new Composite(comp, SWT.NONE);
- buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
-
- GridLayout gridLayout = new GridLayout();
- gridLayout.numColumns = 1;
-
- buttonComposite.setLayout(gridLayout);
- // Button to add a new graph
- addGraphButton = new Button(buttonComposite, SWT.PUSH);
- addGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton);
- addGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_AddGraphButtonToolTip);
- addGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-
- // Button to copy an existing graph
- duplicateGraphButton = new Button(buttonComposite, SWT.PUSH);
- duplicateGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_DuplicateGraphButton);
- duplicateGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_DuplicateGraphButtonToolTip);
- duplicateGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-
- // Button to edit an existing graph
- editGraphButton = new Button(buttonComposite, SWT.PUSH);
- editGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_EditGraphButton);
- editGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_EditGraphButtonToolTip);
- editGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-
- // Button to remove the selected graph/filter
- removeGraphButton = new Button(buttonComposite, SWT.PUSH);
- removeGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_RemoveGraphButton);
- removeGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_RemoveGraphButtonToolTip);
- removeGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-
- // Action to notify the buttons when to enable/disable themselves based
- // on list selection
- graphsTable.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- selectedTableItem = (TableItem) e.item;
- setSelectionControlsEnabled(true);
- }
- });
-
- // Brings up a new dialog box when user clicks the add button. Allows
- // selecting a new graph to display.
- addGraphButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- SelectGraphAndSeriesWizard wizard = new SelectGraphAndSeriesWizard(getCurrentDataset(), null);
- IWorkbench workbench = PlatformUI.getWorkbench();
- wizard.init(workbench, null);
- WizardDialog dialog = new WizardDialog(workbench
- .getActiveWorkbenchWindow().getShell(), wizard);
- dialog.create();
- dialog.open();
-
- GraphData gd = wizard.getGraphData();
-
- if (null != gd) {
- TableItem item = new TableItem(graphsTable, SWT.NONE);
- graphsData.add(gd);
- setUpGraphTableItem(item, gd, false);
- updateLaunchConfigurationDialog();
- }
- }
- });
-
- // Adds a new entry to the list of graphs that is a copy of the one selected.
- duplicateGraphButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- GraphData gd = ((GraphData) selectedTableItem.getData()).getCopy();
-
- TableItem item = new TableItem(graphsTable, SWT.NONE);
- graphsData.add(gd);
- if (badGraphs.contains(selectedTableItem.getData())) {
- badGraphs.add(gd);
- setUpGraphTableItem(item, gd, true);
- } else {
- setUpGraphTableItem(item, gd, false);
- }
- updateLaunchConfigurationDialog();
- }
- });
-
- // When button is clicked, brings up same wizard as the one for adding
- // a graph. Data in the wizard is filled out to match the properties
- // of the selected graph.
- editGraphButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- SelectGraphAndSeriesWizard wizard = new SelectGraphAndSeriesWizard(getCurrentDataset(),
- (GraphData) selectedTableItem.getData());
- IWorkbench workbench = PlatformUI.getWorkbench();
- wizard.init(workbench, null);
- WizardDialog dialog = new WizardDialog(workbench
- .getActiveWorkbenchWindow().getShell(), wizard);
- dialog.create();
- dialog.open();
-
- GraphData gd = wizard.getGraphData();
- if (null == gd) {
- return;
- }
- GraphData old_gd = (GraphData) selectedTableItem.getData();
- if (!gd.equals(old_gd)) {
- badGraphs.remove(old_gd);
- setUpGraphTableItem(selectedTableItem, gd, false);
- graphsData.set(graphsTable.indexOf(selectedTableItem), gd);
- checkErrors(selectedRegex);
- updateLaunchConfigurationDialog();
- }
- }
- });
-
- // Removes the selected graph/filter from the table
- removeGraphButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- GraphData gd = (GraphData) selectedTableItem.getData();
- graphsData.remove(gd);
- badGraphs.remove(gd);
- selectedTableItem.dispose();
- setSelectionControlsEnabled(false);
- checkErrors(selectedRegex);
- updateLaunchConfigurationDialog();
- }
- });
- }
-
- private void removeRegex(boolean autoSelect) {
- int removedRegex = selectedRegex;
- if (autoSelect) {
- // The current selection is to be removed, so select something else that will be available.
- regularExpressionCombo.select(selectedRegex != 0 ? selectedRegex - 1 : 1);
- updateRegexSelection(regularExpressionCombo.getSelectionIndex(), false);
- }
-
- regularExpressionCombo.remove(removedRegex);
- outputList.remove(removedRegex);
- regexErrorMessages.remove(removedRegex);
- columnNamesList.remove(removedRegex);
- cachedNamesList.remove(removedRegex);
- graphsDataList.remove(removedRegex);
-
- if (autoSelect) {
- // Make sure the index of the selection is accurate.
- selectedRegex = regularExpressionCombo.getSelectionIndex();
- }
-
- // Re-add the "Add New Regex" entry if it is missing.
- if (getNumberOfRegexs() == MAX_NUMBER_OF_REGEXS - 1) {
- regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
- }
-
- // Disable the "remove" button if only one selection is left; never want zero items.
- if (getNumberOfRegexs() == 1) {
- removeRegexButton.setEnabled(false);
- }
- updateLaunchConfigurationDialog();
- }
-
- /**
- * This handles UI & list updating whenever a different regular expression is selected.
- * @param newSelection The index of the regex to be selected.
- * @param force If true, the UI will update even if the index of the selected regex did not change.
- */
- private void updateRegexSelection(int newSelection, boolean force) {
- // Quit if the selection didn't change anything, or if the selection is invalid (-1).
- if (newSelection == -1 || (!force && selectedRegex == newSelection)) {
- return;
- }
- selectedRegex = newSelection;
-
- boolean textListenersDisabled = !textListenersEnabled;
- if (!textListenersDisabled) {
- textListenersEnabled = false;
- }
-
- sampleOutputText.setText(outputList.get(selectedRegex));
- cachedNames = cachedNamesList.get(selectedRegex);
-
- // Update the number of columns and their titles here, and not in refreshRegexRows,
- // using the list of saved active names instead of a cachedNames stack.
- ArrayList<String> columnNames = columnNamesList.get(selectedRegex);
- int desiredNumberOfColumns = columnNames.size();
- // Remove all columns to easily update them all immediately afterwards.
- while (numberOfVisibleColumns > 0) {
- removeColumn(false);
- }
- while (numberOfVisibleColumns < desiredNumberOfColumns) {
- addColumn(columnNames.get(numberOfVisibleColumns));
- }
-
- refreshRegexRows();
-
- // Now, only display graphs that are associated with the selected regex.
- graphsData = graphsDataList.get(selectedRegex);
- graphsTable.removeAll();
- selectedTableItem = null;
- setSelectionControlsEnabled(false);
-
- for (GraphData gd : graphsData) {
- TableItem item = new TableItem(graphsTable, SWT.NONE);
- setUpGraphTableItem(item, gd, badGraphs.contains(gd));
- }
- graphsGroup.setText(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase,
- selectedRegex + 1));
-
- if (!textListenersDisabled) {
- textListenersEnabled = true;
- }
- }
-
- private void refreshRegexRows() {
- try {
- pattern = Pattern.compile(regularExpressionCombo.getText());
- matcher = pattern.matcher(sampleOutputText.getText());
- regexErrorMessages.set(selectedRegex, null);
- } catch (PatternSyntaxException e) {
- regexErrorMessages.set(selectedRegex, e.getMessage());
- return;
- }
- regexErrorMessages.set(selectedRegex, checkRegex(regularExpressionCombo.getText()));
- if (regexErrorMessages.get(selectedRegex) != null) {
- return;
- }
-
- int desiredNumberOfColumns = matcher.groupCount();
-
- while (numberOfVisibleColumns < desiredNumberOfColumns) {
- addColumn(null);
- }
-
- while (numberOfVisibleColumns > desiredNumberOfColumns) {
- removeColumn(true);
- }
-
- // Set values
- Control[] children = textFieldsComposite.getChildren();
- for (int i = 0; i < numberOfVisibleColumns; i++) {
- String sampleOutputResults;
- if (matcher.matches()) {
- sampleOutputResults = matcher.group(i+1);
- }
- else if (sampleOutputText.getText().length() == 0) {
- sampleOutputResults = Messages.SystemTapScriptGraphOptionsTab_sampleOutputIsEmpty;
- } else {
- sampleOutputResults = Messages.SystemTapScriptGraphOptionsTab_sampleOutputNoMatch;
- }
- ((Label)children[i*4+3]).setText(" " + sampleOutputResults); //$NON-NLS-1$
- }
-
- // May only add/edit graphs if there is output data being captured.
- addGraphButton.setEnabled(numberOfVisibleColumns > 0);
- if (selectedTableItem != null) {
- editGraphButton.setEnabled(numberOfVisibleColumns > 0);
- }
-
- regexErrorMessages.set(selectedRegex, findBadGraphs(selectedRegex));
- }
-
- /**
- * Checks if a provided regular expression is valid.
- * @param regex The regular expression to check for validity.
- * @return <code>null</code> if the regular expression is valid, or an error message.
- */
- private static String checkRegex(String regex) {
- //TODO may add more invalid regexs here, each with its own error message.
- if (regex.contains("()")) { //$NON-NLS-1$
- return Messages.SystemTapScriptGraphOptionsTab_emptyGroup;
- }
- return null;
- }
-
- /**
- * Adds one column to the list of the currently-selected regex's columns.
- * This creates an extra Text in which the name of the column may be entered,
- * and a corresponding Label containing sample expected output.
- * @param nameToAdd If non-null, the name of the newly-created column will
- * match this String. If null, the column will be given a name recovered from
- * the active stack of cached names, or a default name if one doesn't exist.
- */
- private void addColumn(String nameToAdd) {
- // Show the "shift" buttons of the previous column, if it exists.
- if (this.numberOfVisibleColumns > 0) {
- textFieldsComposite.getChildren()[(this.numberOfVisibleColumns - 1) * 4].setVisible(true);
- textFieldsComposite.getChildren()[(this.numberOfVisibleColumns - 1) * 4 + 1].setVisible(true);
- }
-
- // Add buttons for shifting column names up/down in the list.
- Button buttonUp = new Button(textFieldsComposite, SWT.PUSH);
- buttonUp.setText(Messages.SystemTapScriptGraphOptionsTab_columnShiftUp);
- buttonUp.setVisible(false);
- Button buttonDown = new Button(textFieldsComposite, SWT.PUSH);
- buttonDown.setText(Messages.SystemTapScriptGraphOptionsTab_columnShiftDown);
- buttonDown.setVisible(false);
-
- Text text = new Text(textFieldsComposite, SWT.BORDER);
- GridData data = new GridData(SWT.FILL, SWT.FILL, false, false);
- data.minimumWidth = 200;
- data.widthHint = 200;
- text.setLayoutData(data);
-
- numberOfVisibleColumns++;
- text.addModifyListener(columnNameListener);
- if (nameToAdd == null) {
- // Restore a deleted name by popping from the stack.
- if (cachedNames.size() > 0) {
- text.setText(cachedNames.pop());
- } else {
- text.setText(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase,
- numberOfVisibleColumns));
- }
- } else {
- text.setText(nameToAdd);
- }
-
- Label label = new Label(textFieldsComposite, SWT.BORDER);
- label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-
- textFieldsComposite.layout();
- textFieldsComposite.pack();
-
- // Special value: if an empty string is given, don't add button listeners.
- if (nameToAdd == "") { //$NON-NLS-1$
- return;
- }
-
- // Add button listeners for shifting column names.
- buttonUp.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- Control clickedButton = (Control) e.widget;
- Control[] children = textFieldsComposite.getChildren();
- int currentColumn = 0;
- for (; currentColumn < numberOfVisibleColumns - 1; currentColumn++) {
- if (children[currentColumn*4].equals(clickedButton)) {
- break;
- }
- }
- String edgeName = ((Text)children[currentColumn*4 + 2]).getText();
- for (int i = currentColumn; i < numberOfVisibleColumns - 1; i++) {
- ((Text)children[i*4 + 2]).setText(((Text)children[(i + 1)*4 + 2]).getText());
- }
- ((Text)children[(numberOfVisibleColumns - 1)*4 + 2]).setText(edgeName);
- }
- });
-
- buttonDown.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- Control clickedButton = (Control) e.widget;
- Control[] children = textFieldsComposite.getChildren();
- int currentColumn = 0;
- for (; currentColumn < numberOfVisibleColumns - 1; currentColumn++) {
- if (children[currentColumn*4 + 1].equals(clickedButton)) {
- break;
- }
- }
- String edgeName = ((Text)children[(numberOfVisibleColumns - 1)*4 + 2]).getText();
- for (int i = numberOfVisibleColumns - 1; i > currentColumn; i--) {
- ((Text)children[i*4 + 2]).setText(((Text)children[(i - 1)*4 + 2]).getText());
- }
- ((Text)children[currentColumn*4 + 2]).setText(edgeName);
- }
- });
- }
-
- /**
- * Removes a column from the currently-selected regex, and removes its
- * corresponding Text & Label from the UI.
- * @param saveNames Set to <code>true</code> if the contents of removed
- * columns are to be saved in a stack for later use.
- */
- private void removeColumn(Boolean saveNames) {
- Control[] children = textFieldsComposite.getChildren();
- int i = this.numberOfVisibleColumns*4 - 1;
-
- if (saveNames) {
- // Push the removed name on a stack.
- String name = ((Text)children[i-1]).getText();
- if (name != null && name != "") { //$NON-NLS-1$
- cachedNames.push(name);
- }
- columnNamesList.get(selectedRegex).remove(numberOfVisibleColumns - 1);
- }
-
- children[i].dispose();
- children[i-1].dispose();
- children[i-2].dispose();
- children[i-3].dispose();
-
- // Hide the previous column's "shift" buttons, if it exists.
- if (this.numberOfVisibleColumns > 2) {
- children[i - 6].setVisible(false);
- children[i - 7].setVisible(false);
- }
-
- this.numberOfVisibleColumns--;
-
- textFieldsComposite.layout();
- textFieldsComposite.pack();
- }
-
- /**
- * Marks all graphs belonging to the indicated regular expression that have an
- * error (missing column data, invalid graphID), or unmarks graphs that don't.
- * @param regex The index of the regular expression to check for invalid graphs.
- * @return An appropriate error message if an invalid graph is found, or if the
- * selected regular expression parses nothing.
- */
- private String findBadGraphs(int regex) {
- boolean foundBadID = false;
- boolean foundRemoved = false;
- int numberOfColumns = columnNamesList.get(regex).size();
-
- for (GraphData gd : graphsDataList.get(regex)) {
- boolean singleBadID = false;
- boolean singleRemoved = false;
-
- if (GraphFactory.getGraphName(gd.graphID) == null) {
- singleBadID = true;
- } else {
- if (gd.xSeries >= numberOfColumns) {
- singleRemoved = true;
- }
- for (int s = 0; s < gd.ySeries.length && !singleRemoved; s++) {
- if (gd.ySeries[s] >= numberOfColumns) {
- singleRemoved = true;
- }
- }
- }
- if (singleRemoved || singleBadID) {
- if (!badGraphs.contains(gd)) {
- badGraphs.add(gd);
- setUpGraphTableItem(findGraphTableItem(gd), null, true);
- }
- } else if (badGraphs.contains(gd)) {
- badGraphs.remove(gd);
- setUpGraphTableItem(findGraphTableItem(gd), null, false);
- }
-
- foundBadID |= singleBadID;
- foundRemoved |= singleRemoved;
- }
-
- if (numberOfColumns == 0) {
- return Messages.SystemTapScriptGraphOptionsTab_noGroups;
- }
- if (foundBadID) {
- return Messages.SystemTapScriptGraphOptionsTab_badGraphID;
- }
- if (foundRemoved) {
- return Messages.SystemTapScriptGraphOptionsTab_deletedGraphData;
- }
- return null;
- }
-
- private TableItem findGraphTableItem(GraphData gd) {
- for (TableItem item : graphsTable.getItems()) {
- if (item.getData().equals(gd)) {
- return item;
- }
- }
- return null;
- }
-
- /**
- * Sets up a given {@link TableItem} with the proper title & appearance based on
- * its graph data & (in)valid status.
- * @param item The {@link TableItem} to set up.
- * @param gd The {@link GraphData} that the item will hold. Set to <code>null</code>
- * to preserve the item's existing data.
- * @param bad <code>true</code> if the item should appear as invalid, <code>false</code> otherwise.
- */
- private void setUpGraphTableItem(TableItem item, GraphData gd, boolean bad) {
- // Include a null check to avoid accidentally marking non-visible items.
- if (item == null) {
- return;
- }
- if (gd != null) {
- item.setData(gd);
- } else {
- gd = (GraphData) item.getData();
- }
- item.setForeground(item.getDisplay().getSystemColor(bad ? SWT.COLOR_RED : SWT.COLOR_BLACK));
- String graphName = GraphFactory.getGraphName(gd.graphID);
- if (graphName == null) {
- graphName = Messages.SystemTapScriptGraphOptionsTab_invalidGraphID;
- }
- item.setText(graphName + ":" + gd.title //$NON-NLS-1$
- + (bad ? " " + Messages.SystemTapScriptGraphOptionsTab_invalidGraph : "")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(RUN_WITH_CHART, false);
- configuration.setAttribute(NUMBER_OF_REGEXS, 1);
- configuration.setAttribute(NUMBER_OF_COLUMNS + 0, 0);
- configuration.setAttribute(NUMBER_OF_EXTRAS + 0, 0);
- configuration.setAttribute(REGULAR_EXPRESSION + 0, ""); //$NON-NLS-1$
- configuration.setAttribute(SAMPLE_OUTPUT + 0, ""); //$NON-NLS-1$
- configuration.setAttribute(NUMBER_OF_GRAPHS + 0, 0);
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration configuration) {
- try {
- textListenersEnabled = false;
-
- // Reset lists & settings to keep things idempotent.
- regularExpressionCombo.removeAll();
- outputList.clear();
- regexErrorMessages.clear();
- columnNamesList.clear();
- cachedNamesList.clear();
- graphsTable.removeAll();
- badGraphs.clear();
-
- // There should always be at least one regular expression (a blank one still counts).
- // If configuration's number of regexs is zero, it is outdated.
- int numberOfRegexs = Math.max(configuration.getAttribute(NUMBER_OF_REGEXS, 1), 1);
-
- // Only allow removing regexs if there are more than one.
- removeRegexButton.setEnabled(numberOfRegexs > 1);
-
- for (int r = 0; r < numberOfRegexs; r++) {
- // Save all of the configuration's regular expressions & sample outputs in a list.
- regularExpressionCombo.add(configuration.getAttribute(REGULAR_EXPRESSION + r, "")); //$NON-NLS-1$
- outputList.add(configuration.getAttribute(SAMPLE_OUTPUT + r, "")); //$NON-NLS-1$
-
- // Save each regex's list of group names.
- int numberOfColumns = configuration.getAttribute(NUMBER_OF_COLUMNS + r, 0);
- ArrayList<String> namelist = new ArrayList<>(numberOfColumns);
- for (int i = 0; i < numberOfColumns; i++) {
- namelist.add(configuration.getAttribute(get2DConfigData(REGEX_BOX, r, i), (String)null));
- }
- columnNamesList.add(namelist);
-
- //Reclaim missing column data that was required for existing graphs at the time of the previous "apply".
- int numberOfExtras = configuration.getAttribute(NUMBER_OF_EXTRAS + r, 0);
- Stack<String> oldnames = new Stack<>();
- for (int i = 0; i < numberOfExtras; i++) {
- oldnames.push(configuration.getAttribute(get2DConfigData(EXTRA_BOX, r, i), (String)null));
- }
- cachedNamesList.add(oldnames);
-
- regexErrorMessages.add(null);
- }
- if (getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
- regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
- }
-
- // When possible, preserve the selection on subsequent initializations, for user convenience.
- int defaultSelectedRegex = 0 <= selectedRegex && selectedRegex < numberOfRegexs ? selectedRegex : 0;
- regularExpressionCombo.select(defaultSelectedRegex);
-
- // Add graphs
- graphsDataList = createGraphsFromConfiguration(configuration);
- graphsData = graphsDataList.get(defaultSelectedRegex);
- for (GraphData graphData : graphsData) {
- TableItem item = new TableItem(graphsTable, SWT.NONE);
- setUpGraphTableItem(item, graphData, true);
- }
-
- updateRegexSelection(defaultSelectedRegex, true); // Handles all remaining updates.
- checkAllOtherErrors();
-
- boolean chart = configuration.getAttribute(RUN_WITH_CHART, false);
- setGraphingEnabled(chart);
- this.runWithChartCheckButton.setSelection(chart);
-
- } catch (CoreException e) {
- ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
- } finally {
- textListenersEnabled = true;
- }
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(RUN_WITH_CHART, this.runWithChartCheckButton.getSelection());
-
- int numberOfRegexs = getNumberOfRegexs();
- for (int r = 0; r < numberOfRegexs; r++) {
- // Save data sets, and clear removed ones.
- configuration.setAttribute(REGULAR_EXPRESSION + r, regularExpressionCombo.getItem(r));
- configuration.setAttribute(SAMPLE_OUTPUT + r, outputList.get(r));
-
- ArrayList<String> columnNames = columnNamesList.get(r);
- int numberOfColumns = columnNames.size();
- for (int i = 0; i < numberOfColumns; i++) {
- configuration.setAttribute(get2DConfigData(REGEX_BOX, r, i), columnNames.get(i));
- }
- cleanUpConfigurationItem(configuration, NUMBER_OF_COLUMNS, REGEX_BOX, r, numberOfColumns);
- configuration.setAttribute(NUMBER_OF_COLUMNS + r, numberOfColumns);
-
- // If the current regex has graphs with missing data, store all cached names
- // in the configuration so that they will be easily restorable for next time.
- Stack<String> extranames = cachedNamesList.get(r);
- int numberOfExtras = findBadGraphs(r) == null ? 0 : extranames.size();
- for (int i = 0; i < numberOfExtras; i++) {
- configuration.setAttribute(get2DConfigData(EXTRA_BOX, r, i), extranames.get(i));
- }
- cleanUpConfigurationItem(configuration, NUMBER_OF_EXTRAS, EXTRA_BOX, r, numberOfExtras);
- configuration.setAttribute(NUMBER_OF_EXTRAS + r, numberOfExtras);
-
- // Save new graphs, and clear removed ones.
- LinkedList<GraphData> list = graphsDataList.get(r);
- int numberOfGraphs = list.size();
- for (int i = 0; i < numberOfGraphs; i++) {
- GraphData graphData = list.get(i);
- configuration.setAttribute(get2DConfigData(GRAPH_TITLE, r, i), graphData.title);
- configuration.setAttribute(get2DConfigData(GRAPH_KEY, r, i), graphData.key);
- configuration.setAttribute(get2DConfigData(GRAPH_X_SERIES, r, i), graphData.xSeries);
- configuration.setAttribute(get2DConfigData(GRAPH_ID, r, i), graphData.graphID);
-
- int ySeriesLength = graphData.ySeries.length;
- for (int j = 0; j < ySeriesLength; j++) {
- configuration.setAttribute(get2DConfigData(GRAPH_Y_SERIES, r, i + "_" + j), //$NON-NLS-1$
- graphData.ySeries[j]);
- }
- cleanUpConfigurationGraphYSeries(configuration, r, i, ySeriesLength);
- configuration.setAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, r, i), ySeriesLength);
- }
- cleanUpConfigurationGraphs(configuration, r, numberOfGraphs);
- configuration.setAttribute(NUMBER_OF_GRAPHS + r, numberOfGraphs);
- }
- cleanUpConfiguration(configuration, numberOfRegexs);
- configuration.setAttribute(NUMBER_OF_REGEXS, numberOfRegexs);
- }
-
- /**
- * Removes all configuration attributes associated with deleted regular expressions.
- * @param configuration The configuration to remove attributes from.
- * @param numberOfRegexs The number of regex-related properties to exist in the
- * configuration after cleanup.
- */
- private void cleanUpConfiguration(ILaunchConfigurationWorkingCopy configuration, int numberOfRegexs) {
- int oldNumberOfRegexs = 0;
- try {
- oldNumberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
- } catch (CoreException e) {}
- for (int r = numberOfRegexs; r < oldNumberOfRegexs; r++) {
- configuration.removeAttribute(REGULAR_EXPRESSION + r);
- configuration.removeAttribute(SAMPLE_OUTPUT + r);
-
- cleanUpConfigurationItem(configuration, NUMBER_OF_COLUMNS, REGEX_BOX, r, 0);
- configuration.removeAttribute(NUMBER_OF_COLUMNS + r);
-
- cleanUpConfigurationItem(configuration, NUMBER_OF_COLUMNS, EXTRA_BOX, r, 0);
- configuration.removeAttribute(NUMBER_OF_EXTRAS + r);
-
- cleanUpConfigurationGraphs(configuration, r, 0);
- configuration.removeAttribute(NUMBER_OF_GRAPHS + r);
- }
- }
-
- private void cleanUpConfigurationGraphs(ILaunchConfigurationWorkingCopy configuration, int regex, int newNumberOfGraphs) {
- int oldNumberOfGraphs = 0;
- try {
- oldNumberOfGraphs = configuration.getAttribute(NUMBER_OF_GRAPHS + regex, 0);
- } catch (CoreException e) {}
- for (int i = newNumberOfGraphs; i < oldNumberOfGraphs; i++) {
- configuration.removeAttribute(get2DConfigData(GRAPH_TITLE, regex, i));
- configuration.removeAttribute(get2DConfigData(GRAPH_KEY, regex, i));
- configuration.removeAttribute(get2DConfigData(GRAPH_X_SERIES, regex, i));
- configuration.removeAttribute(get2DConfigData(GRAPH_ID, regex, i));
-
- cleanUpConfigurationGraphYSeries(configuration, regex, i, 0);
- configuration.removeAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, regex, i));
- }
- }
-
- private void cleanUpConfigurationItem(ILaunchConfigurationWorkingCopy configuration, String counter, String property, int regex, int newNumberOfItems) {
- int oldNumberOfItems = 0;
- try {
- oldNumberOfItems = configuration.getAttribute(counter + regex, 0);
- } catch (CoreException e) {}
- for (int i = newNumberOfItems; i < oldNumberOfItems; i++) {
- configuration.removeAttribute(get2DConfigData(property, regex, i));
- }
- }
-
- private void cleanUpConfigurationGraphYSeries(ILaunchConfigurationWorkingCopy configuration, int regex, int graph, int newLength) {
- int oldYSeriesLength = 0;
- try {
- oldYSeriesLength = configuration.getAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, regex, graph), 0);
- } catch (CoreException e) {}
- for (int i = newLength; i < oldYSeriesLength; i++) {
- configuration.removeAttribute(get2DConfigData(GRAPH_Y_SERIES, regex, graph + "_" + i)); //$NON-NLS-1$
- }
- }
-
- /**
- * Checks all regular expressions for errors, except for the currently-selected
- * expression (as it should be checked by {@link #refreshRegexRows}).
- */
- private void checkAllOtherErrors() {
- for (int i = 0, n = getNumberOfRegexs(); i < n; i++) {
- if (i == selectedRegex) {
- continue;
- }
- checkErrors(i);
- }
- }
-
- /**
- * Checks the regular expression of the provided index for errors.
- * Sets the associated error message to contain relevant error information.
- * @param i The index of the regular expression to check for errors.
- */
- private void checkErrors(int i) {
- String regex = regularExpressionCombo.getItem(i);
- try {
- Pattern.compile(regex);
- } catch (PatternSyntaxException e) {
- regexErrorMessages.set(i, e.getMessage());
- return;
- }
-
- String error = findBadGraphs(i);
- if (error == null) {
- error = checkRegex(regex);
- }
-
- regexErrorMessages.set(i, error);
- }
-
- @Override
- public boolean isValid(ILaunchConfiguration launchConfig) {
- setErrorMessage(null);
-
- // If graphic is disabled then everything is valid.
- if (!this.graphingEnabled) {
- return true;
- }
-
- for (int r = 0, n = getNumberOfRegexs(); r < n; r++) {
- String regexErrorMessage = regexErrorMessages.get(r);
- if (regexErrorMessage != null) {
- setErrorMessage(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_regexErrorMsgFormat,
- regularExpressionCombo.getItems()[r], regexErrorMessage));
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * Checks if a launch configuration's Systemtap Graphing settings are valid.
- * @param launchConfig The launch configuration to check for graph validity.
- * @return <code>true</code> if the launch settings are valid, or <code>false</code> if
- * its graph settings are invalid in some way.
- * @since 2.2
- */
- public static boolean isValidLaunch(ILaunchConfiguration launchConfig) throws CoreException {
- // If graphic is disabled then everything is valid.
- if (!launchConfig.getAttribute(RUN_WITH_CHART, false)) {
- return true;
- }
-
- for (int r = 0, n = launchConfig.getAttribute(NUMBER_OF_REGEXS, 1); r < n; r++) {
- // Check for any invalid regexs.
- String regex = launchConfig.getAttribute(REGULAR_EXPRESSION + r, (String) null);
- if (regex == null || checkRegex(regex) != null) {
- return false;
- }
- try {
- Pattern.compile(regex);
- } catch (PatternSyntaxException e) {
- return false;
- }
-
- // If graphs are plotted but no data is captured by one of them, report this as a problem.
- int numberOfColumns = launchConfig.getAttribute(NUMBER_OF_COLUMNS + r, 0);
- if (numberOfColumns == 0) {
- return false;
- }
-
- // Check for graphs that are missing required data.
- for (int i = 0, g = launchConfig.getAttribute(NUMBER_OF_GRAPHS + r, 0); i < g; i++) {
- if (GraphFactory.getGraphName(launchConfig.getAttribute(get2DConfigData(GRAPH_ID, r, i), (String) null)) == null) {
- return false;
- }
- if (launchConfig.getAttribute(get2DConfigData(GRAPH_X_SERIES, r, i), 0) >= numberOfColumns) {
- return false;
- }
- for (int j = 0, y = launchConfig.getAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, r, i), 0); j < y; j++) {
- if (launchConfig.getAttribute(get2DConfigData(GRAPH_Y_SERIES, r, i + "_" + j), 0) >= numberOfColumns) { //$NON-NLS-1$
- return false;
- }
- }
- }
- }
-
- return true;
- }
-
- @Override
- public String getName() {
- return Messages.SystemTapScriptGraphOptionsTab_graphingTitle;
- }
-
- @Override
- public Image getImage() {
- return AbstractUIPlugin.imageDescriptorFromPlugin(IDEPlugin.PLUGIN_ID,
- "icons/graphing_tab.gif").createImage(); //$NON-NLS-1$
- }
-
- private void setGraphingEnabled(boolean enabled) {
- this.graphingEnabled = enabled;
- this.setControlEnabled(outputParsingGroup, enabled);
- this.setControlEnabled(graphsGroup, enabled);
- // Disable buttons that rely on a selected graph if no graph is selected.
- this.setSelectionControlsEnabled(selectedTableItem != null);
- this.addGraphButton.setEnabled(enabled && numberOfVisibleColumns > 0);
- this.removeRegexButton.setEnabled(enabled && getNumberOfRegexs() > 1);
- updateLaunchConfigurationDialog();
- }
-
- private void setControlEnabled(Composite composite, boolean enabled) {
- composite.setEnabled(enabled);
- for (Control child : composite.getChildren()) {
- child.setEnabled(enabled);
- if (child instanceof Composite) {
- setControlEnabled((Composite)child, enabled);
- }
- }
- }
-
- /**
- * Call this to enable/disable all buttons whose actions depend on a selected graph.
- * @param enabled Set to true to enable the buttons; set to false to disable them.
- */
- private void setSelectionControlsEnabled(boolean enabled) {
- duplicateGraphButton.setEnabled(enabled);
- editGraphButton.setEnabled(enabled && numberOfVisibleColumns > 0);
- removeGraphButton.setEnabled(enabled);
- }
+ AbstractLaunchConfigurationTab {
+
+ /**
+ * The maximum number of regular expressions that can be stored in a configuration.
+ */
+ static final int MAX_NUMBER_OF_REGEXS = 20;
+
+ /**
+ * The maximum length of an output-parsing regular expression.
+ */
+ static final int MAX_REGEX_LENGTH = 200;
+
+ // Note: any non-private String key with a trailing underscore is to be appended with an integer when looking up values.
+ static final String RUN_WITH_CHART = "runWithChart"; //$NON-NLS-1$
+ static final String NUMBER_OF_REGEXS = "numberOfRegexs"; //$NON-NLS-1$
+ static final String NUMBER_OF_COLUMNS = "numberOfColumns_"; //$NON-NLS-1$
+ static final String REGEX_BOX = "regexBox_"; //$NON-NLS-1$
+ static final String NUMBER_OF_EXTRAS = "numberOfExtras_"; //$NON-NLS-1$
+ static final String EXTRA_BOX = "extraBox_"; //$NON-NLS-1$
+ static final String REGULAR_EXPRESSION = "regularExpression_"; //$NON-NLS-1$
+ static final String SAMPLE_OUTPUT = "sampleOutput_"; //$NON-NLS-1$
+
+ // Note: all graph-related keys point to 2D lists (regular expression & graph number),
+ // except for GRAPH_Y_SERIES (which is a 3D list).
+ private static final String NUMBER_OF_GRAPHS = "numberOfGraphs"; //$NON-NLS-1$
+ private static final String GRAPH_TITLE = "graphTitle"; //$NON-NLS-1$
+ private static final String GRAPH_KEY = "graphKey"; //$NON-NLS-1$
+ private static final String GRAPH_X_SERIES = "graphXSeries"; //$NON-NLS-1$
+ private static final String GRAPH_ID = "graphID"; //$NON-NLS-1$
+ private static final String GRAPH_Y_SERIES_LENGTH = "graphYSeriesLength"; //$NON-NLS-1$
+ private static final String GRAPH_Y_SERIES = "graphYSeries"; //$NON-NLS-1$
+ protected Pattern pattern;
+ protected Matcher matcher;
+
+ private Combo regularExpressionCombo;
+ private Button removeRegexButton;
+ private Button generateExpsButton;
+
+ private Text sampleOutputText;
+ private Composite textFieldsComposite;
+
+ /**
+ * This value controls whether or not the ModifyListeners associated with
+ * the Texts will perform when dispatched. Sometimes the listeners should
+ * be disabled to prevent needless/unsafe operations.
+ */
+ private boolean textListenersEnabled = true;
+
+ private ScrolledComposite regexTextScrolledComposite;
+ private Group outputParsingGroup;
+ private Button runWithChartCheckButton;
+
+ private Table graphsTable;
+ private Button addGraphButton, duplicateGraphButton, editGraphButton, removeGraphButton;
+ private TableItem selectedTableItem;
+ private Group graphsGroup;
+ private int numberOfVisibleColumns = 0;
+ private boolean graphingEnabled = true;
+
+ /**
+ * A list of error messages, each entry corresponding to an entered regular expression.
+ */
+ private List<String> regexErrorMessages = new ArrayList<>();
+
+ /**
+ * The index of the selected regular expression.
+ */
+ private int selectedRegex = -1;
+
+ /**
+ * A list containing the user-defined sample outputs associated with the regex of every index.
+ */
+ private List<String> outputList = new ArrayList<>();
+
+ /**
+ * A name is given to each group captured by a regular expression. This stack contains
+ * the names of all of a regex's groups that have been deleted, so each name may be
+ * restored (without having to retype it) when a group is added again.
+ */
+ private Stack<String> cachedNames;
+
+ /**
+ * A list of cachedNames stacks, containing one entry for each regular expression stored.
+ */
+ private List<Stack<String>> cachedNamesList = new ArrayList<>();
+
+ /**
+ * A two-dimensional list that holds references to the names given to each regular expression's captured groups.
+ */
+ private List<ArrayList<String>> columnNamesList = new ArrayList<>();
+
+ /**
+ * A list holding the data of every graph for the selected regular expression.
+ */
+ private List<GraphData> graphsData = new LinkedList<>();
+
+ /**
+ * A list of graphsData lists. This is needed because each regular expression has its own set of graphs.
+ */
+ private List<LinkedList<GraphData>> graphsDataList = new ArrayList<>();
+
+ /**
+ * A list of GraphDatas that rely on series information that has been deleted from their relying regex.
+ */
+ private List<GraphData> badGraphs = new LinkedList<>();
+
+ private ModifyListener regexListener = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent event) {
+ if (!textListenersEnabled || regularExpressionCombo.getSelectionIndex() != -1) {
+ return;
+ }
+ regularExpressionCombo.setItem(selectedRegex, regularExpressionCombo.getText());
+ regularExpressionCombo.select(selectedRegex);
+ refreshRegexRows();
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ private ModifyListener sampleOutputListener = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent event) {
+ if (!textListenersEnabled) {
+ return;
+ }
+ outputList.set(selectedRegex, sampleOutputText.getText());
+ refreshRegexRows();
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ private ModifyListener columnNameListener = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent event) {
+ if (!textListenersEnabled) {
+ return;
+ }
+
+ ArrayList<String> columnNames = new ArrayList<>();
+ Control[] children = textFieldsComposite.getChildren();
+ for (int i = 0; i < numberOfVisibleColumns; i++) {
+ columnNames.add(((Text)children[i*4 + 2]).getText());
+ }
+ columnNamesList.set(selectedRegex, columnNames);
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ private SelectionAdapter regexGenerator = new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ MessageDialog dialog;
+ IWorkbench workbench = PlatformUI.getWorkbench();
+ IPath scriptPath = null;
+ for (ILaunchConfigurationTab tab : getLaunchConfigurationDialog().getTabs()) {
+ if (tab instanceof SystemTapScriptLaunchConfigurationTab) {
+ scriptPath = ((SystemTapScriptLaunchConfigurationTab) tab).getScriptPath();
+ break;
+ }
+ }
+ if (scriptPath == null) {
+ dialog = new MessageDialog(workbench
+ .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsErrorTitle, null,
+ Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsError,
+ MessageDialog.ERROR, new String[]{"OK"}, 0); //$NON-NLS-1$
+ dialog.open();
+ return;
+ }
+
+ dialog = new MessageDialog(workbench
+ .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsTitle, null,
+ Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsMessage,
+ MessageDialog.QUESTION, new String[]{"Yes", "Cancel"}, 0); //$NON-NLS-1$ //$NON-NLS-2$
+ int result = dialog.open();
+ if (result != 0) { // Cancel
+ return;
+ }
+
+ textListenersEnabled = false;
+ // If editor of this file is open, take current file contents.
+ String contents = null;
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ IEditorPart editor = ResourceUtil.findEditor(workbench.getActiveWorkbenchWindow().getActivePage(), root.getFile(scriptPath.makeRelativeTo(root.getLocation())));
+ if (editor != null) {
+ ITextEditor tEditor = (ITextEditor) editor.getAdapter(ITextEditor.class);
+ if (tEditor != null) {
+ IDocumentProvider provider = tEditor.getDocumentProvider();
+ IDocument document = provider.getDocument(tEditor.getEditorInput());
+ contents = document.get();
+ }
+ }
+
+ // If chosen file is not being edited or is outside of the workspace, use the saved contents of the file itself.
+ if (contents == null) {
+ File scriptFile = scriptPath.toFile();
+ try (FileInputStream f = new FileInputStream(scriptFile)) {
+ byte[] data = new byte[(int)scriptFile.length()];
+ f.read(data);
+ f.close();
+ contents = new String(data, Charset.defaultCharset());
+ } catch (IOException e1) {
+ dialog = new MessageDialog(workbench
+ .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsErrorTitle, null,
+ Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsError,
+ MessageDialog.ERROR, new String[]{"OK"}, 0); //$NON-NLS-1$
+ dialog.open();
+ return;
+ }
+ }
+
+ // Delete comments from the file contents. Ignore comment markers between quotes.
+ contents = CommentRemover.exec(contents);
+
+ // Now actually search the contents for "printf(...)" statements. (^|[\s({;])printf\("(.+?)",.+\)
+ Pattern pattern = Pattern.compile("(?<=[^\\w])printf\\(\"(.+?)\",.+?\\)"); //$NON-NLS-1$
+ Matcher matcher = pattern.matcher(contents);
+ boolean firstfound = false;
+ while (matcher.find() && (!firstfound || getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS)) {
+ String regex = null;
+
+ // Note: allow optional "long" modifier 'l'. Not captured because it doesn't impact output format.
+ // Also, don't support variable width/precision modifiers (*).
+ // TODO: Consider %m & %M support.
+ Pattern format = Pattern.compile("%([-\\+ \\#0])?(\\d+)?(\\.\\d*)?l?([bcdiopsuxX%])"); //$NON-NLS-1$
+
+ // Only capture until newlines to preserve the "column" format.
+ // Don't try gluing together output from multiple printfs
+ // since asynchronous prints would make things messy.
+ String[] printls = matcher.group(1).split("\\\\n"); //$NON-NLS-1$
+ for (int i = 0; i < printls.length; i++) {
+ String printl = printls[i];
+ // Ignore newlines if they are escaped ("\\n").
+ if (printl.endsWith("\\")) { //$NON-NLS-1$
+ printls[i+1] = printl.concat("\\n" + printls[i+1]); //$NON-NLS-1$
+ continue;
+ }
+
+ Matcher fmatch = format.matcher(printl);
+ int lastend = 0;
+ ArrayList<String> columnNames = new ArrayList<>();
+ int r = 0;
+
+ while (fmatch.find()) {
+ char chr = fmatch.group(4) == null ? '\0' : fmatch.group(4).charAt(0);
+ if (chr == '\0') {
+ // Skip this statement if an invalid regex is found.
+ regex = null;
+ break;
+ }
+ char flag = fmatch.group(1) == null ? '\0' : fmatch.group(1).charAt(0);
+ int width = fmatch.group(2) == null ? 0 : Integer.parseInt(fmatch.group(2));
+ String precision = fmatch.group(3) == null ? null : fmatch.group(3).substring(1);
+
+ // First, add any non-capturing characters.
+ String pre = addRegexEscapes(printl.substring(lastend, fmatch.start()));
+ regex = lastend > 0 ? regex.concat(pre) : pre;
+ lastend = fmatch.end();
+
+ // Now add what will be captured.
+ String target = "("; //$NON-NLS-1$
+ if (chr == 'u' || (flag != '#' && chr == 'o')) {
+ target = target.concat("\\d+"); //$NON-NLS-1$
+ }
+ else if (chr == 'd' || chr == 'i') {
+ if (flag == '+') {
+ target = target.concat("\\+|"); //$NON-NLS-1$
+ } else if (flag == ' ') {
+ target = target.concat(" |"); //$NON-NLS-1$
+ }
+ target = target.concat("-?\\d+"); //$NON-NLS-1$
+ }
+ else if (flag == '#' && chr == 'o') {
+ target = target.concat("0\\d+"); //$NON-NLS-1$
+ }
+ else if (chr == 'p') {
+ target = target.concat("0x[a-f0-9]+"); //$NON-NLS-1$
+ }
+ else if (chr == 'x') {
+ if (flag == '#') {
+ target = target.concat("0x"); //$NON-NLS-1$
+ }
+ target = target.concat("[a-f0-9]+"); //$NON-NLS-1$
+ }
+ else if (chr == 'X') {
+ if (flag == '#') {
+ target = target.concat("0X"); //$NON-NLS-1$
+ }
+ target = target.concat("[A-F0-9]+"); //$NON-NLS-1$
+ }
+ else if (chr == 'b') {
+ target = target.concat("."); //$NON-NLS-1$
+ }
+ else if (chr == 'c') {
+ if (flag != '#') {
+ target = target.concat("."); //$NON-NLS-1$
+ } else {
+ target = target.concat("\\([a-z]|[0-9]{3})|.|\\\\"); //$NON-NLS-1$
+ }
+ }
+ else if (chr == 's') {
+ if (precision != null) {
+ target = target.concat(".{" + precision + "}"); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ target = target.concat(".+"); //$NON-NLS-1$
+ }
+ }
+ else {
+ // Invalid or unhandled format specifier. Skip this regex.
+ regex = null;
+ break;
+ }
+
+ target = target.concat(")"); //$NON-NLS-1$
+
+ // Handle the optional width specifier.
+ // Ignore it for %b, which uses the width value in a different way.
+ if (chr != 'b' && --width > 0) {
+ if (flag == '-') {
+ target = target.concat(" {0," + width + "}"); //$NON-NLS-1$ //$NON-NLS-2$
+ } else if (flag != '0' || chr == 's' || chr == 'c') {
+ target = " {0," + width + "}".concat(target); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ regex = regex.concat(target);
+ columnNames.add(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase, ++r));
+ }
+ if (regex != null) {
+ if (!firstfound) {
+ // Since script output has been found, reset the configuration's regexs.
+ // Only reset once/if something is found, and do it only one time.
+ regularExpressionCombo.removeAll();
+ outputList.clear();
+ regexErrorMessages.clear();
+ columnNamesList.clear();
+ cachedNamesList.clear();
+ graphsTable.removeAll();
+ graphsDataList.clear();
+ badGraphs.clear();
+ firstfound = true;
+ }
+ // Finally, add the uncaptured remainder of the print statement to the regex.
+ regex = regex.concat(addRegexEscapes(printl.substring(lastend)));
+
+ regularExpressionCombo.add(regex);
+ outputList.add(""); //$NON-NLS-1$ //For empty "sample output" entry.
+ regexErrorMessages.add(null);
+ columnNamesList.add(columnNames);
+ cachedNamesList.add(new Stack<String>());
+ graphsDataList.add(new LinkedList<GraphData>());
+ }
+ }
+ }
+ textListenersEnabled = true;
+
+ if (!firstfound) {
+ dialog = new MessageDialog(workbench
+ .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsErrorTitle, null,
+ Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsEmpty,
+ MessageDialog.ERROR, new String[]{"OK"}, 0); //$NON-NLS-1$
+ dialog.open();
+ return;
+ }
+
+ if (getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
+ regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
+ }
+
+ removeRegexButton.setEnabled(getNumberOfRegexs() > 1);
+ regularExpressionCombo.select(0);
+ updateRegexSelection(0, true);
+ checkAllOtherErrors(); // Check for errors in case there was a problem with regex generation
+ updateLaunchConfigurationDialog();
+ }
+
+ /**
+ * This escapes all special regex characters in a string. Escapes must be added
+ * to the generated regexs to capture printf output that doesn't
+ * come from format specifiers (aka literal strings).
+ * @param s The string to add escapes to.
+ * @return The same string, after it has been modified with escapes.
+ */
+ private String addRegexEscapes(String s) {
+ String schars = "[^$.|?*+(){}"; //$NON-NLS-1$
+ for (int i = 0; i < schars.length(); i++) {
+ s = s.replaceAll("(\\" + schars.substring(i,i+1) + ")", "\\\\$1"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ return s;
+ }
+ };
+
+ /**
+ * Returns the list of the names given to reach regular expression.
+ * @param configuration
+ * @return
+ */
+ public static List<String> createDatasetNames(ILaunchConfiguration configuration) {
+ try {
+ int numberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
+ ArrayList<String> names = new ArrayList<>(numberOfRegexs);
+ for (int r = 0; r < numberOfRegexs; r++) {
+ names.add(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, r + 1));
+ }
+ return names;
+ } catch (CoreException e) {
+ ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
+ }
+ return null;
+ }
+
+ /**
+ * Creates a list of parsers, one for each regular expression created, that will be used
+ * to parse the output of a running script.
+ * @param configuration The desired run configuration.
+ * @return A list of parsers.
+ */
+ public static List<IDataSetParser> createDatasetParsers(ILaunchConfiguration configuration) {
+ try {
+ int numberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
+ ArrayList<IDataSetParser> parsers = new ArrayList<>(numberOfRegexs);
+ for (int r = 0; r < numberOfRegexs; r++) {
+ parsers.add(new LineParser("^" + configuration.getAttribute(REGULAR_EXPRESSION + r, "") + "$")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ return parsers;
+ } catch (CoreException e) {
+ ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
+ }
+ return null;
+ }
+
+ /**
+ * Creates a data set corresponding to the titles given to each output column
+ * from each of a run configuration's regular expressions.
+ * @param configuration
+ * @return
+ */
+ public static List<IFilteredDataSet> createDataset(ILaunchConfiguration configuration) {
+ try {
+ int numberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
+ ArrayList<IFilteredDataSet> datasets = new ArrayList<>(numberOfRegexs);
+
+ for (int r = 0; r < numberOfRegexs; r++) {
+ int numberOfColumns = configuration.getAttribute(NUMBER_OF_COLUMNS + r, 0);
+ ArrayList<String> labels = new ArrayList<>(numberOfColumns);
+
+ for (int c = 0; c < numberOfColumns; c++) {
+ labels.add(configuration.getAttribute(get2DConfigData(REGEX_BOX, r, c), "")); //$NON-NLS-1$
+ }
+ datasets.add(DataSetFactory.createFilteredDataSet(RowDataSet.ID, labels.toArray(new String[] {})));
+ }
+
+ return datasets;
+ } catch (CoreException e) {
+ ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
+ }
+ return null;
+ }
+
+ /**
+ * Creates graph data corresponding to the graphs that will plot a script's parsed output data.
+ * @param configuration The desired run configuration.
+ * @return A data set.
+ */
+ public static List<LinkedList<GraphData>> createGraphsFromConfiguration (ILaunchConfiguration configuration)
+ throws CoreException {
+ // Restrict number of regexs to at least one, so at least
+ // one inner list will exist in the return value.
+ int numberOfRegexs = Math.max(configuration.getAttribute(NUMBER_OF_REGEXS, 1), 1);
+ ArrayList<LinkedList<GraphData>> graphsList = new ArrayList<>(numberOfRegexs);
+
+ for (int r = 0; r < numberOfRegexs; r++) {
+ int numberOfGraphs = configuration.getAttribute(NUMBER_OF_GRAPHS + r, 0);
+ LinkedList<GraphData> graphs = new LinkedList<>();
+ for (int i = 0; i < numberOfGraphs; i++) {
+ GraphData graphData = new GraphData();
+ graphData.title = configuration.getAttribute(get2DConfigData(GRAPH_TITLE, r, i), (String) null);
+
+ graphData.key = configuration.getAttribute(get2DConfigData(GRAPH_KEY, r, i), (String) null);
+ graphData.xSeries = configuration.getAttribute(get2DConfigData(GRAPH_X_SERIES, r, i), 0);
+ graphData.graphID = configuration.getAttribute(get2DConfigData(GRAPH_ID, r, i), (String) null);
+
+ int ySeriesLength = configuration.getAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, r, i), 0);
+ if (ySeriesLength == 0) {
+ graphData.ySeries = null;
+ } else {
+ int[] ySeries = new int[ySeriesLength];
+ for (int j = 0; j < ySeriesLength; j++) {
+ ySeries[j] = configuration.getAttribute(get2DConfigData(GRAPH_Y_SERIES, r, i + "_" + j), 0); //$NON-NLS-1$
+ }
+ graphData.ySeries = ySeries;
+ }
+
+ graphs.add(graphData);
+ }
+ graphsList.add(graphs);
+ }
+
+ return graphsList;
+ }
+
+ /**
+ * Returns the key associated with the i'th data item of the r'th regular expression.
+ * @param configDataName The type of data to access from the configuration.
+ * @param r The index of the regular expression.
+ * @param i The index of the data item to access.
+ */
+ private static String get2DConfigData(String configDataName, int r, int i) {
+ return configDataName + r + "_" + i; //$NON-NLS-1$
+ }
+
+ /**
+ * Returns the key associated with the data item of the r'th regular expression, tagged by string s.
+ * @param configDataName The type of data to access from the configuration.
+ * @param r The index of the regular expression.
+ * @param s The string to put at the end of the key.
+ */
+ private static String get2DConfigData(String configDataName, int r, String s) {
+ return configDataName + r + "_" + s; //$NON-NLS-1$
+ }
+
+ /**
+ * Returns the total number of regular expressions of the current configuration.
+ */
+ private int getNumberOfRegexs() {
+ return outputList.size();
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+ GridLayout layout = new GridLayout();
+ Composite top = new Composite(parent, SWT.NONE);
+ setControl(top);
+ top.setLayout(layout);
+ top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+
+ this.runWithChartCheckButton = new Button(top, SWT.CHECK);
+ runWithChartCheckButton.setText(Messages.SystemTapScriptGraphOptionsTab_graphOutputRun);
+ runWithChartCheckButton.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ setGraphingEnabled(runWithChartCheckButton.getSelection());
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ setGraphingEnabled(runWithChartCheckButton.getSelection());
+ }
+ });
+
+ runWithChartCheckButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_graphOutput);
+
+ this.outputParsingGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
+ outputParsingGroup.setText(Messages.SystemTapScriptGraphOptionsTab_outputLabel);
+ outputParsingGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+ this.createColumnSelector(outputParsingGroup);
+
+ this.graphsGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
+ // Set the text here just to allow proper sizing.
+ graphsGroup.setText(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase, 1));
+ graphsGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ createGraphCreateArea(graphsGroup);
+
+ setGraphingEnabled(false);
+ runWithChartCheckButton.setSelection(false);
+ }
+
+ private void createColumnSelector(Composite parent) {
+
+ GridLayout layout = new GridLayout();
+ parent.setLayout(layout);
+
+ Composite topLayout = new Composite(parent, SWT.NONE);
+ topLayout.setLayout(new GridLayout(1, false));
+ topLayout.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
+
+ generateExpsButton = new Button(topLayout, SWT.PUSH);
+ generateExpsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ generateExpsButton.setText(Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsButton);
+ generateExpsButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_generateFromPrintsTooltip);
+ generateExpsButton.addSelectionListener(regexGenerator);
+
+ Composite regexButtonLayout = new Composite(parent, SWT.NONE);
+ regexButtonLayout.setLayout(new GridLayout(3, false));
+ regexButtonLayout.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+
+ Label selectedRegexLabel = new Label(regexButtonLayout, SWT.NONE);
+ selectedRegexLabel.setText(Messages.SystemTapScriptGraphOptionsTab_regexLabel);
+ selectedRegexLabel.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_regexTooltip);
+ regularExpressionCombo = new Combo(regexButtonLayout, SWT.DROP_DOWN);
+ regularExpressionCombo.setTextLimit(MAX_REGEX_LENGTH);
+ regularExpressionCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+ regularExpressionCombo.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ int selected = regularExpressionCombo.getSelectionIndex();
+ if (selected == selectedRegex) {
+ return;
+ }
+
+ // If deselecting an empty regular expression, delete it automatically.
+ if (regularExpressionCombo.getItem(selectedRegex).isEmpty()
+ && graphsDataList.get(selectedRegex).size() == 0
+ && outputList.get(selectedRegex).isEmpty()) {
+
+ // If the deselected regex is the last one in the combo, just quit.
+ // Otherwise, the deleted blank entry would be replaced by another blank entry.
+ if (selected == regularExpressionCombo.getItemCount() - 1) {
+ regularExpressionCombo.select(selectedRegex); // To keep the text blank.
+ return;
+ }
+ removeRegex(false);
+ if (selected > selectedRegex) {
+ selected--;
+ }
+ }
+
+ // When selecting the "Add New Regex" item in the combo (which is always the last item),
+ // update all appropriate values to make room for a new regular expression.
+ if (selected == regularExpressionCombo.getItemCount() - 1 && getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
+ outputList.add(""); //$NON-NLS-1$
+ regexErrorMessages.add(null);
+ columnNamesList.add(new ArrayList<String>());
+ cachedNamesList.add(new Stack<String>());
+ graphsDataList.add(new LinkedList<GraphData>());
+
+ // Remove "Add New Regex" from the selected combo item; make it blank.
+ regularExpressionCombo.setItem(selected, ""); //$NON-NLS-1$
+ regularExpressionCombo.select(selected);
+ updateRegexSelection(selected, false);
+ updateLaunchConfigurationDialog();
+
+ // Enable the "remove" button if only one item was present before.
+ // (Don't do this _every_ time something is added.)
+ if (getNumberOfRegexs() == 2) {
+ removeRegexButton.setEnabled(true);
+ }
+ if (getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
+ regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
+ }
+ } else {
+ updateRegexSelection(selected, false);
+ }
+ }
+ });
+ regularExpressionCombo.addModifyListener(regexListener);
+
+ removeRegexButton = new Button(regexButtonLayout, SWT.PUSH);
+ removeRegexButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
+ removeRegexButton.setText(Messages.SystemTapScriptGraphOptionsTab_regexRemove);
+ removeRegexButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ IWorkbench workbench = PlatformUI.getWorkbench();
+ MessageDialog dialog = new MessageDialog(workbench
+ .getActiveWorkbenchWindow().getShell(), Messages.SystemTapScriptGraphOptionsTab_removeRegexTitle, null,
+ MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_removeRegexAsk,
+ regularExpressionCombo.getItem(selectedRegex)),
+ MessageDialog.QUESTION, new String[]{"Yes", "No"}, 0); //$NON-NLS-1$ //$NON-NLS-2$
+ int result = dialog.open();
+ if (result == 0) { //Yes
+ removeRegex(true);
+ }
+ }
+ });
+
+ GridLayout twoColumns = new GridLayout(2, false);
+
+ Composite regexSummaryComposite = new Composite(parent, SWT.NONE);
+ regexSummaryComposite.setLayout(twoColumns);
+ regexSummaryComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+
+ Label sampleOutputLabel = new Label(regexSummaryComposite, SWT.NONE);
+ sampleOutputLabel.setText(Messages.SystemTapScriptGraphOptionsTab_sampleOutputLabel);
+ sampleOutputLabel.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_sampleOutputTooltip);
+ this.sampleOutputText = new Text(regexSummaryComposite, SWT.BORDER);
+ this.sampleOutputText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ this.sampleOutputText.addModifyListener(sampleOutputListener);
+ sampleOutputText.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_sampleOutputTooltip);
+
+
+ Composite expressionTableLabels = new Composite(parent, SWT.NONE);
+ expressionTableLabels.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
+ expressionTableLabels.setLayout(twoColumns);
+
+ Label label = new Label(expressionTableLabels, SWT.NONE);
+ label.setText(Messages.SystemTapScriptGraphOptionsTab_columnTitle);
+ label.setAlignment(SWT.LEFT);
+
+ Label label2 = new Label(expressionTableLabels, SWT.NONE);
+ label2.setAlignment(SWT.LEFT);
+ label2.setText(Messages.SystemTapScriptGraphOptionsTab_extractedValueLabel);
+
+ this.regexTextScrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.BORDER);
+ GridData data = new GridData(SWT.FILL, SWT.FILL, true, false);
+ data.heightHint = 200;
+ regexTextScrolledComposite.setLayoutData(data);
+
+ textFieldsComposite = new Composite(regexTextScrolledComposite, SWT.NONE);
+ textFieldsComposite.setLayout(new GridLayout(4, false));
+ regexTextScrolledComposite.setContent(textFieldsComposite);
+ regexTextScrolledComposite.setExpandHorizontal(true);
+
+ // To position the column labels properly, add a dummy column and use its children's sizes for reference.
+ // This is necessary since expressionTableLabels can't share a layout with textFieldsComposite.
+ textListenersEnabled = false;
+ addColumn(""); //$NON-NLS-1$
+ data = new GridData(SWT.FILL, SWT.FILL, false, false);
+ data.horizontalIndent = textFieldsComposite.getChildren()[2].getLocation().x;
+ data.widthHint = textFieldsComposite.getChildren()[2].getSize().x;
+ label.setLayoutData(data);
+ label2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
+ removeColumn(false);
+ textListenersEnabled = true;
+ }
+
+ private IDataSet getCurrentDataset() {
+ return DataSetFactory.createDataSet(RowDataSet.ID, columnNamesList.get(selectedRegex).toArray(new String[] {}));
+ }
+
+ private void createGraphCreateArea(Composite comp) {
+ comp.setLayout(new GridLayout(2, false));
+
+ graphsTable = new Table(comp, SWT.SINGLE | SWT.BORDER);
+ GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
+ graphsTable.setLayoutData(layoutData);
+
+ // Button to add another graph
+ Composite buttonComposite = new Composite(comp, SWT.NONE);
+ buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
+
+ GridLayout gridLayout = new GridLayout();
+ gridLayout.numColumns = 1;
+
+ buttonComposite.setLayout(gridLayout);
+ // Button to add a new graph
+ addGraphButton = new Button(buttonComposite, SWT.PUSH);
+ addGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_AddGraphButton);
+ addGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_AddGraphButtonToolTip);
+ addGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+
+ // Button to copy an existing graph
+ duplicateGraphButton = new Button(buttonComposite, SWT.PUSH);
+ duplicateGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_DuplicateGraphButton);
+ duplicateGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_DuplicateGraphButtonToolTip);
+ duplicateGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+
+ // Button to edit an existing graph
+ editGraphButton = new Button(buttonComposite, SWT.PUSH);
+ editGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_EditGraphButton);
+ editGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_EditGraphButtonToolTip);
+ editGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+
+ // Button to remove the selected graph/filter
+ removeGraphButton = new Button(buttonComposite, SWT.PUSH);
+ removeGraphButton.setText(Messages.SystemTapScriptGraphOptionsTab_RemoveGraphButton);
+ removeGraphButton.setToolTipText(Messages.SystemTapScriptGraphOptionsTab_RemoveGraphButtonToolTip);
+ removeGraphButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+
+ // Action to notify the buttons when to enable/disable themselves based
+ // on list selection
+ graphsTable.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ selectedTableItem = (TableItem) e.item;
+ setSelectionControlsEnabled(true);
+ }
+ });
+
+ // Brings up a new dialog box when user clicks the add button. Allows
+ // selecting a new graph to display.
+ addGraphButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ SelectGraphAndSeriesWizard wizard = new SelectGraphAndSeriesWizard(getCurrentDataset(), null);
+ IWorkbench workbench = PlatformUI.getWorkbench();
+ wizard.init(workbench, null);
+ WizardDialog dialog = new WizardDialog(workbench
+ .getActiveWorkbenchWindow().getShell(), wizard);
+ dialog.create();
+ dialog.open();
+
+ GraphData gd = wizard.getGraphData();
+
+ if (null != gd) {
+ TableItem item = new TableItem(graphsTable, SWT.NONE);
+ graphsData.add(gd);
+ setUpGraphTableItem(item, gd, false);
+ updateLaunchConfigurationDialog();
+ }
+ }
+ });
+
+ // Adds a new entry to the list of graphs that is a copy of the one selected.
+ duplicateGraphButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ GraphData gd = ((GraphData) selectedTableItem.getData()).getCopy();
+
+ TableItem item = new TableItem(graphsTable, SWT.NONE);
+ graphsData.add(gd);
+ if (badGraphs.contains(selectedTableItem.getData())) {
+ badGraphs.add(gd);
+ setUpGraphTableItem(item, gd, true);
+ } else {
+ setUpGraphTableItem(item, gd, false);
+ }
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ // When button is clicked, brings up same wizard as the one for adding
+ // a graph. Data in the wizard is filled out to match the properties
+ // of the selected graph.
+ editGraphButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ SelectGraphAndSeriesWizard wizard = new SelectGraphAndSeriesWizard(getCurrentDataset(),
+ (GraphData) selectedTableItem.getData());
+ IWorkbench workbench = PlatformUI.getWorkbench();
+ wizard.init(workbench, null);
+ WizardDialog dialog = new WizardDialog(workbench
+ .getActiveWorkbenchWindow().getShell(), wizard);
+ dialog.create();
+ dialog.open();
+
+ GraphData gd = wizard.getGraphData();
+ if (null == gd) {
+ return;
+ }
+ GraphData old_gd = (GraphData) selectedTableItem.getData();
+ if (!gd.equals(old_gd)) {
+ badGraphs.remove(old_gd);
+ setUpGraphTableItem(selectedTableItem, gd, false);
+ graphsData.set(graphsTable.indexOf(selectedTableItem), gd);
+ checkErrors(selectedRegex);
+ updateLaunchConfigurationDialog();
+ }
+ }
+ });
+
+ // Removes the selected graph/filter from the table
+ removeGraphButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ GraphData gd = (GraphData) selectedTableItem.getData();
+ graphsData.remove(gd);
+ badGraphs.remove(gd);
+ selectedTableItem.dispose();
+ setSelectionControlsEnabled(false);
+ checkErrors(selectedRegex);
+ updateLaunchConfigurationDialog();
+ }
+ });
+ }
+
+ private void removeRegex(boolean autoSelect) {
+ int removedRegex = selectedRegex;
+ if (autoSelect) {
+ // The current selection is to be removed, so select something else that will be available.
+ regularExpressionCombo.select(selectedRegex != 0 ? selectedRegex - 1 : 1);
+ updateRegexSelection(regularExpressionCombo.getSelectionIndex(), false);
+ }
+
+ regularExpressionCombo.remove(removedRegex);
+ outputList.remove(removedRegex);
+ regexErrorMessages.remove(removedRegex);
+ columnNamesList.remove(removedRegex);
+ cachedNamesList.remove(removedRegex);
+ graphsDataList.remove(removedRegex);
+
+ if (autoSelect) {
+ // Make sure the index of the selection is accurate.
+ selectedRegex = regularExpressionCombo.getSelectionIndex();
+ }
+
+ // Re-add the "Add New Regex" entry if it is missing.
+ if (getNumberOfRegexs() == MAX_NUMBER_OF_REGEXS - 1) {
+ regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
+ }
+
+ // Disable the "remove" button if only one selection is left; never want zero items.
+ if (getNumberOfRegexs() == 1) {
+ removeRegexButton.setEnabled(false);
+ }
+ updateLaunchConfigurationDialog();
+ }
+
+ /**
+ * This handles UI & list updating whenever a different regular expression is selected.
+ * @param newSelection The index of the regex to be selected.
+ * @param force If true, the UI will update even if the index of the selected regex did not change.
+ */
+ private void updateRegexSelection(int newSelection, boolean force) {
+ // Quit if the selection didn't change anything, or if the selection is invalid (-1).
+ if (newSelection == -1 || (!force && selectedRegex == newSelection)) {
+ return;
+ }
+ selectedRegex = newSelection;
+
+ boolean textListenersDisabled = !textListenersEnabled;
+ if (!textListenersDisabled) {
+ textListenersEnabled = false;
+ }
+
+ sampleOutputText.setText(outputList.get(selectedRegex));
+ cachedNames = cachedNamesList.get(selectedRegex);
+
+ // Update the number of columns and their titles here, and not in refreshRegexRows,
+ // using the list of saved active names instead of a cachedNames stack.
+ ArrayList<String> columnNames = columnNamesList.get(selectedRegex);
+ int desiredNumberOfColumns = columnNames.size();
+ // Remove all columns to easily update them all immediately afterwards.
+ while (numberOfVisibleColumns > 0) {
+ removeColumn(false);
+ }
+ while (numberOfVisibleColumns < desiredNumberOfColumns) {
+ addColumn(columnNames.get(numberOfVisibleColumns));
+ }
+
+ refreshRegexRows();
+
+ // Now, only display graphs that are associated with the selected regex.
+ graphsData = graphsDataList.get(selectedRegex);
+ graphsTable.removeAll();
+ selectedTableItem = null;
+ setSelectionControlsEnabled(false);
+
+ for (GraphData gd : graphsData) {
+ TableItem item = new TableItem(graphsTable, SWT.NONE);
+ setUpGraphTableItem(item, gd, badGraphs.contains(gd));
+ }
+ graphsGroup.setText(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_graphSetTitleBase,
+ selectedRegex + 1));
+
+ if (!textListenersDisabled) {
+ textListenersEnabled = true;
+ }
+ }
+
+ private void refreshRegexRows() {
+ try {
+ pattern = Pattern.compile(regularExpressionCombo.getText());
+ matcher = pattern.matcher(sampleOutputText.getText());
+ regexErrorMessages.set(selectedRegex, null);
+ } catch (PatternSyntaxException e) {
+ regexErrorMessages.set(selectedRegex, e.getMessage());
+ return;
+ }
+ regexErrorMessages.set(selectedRegex, checkRegex(regularExpressionCombo.getText()));
+ if (regexErrorMessages.get(selectedRegex) != null) {
+ return;
+ }
+
+ int desiredNumberOfColumns = matcher.groupCount();
+
+ while (numberOfVisibleColumns < desiredNumberOfColumns) {
+ addColumn(null);
+ }
+
+ while (numberOfVisibleColumns > desiredNumberOfColumns) {
+ removeColumn(true);
+ }
+
+ // Set values
+ Control[] children = textFieldsComposite.getChildren();
+ for (int i = 0; i < numberOfVisibleColumns; i++) {
+ String sampleOutputResults;
+ if (matcher.matches()) {
+ sampleOutputResults = matcher.group(i+1);
+ }
+ else if (sampleOutputText.getText().length() == 0) {
+ sampleOutputResults = Messages.SystemTapScriptGraphOptionsTab_sampleOutputIsEmpty;
+ } else {
+ sampleOutputResults = Messages.SystemTapScriptGraphOptionsTab_sampleOutputNoMatch;
+ }
+ ((Label)children[i*4+3]).setText(" " + sampleOutputResults); //$NON-NLS-1$
+ }
+
+ // May only add/edit graphs if there is output data being captured.
+ addGraphButton.setEnabled(numberOfVisibleColumns > 0);
+ if (selectedTableItem != null) {
+ editGraphButton.setEnabled(numberOfVisibleColumns > 0);
+ }
+
+ regexErrorMessages.set(selectedRegex, findBadGraphs(selectedRegex));
+ }
+
+ /**
+ * Checks if a provided regular expression is valid.
+ * @param regex The regular expression to check for validity.
+ * @return <code>null</code> if the regular expression is valid, or an error message.
+ */
+ private static String checkRegex(String regex) {
+ //TODO may add more invalid regexs here, each with its own error message.
+ if (regex.contains("()")) { //$NON-NLS-1$
+ return Messages.SystemTapScriptGraphOptionsTab_emptyGroup;
+ }
+ return null;
+ }
+
+ /**
+ * Adds one column to the list of the currently-selected regex's columns.
+ * This creates an extra Text in which the name of the column may be entered,
+ * and a corresponding Label containing sample expected output.
+ * @param nameToAdd If non-null, the name of the newly-created column will
+ * match this String. If null, the column will be given a name recovered from
+ * the active stack of cached names, or a default name if one doesn't exist.
+ */
+ private void addColumn(String nameToAdd) {
+ // Show the "shift" buttons of the previous column, if it exists.
+ if (this.numberOfVisibleColumns > 0) {
+ textFieldsComposite.getChildren()[(this.numberOfVisibleColumns - 1) * 4].setVisible(true);
+ textFieldsComposite.getChildren()[(this.numberOfVisibleColumns - 1) * 4 + 1].setVisible(true);
+ }
+
+ // Add buttons for shifting column names up/down in the list.
+ Button buttonUp = new Button(textFieldsComposite, SWT.PUSH);
+ buttonUp.setText(Messages.SystemTapScriptGraphOptionsTab_columnShiftUp);
+ buttonUp.setVisible(false);
+ Button buttonDown = new Button(textFieldsComposite, SWT.PUSH);
+ buttonDown.setText(Messages.SystemTapScriptGraphOptionsTab_columnShiftDown);
+ buttonDown.setVisible(false);
+
+ Text text = new Text(textFieldsComposite, SWT.BORDER);
+ GridData data = new GridData(SWT.FILL, SWT.FILL, false, false);
+ data.minimumWidth = 200;
+ data.widthHint = 200;
+ text.setLayoutData(data);
+
+ numberOfVisibleColumns++;
+ text.addModifyListener(columnNameListener);
+ if (nameToAdd == null) {
+ // Restore a deleted name by popping from the stack.
+ if (cachedNames.size() > 0) {
+ text.setText(cachedNames.pop());
+ } else {
+ text.setText(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_defaultColumnTitleBase,
+ numberOfVisibleColumns));
+ }
+ } else {
+ text.setText(nameToAdd);
+ }
+
+ Label label = new Label(textFieldsComposite, SWT.BORDER);
+ label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+
+ textFieldsComposite.layout();
+ textFieldsComposite.pack();
+
+ // Special value: if an empty string is given, don't add button listeners.
+ if (nameToAdd == "") { //$NON-NLS-1$
+ return;
+ }
+
+ // Add button listeners for shifting column names.
+ buttonUp.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ Control clickedButton = (Control) e.widget;
+ Control[] children = textFieldsComposite.getChildren();
+ int currentColumn = 0;
+ for (; currentColumn < numberOfVisibleColumns - 1; currentColumn++) {
+ if (children[currentColumn*4].equals(clickedButton)) {
+ break;
+ }
+ }
+ String edgeName = ((Text)children[currentColumn*4 + 2]).getText();
+ for (int i = currentColumn; i < numberOfVisibleColumns - 1; i++) {
+ ((Text)children[i*4 + 2]).setText(((Text)children[(i + 1)*4 + 2]).getText());
+ }
+ ((Text)children[(numberOfVisibleColumns - 1)*4 + 2]).setText(edgeName);
+ }
+ });
+
+ buttonDown.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ Control clickedButton = (Control) e.widget;
+ Control[] children = textFieldsComposite.getChildren();
+ int currentColumn = 0;
+ for (; currentColumn < numberOfVisibleColumns - 1; currentColumn++) {
+ if (children[currentColumn*4 + 1].equals(clickedButton)) {
+ break;
+ }
+ }
+ String edgeName = ((Text)children[(numberOfVisibleColumns - 1)*4 + 2]).getText();
+ for (int i = numberOfVisibleColumns - 1; i > currentColumn; i--) {
+ ((Text)children[i*4 + 2]).setText(((Text)children[(i - 1)*4 + 2]).getText());
+ }
+ ((Text)children[currentColumn*4 + 2]).setText(edgeName);
+ }
+ });
+ }
+
+ /**
+ * Removes a column from the currently-selected regex, and removes its
+ * corresponding Text & Label from the UI.
+ * @param saveNames Set to <code>true</code> if the contents of removed
+ * columns are to be saved in a stack for later use.
+ */
+ private void removeColumn(Boolean saveNames) {
+ Control[] children = textFieldsComposite.getChildren();
+ int i = this.numberOfVisibleColumns*4 - 1;
+
+ if (saveNames) {
+ // Push the removed name on a stack.
+ String name = ((Text)children[i-1]).getText();
+ if (name != null && name != "") { //$NON-NLS-1$
+ cachedNames.push(name);
+ }
+ columnNamesList.get(selectedRegex).remove(numberOfVisibleColumns - 1);
+ }
+
+ children[i].dispose();
+ children[i-1].dispose();
+ children[i-2].dispose();
+ children[i-3].dispose();
+
+ // Hide the previous column's "shift" buttons, if it exists.
+ if (this.numberOfVisibleColumns > 2) {
+ children[i - 6].setVisible(false);
+ children[i - 7].setVisible(false);
+ }
+
+ this.numberOfVisibleColumns--;
+
+ textFieldsComposite.layout();
+ textFieldsComposite.pack();
+ }
+
+ /**
+ * Marks all graphs belonging to the indicated regular expression that have an
+ * error (missing column data, invalid graphID), or unmarks graphs that don't.
+ * @param regex The index of the regular expression to check for invalid graphs.
+ * @return An appropriate error message if an invalid graph is found, or if the
+ * selected regular expression parses nothing.
+ */
+ private String findBadGraphs(int regex) {
+ boolean foundBadID = false;
+ boolean foundRemoved = false;
+ int numberOfColumns = columnNamesList.get(regex).size();
+
+ for (GraphData gd : graphsDataList.get(regex)) {
+ boolean singleBadID = false;
+ boolean singleRemoved = false;
+
+ if (GraphFactory.getGraphName(gd.graphID) == null) {
+ singleBadID = true;
+ } else {
+ if (gd.xSeries >= numberOfColumns) {
+ singleRemoved = true;
+ }
+ for (int s = 0; s < gd.ySeries.length && !singleRemoved; s++) {
+ if (gd.ySeries[s] >= numberOfColumns) {
+ singleRemoved = true;
+ }
+ }
+ }
+ if (singleRemoved || singleBadID) {
+ if (!badGraphs.contains(gd)) {
+ badGraphs.add(gd);
+ setUpGraphTableItem(findGraphTableItem(gd), null, true);
+ }
+ } else if (badGraphs.contains(gd)) {
+ badGraphs.remove(gd);
+ setUpGraphTableItem(findGraphTableItem(gd), null, false);
+ }
+
+ foundBadID |= singleBadID;
+ foundRemoved |= singleRemoved;
+ }
+
+ if (numberOfColumns == 0) {
+ return Messages.SystemTapScriptGraphOptionsTab_noGroups;
+ }
+ if (foundBadID) {
+ return Messages.SystemTapScriptGraphOptionsTab_badGraphID;
+ }
+ if (foundRemoved) {
+ return Messages.SystemTapScriptGraphOptionsTab_deletedGraphData;
+ }
+ return null;
+ }
+
+ private TableItem findGraphTableItem(GraphData gd) {
+ for (TableItem item : graphsTable.getItems()) {
+ if (item.getData().equals(gd)) {
+ return item;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Sets up a given {@link TableItem} with the proper title & appearance based on
+ * its graph data & (in)valid status.
+ * @param item The {@link TableItem} to set up.
+ * @param gd The {@link GraphData} that the item will hold. Set to <code>null</code>
+ * to preserve the item's existing data.
+ * @param bad <code>true</code> if the item should appear as invalid, <code>false</code> otherwise.
+ */
+ private void setUpGraphTableItem(TableItem item, GraphData gd, boolean bad) {
+ // Include a null check to avoid accidentally marking non-visible items.
+ if (item == null) {
+ return;
+ }
+ if (gd != null) {
+ item.setData(gd);
+ } else {
+ gd = (GraphData) item.getData();
+ }
+ item.setForeground(item.getDisplay().getSystemColor(bad ? SWT.COLOR_RED : SWT.COLOR_BLACK));
+ String graphName = GraphFactory.getGraphName(gd.graphID);
+ if (graphName == null) {
+ graphName = Messages.SystemTapScriptGraphOptionsTab_invalidGraphID;
+ }
+ item.setText(graphName + ":" + gd.title //$NON-NLS-1$
+ + (bad ? " " + Messages.SystemTapScriptGraphOptionsTab_invalidGraph : "")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(RUN_WITH_CHART, false);
+ configuration.setAttribute(NUMBER_OF_REGEXS, 1);
+ configuration.setAttribute(NUMBER_OF_COLUMNS + 0, 0);
+ configuration.setAttribute(NUMBER_OF_EXTRAS + 0, 0);
+ configuration.setAttribute(REGULAR_EXPRESSION + 0, ""); //$NON-NLS-1$
+ configuration.setAttribute(SAMPLE_OUTPUT + 0, ""); //$NON-NLS-1$
+ configuration.setAttribute(NUMBER_OF_GRAPHS + 0, 0);
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration configuration) {
+ try {
+ textListenersEnabled = false;
+
+ // Reset lists & settings to keep things idempotent.
+ regularExpressionCombo.removeAll();
+ outputList.clear();
+ regexErrorMessages.clear();
+ columnNamesList.clear();
+ cachedNamesList.clear();
+ graphsTable.removeAll();
+ badGraphs.clear();
+
+ // There should always be at least one regular expression (a blank one still counts).
+ // If configuration's number of regexs is zero, it is outdated.
+ int numberOfRegexs = Math.max(configuration.getAttribute(NUMBER_OF_REGEXS, 1), 1);
+
+ // Only allow removing regexs if there are more than one.
+ removeRegexButton.setEnabled(numberOfRegexs > 1);
+
+ for (int r = 0; r < numberOfRegexs; r++) {
+ // Save all of the configuration's regular expressions & sample outputs in a list.
+ regularExpressionCombo.add(configuration.getAttribute(REGULAR_EXPRESSION + r, "")); //$NON-NLS-1$
+ outputList.add(configuration.getAttribute(SAMPLE_OUTPUT + r, "")); //$NON-NLS-1$
+
+ // Save each regex's list of group names.
+ int numberOfColumns = configuration.getAttribute(NUMBER_OF_COLUMNS + r, 0);
+ ArrayList<String> namelist = new ArrayList<>(numberOfColumns);
+ for (int i = 0; i < numberOfColumns; i++) {
+ namelist.add(configuration.getAttribute(get2DConfigData(REGEX_BOX, r, i), (String)null));
+ }
+ columnNamesList.add(namelist);
+
+ //Reclaim missing column data that was required for existing graphs at the time of the previous "apply".
+ int numberOfExtras = configuration.getAttribute(NUMBER_OF_EXTRAS + r, 0);
+ Stack<String> oldnames = new Stack<>();
+ for (int i = 0; i < numberOfExtras; i++) {
+ oldnames.push(configuration.getAttribute(get2DConfigData(EXTRA_BOX, r, i), (String)null));
+ }
+ cachedNamesList.add(oldnames);
+
+ regexErrorMessages.add(null);
+ }
+ if (getNumberOfRegexs() < MAX_NUMBER_OF_REGEXS) {
+ regularExpressionCombo.add(Messages.SystemTapScriptGraphOptionsTab_regexAddNew);
+ }
+
+ // When possible, preserve the selection on subsequent initializations, for user convenience.
+ int defaultSelectedRegex = 0 <= selectedRegex && selectedRegex < numberOfRegexs ? selectedRegex : 0;
+ regularExpressionCombo.select(defaultSelectedRegex);
+
+ // Add graphs
+ graphsDataList = createGraphsFromConfiguration(configuration);
+ graphsData = graphsDataList.get(defaultSelectedRegex);
+ for (GraphData graphData : graphsData) {
+ TableItem item = new TableItem(graphsTable, SWT.NONE);
+ setUpGraphTableItem(item, graphData, true);
+ }
+
+ updateRegexSelection(defaultSelectedRegex, true); // Handles all remaining updates.
+ checkAllOtherErrors();
+
+ boolean chart = configuration.getAttribute(RUN_WITH_CHART, false);
+ setGraphingEnabled(chart);
+ this.runWithChartCheckButton.setSelection(chart);
+
+ } catch (CoreException e) {
+ ExceptionErrorDialog.openError(Messages.SystemTapScriptGraphOptionsTab_cantInitializeTab, e);
+ } finally {
+ textListenersEnabled = true;
+ }
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(RUN_WITH_CHART, this.runWithChartCheckButton.getSelection());
+
+ int numberOfRegexs = getNumberOfRegexs();
+ for (int r = 0; r < numberOfRegexs; r++) {
+ // Save data sets, and clear removed ones.
+ configuration.setAttribute(REGULAR_EXPRESSION + r, regularExpressionCombo.getItem(r));
+ configuration.setAttribute(SAMPLE_OUTPUT + r, outputList.get(r));
+
+ ArrayList<String> columnNames = columnNamesList.get(r);
+ int numberOfColumns = columnNames.size();
+ for (int i = 0; i < numberOfColumns; i++) {
+ configuration.setAttribute(get2DConfigData(REGEX_BOX, r, i), columnNames.get(i));
+ }
+ cleanUpConfigurationItem(configuration, NUMBER_OF_COLUMNS, REGEX_BOX, r, numberOfColumns);
+ configuration.setAttribute(NUMBER_OF_COLUMNS + r, numberOfColumns);
+
+ // If the current regex has graphs with missing data, store all cached names
+ // in the configuration so that they will be easily restorable for next time.
+ Stack<String> extranames = cachedNamesList.get(r);
+ int numberOfExtras = findBadGraphs(r) == null ? 0 : extranames.size();
+ for (int i = 0; i < numberOfExtras; i++) {
+ configuration.setAttribute(get2DConfigData(EXTRA_BOX, r, i), extranames.get(i));
+ }
+ cleanUpConfigurationItem(configuration, NUMBER_OF_EXTRAS, EXTRA_BOX, r, numberOfExtras);
+ configuration.setAttribute(NUMBER_OF_EXTRAS + r, numberOfExtras);
+
+ // Save new graphs, and clear removed ones.
+ LinkedList<GraphData> list = graphsDataList.get(r);
+ int numberOfGraphs = list.size();
+ for (int i = 0; i < numberOfGraphs; i++) {
+ GraphData graphData = list.get(i);
+ configuration.setAttribute(get2DConfigData(GRAPH_TITLE, r, i), graphData.title);
+ configuration.setAttribute(get2DConfigData(GRAPH_KEY, r, i), graphData.key);
+ configuration.setAttribute(get2DConfigData(GRAPH_X_SERIES, r, i), graphData.xSeries);
+ configuration.setAttribute(get2DConfigData(GRAPH_ID, r, i), graphData.graphID);
+
+ int ySeriesLength = graphData.ySeries.length;
+ for (int j = 0; j < ySeriesLength; j++) {
+ configuration.setAttribute(get2DConfigData(GRAPH_Y_SERIES, r, i + "_" + j), //$NON-NLS-1$
+ graphData.ySeries[j]);
+ }
+ cleanUpConfigurationGraphYSeries(configuration, r, i, ySeriesLength);
+ configuration.setAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, r, i), ySeriesLength);
+ }
+ cleanUpConfigurationGraphs(configuration, r, numberOfGraphs);
+ configuration.setAttribute(NUMBER_OF_GRAPHS + r, numberOfGraphs);
+ }
+ cleanUpConfiguration(configuration, numberOfRegexs);
+ configuration.setAttribute(NUMBER_OF_REGEXS, numberOfRegexs);
+ }
+
+ /**
+ * Removes all configuration attributes associated with deleted regular expressions.
+ * @param configuration The configuration to remove attributes from.
+ * @param numberOfRegexs The number of regex-related properties to exist in the
+ * configuration after cleanup.
+ */
+ private void cleanUpConfiguration(ILaunchConfigurationWorkingCopy configuration, int numberOfRegexs) {
+ int oldNumberOfRegexs = 0;
+ try {
+ oldNumberOfRegexs = configuration.getAttribute(NUMBER_OF_REGEXS, 0);
+ } catch (CoreException e) {}
+ for (int r = numberOfRegexs; r < oldNumberOfRegexs; r++) {
+ configuration.removeAttribute(REGULAR_EXPRESSION + r);
+ configuration.removeAttribute(SAMPLE_OUTPUT + r);
+
+ cleanUpConfigurationItem(configuration, NUMBER_OF_COLUMNS, REGEX_BOX, r, 0);
+ configuration.removeAttribute(NUMBER_OF_COLUMNS + r);
+
+ cleanUpConfigurationItem(configuration, NUMBER_OF_COLUMNS, EXTRA_BOX, r, 0);
+ configuration.removeAttribute(NUMBER_OF_EXTRAS + r);
+
+ cleanUpConfigurationGraphs(configuration, r, 0);
+ configuration.removeAttribute(NUMBER_OF_GRAPHS + r);
+ }
+ }
+
+ private void cleanUpConfigurationGraphs(ILaunchConfigurationWorkingCopy configuration, int regex, int newNumberOfGraphs) {
+ int oldNumberOfGraphs = 0;
+ try {
+ oldNumberOfGraphs = configuration.getAttribute(NUMBER_OF_GRAPHS + regex, 0);
+ } catch (CoreException e) {}
+ for (int i = newNumberOfGraphs; i < oldNumberOfGraphs; i++) {
+ configuration.removeAttribute(get2DConfigData(GRAPH_TITLE, regex, i));
+ configuration.removeAttribute(get2DConfigData(GRAPH_KEY, regex, i));
+ configuration.removeAttribute(get2DConfigData(GRAPH_X_SERIES, regex, i));
+ configuration.removeAttribute(get2DConfigData(GRAPH_ID, regex, i));
+
+ cleanUpConfigurationGraphYSeries(configuration, regex, i, 0);
+ configuration.removeAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, regex, i));
+ }
+ }
+
+ private void cleanUpConfigurationItem(ILaunchConfigurationWorkingCopy configuration, String counter, String property, int regex, int newNumberOfItems) {
+ int oldNumberOfItems = 0;
+ try {
+ oldNumberOfItems = configuration.getAttribute(counter + regex, 0);
+ } catch (CoreException e) {}
+ for (int i = newNumberOfItems; i < oldNumberOfItems; i++) {
+ configuration.removeAttribute(get2DConfigData(property, regex, i));
+ }
+ }
+
+ private void cleanUpConfigurationGraphYSeries(ILaunchConfigurationWorkingCopy configuration, int regex, int graph, int newLength) {
+ int oldYSeriesLength = 0;
+ try {
+ oldYSeriesLength = configuration.getAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, regex, graph), 0);
+ } catch (CoreException e) {}
+ for (int i = newLength; i < oldYSeriesLength; i++) {
+ configuration.removeAttribute(get2DConfigData(GRAPH_Y_SERIES, regex, graph + "_" + i)); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Checks all regular expressions for errors, except for the currently-selected
+ * expression (as it should be checked by {@link #refreshRegexRows}).
+ */
+ private void checkAllOtherErrors() {
+ for (int i = 0, n = getNumberOfRegexs(); i < n; i++) {
+ if (i == selectedRegex) {
+ continue;
+ }
+ checkErrors(i);
+ }
+ }
+
+ /**
+ * Checks the regular expression of the provided index for errors.
+ * Sets the associated error message to contain relevant error information.
+ * @param i The index of the regular expression to check for errors.
+ */
+ private void checkErrors(int i) {
+ String regex = regularExpressionCombo.getItem(i);
+ try {
+ Pattern.compile(regex);
+ } catch (PatternSyntaxException e) {
+ regexErrorMessages.set(i, e.getMessage());
+ return;
+ }
+
+ String error = findBadGraphs(i);
+ if (error == null) {
+ error = checkRegex(regex);
+ }
+
+ regexErrorMessages.set(i, error);
+ }
+
+ @Override
+ public boolean isValid(ILaunchConfiguration launchConfig) {
+ setErrorMessage(null);
+
+ // If graphic is disabled then everything is valid.
+ if (!this.graphingEnabled) {
+ return true;
+ }
+
+ for (int r = 0, n = getNumberOfRegexs(); r < n; r++) {
+ String regexErrorMessage = regexErrorMessages.get(r);
+ if (regexErrorMessage != null) {
+ setErrorMessage(MessageFormat.format(Messages.SystemTapScriptGraphOptionsTab_regexErrorMsgFormat,
+ regularExpressionCombo.getItems()[r], regexErrorMessage));
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Checks if a launch configuration's Systemtap Graphing settings are valid.
+ * @param launchConfig The launch configuration to check for graph validity.
+ * @return <code>true</code> if the launch settings are valid, or <code>false</code> if
+ * its graph settings are invalid in some way.
+ * @since 2.2
+ */
+ public static boolean isValidLaunch(ILaunchConfiguration launchConfig) throws CoreException {
+ // If graphic is disabled then everything is valid.
+ if (!launchConfig.getAttribute(RUN_WITH_CHART, false)) {
+ return true;
+ }
+
+ for (int r = 0, n = launchConfig.getAttribute(NUMBER_OF_REGEXS, 1); r < n; r++) {
+ // Check for any invalid regexs.
+ String regex = launchConfig.getAttribute(REGULAR_EXPRESSION + r, (String) null);
+ if (regex == null || checkRegex(regex) != null) {
+ return false;
+ }
+ try {
+ Pattern.compile(regex);
+ } catch (PatternSyntaxException e) {
+ return false;
+ }
+
+ // If graphs are plotted but no data is captured by one of them, report this as a problem.
+ int numberOfColumns = launchConfig.getAttribute(NUMBER_OF_COLUMNS + r, 0);
+ if (numberOfColumns == 0) {
+ return false;
+ }
+
+ // Check for graphs that are missing required data.
+ for (int i = 0, g = launchConfig.getAttribute(NUMBER_OF_GRAPHS + r, 0); i < g; i++) {
+ if (GraphFactory.getGraphName(launchConfig.getAttribute(get2DConfigData(GRAPH_ID, r, i), (String) null)) == null) {
+ return false;
+ }
+ if (launchConfig.getAttribute(get2DConfigData(GRAPH_X_SERIES, r, i), 0) >= numberOfColumns) {
+ return false;
+ }
+ for (int j = 0, y = launchConfig.getAttribute(get2DConfigData(GRAPH_Y_SERIES_LENGTH, r, i), 0); j < y; j++) {
+ if (launchConfig.getAttribute(get2DConfigData(GRAPH_Y_SERIES, r, i + "_" + j), 0) >= numberOfColumns) { //$NON-NLS-1$
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public String getName() {
+ return Messages.SystemTapScriptGraphOptionsTab_graphingTitle;
+ }
+
+ @Override
+ public Image getImage() {
+ return AbstractUIPlugin.imageDescriptorFromPlugin(IDEPlugin.PLUGIN_ID,
+ "icons/graphing_tab.gif").createImage(); //$NON-NLS-1$
+ }
+
+ private void setGraphingEnabled(boolean enabled) {
+ this.graphingEnabled = enabled;
+ this.setControlEnabled(outputParsingGroup, enabled);
+ this.setControlEnabled(graphsGroup, enabled);
+ // Disable buttons that rely on a selected graph if no graph is selected.
+ this.setSelectionControlsEnabled(selectedTableItem != null);
+ this.addGraphButton.setEnabled(enabled && numberOfVisibleColumns > 0);
+ this.removeRegexButton.setEnabled(enabled && getNumberOfRegexs() > 1);
+ updateLaunchConfigurationDialog();
+ }
+
+ private void setControlEnabled(Composite composite, boolean enabled) {
+ composite.setEnabled(enabled);
+ for (Control child : composite.getChildren()) {
+ child.setEnabled(enabled);
+ if (child instanceof Composite) {
+ setControlEnabled((Composite)child, enabled);
+ }
+ }
+ }
+
+ /**
+ * Call this to enable/disable all buttons whose actions depend on a selected graph.
+ * @param enabled Set to true to enable the buttons; set to false to disable them.
+ */
+ private void setSelectionControlsEnabled(boolean enabled) {
+ duplicateGraphButton.setEnabled(enabled);
+ editGraphButton.setEnabled(enabled && numberOfVisibleColumns > 0);
+ removeGraphButton.setEnabled(enabled);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunch.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunch.java
index 7a04169047..36444cea05 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunch.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunch.java
@@ -9,95 +9,95 @@ import org.eclipse.linuxtools.systemtap.ui.consolelog.structures.ScriptConsole;
import org.eclipse.linuxtools.systemtap.ui.consolelog.structures.ScriptConsole.ScriptConsoleObserver;
public class SystemTapScriptLaunch extends Launch
- implements ScriptConsoleObserver {
+ implements ScriptConsoleObserver {
- private ScriptConsole console = null;
- private boolean runStarted = false;
- private boolean runStopped = false;
+ private ScriptConsole console = null;
+ private boolean runStarted = false;
+ private boolean runStopped = false;
- public SystemTapScriptLaunch(ILaunchConfiguration launchConfiguration, String mode) {
- super(launchConfiguration, mode, null);
- }
+ public SystemTapScriptLaunch(ILaunchConfiguration launchConfiguration, String mode) {
+ super(launchConfiguration, mode, null);
+ }
- public void setConsole(ScriptConsole console) {
- // If another launch is using the same console, remove that launch since
- // ScriptConsole prevents two identical stap scripts from being be run at once.
- this.console = console;
- ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
- for (ILaunch launch : manager.getLaunches()) {
- if (launch.equals(this)) {
- continue;
- }
- if (launch instanceof SystemTapScriptLaunch) {
- SystemTapScriptLaunch olaunch = (SystemTapScriptLaunch) launch;
- if (olaunch.console == null || olaunch.console.equals(console)) {
- olaunch.forceRemove();
- }
- }
- }
- console.addScriptConsoleObserver(this);
- }
+ public void setConsole(ScriptConsole console) {
+ // If another launch is using the same console, remove that launch since
+ // ScriptConsole prevents two identical stap scripts from being be run at once.
+ this.console = console;
+ ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
+ for (ILaunch launch : manager.getLaunches()) {
+ if (launch.equals(this)) {
+ continue;
+ }
+ if (launch instanceof SystemTapScriptLaunch) {
+ SystemTapScriptLaunch olaunch = (SystemTapScriptLaunch) launch;
+ if (olaunch.console == null || olaunch.console.equals(console)) {
+ olaunch.forceRemove();
+ }
+ }
+ }
+ console.addScriptConsoleObserver(this);
+ }
- public ScriptConsole getConsole() {
- return console;
- }
+ public ScriptConsole getConsole() {
+ return console;
+ }
- @Override
- public void runningStateChanged(boolean started, boolean stopped) {
- if (!runStarted && started) {
- runStarted = started;
- if (console.getCommand().getProcess() != null) {
- DebugPlugin.newProcess(this, console.getCommand().getProcess(), console.getName());
- }
- if (stopped) {
- runStopped = true;
- }
- console.removeScriptConsoleObserver(this);
- }
- }
+ @Override
+ public void runningStateChanged(boolean started, boolean stopped) {
+ if (!runStarted && started) {
+ runStarted = started;
+ if (console.getCommand().getProcess() != null) {
+ DebugPlugin.newProcess(this, console.getCommand().getProcess(), console.getName());
+ }
+ if (stopped) {
+ runStopped = true;
+ }
+ console.removeScriptConsoleObserver(this);
+ }
+ }
- @Override
- public boolean canTerminate() {
- return !isTerminated();
- }
+ @Override
+ public boolean canTerminate() {
+ return !isTerminated();
+ }
- @Override
- public boolean isTerminated() {
- if (!runStopped) {
- if (super.isTerminated() || (console != null && !console.isRunning())) {
- runStopped = true;
- }
- }
- return runStopped;
- }
+ @Override
+ public boolean isTerminated() {
+ if (!runStopped) {
+ if (super.isTerminated() || (console != null && !console.isRunning())) {
+ runStopped = true;
+ }
+ }
+ return runStopped;
+ }
- @Override
- public void terminate() {
- if (console != null) {
- console.stop();
- }
- }
+ @Override
+ public void terminate() {
+ if (console != null) {
+ console.stop();
+ }
+ }
- @Override
- public void launchRemoved(ILaunch launch) {
- super.launchRemoved(launch);
- if (launch.equals(this)) {
- removeConsole();
- }
- }
+ @Override
+ public void launchRemoved(ILaunch launch) {
+ super.launchRemoved(launch);
+ if (launch.equals(this)) {
+ removeConsole();
+ }
+ }
- private void removeConsole() {
- if (console != null) {
- console.removeScriptConsoleObserver(this);
- console.stop();
- console = null;
- }
- }
+ private void removeConsole() {
+ if (console != null) {
+ console.removeScriptConsoleObserver(this);
+ console.stop();
+ console = null;
+ }
+ }
- public void forceRemove() {
- removeConsole();
- runStopped = true;
- ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
- manager.removeLaunch(this);
- }
+ public void forceRemove() {
+ removeConsole();
+ runStopped = true;
+ ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
+ manager.removeLaunch(this);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationDelegate.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationDelegate.java
index c22b853873..8f95f5c435 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationDelegate.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationDelegate.java
@@ -42,137 +42,137 @@ import org.eclipse.linuxtools.systemtap.structures.process.SystemTapRuntimeProce
import org.eclipse.linuxtools.systemtap.ui.consolelog.structures.RemoteScriptOptions;
public class SystemTapScriptLaunchConfigurationDelegate extends
- LaunchConfigurationDelegate {
-
- static final String CONFIGURATION_TYPE = "org.eclipse.linuxtools.systemtap.ui.ide.SystemTapLaunchConfigurationType"; //$NON-NLS-1$
-
- private IProject[] scriptProject;
-
- /**
- * Keep a reference to the target running script's parent project, so only that project
- * will be saved when the script is run.
- */
- @Override
- protected IProject[] getBuildOrder(ILaunchConfiguration configuration, String mode) {
- return scriptProject;
- }
-
- @Override
- public ILaunch getLaunch(ILaunchConfiguration configuration, String mode) {
- return new SystemTapScriptLaunch(configuration, mode);
- }
-
- @Override
- public boolean preLaunchCheck(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException {
- // Force the configuration to use the proper Process Factory.
- if (!configuration.getAttribute(DebugPlugin.ATTR_PROCESS_FACTORY_ID, "").equals(SystemTapRuntimeProcessFactory.PROCESS_FACTORY_ID)) { //$NON-NLS-1$
- ILaunchConfigurationWorkingCopy wc = configuration.getWorkingCopy();
- wc.setAttribute(DebugPlugin.ATTR_PROCESS_FACTORY_ID, SystemTapRuntimeProcessFactory.PROCESS_FACTORY_ID);
- wc.doSave();
- }
- // Find the parent project of the target script.
- IPath path = Path.fromOSString(configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.SCRIPT_PATH_ATTR, (String)null));
- IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
- scriptProject = file == null ? null : new IProject[]{file.getProject()};
-
- // Only save the target script's project if a project is found.
- if (scriptProject != null) {
- return super.preLaunchCheck(configuration, mode, monitor);
- }
- return true;
- }
-
- @Override
- public void launch(ILaunchConfiguration configuration, String mode,
- ILaunch launch, IProgressMonitor monitor) throws CoreException {
-
- // Wait for other stap launches' consoles to be initiated before starting a new launch.
- ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
- for (ILaunch olaunch : manager.getLaunches()) {
- if (olaunch.equals(launch)) {
- continue;
- }
- if (olaunch instanceof SystemTapScriptLaunch && ((SystemTapScriptLaunch) olaunch).getConsole() == null) {
- throw new CoreException(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID,
- Messages.SystemTapScriptLaunchError_waitForConsoles));
- }
- }
-
- if (!SystemTapScriptGraphOptionsTab.isValidLaunch(configuration)) {
- throw new CoreException(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID, Messages.SystemTapScriptLaunchError_graph));
- }
-
- RunScriptHandler action;
-
- boolean runWithChart = configuration.getAttribute(SystemTapScriptGraphOptionsTab.RUN_WITH_CHART, false);
- // If runWithChart is true there must be at least one graph, but this isn't guaranteed
- // to be true for outdated Launch Configurations. So for safety, make sure there are graphs.
- int numGraphs = configuration.getAttribute(SystemTapScriptGraphOptionsTab.NUMBER_OF_REGEXS, 0);
- if (runWithChart && numGraphs > 0){
- List<IDataSetParser> parsers = SystemTapScriptGraphOptionsTab.createDatasetParsers(configuration);
- List<IFilteredDataSet> dataSets = SystemTapScriptGraphOptionsTab.createDataset(configuration);
- List<String> names = SystemTapScriptGraphOptionsTab.createDatasetNames(configuration);
- List<LinkedList<GraphData>> graphs = SystemTapScriptGraphOptionsTab.createGraphsFromConfiguration(configuration);
- action = new RunScriptChartHandler(parsers, dataSets, names, graphs);
- }else{
- action = new RunScriptHandler();
- }
-
- // Path
- IPath scriptPath = new Path(configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.SCRIPT_PATH_ATTR, "")); //$NON-NLS-1$
- if (!scriptPath.toFile().exists()) {
- throw new CoreException(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID,
- MessageFormat.format(Messages.SystemTapScriptLaunchError_fileNotFound, scriptPath.toString())));
- }
- String extension = scriptPath.getFileExtension();
- if (extension == null || !extension.equals("stp")) { //$NON-NLS-1$
- throw new CoreException(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID,
- MessageFormat.format(Messages.SystemTapScriptLaunchError_fileNotStp, scriptPath.toString())));
- }
- action.setPath(scriptPath);
-
- // Run locally and/or as current user.
- boolean runAsCurrentUser = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.CURRENT_USER_ATTR, true);
- boolean runLocal = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.LOCAL_HOST_ATTR, true);
-
- action.setRemoteScriptOptions(runLocal && runAsCurrentUser ? null : new RemoteScriptOptions(
- configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.USER_NAME_ATTR, ""), //$NON-NLS-1$
- configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.USER_PASS_ATTR, ""), //$NON-NLS-1$
- configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.HOST_NAME_ATTR, "localhost"))); //$NON-NLS-1$
-
- String value = configuration.getAttribute(IDEPreferenceConstants.STAP_CMD_OPTION[IDEPreferenceConstants.KEY], ""); //$NON-NLS-1$
- if (!value.isEmpty()){
- action.addComandLineOptions(IDEPreferenceConstants.STAP_CMD_OPTION[IDEPreferenceConstants.FLAG] + " " + value); //$NON-NLS-1$
- }
-
- // Add command line options
- for(int i=0; i<IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length; i++) {
- boolean flag = configuration.getAttribute(
- IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.KEY],
- false);
- if (flag){
- action.addComandLineOptions(IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.FLAG]);
- }
- }
-
- for(int i=0; i<IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
- value = configuration.getAttribute(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.KEY],""); //$NON-NLS-1$
- if (!value.isEmpty()){
- action.addComandLineOptions(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.FLAG] + " " + value); //$NON-NLS-1$
- }
- }
-
- value = configuration.getAttribute(SystemTapScriptOptionsTab.MISC_COMMANDLINE_OPTIONS,""); //$NON-NLS-1$
- if (!value.isEmpty()){
- action.addComandLineOptions(value);
- }
-
- action.setLaunch((SystemTapScriptLaunch) launch);
- try {
- action.execute(null);
- } catch (ExecutionException e) {
- throw new CoreException(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID, e.getMessage()));
- }
- }
+ LaunchConfigurationDelegate {
+
+ static final String CONFIGURATION_TYPE = "org.eclipse.linuxtools.systemtap.ui.ide.SystemTapLaunchConfigurationType"; //$NON-NLS-1$
+
+ private IProject[] scriptProject;
+
+ /**
+ * Keep a reference to the target running script's parent project, so only that project
+ * will be saved when the script is run.
+ */
+ @Override
+ protected IProject[] getBuildOrder(ILaunchConfiguration configuration, String mode) {
+ return scriptProject;
+ }
+
+ @Override
+ public ILaunch getLaunch(ILaunchConfiguration configuration, String mode) {
+ return new SystemTapScriptLaunch(configuration, mode);
+ }
+
+ @Override
+ public boolean preLaunchCheck(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException {
+ // Force the configuration to use the proper Process Factory.
+ if (!configuration.getAttribute(DebugPlugin.ATTR_PROCESS_FACTORY_ID, "").equals(SystemTapRuntimeProcessFactory.PROCESS_FACTORY_ID)) { //$NON-NLS-1$
+ ILaunchConfigurationWorkingCopy wc = configuration.getWorkingCopy();
+ wc.setAttribute(DebugPlugin.ATTR_PROCESS_FACTORY_ID, SystemTapRuntimeProcessFactory.PROCESS_FACTORY_ID);
+ wc.doSave();
+ }
+ // Find the parent project of the target script.
+ IPath path = Path.fromOSString(configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.SCRIPT_PATH_ATTR, (String)null));
+ IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
+ scriptProject = file == null ? null : new IProject[]{file.getProject()};
+
+ // Only save the target script's project if a project is found.
+ if (scriptProject != null) {
+ return super.preLaunchCheck(configuration, mode, monitor);
+ }
+ return true;
+ }
+
+ @Override
+ public void launch(ILaunchConfiguration configuration, String mode,
+ ILaunch launch, IProgressMonitor monitor) throws CoreException {
+
+ // Wait for other stap launches' consoles to be initiated before starting a new launch.
+ ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
+ for (ILaunch olaunch : manager.getLaunches()) {
+ if (olaunch.equals(launch)) {
+ continue;
+ }
+ if (olaunch instanceof SystemTapScriptLaunch && ((SystemTapScriptLaunch) olaunch).getConsole() == null) {
+ throw new CoreException(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID,
+ Messages.SystemTapScriptLaunchError_waitForConsoles));
+ }
+ }
+
+ if (!SystemTapScriptGraphOptionsTab.isValidLaunch(configuration)) {
+ throw new CoreException(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID, Messages.SystemTapScriptLaunchError_graph));
+ }
+
+ RunScriptHandler action;
+
+ boolean runWithChart = configuration.getAttribute(SystemTapScriptGraphOptionsTab.RUN_WITH_CHART, false);
+ // If runWithChart is true there must be at least one graph, but this isn't guaranteed
+ // to be true for outdated Launch Configurations. So for safety, make sure there are graphs.
+ int numGraphs = configuration.getAttribute(SystemTapScriptGraphOptionsTab.NUMBER_OF_REGEXS, 0);
+ if (runWithChart && numGraphs > 0){
+ List<IDataSetParser> parsers = SystemTapScriptGraphOptionsTab.createDatasetParsers(configuration);
+ List<IFilteredDataSet> dataSets = SystemTapScriptGraphOptionsTab.createDataset(configuration);
+ List<String> names = SystemTapScriptGraphOptionsTab.createDatasetNames(configuration);
+ List<LinkedList<GraphData>> graphs = SystemTapScriptGraphOptionsTab.createGraphsFromConfiguration(configuration);
+ action = new RunScriptChartHandler(parsers, dataSets, names, graphs);
+ }else{
+ action = new RunScriptHandler();
+ }
+
+ // Path
+ IPath scriptPath = new Path(configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.SCRIPT_PATH_ATTR, "")); //$NON-NLS-1$
+ if (!scriptPath.toFile().exists()) {
+ throw new CoreException(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID,
+ MessageFormat.format(Messages.SystemTapScriptLaunchError_fileNotFound, scriptPath.toString())));
+ }
+ String extension = scriptPath.getFileExtension();
+ if (extension == null || !extension.equals("stp")) { //$NON-NLS-1$
+ throw new CoreException(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID,
+ MessageFormat.format(Messages.SystemTapScriptLaunchError_fileNotStp, scriptPath.toString())));
+ }
+ action.setPath(scriptPath);
+
+ // Run locally and/or as current user.
+ boolean runAsCurrentUser = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.CURRENT_USER_ATTR, true);
+ boolean runLocal = configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.LOCAL_HOST_ATTR, true);
+
+ action.setRemoteScriptOptions(runLocal && runAsCurrentUser ? null : new RemoteScriptOptions(
+ configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.USER_NAME_ATTR, ""), //$NON-NLS-1$
+ configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.USER_PASS_ATTR, ""), //$NON-NLS-1$
+ configuration.getAttribute(SystemTapScriptLaunchConfigurationTab.HOST_NAME_ATTR, "localhost"))); //$NON-NLS-1$
+
+ String value = configuration.getAttribute(IDEPreferenceConstants.STAP_CMD_OPTION[IDEPreferenceConstants.KEY], ""); //$NON-NLS-1$
+ if (!value.isEmpty()){
+ action.addComandLineOptions(IDEPreferenceConstants.STAP_CMD_OPTION[IDEPreferenceConstants.FLAG] + " " + value); //$NON-NLS-1$
+ }
+
+ // Add command line options
+ for(int i=0; i<IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length; i++) {
+ boolean flag = configuration.getAttribute(
+ IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.KEY],
+ false);
+ if (flag){
+ action.addComandLineOptions(IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.FLAG]);
+ }
+ }
+
+ for(int i=0; i<IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
+ value = configuration.getAttribute(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.KEY],""); //$NON-NLS-1$
+ if (!value.isEmpty()){
+ action.addComandLineOptions(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.FLAG] + " " + value); //$NON-NLS-1$
+ }
+ }
+
+ value = configuration.getAttribute(SystemTapScriptOptionsTab.MISC_COMMANDLINE_OPTIONS,""); //$NON-NLS-1$
+ if (!value.isEmpty()){
+ action.addComandLineOptions(value);
+ }
+
+ action.setLaunch((SystemTapScriptLaunch) launch);
+ try {
+ action.execute(null);
+ } catch (ExecutionException e) {
+ throw new CoreException(new Status(IStatus.ERROR, IDEPlugin.PLUGIN_ID, e.getMessage()));
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationTab.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationTab.java
index 0c4d63ee8f..5640440fdb 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationTab.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationTab.java
@@ -48,300 +48,300 @@ import org.eclipse.ui.ide.ResourceUtil;
import org.eclipse.ui.plugin.AbstractUIPlugin;
public class SystemTapScriptLaunchConfigurationTab extends
- AbstractLaunchConfigurationTab {
-
- static final String SCRIPT_PATH_ATTR = "ScriptPath"; //$NON-NLS-1$
- static final String CURRENT_USER_ATTR = "executeAsCurrentUser"; //$NON-NLS-1$
- static final String USER_NAME_ATTR = "userName"; //$NON-NLS-1$
- static final String USER_PASS_ATTR = "userPassword"; //$NON-NLS-1$
- static final String LOCAL_HOST_ATTR = "executeOnLocalHost"; //$NON-NLS-1$
- static final String HOST_NAME_ATTR = "hostName"; //$NON-NLS-1$
-
- private Text scriptPathText;
- private Button currentUserCheckButton;
- private Text userNameText;
- private Text userPasswordText;
- private Button localHostCheckButton;
- private Text hostNameText;
- private Label userNameLabel;
- private Label userPasswordLabel;
- private Label hostNamelabel;
- private FileDialog fileDialog;
-
- /**
- * @return The path of the chosen script the Run Configuration will be applied to,
- * or <code>null</code> if no file exists at the given path.
- */
- IPath getScriptPath() {
- IPath scriptPath = new Path(scriptPathText.getText());
- return scriptPath.toFile().exists() ? scriptPath : null;
- }
-
- @Override
- public void createControl(Composite parent) {
-
- this.fileDialog = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OPEN);
+ AbstractLaunchConfigurationTab {
+
+ static final String SCRIPT_PATH_ATTR = "ScriptPath"; //$NON-NLS-1$
+ static final String CURRENT_USER_ATTR = "executeAsCurrentUser"; //$NON-NLS-1$
+ static final String USER_NAME_ATTR = "userName"; //$NON-NLS-1$
+ static final String USER_PASS_ATTR = "userPassword"; //$NON-NLS-1$
+ static final String LOCAL_HOST_ATTR = "executeOnLocalHost"; //$NON-NLS-1$
+ static final String HOST_NAME_ATTR = "hostName"; //$NON-NLS-1$
+
+ private Text scriptPathText;
+ private Button currentUserCheckButton;
+ private Text userNameText;
+ private Text userPasswordText;
+ private Button localHostCheckButton;
+ private Text hostNameText;
+ private Label userNameLabel;
+ private Label userPasswordLabel;
+ private Label hostNamelabel;
+ private FileDialog fileDialog;
+
+ /**
+ * @return The path of the chosen script the Run Configuration will be applied to,
+ * or <code>null</code> if no file exists at the given path.
+ */
+ IPath getScriptPath() {
+ IPath scriptPath = new Path(scriptPathText.getText());
+ return scriptPath.toFile().exists() ? scriptPath : null;
+ }
+
+ @Override
+ public void createControl(Composite parent) {
+
+ this.fileDialog = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OPEN);
fileDialog.setText(Messages.SystemTapScriptLaunchConfigurationTab_selectScript);
fileDialog.setFilterPath(Platform.getLocation().toOSString());
- GridLayout layout = new GridLayout();
- Composite top = new Composite(parent, SWT.NONE);
- setControl(top);
- top.setLayout(layout);
- top.setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true));
-
- // Script path
- Group scriptSettingsGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
- scriptSettingsGroup.setText(Messages.SystemTapScriptLaunchConfigurationTab_script);
- scriptSettingsGroup.setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, false));
- layout = new GridLayout();
- layout.numColumns = 2;
- scriptSettingsGroup.setLayout(layout);
- this.scriptPathText = new Text(scriptSettingsGroup, SWT.SINGLE | SWT.BORDER);
- scriptPathText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- scriptPathText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- });
- Button selectScriptButon = new Button(scriptSettingsGroup, 0);
- GridData gridData = new GridData();
- gridData.widthHint = 110;
- selectScriptButon.setLayoutData(gridData);
- selectScriptButon.setText(Messages.SystemTapScriptLaunchConfigurationTab_browse);
- selectScriptButon.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- String path = fileDialog.open();
- if (path != null){
- scriptPathText.setText(path);
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- // User Settings
- Group userSettingsGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
- layout = new GridLayout();
- userSettingsGroup.setLayout(layout);
- layout.numColumns = 2;
- userSettingsGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-
- this.currentUserCheckButton = new Button(userSettingsGroup, SWT.CHECK);
- currentUserCheckButton.setText(Messages.SystemTapScriptLaunchConfigurationTab_currentUser);
- currentUserCheckButton.setSelection(true);
- gridData = new GridData();
- gridData.horizontalSpan = 2;
- currentUserCheckButton.setLayoutData(gridData);
-
- this.userNameLabel = new Label(userSettingsGroup, SWT.NONE);
- userNameLabel.setText(Messages.SystemTapScriptLaunchConfigurationTab_username);
- this.userNameText = new Text(userSettingsGroup, SWT.SINGLE | SWT.BORDER);
- userNameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-
- this.userPasswordLabel = new Label(userSettingsGroup, SWT.NONE);
- userPasswordLabel.setText(Messages.SystemTapScriptLaunchConfigurationTab_password);
- this.userPasswordText = new Text(userSettingsGroup, SWT.SINGLE | SWT.BORDER | SWT.PASSWORD);
- userPasswordText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
-
- userSettingsGroup.setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, false));
- userSettingsGroup.setText(Messages.SystemTapScriptLaunchConfigurationTab_user);
-
- currentUserCheckButton.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- update();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- update();
- }
-
- private void update(){
- boolean enable = !currentUserCheckButton.getSelection();
- setUserGroupEnablement(enable);
- updateLaunchConfigurationDialog();
- }
- });
-
- userNameText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- });
-
- userPasswordText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- });
-
- setUserGroupEnablement(false);
-
- // Host settings
- Group hostSettingsGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
- hostSettingsGroup.setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, false));
- hostSettingsGroup.setText(Messages.SystemTapScriptLaunchConfigurationTab_host);
- layout = new GridLayout();
- hostSettingsGroup.setLayout(layout);
- layout.numColumns = 2;
-
- this.localHostCheckButton = new Button(hostSettingsGroup, SWT.CHECK);
- localHostCheckButton.setText(Messages.SystemTapScriptLaunchConfigurationTab_runLocally);
- gridData = new GridData();
- gridData.horizontalSpan = 2;
-
- this.hostNamelabel = new Label(hostSettingsGroup, SWT.NONE);
- hostNamelabel.setText(Messages.SystemTapScriptLaunchConfigurationTab_hostname);
- this.hostNameText = new Text(hostSettingsGroup, SWT.SINGLE | SWT.BORDER);
- hostNameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- localHostCheckButton.setLayoutData(gridData);
- localHostCheckButton.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- update();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- update();
- }
-
- private void update(){
- updateLaunchConfigurationDialog();
- }
- });
- hostNameText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- });
- }
-
- private void setUserGroupEnablement(boolean enable){
- userNameText.setEnabled(enable);
- userNameLabel.setEnabled(enable);
- userPasswordText.setEnabled(enable);
- userPasswordLabel.setEnabled(enable);
- }
-
- private void setHostGroupEnablement(boolean enable){
- hostNamelabel.setEnabled(enable);
- hostNameText.setEnabled(enable);
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(SCRIPT_PATH_ATTR, this.getSelectedScriptPath());
- configuration.setAttribute(CURRENT_USER_ATTR, true);
- configuration.setAttribute(USER_NAME_ATTR, ""); //$NON-NLS-1$
- configuration.setAttribute(USER_PASS_ATTR, ""); //$NON-NLS-1$
- configuration.setAttribute(LOCAL_HOST_ATTR, true);
- configuration.setAttribute(HOST_NAME_ATTR, ""); //$NON-NLS-1$
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration configuration) {
- try {
- this.scriptPathText.setText(configuration.getAttribute(SCRIPT_PATH_ATTR, "")); //$NON-NLS-1$
- this.currentUserCheckButton.setSelection(configuration.getAttribute(CURRENT_USER_ATTR, true));
- this.userNameText.setText(configuration.getAttribute(USER_NAME_ATTR, "")); //$NON-NLS-1$
- this.userPasswordText.setText(configuration.getAttribute(USER_PASS_ATTR, "")); //$NON-NLS-1$
- this.localHostCheckButton.setSelection(configuration.getAttribute(LOCAL_HOST_ATTR, true));
- this.hostNameText.setText(configuration.getAttribute(HOST_NAME_ATTR, "")); //$NON-NLS-1$
- } catch (CoreException e) {
- ExceptionErrorDialog.openError(Messages.SystemTapScriptLaunchConfigurationTab_errorInitializingTab, e);
- }
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(SCRIPT_PATH_ATTR, this.scriptPathText.getText());
- configuration.setAttribute(CURRENT_USER_ATTR, this.currentUserCheckButton.getSelection());
- configuration.setAttribute(USER_NAME_ATTR, this.userNameText.getText());
- configuration.setAttribute(USER_PASS_ATTR, this.userPasswordText.getText());
- configuration.setAttribute(LOCAL_HOST_ATTR, this.localHostCheckButton.getSelection());
- configuration.setAttribute(HOST_NAME_ATTR, this.hostNameText.getText());
-
- boolean enable = !currentUserCheckButton.getSelection();
- setUserGroupEnablement(enable);
-
- enable = !localHostCheckButton.getSelection();
- setHostGroupEnablement(enable);
- }
-
- @Override
- public boolean isValid(ILaunchConfiguration launchConfig) {
- setErrorMessage(null);
-
- IPath scriptPath = getScriptPath();
- if (scriptPath == null) {
- setErrorMessage(MessageFormat.format(Messages.SystemTapScriptLaunchConfigurationTab_fileNotFound, scriptPathText.getText()));
- return false;
- }
- String extension = scriptPath.getFileExtension();
- if (extension == null || !extension.equals("stp")) { //$NON-NLS-1$
- setErrorMessage(Messages.SystemTapScriptLaunchConfigurationTab_fileNotStp);
- return false;
- }
-
- return true;
- }
-
- @Override
- public String getName() {
- return Messages.SystemTapScriptLaunchConfigurationTab_general;
- }
-
- private String getSelectedScriptPath(){
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
-
- String pathString = ""; //$NON-NLS-1$
-
- if (window != null)
- {
- ISelection selection = window.getSelectionService().getSelection();
-
- // Figure out the selected systemtap script
- if (selection instanceof TreeSelection){
- Object selectedElement = ((TreeSelection)selection).getFirstElement();
- if (selectedElement instanceof IFile)
- {
- IPath path = ((IFile)selectedElement).getLocation();
- pathString = path.toOSString();
- }
- }
-
- // If it is a text selection use the path from the active editor.
- if (selection instanceof TextSelection){
- IEditorPart ed = window.getActivePage().getActiveEditor();
- if(ed.getEditorInput() instanceof PathEditorInput) {
- pathString = ((PathEditorInput)ed.getEditorInput()).getPath().toString();
- } else {
- pathString = ResourceUtil.getFile(ed.getEditorInput()).getLocation().toString();
- }
- }
- }
-
- if (pathString.endsWith(".stp")) { //$NON-NLS-1$
- return pathString;
- }
-
- return ""; //$NON-NLS-1$
- }
-
- @Override
- public Image getImage() {
- return AbstractUIPlugin.imageDescriptorFromPlugin(IDEPlugin.PLUGIN_ID,
- "icons/main_tab.gif").createImage(); //$NON-NLS-1$
- }
+ GridLayout layout = new GridLayout();
+ Composite top = new Composite(parent, SWT.NONE);
+ setControl(top);
+ top.setLayout(layout);
+ top.setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true));
+
+ // Script path
+ Group scriptSettingsGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
+ scriptSettingsGroup.setText(Messages.SystemTapScriptLaunchConfigurationTab_script);
+ scriptSettingsGroup.setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, false));
+ layout = new GridLayout();
+ layout.numColumns = 2;
+ scriptSettingsGroup.setLayout(layout);
+ this.scriptPathText = new Text(scriptSettingsGroup, SWT.SINGLE | SWT.BORDER);
+ scriptPathText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ scriptPathText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+ Button selectScriptButon = new Button(scriptSettingsGroup, 0);
+ GridData gridData = new GridData();
+ gridData.widthHint = 110;
+ selectScriptButon.setLayoutData(gridData);
+ selectScriptButon.setText(Messages.SystemTapScriptLaunchConfigurationTab_browse);
+ selectScriptButon.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ String path = fileDialog.open();
+ if (path != null){
+ scriptPathText.setText(path);
+ }
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+
+ // User Settings
+ Group userSettingsGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
+ layout = new GridLayout();
+ userSettingsGroup.setLayout(layout);
+ layout.numColumns = 2;
+ userSettingsGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+
+ this.currentUserCheckButton = new Button(userSettingsGroup, SWT.CHECK);
+ currentUserCheckButton.setText(Messages.SystemTapScriptLaunchConfigurationTab_currentUser);
+ currentUserCheckButton.setSelection(true);
+ gridData = new GridData();
+ gridData.horizontalSpan = 2;
+ currentUserCheckButton.setLayoutData(gridData);
+
+ this.userNameLabel = new Label(userSettingsGroup, SWT.NONE);
+ userNameLabel.setText(Messages.SystemTapScriptLaunchConfigurationTab_username);
+ this.userNameText = new Text(userSettingsGroup, SWT.SINGLE | SWT.BORDER);
+ userNameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+
+ this.userPasswordLabel = new Label(userSettingsGroup, SWT.NONE);
+ userPasswordLabel.setText(Messages.SystemTapScriptLaunchConfigurationTab_password);
+ this.userPasswordText = new Text(userSettingsGroup, SWT.SINGLE | SWT.BORDER | SWT.PASSWORD);
+ userPasswordText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+
+ userSettingsGroup.setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, false));
+ userSettingsGroup.setText(Messages.SystemTapScriptLaunchConfigurationTab_user);
+
+ currentUserCheckButton.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ update();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ update();
+ }
+
+ private void update(){
+ boolean enable = !currentUserCheckButton.getSelection();
+ setUserGroupEnablement(enable);
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ userNameText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ userPasswordText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ setUserGroupEnablement(false);
+
+ // Host settings
+ Group hostSettingsGroup = new Group(top, SWT.SHADOW_ETCHED_IN);
+ hostSettingsGroup.setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, false));
+ hostSettingsGroup.setText(Messages.SystemTapScriptLaunchConfigurationTab_host);
+ layout = new GridLayout();
+ hostSettingsGroup.setLayout(layout);
+ layout.numColumns = 2;
+
+ this.localHostCheckButton = new Button(hostSettingsGroup, SWT.CHECK);
+ localHostCheckButton.setText(Messages.SystemTapScriptLaunchConfigurationTab_runLocally);
+ gridData = new GridData();
+ gridData.horizontalSpan = 2;
+
+ this.hostNamelabel = new Label(hostSettingsGroup, SWT.NONE);
+ hostNamelabel.setText(Messages.SystemTapScriptLaunchConfigurationTab_hostname);
+ this.hostNameText = new Text(hostSettingsGroup, SWT.SINGLE | SWT.BORDER);
+ hostNameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
+ localHostCheckButton.setLayoutData(gridData);
+ localHostCheckButton.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ update();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ update();
+ }
+
+ private void update(){
+ updateLaunchConfigurationDialog();
+ }
+ });
+ hostNameText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+ }
+
+ private void setUserGroupEnablement(boolean enable){
+ userNameText.setEnabled(enable);
+ userNameLabel.setEnabled(enable);
+ userPasswordText.setEnabled(enable);
+ userPasswordLabel.setEnabled(enable);
+ }
+
+ private void setHostGroupEnablement(boolean enable){
+ hostNamelabel.setEnabled(enable);
+ hostNameText.setEnabled(enable);
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(SCRIPT_PATH_ATTR, this.getSelectedScriptPath());
+ configuration.setAttribute(CURRENT_USER_ATTR, true);
+ configuration.setAttribute(USER_NAME_ATTR, ""); //$NON-NLS-1$
+ configuration.setAttribute(USER_PASS_ATTR, ""); //$NON-NLS-1$
+ configuration.setAttribute(LOCAL_HOST_ATTR, true);
+ configuration.setAttribute(HOST_NAME_ATTR, ""); //$NON-NLS-1$
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration configuration) {
+ try {
+ this.scriptPathText.setText(configuration.getAttribute(SCRIPT_PATH_ATTR, "")); //$NON-NLS-1$
+ this.currentUserCheckButton.setSelection(configuration.getAttribute(CURRENT_USER_ATTR, true));
+ this.userNameText.setText(configuration.getAttribute(USER_NAME_ATTR, "")); //$NON-NLS-1$
+ this.userPasswordText.setText(configuration.getAttribute(USER_PASS_ATTR, "")); //$NON-NLS-1$
+ this.localHostCheckButton.setSelection(configuration.getAttribute(LOCAL_HOST_ATTR, true));
+ this.hostNameText.setText(configuration.getAttribute(HOST_NAME_ATTR, "")); //$NON-NLS-1$
+ } catch (CoreException e) {
+ ExceptionErrorDialog.openError(Messages.SystemTapScriptLaunchConfigurationTab_errorInitializingTab, e);
+ }
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(SCRIPT_PATH_ATTR, this.scriptPathText.getText());
+ configuration.setAttribute(CURRENT_USER_ATTR, this.currentUserCheckButton.getSelection());
+ configuration.setAttribute(USER_NAME_ATTR, this.userNameText.getText());
+ configuration.setAttribute(USER_PASS_ATTR, this.userPasswordText.getText());
+ configuration.setAttribute(LOCAL_HOST_ATTR, this.localHostCheckButton.getSelection());
+ configuration.setAttribute(HOST_NAME_ATTR, this.hostNameText.getText());
+
+ boolean enable = !currentUserCheckButton.getSelection();
+ setUserGroupEnablement(enable);
+
+ enable = !localHostCheckButton.getSelection();
+ setHostGroupEnablement(enable);
+ }
+
+ @Override
+ public boolean isValid(ILaunchConfiguration launchConfig) {
+ setErrorMessage(null);
+
+ IPath scriptPath = getScriptPath();
+ if (scriptPath == null) {
+ setErrorMessage(MessageFormat.format(Messages.SystemTapScriptLaunchConfigurationTab_fileNotFound, scriptPathText.getText()));
+ return false;
+ }
+ String extension = scriptPath.getFileExtension();
+ if (extension == null || !extension.equals("stp")) { //$NON-NLS-1$
+ setErrorMessage(Messages.SystemTapScriptLaunchConfigurationTab_fileNotStp);
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public String getName() {
+ return Messages.SystemTapScriptLaunchConfigurationTab_general;
+ }
+
+ private String getSelectedScriptPath(){
+ IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+
+ String pathString = ""; //$NON-NLS-1$
+
+ if (window != null)
+ {
+ ISelection selection = window.getSelectionService().getSelection();
+
+ // Figure out the selected systemtap script
+ if (selection instanceof TreeSelection){
+ Object selectedElement = ((TreeSelection)selection).getFirstElement();
+ if (selectedElement instanceof IFile)
+ {
+ IPath path = ((IFile)selectedElement).getLocation();
+ pathString = path.toOSString();
+ }
+ }
+
+ // If it is a text selection use the path from the active editor.
+ if (selection instanceof TextSelection){
+ IEditorPart ed = window.getActivePage().getActiveEditor();
+ if(ed.getEditorInput() instanceof PathEditorInput) {
+ pathString = ((PathEditorInput)ed.getEditorInput()).getPath().toString();
+ } else {
+ pathString = ResourceUtil.getFile(ed.getEditorInput()).getLocation().toString();
+ }
+ }
+ }
+
+ if (pathString.endsWith(".stp")) { //$NON-NLS-1$
+ return pathString;
+ }
+
+ return ""; //$NON-NLS-1$
+ }
+
+ @Override
+ public Image getImage() {
+ return AbstractUIPlugin.imageDescriptorFromPlugin(IDEPlugin.PLUGIN_ID,
+ "icons/main_tab.gif").createImage(); //$NON-NLS-1$
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationTabGroup.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationTabGroup.java
index 761f4bdece..475f6323ea 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationTabGroup.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchConfigurationTabGroup.java
@@ -17,19 +17,19 @@ import org.eclipse.debug.ui.CommonTab;
import org.eclipse.debug.ui.ILaunchConfigurationDialog;
public class SystemTapScriptLaunchConfigurationTabGroup extends
- AbstractLaunchConfigurationTabGroup {
+ AbstractLaunchConfigurationTabGroup {
- public SystemTapScriptLaunchConfigurationTabGroup() {
- }
+ public SystemTapScriptLaunchConfigurationTabGroup() {
+ }
- @Override
- public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
- AbstractLaunchConfigurationTab[] tabs = new AbstractLaunchConfigurationTab[] {
- new SystemTapScriptLaunchConfigurationTab(),
- new SystemTapScriptOptionsTab(),
- new SystemTapScriptGraphOptionsTab(),
- new CommonTab() };
- setTabs(tabs);
- }
+ @Override
+ public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
+ AbstractLaunchConfigurationTab[] tabs = new AbstractLaunchConfigurationTab[] {
+ new SystemTapScriptLaunchConfigurationTab(),
+ new SystemTapScriptOptionsTab(),
+ new SystemTapScriptGraphOptionsTab(),
+ new CommonTab() };
+ setTabs(tabs);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchShortcut.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchShortcut.java
index 3ed71d458a..3446d71c06 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchShortcut.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptLaunchShortcut.java
@@ -34,117 +34,117 @@ import org.eclipse.ui.ide.ResourceUtil;
public class SystemTapScriptLaunchShortcut extends ProfileLaunchShortcut implements ILaunchShortcut2 {
- @Override
- public void launch(IEditorPart editor, String mode) {
- String path;
- String project = null;
- if(editor.getEditorInput() instanceof PathEditorInput){
- path = ((PathEditorInput)editor.getEditorInput()).getPath().toString();
- } else {
- IFile file = ResourceUtil.getFile(editor.getEditorInput());
- path = file.getLocation().toString();
- project = file.getProject().getName();
- }
- this.searchAndLaunch(path, project);
- }
-
- @Override
- public void launch(ISelection selection, String mode) {
- IFile file = (IFile)((TreeSelection)selection).getFirstElement();
- String path = file.getLocation().toOSString();
- String project = file.getProject().getName();
- this.searchAndLaunch(path, project);
- }
-
- private void searchAndLaunch(String path, String project){
- ILaunchConfiguration configuration = findLaunchConfiguration(path, project);
- if (configuration == null){
- return;
- }
- try {
- configuration.launch(ILaunchManager.RUN_MODE, new NullProgressMonitor());
- } catch (CoreException e) {
- ExceptionErrorDialog.openError(Messages.SystemTapScriptLaunchShortcut_couldNotLaunchScript, e);
- }
-
- }
-
- private ILaunchConfiguration findLaunchConfiguration(String scriptPath, String scriptProject) {
- ILaunchConfiguration configuration = null;
- ArrayList<ILaunchConfiguration> candidateConfigurations = new ArrayList<>();
- try {
- ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
- ILaunchConfiguration[] configs = launchManager
- .getLaunchConfigurations(getLaunchConfigType());
-
- for (ILaunchConfiguration config: configs){
- if (config.getAttribute(SystemTapScriptLaunchConfigurationTab.SCRIPT_PATH_ATTR, "").equals(scriptPath)){ //$NON-NLS-1$
- candidateConfigurations.add(config);
- }
- }
-
- int candidateCount = candidateConfigurations.size();
- if (candidateCount == 0) {
- LinkedList<String> configNames = new LinkedList<>();
- configs = launchManager.getLaunchConfigurations();
- for (ILaunchConfiguration config : configs) {
- configNames.add(config.getName());
- }
- String configName = (scriptProject == null ? "" : scriptProject + " ") //$NON-NLS-1$ //$NON-NLS-2$
- + Path.fromOSString(scriptPath).lastSegment();
- String wcName = configName;
- int conflict_index, conflict_count = 0;
- while ((conflict_index = configNames.indexOf(wcName)) != -1) {
- wcName = configName.concat(String.format(" (%d)", ++conflict_count)); //$NON-NLS-1$
- configNames.remove(conflict_index);
- }
-
- ILaunchConfigurationType type = getLaunchConfigType();
- ILaunchConfigurationWorkingCopy wc = type.newInstance(null, wcName);
- wc.setAttribute(SystemTapScriptLaunchConfigurationTab.SCRIPT_PATH_ATTR, scriptPath);
- configuration = wc.doSave();
- } else if (candidateCount == 1) {
- configuration = candidateConfigurations.get(0);
- } else {
- configuration = chooseConfiguration(candidateConfigurations,
- ILaunchManager.RUN_MODE);
- }
- } catch (CoreException e) {
- ExceptionErrorDialog.openError(Messages.SystemTapScriptLaunchShortcut_couldNotFindConfig, e);
- }
-
- return configuration;
- }
-
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(
- SystemTapScriptLaunchConfigurationDelegate.CONFIGURATION_TYPE);
- }
-
- @Override
- protected void setDefaultProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
- }
-
- @Override
- public ILaunchConfiguration[] getLaunchConfigurations(ISelection selection) {
- return null;
- }
-
- @Override
- public ILaunchConfiguration[] getLaunchConfigurations(IEditorPart editorpart) {
- return null;
- }
-
- @Override
- public IResource getLaunchableResource(ISelection selection) {
- return null;
- }
-
- @Override
- public IResource getLaunchableResource(IEditorPart editorpart) {
- return null;
- }
+ @Override
+ public void launch(IEditorPart editor, String mode) {
+ String path;
+ String project = null;
+ if(editor.getEditorInput() instanceof PathEditorInput){
+ path = ((PathEditorInput)editor.getEditorInput()).getPath().toString();
+ } else {
+ IFile file = ResourceUtil.getFile(editor.getEditorInput());
+ path = file.getLocation().toString();
+ project = file.getProject().getName();
+ }
+ this.searchAndLaunch(path, project);
+ }
+
+ @Override
+ public void launch(ISelection selection, String mode) {
+ IFile file = (IFile)((TreeSelection)selection).getFirstElement();
+ String path = file.getLocation().toOSString();
+ String project = file.getProject().getName();
+ this.searchAndLaunch(path, project);
+ }
+
+ private void searchAndLaunch(String path, String project){
+ ILaunchConfiguration configuration = findLaunchConfiguration(path, project);
+ if (configuration == null){
+ return;
+ }
+ try {
+ configuration.launch(ILaunchManager.RUN_MODE, new NullProgressMonitor());
+ } catch (CoreException e) {
+ ExceptionErrorDialog.openError(Messages.SystemTapScriptLaunchShortcut_couldNotLaunchScript, e);
+ }
+
+ }
+
+ private ILaunchConfiguration findLaunchConfiguration(String scriptPath, String scriptProject) {
+ ILaunchConfiguration configuration = null;
+ ArrayList<ILaunchConfiguration> candidateConfigurations = new ArrayList<>();
+ try {
+ ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
+ ILaunchConfiguration[] configs = launchManager
+ .getLaunchConfigurations(getLaunchConfigType());
+
+ for (ILaunchConfiguration config: configs){
+ if (config.getAttribute(SystemTapScriptLaunchConfigurationTab.SCRIPT_PATH_ATTR, "").equals(scriptPath)){ //$NON-NLS-1$
+ candidateConfigurations.add(config);
+ }
+ }
+
+ int candidateCount = candidateConfigurations.size();
+ if (candidateCount == 0) {
+ LinkedList<String> configNames = new LinkedList<>();
+ configs = launchManager.getLaunchConfigurations();
+ for (ILaunchConfiguration config : configs) {
+ configNames.add(config.getName());
+ }
+ String configName = (scriptProject == null ? "" : scriptProject + " ") //$NON-NLS-1$ //$NON-NLS-2$
+ + Path.fromOSString(scriptPath).lastSegment();
+ String wcName = configName;
+ int conflict_index, conflict_count = 0;
+ while ((conflict_index = configNames.indexOf(wcName)) != -1) {
+ wcName = configName.concat(String.format(" (%d)", ++conflict_count)); //$NON-NLS-1$
+ configNames.remove(conflict_index);
+ }
+
+ ILaunchConfigurationType type = getLaunchConfigType();
+ ILaunchConfigurationWorkingCopy wc = type.newInstance(null, wcName);
+ wc.setAttribute(SystemTapScriptLaunchConfigurationTab.SCRIPT_PATH_ATTR, scriptPath);
+ configuration = wc.doSave();
+ } else if (candidateCount == 1) {
+ configuration = candidateConfigurations.get(0);
+ } else {
+ configuration = chooseConfiguration(candidateConfigurations,
+ ILaunchManager.RUN_MODE);
+ }
+ } catch (CoreException e) {
+ ExceptionErrorDialog.openError(Messages.SystemTapScriptLaunchShortcut_couldNotFindConfig, e);
+ }
+
+ return configuration;
+ }
+
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(
+ SystemTapScriptLaunchConfigurationDelegate.CONFIGURATION_TYPE);
+ }
+
+ @Override
+ protected void setDefaultProfileAttributes(ILaunchConfigurationWorkingCopy wc) {
+ }
+
+ @Override
+ public ILaunchConfiguration[] getLaunchConfigurations(ISelection selection) {
+ return null;
+ }
+
+ @Override
+ public ILaunchConfiguration[] getLaunchConfigurations(IEditorPart editorpart) {
+ return null;
+ }
+
+ @Override
+ public IResource getLaunchableResource(ISelection selection) {
+ return null;
+ }
+
+ @Override
+ public IResource getLaunchableResource(IEditorPart editorpart) {
+ return null;
+ }
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptOptionsTab.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptOptionsTab.java
index 63e525b833..ce9d746760 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptOptionsTab.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/launcher/SystemTapScriptOptionsTab.java
@@ -42,244 +42,244 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
public class SystemTapScriptOptionsTab extends AbstractLaunchConfigurationTab {
- static final String MISC_COMMANDLINE_OPTIONS = "MiscComandLineOptions"; //$NON-NLS-1$
-
- private Button checkBox[] = new Button[IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length];
- private Text text[] = new Text[IDEPreferenceConstants.STAP_STRING_OPTIONS.length];
- private Text targetProgramText;
-
- private ModifyListener modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
- private FileDialog fileDialog;
- private Text miscCommandsText;
-
- private Button dyninstCheckBox;
-
- private Text targetPidText;
-
- @Override
- public void createControl(Composite parent) {
-
- GridLayout singleColumnGridLayout = new GridLayout();
- singleColumnGridLayout.numColumns = 1;
- Composite comp = new Composite(parent, SWT.NONE);
- setControl(comp);
- comp.setLayout(singleColumnGridLayout);
- comp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- this.fileDialog = new FileDialog(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getShell(), SWT.OPEN);
- fileDialog.setText(Messages.SystemTapScriptOptionsTab_selectExec);
- fileDialog.setFilterPath(Platform.getLocation().toOSString());
- // Target Executable path
- Group targetExecutableGroup = new Group(comp, SWT.SHADOW_ETCHED_IN);
- targetExecutableGroup.setText(Messages.SystemTapScriptOptionsTab_targetExec);
- targetExecutableGroup
- .setToolTipText(Messages.SystemTapScriptOptionsTab_targetToolTip);
-
- targetExecutableGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
- true, false));
- GridLayout twoColumnGridLayout = new GridLayout();
- twoColumnGridLayout.numColumns = 2;
- targetExecutableGroup.setLayout(twoColumnGridLayout);
- this.targetProgramText = new Text(targetExecutableGroup, SWT.SINGLE
- | SWT.BORDER);
- targetProgramText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
- true));
- targetProgramText.addModifyListener(modifyListener);
- Button selectTargetProgramButton = new Button(targetExecutableGroup, 0);
- GridData gridData = new GridData();
-
- selectTargetProgramButton.setLayoutData(gridData);
- selectTargetProgramButton
- .setText(Messages.SystemTapScriptLaunchConfigurationTab_browse);
- selectTargetProgramButton.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- String fileName = fileDialog.open();
- if (fileName != null) {
- targetProgramText.setText(fileName);
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- // Check boxes
- Composite cmpChkBoxes = new Composite(comp, SWT.NONE);
- cmpChkBoxes.setLayout(twoColumnGridLayout);
- cmpChkBoxes.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
-
- for (int i = 0; i < IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length; i++) {
- checkBox[i] = new Button(cmpChkBoxes, SWT.CHECK);
- checkBox[i]
- .setText(IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.LABEL]
- + " (" + IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.FLAG] + ")"); //$NON-NLS-1$//$NON-NLS-2$
- checkBox[i].addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateLaunchConfigurationDialog();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateLaunchConfigurationDialog();
- }
- });
- checkBox[i]
- .setToolTipText(IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.TOOLTIP]);
-
- if (IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.FLAG]
- .contains(Messages.SystemTapScriptOptionsTab_dyninst)) {
- this.dyninstCheckBox = checkBox[i];
- }
- }
-
- // Labels and Text fields
- Composite cmpTxtBoxes = new Composite(comp, SWT.NONE);
- cmpTxtBoxes.setLayout(twoColumnGridLayout);
- cmpTxtBoxes.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
-
- Label label;
- for (int i = 0; i < IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
- label = new Label(cmpTxtBoxes, SWT.NONE);
- label.setText(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.LABEL]
- + " (" + IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.FLAG] + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- label.setToolTipText(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.TOOLTIP]);
- text[i] = new Text(cmpTxtBoxes, SWT.BORDER);
- text[i].setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, true));
- text[i].addModifyListener(modifyListener);
- text[i].setToolTipText(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.TOOLTIP]);
-
- if (IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.FLAG]
- .contains("-x")) { //$NON-NLS-1$
- this.targetPidText = text[i];
- }
- }
-
- label = new Label(cmpTxtBoxes, SWT.NONE);
- label.setText(Messages.SystemTapScriptOptionsTab_otherOptions);
- miscCommandsText = new Text(cmpTxtBoxes, SWT.BORDER);
- miscCommandsText.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING,
- true, true));
- miscCommandsText.addModifyListener(modifyListener);
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
- IPreferenceStore store = IDEPlugin.getDefault().getPreferenceStore();
-
- configuration.setAttribute(STAP_CMD_OPTION[KEY],
- store.getString(STAP_CMD_OPTION[IDEPreferenceConstants.KEY]));
-
- for (int i = 0; i < IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length; i++) {
- configuration
- .setAttribute(
- IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.KEY],
- store.getBoolean(IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.KEY]));
- }
-
- for (int i = 0; i < IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
- configuration
- .setAttribute(
- IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.KEY],
- store.getString(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.KEY]));
- }
-
- configuration.setAttribute(MISC_COMMANDLINE_OPTIONS,
- store.getString(MISC_COMMANDLINE_OPTIONS));
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration configuration) {
- try {
- targetProgramText.setText(configuration.getAttribute(
- STAP_CMD_OPTION[KEY], "")); //$NON-NLS-1$
-
- for (int i = 0; i < IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length; i++) {
- checkBox[i]
- .setSelection(configuration
- .getAttribute(
- IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.KEY],
- false));
- }
-
- for (int i = 0; i < IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
- text[i].setText(configuration
- .getAttribute(
- IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.KEY],
- "")); //$NON-NLS-1$
- }
-
- miscCommandsText.setText(configuration.getAttribute(
- MISC_COMMANDLINE_OPTIONS, "")); //$NON-NLS-1$
-
- } catch (Exception e) {
- ExceptionErrorDialog
- .openError(
- Messages.SystemTapScriptOptionsTab_initializeConfigurationFailed,
- e);
- }
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
-
- configuration.setAttribute(STAP_CMD_OPTION[KEY],
- targetProgramText.getText());
-
- for (int i = 0; i < STAP_BOOLEAN_OPTIONS.length; i++) {
- configuration.setAttribute(STAP_BOOLEAN_OPTIONS[i][KEY],
- checkBox[i].getSelection());
- }
-
- for (int i = 0; i < IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
- configuration.setAttribute(
- IDEPreferenceConstants.STAP_STRING_OPTIONS[i][KEY],
- text[i].getText());
- }
-
- configuration.setAttribute(MISC_COMMANDLINE_OPTIONS,
- miscCommandsText.getText());
- }
-
- @Override
- public String getName() {
- return Messages.SystemTapScriptLaunchConfigurationTab_tabName;
- }
-
- @Override
- public boolean isValid(ILaunchConfiguration launchConfig) {
- setErrorMessage(null);
-
- // If dyninst is being used a pid or a target executable must be
- // specified.
- if (this.dyninstCheckBox.getSelection()
- && this.targetProgramText.getText().isEmpty()
- && this.targetPidText.getText().isEmpty()) {
- setErrorMessage(Messages.SystemTapScriptOptionsTab_dyninstError);
- return false;
- }
-
- if (!this.targetPidText.getText().isEmpty() && !this.targetPidText.getText().matches("[0-9]*")) { //$NON-NLS-1$
- setErrorMessage(Messages.SystemTapScriptOptionsTab_pidError);
- return false;
- }
-
- return true;
- }
-
- @Override
- public Image getImage() {
- return AbstractUIPlugin.imageDescriptorFromPlugin(IDEPlugin.PLUGIN_ID,
- "icons/smileytap_small.gif").createImage(); //$NON-NLS-1$
- }
+ static final String MISC_COMMANDLINE_OPTIONS = "MiscComandLineOptions"; //$NON-NLS-1$
+
+ private Button checkBox[] = new Button[IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length];
+ private Text text[] = new Text[IDEPreferenceConstants.STAP_STRING_OPTIONS.length];
+ private Text targetProgramText;
+
+ private ModifyListener modifyListener = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+ private FileDialog fileDialog;
+ private Text miscCommandsText;
+
+ private Button dyninstCheckBox;
+
+ private Text targetPidText;
+
+ @Override
+ public void createControl(Composite parent) {
+
+ GridLayout singleColumnGridLayout = new GridLayout();
+ singleColumnGridLayout.numColumns = 1;
+ Composite comp = new Composite(parent, SWT.NONE);
+ setControl(comp);
+ comp.setLayout(singleColumnGridLayout);
+ comp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+
+ this.fileDialog = new FileDialog(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getShell(), SWT.OPEN);
+ fileDialog.setText(Messages.SystemTapScriptOptionsTab_selectExec);
+ fileDialog.setFilterPath(Platform.getLocation().toOSString());
+ // Target Executable path
+ Group targetExecutableGroup = new Group(comp, SWT.SHADOW_ETCHED_IN);
+ targetExecutableGroup.setText(Messages.SystemTapScriptOptionsTab_targetExec);
+ targetExecutableGroup
+ .setToolTipText(Messages.SystemTapScriptOptionsTab_targetToolTip);
+
+ targetExecutableGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL,
+ true, false));
+ GridLayout twoColumnGridLayout = new GridLayout();
+ twoColumnGridLayout.numColumns = 2;
+ targetExecutableGroup.setLayout(twoColumnGridLayout);
+ this.targetProgramText = new Text(targetExecutableGroup, SWT.SINGLE
+ | SWT.BORDER);
+ targetProgramText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
+ true));
+ targetProgramText.addModifyListener(modifyListener);
+ Button selectTargetProgramButton = new Button(targetExecutableGroup, 0);
+ GridData gridData = new GridData();
+
+ selectTargetProgramButton.setLayoutData(gridData);
+ selectTargetProgramButton
+ .setText(Messages.SystemTapScriptLaunchConfigurationTab_browse);
+ selectTargetProgramButton.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ String fileName = fileDialog.open();
+ if (fileName != null) {
+ targetProgramText.setText(fileName);
+ }
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+
+ // Check boxes
+ Composite cmpChkBoxes = new Composite(comp, SWT.NONE);
+ cmpChkBoxes.setLayout(twoColumnGridLayout);
+ cmpChkBoxes.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
+
+ for (int i = 0; i < IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length; i++) {
+ checkBox[i] = new Button(cmpChkBoxes, SWT.CHECK);
+ checkBox[i]
+ .setText(IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.LABEL]
+ + " (" + IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.FLAG] + ")"); //$NON-NLS-1$//$NON-NLS-2$
+ checkBox[i].addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ });
+ checkBox[i]
+ .setToolTipText(IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.TOOLTIP]);
+
+ if (IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.FLAG]
+ .contains(Messages.SystemTapScriptOptionsTab_dyninst)) {
+ this.dyninstCheckBox = checkBox[i];
+ }
+ }
+
+ // Labels and Text fields
+ Composite cmpTxtBoxes = new Composite(comp, SWT.NONE);
+ cmpTxtBoxes.setLayout(twoColumnGridLayout);
+ cmpTxtBoxes.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
+
+ Label label;
+ for (int i = 0; i < IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
+ label = new Label(cmpTxtBoxes, SWT.NONE);
+ label.setText(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.LABEL]
+ + " (" + IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.FLAG] + ")"); //$NON-NLS-1$ //$NON-NLS-2$
+ label.setToolTipText(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.TOOLTIP]);
+ text[i] = new Text(cmpTxtBoxes, SWT.BORDER);
+ text[i].setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, true));
+ text[i].addModifyListener(modifyListener);
+ text[i].setToolTipText(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.TOOLTIP]);
+
+ if (IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.FLAG]
+ .contains("-x")) { //$NON-NLS-1$
+ this.targetPidText = text[i];
+ }
+ }
+
+ label = new Label(cmpTxtBoxes, SWT.NONE);
+ label.setText(Messages.SystemTapScriptOptionsTab_otherOptions);
+ miscCommandsText = new Text(cmpTxtBoxes, SWT.BORDER);
+ miscCommandsText.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING,
+ true, true));
+ miscCommandsText.addModifyListener(modifyListener);
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
+ IPreferenceStore store = IDEPlugin.getDefault().getPreferenceStore();
+
+ configuration.setAttribute(STAP_CMD_OPTION[KEY],
+ store.getString(STAP_CMD_OPTION[IDEPreferenceConstants.KEY]));
+
+ for (int i = 0; i < IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length; i++) {
+ configuration
+ .setAttribute(
+ IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.KEY],
+ store.getBoolean(IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.KEY]));
+ }
+
+ for (int i = 0; i < IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
+ configuration
+ .setAttribute(
+ IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.KEY],
+ store.getString(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.KEY]));
+ }
+
+ configuration.setAttribute(MISC_COMMANDLINE_OPTIONS,
+ store.getString(MISC_COMMANDLINE_OPTIONS));
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration configuration) {
+ try {
+ targetProgramText.setText(configuration.getAttribute(
+ STAP_CMD_OPTION[KEY], "")); //$NON-NLS-1$
+
+ for (int i = 0; i < IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length; i++) {
+ checkBox[i]
+ .setSelection(configuration
+ .getAttribute(
+ IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.KEY],
+ false));
+ }
+
+ for (int i = 0; i < IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
+ text[i].setText(configuration
+ .getAttribute(
+ IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.KEY],
+ "")); //$NON-NLS-1$
+ }
+
+ miscCommandsText.setText(configuration.getAttribute(
+ MISC_COMMANDLINE_OPTIONS, "")); //$NON-NLS-1$
+
+ } catch (Exception e) {
+ ExceptionErrorDialog
+ .openError(
+ Messages.SystemTapScriptOptionsTab_initializeConfigurationFailed,
+ e);
+ }
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy configuration) {
+
+ configuration.setAttribute(STAP_CMD_OPTION[KEY],
+ targetProgramText.getText());
+
+ for (int i = 0; i < STAP_BOOLEAN_OPTIONS.length; i++) {
+ configuration.setAttribute(STAP_BOOLEAN_OPTIONS[i][KEY],
+ checkBox[i].getSelection());
+ }
+
+ for (int i = 0; i < IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
+ configuration.setAttribute(
+ IDEPreferenceConstants.STAP_STRING_OPTIONS[i][KEY],
+ text[i].getText());
+ }
+
+ configuration.setAttribute(MISC_COMMANDLINE_OPTIONS,
+ miscCommandsText.getText());
+ }
+
+ @Override
+ public String getName() {
+ return Messages.SystemTapScriptLaunchConfigurationTab_tabName;
+ }
+
+ @Override
+ public boolean isValid(ILaunchConfiguration launchConfig) {
+ setErrorMessage(null);
+
+ // If dyninst is being used a pid or a target executable must be
+ // specified.
+ if (this.dyninstCheckBox.getSelection()
+ && this.targetProgramText.getText().isEmpty()
+ && this.targetPidText.getText().isEmpty()) {
+ setErrorMessage(Messages.SystemTapScriptOptionsTab_dyninstError);
+ return false;
+ }
+
+ if (!this.targetPidText.getText().isEmpty() && !this.targetPidText.getText().matches("[0-9]*")) { //$NON-NLS-1$
+ setErrorMessage(Messages.SystemTapScriptOptionsTab_pidError);
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public Image getImage() {
+ return AbstractUIPlugin.imageDescriptorFromPlugin(IDEPlugin.PLUGIN_ID,
+ "icons/smileytap_small.gif").createImage(); //$NON-NLS-1$
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/CodeAssistPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/CodeAssistPreferencePage.java
index 9d4829bada..127174bac9 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/CodeAssistPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/CodeAssistPreferencePage.java
@@ -23,47 +23,47 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class CodeAssistPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- public CodeAssistPreferencePage() {
- super(GRID);
- setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
- setDescription(Localization.getString("CodeAssistPreferencePage.CodeAssistPreferenceDescription")); //$NON-NLS-1$
- }
-
- /**
- * Creates the field editors. Field editors are abstractions of
- * the common GUI blocks needed to manipulate various types
- * of preferences. Each field editor knows how to save and
- * restore itself.
- */
- @Override
- public void createFieldEditors() {
- addField(
- new BooleanFieldEditor(
- IDEPreferenceConstants.P_USE_CODE_ASSIST,
- Localization.getString("CodeAssistPreferencePage.UseCodeAssist"), //$NON-NLS-1$
- getFieldEditorParent()));
- addField(new RadioGroupFieldEditor(
- IDEPreferenceConstants.P_COMPLETION,
- Localization.getString("CodeAssistPreferencePage.HowCodeAdded"), //$NON-NLS-1$
- 1,
- new String[][] {
- {Localization.getString("CodeAssistPreferencePage.Insert"), IDEPreferenceConstants.P_COMPLETION_INSERT }, //$NON-NLS-1$
- {Localization.getString("CodeAssistPreferencePage.Overwrite"), IDEPreferenceConstants.P_COMPLETION_OVERWRITE }}, //$NON-NLS-1$
- getFieldEditorParent()));
- addField(
- new IntegerFieldEditor(
- IDEPreferenceConstants.P_ACTIVATION_DELAY,
- Localization.getString("CodeAssistPreferencePage.ActivationDelay"), //$NON-NLS-1$
- getFieldEditorParent()));
- addField(
- new StringFieldEditor(
- IDEPreferenceConstants.P_ACTIVATION_TRIGGER,
- Localization.getString("CodeAssistPreferencePage.ActivationTrigger"), //$NON-NLS-1$
- getFieldEditorParent()));
- }
+ public CodeAssistPreferencePage() {
+ super(GRID);
+ setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
+ setDescription(Localization.getString("CodeAssistPreferencePage.CodeAssistPreferenceDescription")); //$NON-NLS-1$
+ }
- @Override
- public void init(IWorkbench workbench) {
- }
+ /**
+ * Creates the field editors. Field editors are abstractions of
+ * the common GUI blocks needed to manipulate various types
+ * of preferences. Each field editor knows how to save and
+ * restore itself.
+ */
+ @Override
+ public void createFieldEditors() {
+ addField(
+ new BooleanFieldEditor(
+ IDEPreferenceConstants.P_USE_CODE_ASSIST,
+ Localization.getString("CodeAssistPreferencePage.UseCodeAssist"), //$NON-NLS-1$
+ getFieldEditorParent()));
+ addField(new RadioGroupFieldEditor(
+ IDEPreferenceConstants.P_COMPLETION,
+ Localization.getString("CodeAssistPreferencePage.HowCodeAdded"), //$NON-NLS-1$
+ 1,
+ new String[][] {
+ {Localization.getString("CodeAssistPreferencePage.Insert"), IDEPreferenceConstants.P_COMPLETION_INSERT }, //$NON-NLS-1$
+ {Localization.getString("CodeAssistPreferencePage.Overwrite"), IDEPreferenceConstants.P_COMPLETION_OVERWRITE }}, //$NON-NLS-1$
+ getFieldEditorParent()));
+ addField(
+ new IntegerFieldEditor(
+ IDEPreferenceConstants.P_ACTIVATION_DELAY,
+ Localization.getString("CodeAssistPreferencePage.ActivationDelay"), //$NON-NLS-1$
+ getFieldEditorParent()));
+ addField(
+ new StringFieldEditor(
+ IDEPreferenceConstants.P_ACTIVATION_TRIGGER,
+ Localization.getString("CodeAssistPreferencePage.ActivationTrigger"), //$NON-NLS-1$
+ getFieldEditorParent()));
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ConditionalExpressionValidator.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ConditionalExpressionValidator.java
index a400539348..f8e00c0998 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ConditionalExpressionValidator.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ConditionalExpressionValidator.java
@@ -17,30 +17,30 @@ import org.eclipse.jface.dialogs.IInputValidator;
public class ConditionalExpressionValidator implements IInputValidator {
- /**
- * Determines whether or not the string is valid within the contraints.
- *
- * @param s The string to check.
- *
- * @return The return message.
- */
- @Override
- public String isValid(String s) {
- if(null == s) {
- return Messages.ConditionalExpressionValidator_NotNull;
- }
- if(!s.startsWith("if")) {//$NON-NLS-1$
- return Messages.ConditionalExpressionValidator_MustStartWith;
- }
- if(!s.contains("(")) {//$NON-NLS-1$
- return Messages.ConditionalExpressionValidator_MustContain;
- }
- if(!s.endsWith(")")) {//$NON-NLS-1$
- return Messages.ConditionalExpressionValidator_MustEndWith;
- }
- if(s.length() < 5) {
- return Messages.ConditionalExpressionValidator_MustEnterSomething;
- }
- return null;
- }
+ /**
+ * Determines whether or not the string is valid within the contraints.
+ *
+ * @param s The string to check.
+ *
+ * @return The return message.
+ */
+ @Override
+ public String isValid(String s) {
+ if(null == s) {
+ return Messages.ConditionalExpressionValidator_NotNull;
+ }
+ if(!s.startsWith("if")) {//$NON-NLS-1$
+ return Messages.ConditionalExpressionValidator_MustStartWith;
+ }
+ if(!s.contains("(")) {//$NON-NLS-1$
+ return Messages.ConditionalExpressionValidator_MustContain;
+ }
+ if(!s.endsWith(")")) {//$NON-NLS-1$
+ return Messages.ConditionalExpressionValidator_MustEndWith;
+ }
+ if(s.length() < 5) {
+ return Messages.ConditionalExpressionValidator_MustEnterSomething;
+ }
+ return null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ConditionalFilterPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ConditionalFilterPreferencePage.java
index 1e8b7c1cee..47d1f53a4e 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ConditionalFilterPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ConditionalFilterPreferencePage.java
@@ -20,19 +20,19 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class ConditionalFilterPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- public ConditionalFilterPreferencePage() {
- super(GRID);
- setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
- setDescription(Localization.getString("ConditionalFilterPreferencePage.ConditiionalFilterSelector")); //$NON-NLS-1$
- }
-
- @Override
- public void createFieldEditors() {
- addField(new ListEditor(IDEPreferenceConstants.P_CONDITIONAL_FILTERS,
- Localization.getString("ConditionalFilterPreferencePage.ConditionalFilters"), Localization.getString("ConditionalFilterPreferencePage.NewFilter"), "if()", new ConditionalExpressionValidator(), getFieldEditorParent())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
+ public ConditionalFilterPreferencePage() {
+ super(GRID);
+ setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
+ setDescription(Localization.getString("ConditionalFilterPreferencePage.ConditiionalFilterSelector")); //$NON-NLS-1$
+ }
- @Override
- public void init(IWorkbench workbench) {
- }
+ @Override
+ public void createFieldEditors() {
+ addField(new ListEditor(IDEPreferenceConstants.P_CONDITIONAL_FILTERS,
+ Localization.getString("ConditionalFilterPreferencePage.ConditionalFilters"), Localization.getString("ConditionalFilterPreferencePage.NewFilter"), "if()", new ConditionalExpressionValidator(), getFieldEditorParent())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/DirectoryValidator.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/DirectoryValidator.java
index 748fa2d245..8f082442bc 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/DirectoryValidator.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/DirectoryValidator.java
@@ -17,27 +17,27 @@ import org.eclipse.jface.dialogs.IInputValidator;
public class DirectoryValidator implements IInputValidator {
- /**
- * Determines whether or not the string is valid within the contraints.
- *
- * @param s The string to check.
- *
- * @return The return message.
- */
- @Override
- public String isValid(String s) {
- if(null == s) {
- return Messages.DirectoryValidator_NotNull;
- }
- if(s.length() < 1) {
- return Messages.DirectoryValidator_FolderName;
- }
- if(!s.endsWith("/")) {//$NON-NLS-1$
- return Messages.DirectoryValidator_MustEnd;
- }
- if(s.contains("//")) {//$NON-NLS-1$
- return Messages.DirectoryValidator_CanNotContain;
- }
- return null;
- }
+ /**
+ * Determines whether or not the string is valid within the contraints.
+ *
+ * @param s The string to check.
+ *
+ * @return The return message.
+ */
+ @Override
+ public String isValid(String s) {
+ if(null == s) {
+ return Messages.DirectoryValidator_NotNull;
+ }
+ if(s.length() < 1) {
+ return Messages.DirectoryValidator_FolderName;
+ }
+ if(!s.endsWith("/")) {//$NON-NLS-1$
+ return Messages.DirectoryValidator_MustEnd;
+ }
+ if(s.contains("//")) {//$NON-NLS-1$
+ return Messages.DirectoryValidator_CanNotContain;
+ }
+ return null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/EditorPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/EditorPreferencePage.java
index 1fbea1b548..1d14b17359 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/EditorPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/EditorPreferencePage.java
@@ -21,25 +21,25 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class EditorPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- public EditorPreferencePage() {
- super(GRID);
- setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
- setDescription(Localization.getString("EditorPreferencePage.EditorPreferenceDescription")); //$NON-NLS-1$
- }
-
- @Override
- public void createFieldEditors() {
- addField(new ColorFieldEditor(
- IDEPreferenceConstants.P_EDITOR_BACKGROUND,
- Localization.getString("EditorPreferencePage.BackgroundColor"), getFieldEditorParent())); //$NON-NLS-1$
-
- addField(new BooleanFieldEditor(
- IDEPreferenceConstants.P_SHOW_LINE_NUMBERS,
- Localization.getString("EditorPreferencePage.ShowLineNumbers"), //$NON-NLS-1$
- getFieldEditorParent()));
- }
+ public EditorPreferencePage() {
+ super(GRID);
+ setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
+ setDescription(Localization.getString("EditorPreferencePage.EditorPreferenceDescription")); //$NON-NLS-1$
+ }
- @Override
- public void init(IWorkbench workbench) {
- }
+ @Override
+ public void createFieldEditors() {
+ addField(new ColorFieldEditor(
+ IDEPreferenceConstants.P_EDITOR_BACKGROUND,
+ Localization.getString("EditorPreferencePage.BackgroundColor"), getFieldEditorParent())); //$NON-NLS-1$
+
+ addField(new BooleanFieldEditor(
+ IDEPreferenceConstants.P_SHOW_LINE_NUMBERS,
+ Localization.getString("EditorPreferencePage.ShowLineNumbers"), //$NON-NLS-1$
+ getFieldEditorParent()));
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/EnvironmentVariablesPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/EnvironmentVariablesPreferencePage.java
index 5426114c45..c5f1af46e2 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/EnvironmentVariablesPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/EnvironmentVariablesPreferencePage.java
@@ -28,132 +28,132 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class EnvironmentVariablesPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
- /**
- * Set the description of the page.
- */
- public EnvironmentVariablesPreferencePage() {
- super();
- setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
- setDescription(Messages.EnvironmentVariablesPreferencePage_Title);
- }
-
- @Override
- public void init(IWorkbench workbench) {
- }
-
- /**
- * Creates a ScrolledComposite, sets options on oit, opens string field editors for the
- * preferences.
- *
- * @param parent The parent of the ScrolledComposite object.
- *
- * @return The ScrolledComposite object that is created configured.
- */
- @Override
- protected Control createContents(Composite parent) {
- ScrolledComposite sc = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL );
- Composite c = new Composite(sc, SWT.NONE);
- sc.setExpandHorizontal(true);
- sc.setExpandVertical(true);
- sc.setContent(c);
-
- envVariables = new StringFieldEditor[PreferenceConstants.P_ENV.length];
- for(int i=0; i<envVariables.length; i++) {
- envVariables[i] = createStringFieldEditor(PreferenceConstants.P_ENV[i][0],
- PreferenceConstants.P_ENV[i][1], c);
- }
- return sc;
- }
-
- /**
- * Creates and returns a StringFieldEditor object with preferences set to it.
- *
- * @param name Name of the field.
- * @param lblText Label text of the field.
- * @param parent Composite object parent of the object.
- *
- * @return The created and configued StringFieldEditor ojbect.
- */
- private StringFieldEditor createStringFieldEditor(String name, String lblText, Composite parent) {
- StringFieldEditor sfe = new StringFieldEditor(name, lblText, parent);
- sfe.setPage(this);
- sfe.setPreferenceStore(getPreferenceStore());
- sfe.load();
-
- return sfe;
- }
-
- /**
- * Loads the default environment variables.
- */
- @Override
- protected void performDefaults() {
- for (StringFieldEditor envVariable : envVariables) {
- envVariable.loadDefault();
- }
-
- super.performDefaults();
- }
-
- /**
- * Stores the modified environment variables.
- *
- * @return True.
- */
- @Override
- public boolean performOk() {
- for (StringFieldEditor envVariable : envVariables) {
- envVariable.store();
- }
-
- return true;
- }
-
- /**
- * Returns the currently stored environment variables in the form of a string array.
- *
- * @return The string array containing the current environment variables.
- */
- public static String[] getEnvironmentVariables() {
- ArrayList<String> vars = new ArrayList<>();
- String[] envVars = null;
- String var;
-
- int i;
- if(null == IDEPlugin.getDefault() || null == IDEPlugin.getDefault().getPreferenceStore()) {
- return null;
- }
- IPreferenceStore p = IDEPlugin.getDefault().getPreferenceStore();
- for(i=0; i<PreferenceConstants.P_ENV.length; i++) {
- var = p.getString(PreferenceConstants.P_ENV[i][0]).trim();
- if(!var.isEmpty()) {
- vars.add(PreferenceConstants.P_ENV[i][0] + "=" + var); //$NON-NLS-1$
- }
- }
-
- if(vars.size() > 0) {
- envVars = new String[vars.size()];
- for (i = 0; i < vars.size(); i++) {
- envVars[i] = vars.get(i);
- }
- }
-
- return envVars;
- }
-
- /**
- * Clears the environment variables string array.
- */
- @Override
- public void dispose() {
- super.dispose();
-
- for(int i=0; i<envVariables.length; i++) {
- envVariables[i].dispose();
- envVariables[i] = null;
- }
- envVariables = null;
- }
-
- private static StringFieldEditor[] envVariables;
+ /**
+ * Set the description of the page.
+ */
+ public EnvironmentVariablesPreferencePage() {
+ super();
+ setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
+ setDescription(Messages.EnvironmentVariablesPreferencePage_Title);
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ }
+
+ /**
+ * Creates a ScrolledComposite, sets options on oit, opens string field editors for the
+ * preferences.
+ *
+ * @param parent The parent of the ScrolledComposite object.
+ *
+ * @return The ScrolledComposite object that is created configured.
+ */
+ @Override
+ protected Control createContents(Composite parent) {
+ ScrolledComposite sc = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL );
+ Composite c = new Composite(sc, SWT.NONE);
+ sc.setExpandHorizontal(true);
+ sc.setExpandVertical(true);
+ sc.setContent(c);
+
+ envVariables = new StringFieldEditor[PreferenceConstants.P_ENV.length];
+ for(int i=0; i<envVariables.length; i++) {
+ envVariables[i] = createStringFieldEditor(PreferenceConstants.P_ENV[i][0],
+ PreferenceConstants.P_ENV[i][1], c);
+ }
+ return sc;
+ }
+
+ /**
+ * Creates and returns a StringFieldEditor object with preferences set to it.
+ *
+ * @param name Name of the field.
+ * @param lblText Label text of the field.
+ * @param parent Composite object parent of the object.
+ *
+ * @return The created and configued StringFieldEditor ojbect.
+ */
+ private StringFieldEditor createStringFieldEditor(String name, String lblText, Composite parent) {
+ StringFieldEditor sfe = new StringFieldEditor(name, lblText, parent);
+ sfe.setPage(this);
+ sfe.setPreferenceStore(getPreferenceStore());
+ sfe.load();
+
+ return sfe;
+ }
+
+ /**
+ * Loads the default environment variables.
+ */
+ @Override
+ protected void performDefaults() {
+ for (StringFieldEditor envVariable : envVariables) {
+ envVariable.loadDefault();
+ }
+
+ super.performDefaults();
+ }
+
+ /**
+ * Stores the modified environment variables.
+ *
+ * @return True.
+ */
+ @Override
+ public boolean performOk() {
+ for (StringFieldEditor envVariable : envVariables) {
+ envVariable.store();
+ }
+
+ return true;
+ }
+
+ /**
+ * Returns the currently stored environment variables in the form of a string array.
+ *
+ * @return The string array containing the current environment variables.
+ */
+ public static String[] getEnvironmentVariables() {
+ ArrayList<String> vars = new ArrayList<>();
+ String[] envVars = null;
+ String var;
+
+ int i;
+ if(null == IDEPlugin.getDefault() || null == IDEPlugin.getDefault().getPreferenceStore()) {
+ return null;
+ }
+ IPreferenceStore p = IDEPlugin.getDefault().getPreferenceStore();
+ for(i=0; i<PreferenceConstants.P_ENV.length; i++) {
+ var = p.getString(PreferenceConstants.P_ENV[i][0]).trim();
+ if(!var.isEmpty()) {
+ vars.add(PreferenceConstants.P_ENV[i][0] + "=" + var); //$NON-NLS-1$
+ }
+ }
+
+ if(vars.size() > 0) {
+ envVars = new String[vars.size()];
+ for (i = 0; i < vars.size(); i++) {
+ envVars[i] = vars.get(i);
+ }
+ }
+
+ return envVars;
+ }
+
+ /**
+ * Clears the environment variables string array.
+ */
+ @Override
+ public void dispose() {
+ super.dispose();
+
+ for(int i=0; i<envVariables.length; i++) {
+ envVariables[i].dispose();
+ envVariables[i] = null;
+ }
+ envVariables = null;
+ }
+
+ private static StringFieldEditor[] envVariables;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/IDEPreferenceConstants.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/IDEPreferenceConstants.java
index 7def8d0c75..285f1d100f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/IDEPreferenceConstants.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/IDEPreferenceConstants.java
@@ -12,69 +12,69 @@
package org.eclipse.linuxtools.internal.systemtap.ui.ide.preferences;
public class IDEPreferenceConstants {
- //ide
- public static final String P_STORED_TREE = "UseStoredTreePreference"; //$NON-NLS-1$
- public static final String P_REMOTE_PROBES = "RemoteProbes"; //$NON-NLS-1$
+ //ide
+ public static final String P_STORED_TREE = "UseStoredTreePreference"; //$NON-NLS-1$
+ public static final String P_REMOTE_PROBES = "RemoteProbes"; //$NON-NLS-1$
- //ide.path
- public static final String P_KERNEL_SOURCE = "KernelSourcePreference"; //$NON-NLS-1$
- public static final String P_EXCLUDED_KERNEL_SOURCE = "ExcludedKernelSource"; //$NON-NLS-1$
- public static final String P_REMOTE_LOCAL_KERNEL_SOURCE = "RemoteLocalKernelSource"; //$NON-NLS-1$
+ //ide.path
+ public static final String P_KERNEL_SOURCE = "KernelSourcePreference"; //$NON-NLS-1$
+ public static final String P_EXCLUDED_KERNEL_SOURCE = "ExcludedKernelSource"; //$NON-NLS-1$
+ public static final String P_REMOTE_LOCAL_KERNEL_SOURCE = "RemoteLocalKernelSource"; //$NON-NLS-1$
- //ide.stap.tapsets
- public static final String P_TAPSETS = "TapsetPreference"; //$NON-NLS-1$
+ //ide.stap.tapsets
+ public static final String P_TAPSETS = "TapsetPreference"; //$NON-NLS-1$
- //ide.editor
- public static final String P_EDITOR_BACKGROUND = "EditorBackgroundPreference"; //$NON-NLS-1$
- public static final String P_SHOW_LINE_NUMBERS = "ShowLineNumbers"; //$NON-NLS-1$
+ //ide.editor
+ public static final String P_EDITOR_BACKGROUND = "EditorBackgroundPreference"; //$NON-NLS-1$
+ public static final String P_SHOW_LINE_NUMBERS = "ShowLineNumbers"; //$NON-NLS-1$
- //ide.editor.codeassist
- public static final String P_USE_CODE_ASSIST = "UseCodeAssistPreference"; //$NON-NLS-1$
- public static final String P_COMPLETION = "CompletionPreference"; //$NON-NLS-1$
- public static final String P_COMPLETION_INSERT = "CompletionInsertPreference"; //$NON-NLS-1$
- public static final String P_COMPLETION_OVERWRITE = "CompletionOverwritePreference"; //$NON-NLS-1$
- public static final String P_ACTIVATION_DELAY = "ActivationDelayPreference"; //$NON-NLS-1$
- public static final String P_ACTIVATION_TRIGGER = "ActivationTriggerPreference"; //$NON-NLS-1$
+ //ide.editor.codeassist
+ public static final String P_USE_CODE_ASSIST = "UseCodeAssistPreference"; //$NON-NLS-1$
+ public static final String P_COMPLETION = "CompletionPreference"; //$NON-NLS-1$
+ public static final String P_COMPLETION_INSERT = "CompletionInsertPreference"; //$NON-NLS-1$
+ public static final String P_COMPLETION_OVERWRITE = "CompletionOverwritePreference"; //$NON-NLS-1$
+ public static final String P_ACTIVATION_DELAY = "ActivationDelayPreference"; //$NON-NLS-1$
+ public static final String P_ACTIVATION_TRIGGER = "ActivationTriggerPreference"; //$NON-NLS-1$
- //ide.editor.preferenceconstants
- public static final String P_CONDITIONAL_FILTERS = "ConditionalFilters"; //$NON-NLS-1$
+ //ide.editor.preferenceconstants
+ public static final String P_CONDITIONAL_FILTERS = "ConditionalFilters"; //$NON-NLS-1$
- public static final int FLAG = 0;
- public static final int LABEL = 1;
- public static final int KEY = 2;
- public static final int TOOLTIP = 3;
+ public static final int FLAG = 0;
+ public static final int LABEL = 1;
+ public static final int KEY = 2;
+ public static final int TOOLTIP = 3;
- public static final String[][] STAP_BOOLEAN_OPTIONS = new String[][] {
- {"-k", "Keep temporary directory", "kStapPreference", "Keep the temporary directory after all processing. This may be useful in order to examine the generated C code, or to reuse the compiled kernel object."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- {"-u", "Unoptimized translation", "uStapPreference", "Unoptimized mode. Disable unused code elision during elabora‐tion."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- {"-b", "Bulk (relayfs) mode", "bStapPreference", "Use bulk mode (percpu files) for kernel-to-user data transfer."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- {"-t", "Benchmarking timing information", "tStapPreference", "Collect timing information on the number of times probe executes and average amount of time spent in each probe-point. Also shows the derivation for each probe-point."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- {"-v", "Increase verbosity", "vStapPreference", "Increase verbosity for all passes."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- {"--runtime=dyninst", "Use dyninst", "dyninstStapPreference", "Dyninst mode allows you to probe userspace processes without root access. This mode requires a -c COMMAND or a -x PID"}}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ public static final String[][] STAP_BOOLEAN_OPTIONS = new String[][] {
+ {"-k", "Keep temporary directory", "kStapPreference", "Keep the temporary directory after all processing. This may be useful in order to examine the generated C code, or to reuse the compiled kernel object."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ {"-u", "Unoptimized translation", "uStapPreference", "Unoptimized mode. Disable unused code elision during elabora‐tion."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ {"-b", "Bulk (relayfs) mode", "bStapPreference", "Use bulk mode (percpu files) for kernel-to-user data transfer."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ {"-t", "Benchmarking timing information", "tStapPreference", "Collect timing information on the number of times probe executes and average amount of time spent in each probe-point. Also shows the derivation for each probe-point."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ {"-v", "Increase verbosity", "vStapPreference", "Increase verbosity for all passes."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ {"--runtime=dyninst", "Use dyninst", "dyninstStapPreference", "Dyninst mode allows you to probe userspace processes without root access. This mode requires a -c COMMAND or a -x PID"}}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- public static final String[][] STAP_STRING_OPTIONS = new String[][] {
- {"-p", "Stop at pass", "pStapPreference", "Stop after the given pass number. The passes are numbered 1-5: parse, elaborate, translate, compile, run."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- {"-s", "Buffer size", "sStapPreference", "The size of the buffer in megabytes used for kernel-to-user data transfer. On a multiprocessor in bulk mode, this is a per-processor amount."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- {"-R", "Runtime directory", "RStapPreference", "Look for the systemtap runtime sources in the given directory."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- {"-r", "Kernel release", "rStapPreference", "Specify a kernel version to use"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- {"-o", "Output file", "oStapPreference", "Send standard output to the given file"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- {"-x", "Target PID", "xStapPreference", "Set target() to the given PID. This allows scripts to be written that filter on a specific process."}}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ public static final String[][] STAP_STRING_OPTIONS = new String[][] {
+ {"-p", "Stop at pass", "pStapPreference", "Stop after the given pass number. The passes are numbered 1-5: parse, elaborate, translate, compile, run."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ {"-s", "Buffer size", "sStapPreference", "The size of the buffer in megabytes used for kernel-to-user data transfer. On a multiprocessor in bulk mode, this is a per-processor amount."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ {"-R", "Runtime directory", "RStapPreference", "Look for the systemtap runtime sources in the given directory."}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ {"-r", "Kernel release", "rStapPreference", "Specify a kernel version to use"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ {"-o", "Output file", "oStapPreference", "Send standard output to the given file"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ {"-x", "Target PID", "xStapPreference", "Set target() to the given PID. This allows scripts to be written that filter on a specific process."}}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- public static final String[] STAP_CMD_OPTION = new String[] {"-c", "CMD run CMD under systemtap", "cStapPreference", "start the probes, run CMD, and exit when it finishes"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ public static final String[] STAP_CMD_OPTION = new String[] {"-c", "CMD run CMD under systemtap", "cStapPreference", "start the probes, run CMD, and exit when it finishes"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- //ide.editor.syntaxcoloring
- public static final String P_STP_DEFAULT_COLOR = "stpDefaultColorPreference"; //$NON-NLS-1$
- public static final String P_STP_KEYWORD_COLOR = "stpKeywordColorPreference"; //$NON-NLS-1$
- public static final String P_STP_EMBEDDED_C_COLOR = "stpEmbeddedCColorPreference"; //$NON-NLS-1$
- public static final String P_STP_EMBEDDED_COLOR = "stpEmbeddedColorPreference"; //$NON-NLS-1$
- public static final String P_STP_COMMENT_COLOR = "stpCommentColorPreference"; //$NON-NLS-1$
- public static final String P_STP_TYPE_COLOR = "stpTypeColorPreference"; //$NON-NLS-1$
- public static final String P_STP_STRING_COLOR = "stpStringColorPreference"; //$NON-NLS-1$
- public static final String P_C_DEFAULT_COLOR = "cDefaultColorPreference"; //$NON-NLS-1$
- public static final String P_C_KEYWORD_COLOR = "cKeywordColorPreference"; //$NON-NLS-1$
- public static final String P_C_COMMENT_COLOR = "cCommentColorPreference"; //$NON-NLS-1$
- public static final String P_C_PREPROCESSOR_COLOR = "cPreprocessorColorPreference"; //$NON-NLS-1$
- public static final String P_C_TYPE_COLOR = "cTypeColorPreference"; //$NON-NLS-1$
- public static final String P_C_STRING_COLOR = "cStringColorPreference"; //$NON-NLS-1$
+ //ide.editor.syntaxcoloring
+ public static final String P_STP_DEFAULT_COLOR = "stpDefaultColorPreference"; //$NON-NLS-1$
+ public static final String P_STP_KEYWORD_COLOR = "stpKeywordColorPreference"; //$NON-NLS-1$
+ public static final String P_STP_EMBEDDED_C_COLOR = "stpEmbeddedCColorPreference"; //$NON-NLS-1$
+ public static final String P_STP_EMBEDDED_COLOR = "stpEmbeddedColorPreference"; //$NON-NLS-1$
+ public static final String P_STP_COMMENT_COLOR = "stpCommentColorPreference"; //$NON-NLS-1$
+ public static final String P_STP_TYPE_COLOR = "stpTypeColorPreference"; //$NON-NLS-1$
+ public static final String P_STP_STRING_COLOR = "stpStringColorPreference"; //$NON-NLS-1$
+ public static final String P_C_DEFAULT_COLOR = "cDefaultColorPreference"; //$NON-NLS-1$
+ public static final String P_C_KEYWORD_COLOR = "cKeywordColorPreference"; //$NON-NLS-1$
+ public static final String P_C_COMMENT_COLOR = "cCommentColorPreference"; //$NON-NLS-1$
+ public static final String P_C_PREPROCESSOR_COLOR = "cPreprocessorColorPreference"; //$NON-NLS-1$
+ public static final String P_C_TYPE_COLOR = "cTypeColorPreference"; //$NON-NLS-1$
+ public static final String P_C_STRING_COLOR = "cStringColorPreference"; //$NON-NLS-1$
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/IDEPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/IDEPreferencePage.java
index 3badd1607c..074bba7255 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/IDEPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/IDEPreferencePage.java
@@ -20,26 +20,26 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class IDEPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- public IDEPreferencePage() {
- super(GRID);
- setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
- setDescription("Preferences when loading the IDE perspective"); //$NON-NLS-1$
- }
-
- @Override
- public void createFieldEditors() {
- addField(new BooleanFieldEditor(
- IDEPreferenceConstants.P_STORED_TREE,
- Localization.getString("IDEPreferencePage.UseStoredTapsetTree"), //$NON-NLS-1$
- getFieldEditorParent()));
- addField(new BooleanFieldEditor(
- IDEPreferenceConstants.P_REMOTE_PROBES,
- Localization.getString("IDEPreferencePage.RemoteProbes"), //$NON-NLS-1$
- getFieldEditorParent()));
- }
+ public IDEPreferencePage() {
+ super(GRID);
+ setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
+ setDescription("Preferences when loading the IDE perspective"); //$NON-NLS-1$
+ }
- @Override
- public void init(IWorkbench workbench) {
- }
+ @Override
+ public void createFieldEditors() {
+ addField(new BooleanFieldEditor(
+ IDEPreferenceConstants.P_STORED_TREE,
+ Localization.getString("IDEPreferencePage.UseStoredTapsetTree"), //$NON-NLS-1$
+ getFieldEditorParent()));
+ addField(new BooleanFieldEditor(
+ IDEPreferenceConstants.P_REMOTE_PROBES,
+ Localization.getString("IDEPreferencePage.RemoteProbes"), //$NON-NLS-1$
+ getFieldEditorParent()));
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ListEditor.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ListEditor.java
index 9b47133022..a7c7397b06 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ListEditor.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/ListEditor.java
@@ -29,14 +29,14 @@ public class ListEditor extends org.eclipse.jface.preference.ListEditor {
}
/**
- * Creates and populates a StringBuffer with the supplied items.
- *
- * @param items An array of strings to make the StringBuffer with.
- *
- * @return Returns the StringBuffer.
- */
- @Override
- protected String createList(String[] items) {
+ * Creates and populates a StringBuffer with the supplied items.
+ *
+ * @param items An array of strings to make the StringBuffer with.
+ *
+ * @return Returns the StringBuffer.
+ */
+ @Override
+ protected String createList(String[] items) {
StringBuffer path = new StringBuffer();
for (String item: items) {
@@ -47,22 +47,22 @@ public class ListEditor extends org.eclipse.jface.preference.ListEditor {
}
@Override
- protected String getNewInputObject() {
- InputDialog dialog = new InputDialog(getShell(), dialogTitle, null, initialVal, validator);
- dialog.open();
+ protected String getNewInputObject() {
+ InputDialog dialog = new InputDialog(getShell(), dialogTitle, null, initialVal, validator);
+ dialog.open();
return dialog.getValue();
}
/**
- * Parses the passed in string into an array of strings.
- *
- * @param stringList The string to pass parse.
- *
- * @return Returns the array of strings.
- */
- @Override
- protected String[] parseString(String stringList) {
+ * Parses the passed in string into an array of strings.
+ *
+ * @param stringList The string to pass parse.
+ *
+ * @return Returns the array of strings.
+ */
+ @Override
+ protected String[] parseString(String stringList) {
StringTokenizer st = new StringTokenizer(stringList, File.pathSeparator + "\n\r"); //$NON-NLS-1$
ArrayList<Object> v = new ArrayList<>();
while (st.hasMoreElements()) {
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/LocalRemoteDirectoryEditor.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/LocalRemoteDirectoryEditor.java
index 3ca803ac05..bed12b7c0a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/LocalRemoteDirectoryEditor.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/LocalRemoteDirectoryEditor.java
@@ -16,41 +16,41 @@ import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
public class LocalRemoteDirectoryEditor extends DirectoryFieldEditor {
- private boolean remote, isEnabled = true;
- public LocalRemoteDirectoryEditor(String name, String labelText, Composite parent, boolean remote) {
- super(name, labelText, parent);
- this.setRemote(remote, parent);
- }
-
- public boolean getRemote() {
- return this.remote;
- }
-
- public void setRemote(boolean remote, Composite parent) {
- this.remote = remote;
- Button b = getChangeControl(parent);
- if (isEnabled)
- b.setEnabled(!remote);
- }
-
- @Override
- public String changePressed() {
- if (this.remote)
- return ""; //$NON-NLS-1$
- return super.changePressed();
- }
-
- @Override
- protected boolean doCheckState() {
- if (this.remote)
- return true;
- return super.doCheckState();
- }
-
- @Override
- public void setEnabled(boolean enabled, Composite parent) {
- super.setEnabled(enabled, parent);
- isEnabled = enabled;
- this.setRemote(this.remote, parent);
- }
+ private boolean remote, isEnabled = true;
+ public LocalRemoteDirectoryEditor(String name, String labelText, Composite parent, boolean remote) {
+ super(name, labelText, parent);
+ this.setRemote(remote, parent);
+ }
+
+ public boolean getRemote() {
+ return this.remote;
+ }
+
+ public void setRemote(boolean remote, Composite parent) {
+ this.remote = remote;
+ Button b = getChangeControl(parent);
+ if (isEnabled)
+ b.setEnabled(!remote);
+ }
+
+ @Override
+ public String changePressed() {
+ if (this.remote)
+ return ""; //$NON-NLS-1$
+ return super.changePressed();
+ }
+
+ @Override
+ protected boolean doCheckState() {
+ if (this.remote)
+ return true;
+ return super.doCheckState();
+ }
+
+ @Override
+ public void setEnabled(boolean enabled, Composite parent) {
+ super.setEnabled(enabled, parent);
+ isEnabled = enabled;
+ this.setRemote(this.remote, parent);
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/Messages.java
index 2ddf95b65a..6a175ed1d0 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/Messages.java
@@ -13,23 +13,23 @@ package org.eclipse.linuxtools.internal.systemtap.ui.ide.preferences;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.preferences.messages"; //$NON-NLS-1$
- public static String ConditionalExpressionValidator_MustContain;
- public static String ConditionalExpressionValidator_MustEndWith;
- public static String ConditionalExpressionValidator_MustEnterSomething;
- public static String ConditionalExpressionValidator_MustStartWith;
- public static String ConditionalExpressionValidator_NotNull;
- public static String DirectoryValidator_CanNotContain;
- public static String DirectoryValidator_FolderName;
- public static String DirectoryValidator_MustEnd;
- public static String DirectoryValidator_NotNull;
- public static String EnvironmentVariablesPreferencePage_Title;
- public static String SystemTapPreferencePageDescription;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.preferences.messages"; //$NON-NLS-1$
+ public static String ConditionalExpressionValidator_MustContain;
+ public static String ConditionalExpressionValidator_MustEndWith;
+ public static String ConditionalExpressionValidator_MustEnterSomething;
+ public static String ConditionalExpressionValidator_MustStartWith;
+ public static String ConditionalExpressionValidator_NotNull;
+ public static String DirectoryValidator_CanNotContain;
+ public static String DirectoryValidator_FolderName;
+ public static String DirectoryValidator_MustEnd;
+ public static String DirectoryValidator_NotNull;
+ public static String EnvironmentVariablesPreferencePage_Title;
+ public static String SystemTapPreferencePageDescription;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PathPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PathPreferencePage.java
index 99f1946d57..25da7767ab 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PathPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PathPreferencePage.java
@@ -22,55 +22,55 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class PathPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- public static final String REMOTE = "remote"; //$NON-NLS-1$
- public static final String LOCAL = "local"; //$NON-NLS-1$
- private LocalRemoteDirectoryEditor directoryEditor;
+ public static final String REMOTE = "remote"; //$NON-NLS-1$
+ public static final String LOCAL = "local"; //$NON-NLS-1$
+ private LocalRemoteDirectoryEditor directoryEditor;
- public PathPreferencePage() {
- super(GRID);
- setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
- }
+ public PathPreferencePage() {
+ super(GRID);
+ setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
+ }
- @Override
- public void createFieldEditors() {
- Composite parent = getFieldEditorParent();
- String labels[][] = {{Localization.getString("PathPreferencePage.LocalMachine"), LOCAL}, //$NON-NLS-1$
- {Localization.getString("PathPreferencePage.RemoteMachine"), REMOTE}}; //$NON-NLS-1$
- RadioGroupFieldEditor radioEditor = new RadioGroupFieldEditor(IDEPreferenceConstants.P_REMOTE_LOCAL_KERNEL_SOURCE,
- Localization.getString("PathPreferencePage.RemoteOrLocalRadio"), 1, labels, parent, true) { //$NON-NLS-1$
- @Override
- protected void fireValueChanged(String property,
- Object oldValue,
- Object newValue){
- super.fireValueChanged(property, oldValue, newValue);
- if (!oldValue.equals(newValue) && directoryEditor != null) {
- if (newValue.equals(REMOTE))
- directoryEditor.setRemote(true, getFieldEditorParent());
- else
- directoryEditor.setRemote(false, getFieldEditorParent());
- }
- }
- };
- addField(radioEditor);
+ @Override
+ public void createFieldEditors() {
+ Composite parent = getFieldEditorParent();
+ String labels[][] = {{Localization.getString("PathPreferencePage.LocalMachine"), LOCAL}, //$NON-NLS-1$
+ {Localization.getString("PathPreferencePage.RemoteMachine"), REMOTE}}; //$NON-NLS-1$
+ RadioGroupFieldEditor radioEditor = new RadioGroupFieldEditor(IDEPreferenceConstants.P_REMOTE_LOCAL_KERNEL_SOURCE,
+ Localization.getString("PathPreferencePage.RemoteOrLocalRadio"), 1, labels, parent, true) { //$NON-NLS-1$
+ @Override
+ protected void fireValueChanged(String property,
+ Object oldValue,
+ Object newValue){
+ super.fireValueChanged(property, oldValue, newValue);
+ if (!oldValue.equals(newValue) && directoryEditor != null) {
+ if (newValue.equals(REMOTE))
+ directoryEditor.setRemote(true, getFieldEditorParent());
+ else
+ directoryEditor.setRemote(false, getFieldEditorParent());
+ }
+ }
+ };
+ addField(radioEditor);
- IPreferenceStore p = IDEPlugin.getDefault().getPreferenceStore();
- String remoteOrLocal = p.getString(IDEPreferenceConstants.P_REMOTE_LOCAL_KERNEL_SOURCE);
- boolean remote;
- if (remoteOrLocal.equals(REMOTE))
- remote = true;
- else
- remote = false;
+ IPreferenceStore p = IDEPlugin.getDefault().getPreferenceStore();
+ String remoteOrLocal = p.getString(IDEPreferenceConstants.P_REMOTE_LOCAL_KERNEL_SOURCE);
+ boolean remote;
+ if (remoteOrLocal.equals(REMOTE))
+ remote = true;
+ else
+ remote = false;
- directoryEditor = new LocalRemoteDirectoryEditor(IDEPreferenceConstants.P_KERNEL_SOURCE,
- Localization.getString("PathPreferencePage.KernelSourceDirectory"), parent, remote); //$NON-NLS-1$
- addField(directoryEditor);
+ directoryEditor = new LocalRemoteDirectoryEditor(IDEPreferenceConstants.P_KERNEL_SOURCE,
+ Localization.getString("PathPreferencePage.KernelSourceDirectory"), parent, remote); //$NON-NLS-1$
+ addField(directoryEditor);
- addField(new ListEditor(IDEPreferenceConstants.P_EXCLUDED_KERNEL_SOURCE,
- Localization.getString("PathPreferencePage.ExcludedSourceFolders"), Localization.getString("PathPreferencePage.ExcludedDirectory"), "", new DirectoryValidator(), parent)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ addField(new ListEditor(IDEPreferenceConstants.P_EXCLUDED_KERNEL_SOURCE,
+ Localization.getString("PathPreferencePage.ExcludedSourceFolders"), Localization.getString("PathPreferencePage.ExcludedDirectory"), "", new DirectoryValidator(), parent)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
+ }
- @Override
- public void init(IWorkbench workbench) {
- }
+ @Override
+ public void init(IWorkbench workbench) {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PreferenceConstants.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PreferenceConstants.java
index 2a4e151457..fc5a779515 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PreferenceConstants.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PreferenceConstants.java
@@ -16,12 +16,12 @@ package org.eclipse.linuxtools.internal.systemtap.ui.ide.preferences;
*/
public class PreferenceConstants {
- //environmentvariables
- public static final String[][] P_ENV = new String[][] {
- {"EnvLdLibraryPath", "LD_LIBRARY_PATH"}, //$NON-NLS-1$ //$NON-NLS-2$
- {"EnvPath", "PATH"}, //$NON-NLS-1$ //$NON-NLS-2$
- {"EnvSystemtapTapset", "SYSTEMTAP_TAPSET"}, //$NON-NLS-1$ //$NON-NLS-2$
- {"EnvSystemtapRuntime", "SYSTEMTAP_RUNTIME"}, //$NON-NLS-1$ //$NON-NLS-2$
- };
+ //environmentvariables
+ public static final String[][] P_ENV = new String[][] {
+ {"EnvLdLibraryPath", "LD_LIBRARY_PATH"}, //$NON-NLS-1$ //$NON-NLS-2$
+ {"EnvPath", "PATH"}, //$NON-NLS-1$ //$NON-NLS-2$
+ {"EnvSystemtapTapset", "SYSTEMTAP_TAPSET"}, //$NON-NLS-1$ //$NON-NLS-2$
+ {"EnvSystemtapRuntime", "SYSTEMTAP_RUNTIME"}, //$NON-NLS-1$ //$NON-NLS-2$
+ };
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PreferenceInitializer.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PreferenceInitializer.java
index 740296bc8a..ad14abbb3d 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PreferenceInitializer.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/PreferenceInitializer.java
@@ -25,92 +25,92 @@ import org.eclipse.swt.graphics.RGB;
public class PreferenceInitializer extends AbstractPreferenceInitializer {
- private static final String[] KERNEL_SOURCE_PATH = {"/usr/src/kernels/{kernel_version}", //$NON-NLS-1$
- "/usr/src/linux", //$NON-NLS-1$
- "/usr/src/linux-{kernel_version}" }; //$NON-NLS-1$
-
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = IDEPlugin.getDefault().getPreferenceStore();
-
- //ide
- store.setDefault(IDEPreferenceConstants.P_STORED_TREE, false);
- store.setDefault(IDEPreferenceConstants.P_REMOTE_PROBES, false);
-
- //ide.path
- store.setDefault(IDEPreferenceConstants.P_KERNEL_SOURCE, getKernelSourceLocation());
- store.setDefault(IDEPreferenceConstants.P_EXCLUDED_KERNEL_SOURCE,
- "CVS/" + File.pathSeparator + //$NON-NLS-1$
- ".svn/" + File.pathSeparator + //$NON-NLS-1$
- "{arch}/" + File.pathSeparator + //$NON-NLS-1$
- ".arch-ids/" + File.pathSeparator + //$NON-NLS-1$
- ".bzr/" + File.pathSeparator + //$NON-NLS-1$
- "debian/" + File.pathSeparator + //$NON-NLS-1$
- ".git/"); //$NON-NLS-1$
- store.setDefault(IDEPreferenceConstants.P_REMOTE_LOCAL_KERNEL_SOURCE, PathPreferencePage.LOCAL);
-
- //ide.stap.tapsets
- store.setDefault(IDEPreferenceConstants.P_TAPSETS, ""); //$NON-NLS-1$
-
- //ide.editor
- PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_EDITOR_BACKGROUND, new RGB(255,255,255));
- store.setDefault(IDEPreferenceConstants.P_SHOW_LINE_NUMBERS, false);
-
- //ide.editor.codeassist
- store.setDefault(IDEPreferenceConstants.P_USE_CODE_ASSIST, true);
- store.setDefault(IDEPreferenceConstants.P_COMPLETION, IDEPreferenceConstants.P_COMPLETION_INSERT);
- store.setDefault(IDEPreferenceConstants.P_ACTIVATION_DELAY, 200);
- store.setDefault(IDEPreferenceConstants.P_ACTIVATION_TRIGGER, "."); //$NON-NLS-1$
-
- //ide.editor.conditionalfilters
- store.setDefault(IDEPreferenceConstants.P_CONDITIONAL_FILTERS,
- "if(pid=currentpid)" + File.pathSeparator + //$NON-NLS-1$
- "if(execname=cmdname)" + File.pathSeparator + //$NON-NLS-1$
- "if(cpu=0)" + File.pathSeparator + //$NON-NLS-1$
- "if(caller=functionname)"); //$NON-NLS-1$
-
-
- //ide.stap.stapoptions
- for(int i=0; i<IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length; i++) {
- store.setDefault(IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.KEY], false);
- }
-
- for(int i=0; i<IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
- store.setDefault(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.KEY], ""); //$NON-NLS-1$
- }
-
- //ide.editor.syntaxcoloring
- PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_DEFAULT_COLOR, STPColorConstants.DEFAULT);
- PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_KEYWORD_COLOR, STPColorConstants.KEYWORD);
- PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_EMBEDDED_C_COLOR, STPColorConstants.EMBEDDEDC);
- PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_EMBEDDED_COLOR, STPColorConstants.EMBEDDED);
- PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_COMMENT_COLOR, STPColorConstants.COMMENT);
- PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_TYPE_COLOR, STPColorConstants.TYPE);
- PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_STRING_COLOR, STPColorConstants.STP_STRING);
-
- }
-
- private String getKernelSourceLocation(){
- // Find out the version of the currently running kernel.
- String version = ""; //$NON-NLS-1$
- try {
- Process process = RuntimeProcessFactory.getFactory().exec("uname -r", null, null);//$NON-NLS-1$
- BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
- version = reader.readLine();
- } catch (IOException e) {
- // Could not run uname use an empty String
- }
-
- // Go over the search path looking for the file System.map
- for (String path : KERNEL_SOURCE_PATH) {
- path = path.replace("{kernel_version}", version); //$NON-NLS-1$
- File file = new File(path+ "/System.map"); //$NON-NLS-1$
- if (file.exists()){
- return path;
- }
- }
-
- return ""; //$NON-NLS-1$
- }
+ private static final String[] KERNEL_SOURCE_PATH = {"/usr/src/kernels/{kernel_version}", //$NON-NLS-1$
+ "/usr/src/linux", //$NON-NLS-1$
+ "/usr/src/linux-{kernel_version}" }; //$NON-NLS-1$
+
+ @Override
+ public void initializeDefaultPreferences() {
+ IPreferenceStore store = IDEPlugin.getDefault().getPreferenceStore();
+
+ //ide
+ store.setDefault(IDEPreferenceConstants.P_STORED_TREE, false);
+ store.setDefault(IDEPreferenceConstants.P_REMOTE_PROBES, false);
+
+ //ide.path
+ store.setDefault(IDEPreferenceConstants.P_KERNEL_SOURCE, getKernelSourceLocation());
+ store.setDefault(IDEPreferenceConstants.P_EXCLUDED_KERNEL_SOURCE,
+ "CVS/" + File.pathSeparator + //$NON-NLS-1$
+ ".svn/" + File.pathSeparator + //$NON-NLS-1$
+ "{arch}/" + File.pathSeparator + //$NON-NLS-1$
+ ".arch-ids/" + File.pathSeparator + //$NON-NLS-1$
+ ".bzr/" + File.pathSeparator + //$NON-NLS-1$
+ "debian/" + File.pathSeparator + //$NON-NLS-1$
+ ".git/"); //$NON-NLS-1$
+ store.setDefault(IDEPreferenceConstants.P_REMOTE_LOCAL_KERNEL_SOURCE, PathPreferencePage.LOCAL);
+
+ //ide.stap.tapsets
+ store.setDefault(IDEPreferenceConstants.P_TAPSETS, ""); //$NON-NLS-1$
+
+ //ide.editor
+ PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_EDITOR_BACKGROUND, new RGB(255,255,255));
+ store.setDefault(IDEPreferenceConstants.P_SHOW_LINE_NUMBERS, false);
+
+ //ide.editor.codeassist
+ store.setDefault(IDEPreferenceConstants.P_USE_CODE_ASSIST, true);
+ store.setDefault(IDEPreferenceConstants.P_COMPLETION, IDEPreferenceConstants.P_COMPLETION_INSERT);
+ store.setDefault(IDEPreferenceConstants.P_ACTIVATION_DELAY, 200);
+ store.setDefault(IDEPreferenceConstants.P_ACTIVATION_TRIGGER, "."); //$NON-NLS-1$
+
+ //ide.editor.conditionalfilters
+ store.setDefault(IDEPreferenceConstants.P_CONDITIONAL_FILTERS,
+ "if(pid=currentpid)" + File.pathSeparator + //$NON-NLS-1$
+ "if(execname=cmdname)" + File.pathSeparator + //$NON-NLS-1$
+ "if(cpu=0)" + File.pathSeparator + //$NON-NLS-1$
+ "if(caller=functionname)"); //$NON-NLS-1$
+
+
+ //ide.stap.stapoptions
+ for(int i=0; i<IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS.length; i++) {
+ store.setDefault(IDEPreferenceConstants.STAP_BOOLEAN_OPTIONS[i][IDEPreferenceConstants.KEY], false);
+ }
+
+ for(int i=0; i<IDEPreferenceConstants.STAP_STRING_OPTIONS.length; i++) {
+ store.setDefault(IDEPreferenceConstants.STAP_STRING_OPTIONS[i][IDEPreferenceConstants.KEY], ""); //$NON-NLS-1$
+ }
+
+ //ide.editor.syntaxcoloring
+ PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_DEFAULT_COLOR, STPColorConstants.DEFAULT);
+ PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_KEYWORD_COLOR, STPColorConstants.KEYWORD);
+ PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_EMBEDDED_C_COLOR, STPColorConstants.EMBEDDEDC);
+ PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_EMBEDDED_COLOR, STPColorConstants.EMBEDDED);
+ PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_COMMENT_COLOR, STPColorConstants.COMMENT);
+ PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_TYPE_COLOR, STPColorConstants.TYPE);
+ PreferenceConverter.setDefault(store, IDEPreferenceConstants.P_STP_STRING_COLOR, STPColorConstants.STP_STRING);
+
+ }
+
+ private String getKernelSourceLocation(){
+ // Find out the version of the currently running kernel.
+ String version = ""; //$NON-NLS-1$
+ try {
+ Process process = RuntimeProcessFactory.getFactory().exec("uname -r", null, null);//$NON-NLS-1$
+ BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ version = reader.readLine();
+ } catch (IOException e) {
+ // Could not run uname use an empty String
+ }
+
+ // Go over the search path looking for the file System.map
+ for (String path : KERNEL_SOURCE_PATH) {
+ path = path.replace("{kernel_version}", version); //$NON-NLS-1$
+ File file = new File(path+ "/System.map"); //$NON-NLS-1$
+ if (file.exists()){
+ return path;
+ }
+ }
+
+ return ""; //$NON-NLS-1$
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/SyntaxColoringPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/SyntaxColoringPreferencePage.java
index af27220507..c2aec9723f 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/SyntaxColoringPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/SyntaxColoringPreferencePage.java
@@ -24,100 +24,100 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class SyntaxColoringPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
- public SyntaxColoringPreferencePage() {
- super();
- setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
- setDescription(Localization.getString("SyntaxColoringPreferencePage.SyntaxColoringOptions")); //$NON-NLS-1$
- }
-
- @Override
- public void init(IWorkbench workbench) {
- }
-
- @Override
- protected Control createContents(Composite parent) {
- //STP Editor
- Composite comp = new Composite(parent, SWT.NULL);
- comp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- stpDC = createColorFieldEditor(
- IDEPreferenceConstants.P_STP_DEFAULT_COLOR,
- Localization.getString("SyntaxColoringPreferencePage.DefaultColor"), comp); //$NON-NLS-1$
- stpKC = createColorFieldEditor(
- IDEPreferenceConstants.P_STP_KEYWORD_COLOR,
- Localization.getString("SyntaxColoringPreferencePage.KeywordColor"), comp); //$NON-NLS-1$
- stpEC = createColorFieldEditor(
- IDEPreferenceConstants.P_STP_EMBEDDED_C_COLOR,
- Localization.getString("SyntaxColoringPreferencePage.EmbeddedCColor"), comp); //$NON-NLS-1$
- stpEE = createColorFieldEditor(
- IDEPreferenceConstants.P_STP_EMBEDDED_COLOR,
- Localization.getString("SyntaxColoringPreferencePage.EmbeddedColor"), comp); //$NON-NLS-1$
- stpCC = createColorFieldEditor(
- IDEPreferenceConstants.P_STP_COMMENT_COLOR,
- Localization.getString("SyntaxColoringPreferencePage.CommentColor"), comp); //$NON-NLS-1$
- stpTC = createColorFieldEditor(
- IDEPreferenceConstants.P_STP_TYPE_COLOR,
- Localization.getString("SyntaxColoringPreferencePage.TypeColor"), comp); //$NON-NLS-1$
- stpSC = createColorFieldEditor(
- IDEPreferenceConstants.P_STP_STRING_COLOR,
- Localization.getString("SyntaxColoringPreferencePage.StringColor"), comp); //$NON-NLS-1$
-
- return comp;
- }
-
- private ColorFieldEditor createColorFieldEditor(String name, String lblText, Composite parent) {
- ColorFieldEditor cfe = new ColorFieldEditor(name, lblText, parent);
- cfe.setPage(this);
- cfe.setPreferenceStore(getPreferenceStore());
- cfe.load();
-
- return cfe;
- }
-
- @Override
- protected void performDefaults() {
- stpDC.loadDefault();
- stpKC.loadDefault();
- stpEC.loadDefault();
- stpEE.loadDefault();
- stpCC.loadDefault();
- stpTC.loadDefault();
- stpSC.loadDefault();
-
- super.performDefaults();
- }
-
- @Override
- public boolean performOk() {
- stpDC.store();
- stpKC.store();
- stpEC.store();
- stpEE.store();
- stpCC.store();
- stpTC.store();
- stpSC.store();
-
- return true;
- }
-
- @Override
- public void dispose() {
- super.dispose();
- stpDC.dispose();
- stpKC.dispose();
- stpEC.dispose();
- stpEE.dispose();
- stpCC.dispose();
- stpTC.dispose();
- stpSC.dispose();
- stpDC = null;
- stpKC = null;
- stpEC = null;
- stpEE = null;
- stpCC = null;
- stpTC = null;
- stpSC = null;
- }
-
- private ColorFieldEditor stpDC, stpKC, stpEC, stpEE, stpCC, stpTC, stpSC;
+ public SyntaxColoringPreferencePage() {
+ super();
+ setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
+ setDescription(Localization.getString("SyntaxColoringPreferencePage.SyntaxColoringOptions")); //$NON-NLS-1$
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ }
+
+ @Override
+ protected Control createContents(Composite parent) {
+ //STP Editor
+ Composite comp = new Composite(parent, SWT.NULL);
+ comp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+
+ stpDC = createColorFieldEditor(
+ IDEPreferenceConstants.P_STP_DEFAULT_COLOR,
+ Localization.getString("SyntaxColoringPreferencePage.DefaultColor"), comp); //$NON-NLS-1$
+ stpKC = createColorFieldEditor(
+ IDEPreferenceConstants.P_STP_KEYWORD_COLOR,
+ Localization.getString("SyntaxColoringPreferencePage.KeywordColor"), comp); //$NON-NLS-1$
+ stpEC = createColorFieldEditor(
+ IDEPreferenceConstants.P_STP_EMBEDDED_C_COLOR,
+ Localization.getString("SyntaxColoringPreferencePage.EmbeddedCColor"), comp); //$NON-NLS-1$
+ stpEE = createColorFieldEditor(
+ IDEPreferenceConstants.P_STP_EMBEDDED_COLOR,
+ Localization.getString("SyntaxColoringPreferencePage.EmbeddedColor"), comp); //$NON-NLS-1$
+ stpCC = createColorFieldEditor(
+ IDEPreferenceConstants.P_STP_COMMENT_COLOR,
+ Localization.getString("SyntaxColoringPreferencePage.CommentColor"), comp); //$NON-NLS-1$
+ stpTC = createColorFieldEditor(
+ IDEPreferenceConstants.P_STP_TYPE_COLOR,
+ Localization.getString("SyntaxColoringPreferencePage.TypeColor"), comp); //$NON-NLS-1$
+ stpSC = createColorFieldEditor(
+ IDEPreferenceConstants.P_STP_STRING_COLOR,
+ Localization.getString("SyntaxColoringPreferencePage.StringColor"), comp); //$NON-NLS-1$
+
+ return comp;
+ }
+
+ private ColorFieldEditor createColorFieldEditor(String name, String lblText, Composite parent) {
+ ColorFieldEditor cfe = new ColorFieldEditor(name, lblText, parent);
+ cfe.setPage(this);
+ cfe.setPreferenceStore(getPreferenceStore());
+ cfe.load();
+
+ return cfe;
+ }
+
+ @Override
+ protected void performDefaults() {
+ stpDC.loadDefault();
+ stpKC.loadDefault();
+ stpEC.loadDefault();
+ stpEE.loadDefault();
+ stpCC.loadDefault();
+ stpTC.loadDefault();
+ stpSC.loadDefault();
+
+ super.performDefaults();
+ }
+
+ @Override
+ public boolean performOk() {
+ stpDC.store();
+ stpKC.store();
+ stpEC.store();
+ stpEE.store();
+ stpCC.store();
+ stpTC.store();
+ stpSC.store();
+
+ return true;
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ stpDC.dispose();
+ stpKC.dispose();
+ stpEC.dispose();
+ stpEE.dispose();
+ stpCC.dispose();
+ stpTC.dispose();
+ stpSC.dispose();
+ stpDC = null;
+ stpKC = null;
+ stpEC = null;
+ stpEE = null;
+ stpCC = null;
+ stpTC = null;
+ stpSC = null;
+ }
+
+ private ColorFieldEditor stpDC, stpKC, stpEC, stpEE, stpCC, stpTC, stpSC;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/SystemTapPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/SystemTapPreferencePage.java
index a1cabed287..9589505a51 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/SystemTapPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/SystemTapPreferencePage.java
@@ -19,23 +19,23 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class SystemTapPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- /**
- * Get the current preferences.
- */
- public SystemTapPreferencePage() {
- super();
- setDescription(Messages.SystemTapPreferencePageDescription);
- }
-
- /**
- * Sets up the field editors for optional change by the user.
- */
- @Override
- public void createFieldEditors() {
- }
-
- @Override
- public void init(IWorkbench workbench) {
- }
+ /**
+ * Get the current preferences.
+ */
+ public SystemTapPreferencePage() {
+ super();
+ setDescription(Messages.SystemTapPreferencePageDescription);
+ }
+
+ /**
+ * Sets up the field editors for optional change by the user.
+ */
+ @Override
+ public void createFieldEditors() {
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/TapsetsPreferencePage.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/TapsetsPreferencePage.java
index 29e62c93bf..37fe25dcba 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/TapsetsPreferencePage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/preferences/TapsetsPreferencePage.java
@@ -20,25 +20,25 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
public class TapsetsPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- public TapsetsPreferencePage() {
- super(GRID);
- setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
- setDescription(Localization.getString("TapsetsPreferencePage.AdditionalTapsetsCategory")); //$NON-NLS-1$
- }
-
- /**
- * Creates the field editors. Field editors are abstractions of
- * the common GUI blocks needed to manipulate various types
- * of preferences. Each field editor knows how to save and
- * restore itself.
- */
- @Override
- public void createFieldEditors() {
- addField(new PathEditor(IDEPreferenceConstants.P_TAPSETS,
- Localization.getString("TapsetsPreferencePage.AdditionalTapsets"), Localization.getString("TapsetsPreferencePage.TapsetDirectory"), getFieldEditorParent())); //$NON-NLS-1$ //$NON-NLS-2$
- }
+ public TapsetsPreferencePage() {
+ super(GRID);
+ setPreferenceStore(IDEPlugin.getDefault().getPreferenceStore());
+ setDescription(Localization.getString("TapsetsPreferencePage.AdditionalTapsetsCategory")); //$NON-NLS-1$
+ }
- @Override
- public void init(IWorkbench workbench) {
- }
+ /**
+ * Creates the field editors. Field editors are abstractions of
+ * the common GUI blocks needed to manipulate various types
+ * of preferences. Each field editor knows how to save and
+ * restore itself.
+ */
+ @Override
+ public void createFieldEditors() {
+ addField(new PathEditor(IDEPreferenceConstants.P_TAPSETS,
+ Localization.getString("TapsetsPreferencePage.AdditionalTapsets"), Localization.getString("TapsetsPreferencePage.TapsetDirectory"), getFieldEditorParent())); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Override
+ public void init(IWorkbench workbench) {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FuncparamNodeData.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FuncparamNodeData.java
index f6212437dd..8733da589b 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FuncparamNodeData.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FuncparamNodeData.java
@@ -19,27 +19,27 @@ import org.eclipse.linuxtools.systemtap.structures.TreeNode;
*/
public class FuncparamNodeData implements ISingleTypedNode {
- private final String line;
- private final String type;
+ private final String line;
+ private final String type;
- @Override
- public String toString() {
- return line;
- }
+ @Override
+ public String toString() {
+ return line;
+ }
- @Override
- public String getType() {
- return type;
- }
+ @Override
+ public String getType() {
+ return type;
+ }
- /**
- * Create a new instance of function parameter information. (Note that the name of a function
- * or parameter is stored in a {@link TreeNode}, not here.)
- * @param line The <code>String</code> representation of the entire parameter.
- * @param type The <code>String</code> representation of only the parameter's type.
- */
- public FuncparamNodeData(String line, String type) {
- this.line = line;
- this.type = type == null ? FunctionParser.UNKNOWN_TYPE : type; // Parameters can't be void.
- }
+ /**
+ * Create a new instance of function parameter information. (Note that the name of a function
+ * or parameter is stored in a {@link TreeNode}, not here.)
+ * @param line The <code>String</code> representation of the entire parameter.
+ * @param type The <code>String</code> representation of only the parameter's type.
+ */
+ public FuncparamNodeData(String line, String type) {
+ this.line = line;
+ this.type = type == null ? FunctionParser.UNKNOWN_TYPE : type; // Parameters can't be void.
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FunctionNodeData.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FunctionNodeData.java
index f18ed04680..6ae140a078 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FunctionNodeData.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FunctionNodeData.java
@@ -18,44 +18,44 @@ import org.eclipse.linuxtools.systemtap.structures.TreeNode;
* @since 3.0
*/
public class FunctionNodeData implements ISearchableNode, ISingleTypedNode {
- private final String line;
- private final String type;
-
- @Override
- public boolean isRegexSearch() {
- return false;
- }
-
- /**
- * @return the text to search a file with for the definition of this function.
- */
- @Override
- public String getSearchToken() {
- return line;
- }
-
- @Override
- public String toString() {
- return getSearchToken();
- }
-
- /**
- * @return the <code>String</code> representation of the return type of the
- * node's function (<code>null</code> for void functions).
- */
- @Override
- public String getType() {
- return type;
- }
-
- /**
- * Create a new instance of function node information. (Note that the name of a function
- * or parameter is stored in a {@link TreeNode}, not here.)
- * @param line Set this to the original script text that defines this function.
- * @param type The <code>String</code> representation of the return type of the function.
- */
- public FunctionNodeData(String line, String type) {
- this.line = line;
- this.type = type;
- }
+ private final String line;
+ private final String type;
+
+ @Override
+ public boolean isRegexSearch() {
+ return false;
+ }
+
+ /**
+ * @return the text to search a file with for the definition of this function.
+ */
+ @Override
+ public String getSearchToken() {
+ return line;
+ }
+
+ @Override
+ public String toString() {
+ return getSearchToken();
+ }
+
+ /**
+ * @return the <code>String</code> representation of the return type of the
+ * node's function (<code>null</code> for void functions).
+ */
+ @Override
+ public String getType() {
+ return type;
+ }
+
+ /**
+ * Create a new instance of function node information. (Note that the name of a function
+ * or parameter is stored in a {@link TreeNode}, not here.)
+ * @param line Set this to the original script text that defines this function.
+ * @param type The <code>String</code> representation of the return type of the function.
+ */
+ public FunctionNodeData(String line, String type) {
+ this.line = line;
+ this.type = type;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FunctionParser.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FunctionParser.java
index 904ac20c42..1c5961665d 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FunctionParser.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/FunctionParser.java
@@ -34,154 +34,154 @@ import org.eclipse.linuxtools.systemtap.structures.TreeNode;
*/
public class FunctionParser extends TapsetParser {
- static FunctionParser parser = null;
- private TreeNode functions;
-
- /**
- * The descriptor used for unresolvable types.
- */
- public static final String UNKNOWN_TYPE = "unknown"; //$NON-NLS-1$
-
- private static final String functionRegex = "(?s)(?<!\\w)function\\s+{0}(?:\\s*:\\s*(\\w+))?\\s*\\(([^)]+?)?\\)"; //$NON-NLS-1$
- private static final Pattern pFunction = Pattern.compile("function (?!_)(\\w+) \\(.*?\\)"); //$NON-NLS-1$
- private static final Pattern pParams = Pattern.compile("(\\w+)(?:\\s*:\\s*(\\w+))?"); //$NON-NLS-1$
- private static final Pattern pAllCaps = Pattern.compile("[A-Z_1-9]*"); //$NON-NLS-1$
- private static final Pattern pReturn = Pattern.compile("\\sreturn\\W"); //$NON-NLS-1$
-
- public static FunctionParser getInstance(){
- if (parser != null) {
- return parser;
- }
- parser = new FunctionParser();
- return parser;
- }
-
- private FunctionParser() {
- super("Function Parser"); //$NON-NLS-1$
- }
-
- /**
- * Returns the root node of the tree of functions generated by
- * parseFiles. Functions are grouped by source file.
- * @return A tree of tapset functions grouped by file.
- */
- public synchronized TreeNode getFunctions() {
- return functions;
- }
-
- /**
- * This method will clean up everything from the run.
- */
- public void dispose() {
- functions.dispose();
- }
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- boolean cancelled = runPass2Functions();
- functions.sortTree();
- fireUpdateEvent(); //Inform listeners that everything is done
- return new Status(!cancelled ? IStatus.OK : IStatus.CANCEL, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
- }
-
- /**
- * This method is used to build up the list of functions that were found
- * during the first pass of stap. Stap is invoked by: $stap -v -p1 -e
- * 'probe begin{}' and parsing the output.
- *
- * FunctionTree organized as:
- * Root->Functions->Parameters
- *
- * @return <code>false</code> if a cancellation prevented all probes from being added;
- * <code>true</code> otherwise.
- */
- private boolean runPass2Functions() {
- String tapsetContents = SharedParser.getInstance().getTapsetContents();
- if (cancelRequested) {
- return false;
- }
- // Create a new function tree each time, so as to not add duplicates
- functions = new TreeNode("", false); //$NON-NLS-1$
- if (tapsetContents == null) {
- // Functions are only drawn from the tapset dump, so exit if it's empty.
- return true;
- }
- try (Scanner st = new Scanner(tapsetContents)) {
- String filename = null;
- String scriptText = null;
-
- SharedParser sparser = SharedParser.getInstance();
- while (st.hasNextLine()) {
- if (cancelRequested) {
- return false;
- }
- String tok = st.nextLine();
- Matcher mFilename = sparser.filePattern.matcher(tok);
- if (mFilename.matches()) {
- filename = mFilename.group(1).toString();
- scriptText = null;
- } else if (filename != null) {
- Matcher mFunction = pFunction.matcher(tok);
- if (mFunction.matches()) {
- String functionName = mFunction.group(1);
- if (pAllCaps.matcher(functionName).matches()) {
- // Ignore ALL_CAPS functions, since they are not meant for end-user use.
- continue;
- }
- if (scriptText == null) {
- // If this is the first time seeing this file, remove its comments.
- scriptText = CommentRemover.execWithFile(filename);
- }
- addFunctionFromScript(functionName, scriptText, filename);
- }
- }
- }
- return true;
- }
- }
-
- private void addFunctionFromScript(String functionName, String scriptText, String scriptFilename) {
- String regex = MessageFormat.format(functionRegex, functionName);
- Matcher mScript = Pattern.compile(regex).matcher(scriptText);
- if (mScript.find()) {
- String functionLine = mScript.group();
- String functionType = mScript.group(1);
- // If the function has no return type, look for a "return" statement to check
- // if it's really a void function, or if its return type is just unspecified
- if (functionType == null && getNextBlockContents(scriptText, mScript.end(), pReturn)) {
- functionType = UNKNOWN_TYPE;
- }
- TreeDefinitionNode function = new TreeDefinitionNode(
- new FunctionNodeData(functionLine, functionType),
- functionName, scriptFilename, true);
- functions.add(function);
- addParamsFromString(mScript.group(2), function);
- }
- }
-
- private boolean getNextBlockContents(String scriptText, int start, Pattern p) {
- int end, bcount = 1;
- start = scriptText.indexOf('{', start) + 1;
- for (end = start; end < scriptText.length(); end++) {
- char c = scriptText.charAt(end);
- if (c == '{') {
- bcount++;
- } else if (c == '}' && --bcount == 0) {
- break;
- }
- }
- return p.matcher(scriptText.substring(start, end)).find();
- }
-
- private void addParamsFromString(String params, TreeNode parentFunction) {
- if (params != null) {
- Matcher mParams = pParams.matcher(params);
- while (mParams.find()) {
- parentFunction.add(new TreeNode(
- new FuncparamNodeData(mParams.group(), mParams.group(2)),
- mParams.group(1), false));
- }
- }
- }
+ static FunctionParser parser = null;
+ private TreeNode functions;
+
+ /**
+ * The descriptor used for unresolvable types.
+ */
+ public static final String UNKNOWN_TYPE = "unknown"; //$NON-NLS-1$
+
+ private static final String functionRegex = "(?s)(?<!\\w)function\\s+{0}(?:\\s*:\\s*(\\w+))?\\s*\\(([^)]+?)?\\)"; //$NON-NLS-1$
+ private static final Pattern pFunction = Pattern.compile("function (?!_)(\\w+) \\(.*?\\)"); //$NON-NLS-1$
+ private static final Pattern pParams = Pattern.compile("(\\w+)(?:\\s*:\\s*(\\w+))?"); //$NON-NLS-1$
+ private static final Pattern pAllCaps = Pattern.compile("[A-Z_1-9]*"); //$NON-NLS-1$
+ private static final Pattern pReturn = Pattern.compile("\\sreturn\\W"); //$NON-NLS-1$
+
+ public static FunctionParser getInstance(){
+ if (parser != null) {
+ return parser;
+ }
+ parser = new FunctionParser();
+ return parser;
+ }
+
+ private FunctionParser() {
+ super("Function Parser"); //$NON-NLS-1$
+ }
+
+ /**
+ * Returns the root node of the tree of functions generated by
+ * parseFiles. Functions are grouped by source file.
+ * @return A tree of tapset functions grouped by file.
+ */
+ public synchronized TreeNode getFunctions() {
+ return functions;
+ }
+
+ /**
+ * This method will clean up everything from the run.
+ */
+ public void dispose() {
+ functions.dispose();
+ }
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ boolean cancelled = runPass2Functions();
+ functions.sortTree();
+ fireUpdateEvent(); //Inform listeners that everything is done
+ return new Status(!cancelled ? IStatus.OK : IStatus.CANCEL, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
+ }
+
+ /**
+ * This method is used to build up the list of functions that were found
+ * during the first pass of stap. Stap is invoked by: $stap -v -p1 -e
+ * 'probe begin{}' and parsing the output.
+ *
+ * FunctionTree organized as:
+ * Root->Functions->Parameters
+ *
+ * @return <code>false</code> if a cancellation prevented all probes from being added;
+ * <code>true</code> otherwise.
+ */
+ private boolean runPass2Functions() {
+ String tapsetContents = SharedParser.getInstance().getTapsetContents();
+ if (cancelRequested) {
+ return false;
+ }
+ // Create a new function tree each time, so as to not add duplicates
+ functions = new TreeNode("", false); //$NON-NLS-1$
+ if (tapsetContents == null) {
+ // Functions are only drawn from the tapset dump, so exit if it's empty.
+ return true;
+ }
+ try (Scanner st = new Scanner(tapsetContents)) {
+ String filename = null;
+ String scriptText = null;
+
+ SharedParser sparser = SharedParser.getInstance();
+ while (st.hasNextLine()) {
+ if (cancelRequested) {
+ return false;
+ }
+ String tok = st.nextLine();
+ Matcher mFilename = sparser.filePattern.matcher(tok);
+ if (mFilename.matches()) {
+ filename = mFilename.group(1).toString();
+ scriptText = null;
+ } else if (filename != null) {
+ Matcher mFunction = pFunction.matcher(tok);
+ if (mFunction.matches()) {
+ String functionName = mFunction.group(1);
+ if (pAllCaps.matcher(functionName).matches()) {
+ // Ignore ALL_CAPS functions, since they are not meant for end-user use.
+ continue;
+ }
+ if (scriptText == null) {
+ // If this is the first time seeing this file, remove its comments.
+ scriptText = CommentRemover.execWithFile(filename);
+ }
+ addFunctionFromScript(functionName, scriptText, filename);
+ }
+ }
+ }
+ return true;
+ }
+ }
+
+ private void addFunctionFromScript(String functionName, String scriptText, String scriptFilename) {
+ String regex = MessageFormat.format(functionRegex, functionName);
+ Matcher mScript = Pattern.compile(regex).matcher(scriptText);
+ if (mScript.find()) {
+ String functionLine = mScript.group();
+ String functionType = mScript.group(1);
+ // If the function has no return type, look for a "return" statement to check
+ // if it's really a void function, or if its return type is just unspecified
+ if (functionType == null && getNextBlockContents(scriptText, mScript.end(), pReturn)) {
+ functionType = UNKNOWN_TYPE;
+ }
+ TreeDefinitionNode function = new TreeDefinitionNode(
+ new FunctionNodeData(functionLine, functionType),
+ functionName, scriptFilename, true);
+ functions.add(function);
+ addParamsFromString(mScript.group(2), function);
+ }
+ }
+
+ private boolean getNextBlockContents(String scriptText, int start, Pattern p) {
+ int end, bcount = 1;
+ start = scriptText.indexOf('{', start) + 1;
+ for (end = start; end < scriptText.length(); end++) {
+ char c = scriptText.charAt(end);
+ if (c == '{') {
+ bcount++;
+ } else if (c == '}' && --bcount == 0) {
+ break;
+ }
+ }
+ return p.matcher(scriptText.substring(start, end)).find();
+ }
+
+ private void addParamsFromString(String params, TreeNode parentFunction) {
+ if (params != null) {
+ Matcher mParams = pParams.matcher(params);
+ while (mParams.find()) {
+ parentFunction.add(new TreeNode(
+ new FuncparamNodeData(mParams.group(), mParams.group(2)),
+ mParams.group(1), false));
+ }
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ISearchableNode.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ISearchableNode.java
index 3f4d38afad..e207e1e58a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ISearchableNode.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ISearchableNode.java
@@ -12,6 +12,6 @@
package org.eclipse.linuxtools.internal.systemtap.ui.ide.structures;
public interface ISearchableNode {
- String getSearchToken();
- boolean isRegexSearch();
+ String getSearchToken();
+ boolean isRegexSearch();
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ISingleTypedNode.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ISingleTypedNode.java
index de90470e71..94d5f7b161 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ISingleTypedNode.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ISingleTypedNode.java
@@ -12,5 +12,5 @@
package org.eclipse.linuxtools.internal.systemtap.ui.ide.structures;
public interface ISingleTypedNode {
- String getType();
+ String getType();
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/Messages.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/Messages.java
index 7c1a611396..64e8b9a515 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/Messages.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/Messages.java
@@ -16,18 +16,18 @@ import org.eclipse.osgi.util.NLS;
* @since 2.0
*/
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.structures.messages"; //$NON-NLS-1$
- public static String ProbeParser_errorInitializingStaticProbes;
- public static String ProbeParser_staticProbes;
- public static String ProbeParser_aliasProbes;
- public static String TapsetParser_CannotRunStapMessage;
- public static String TapsetParser_CannotRunStapTitle;
- public static String TapsetParser_ErrorRunningSystemtap;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.systemtap.ui.ide.structures.messages"; //$NON-NLS-1$
+ public static String ProbeParser_errorInitializingStaticProbes;
+ public static String ProbeParser_staticProbes;
+ public static String ProbeParser_aliasProbes;
+ public static String TapsetParser_CannotRunStapMessage;
+ public static String TapsetParser_CannotRunStapTitle;
+ public static String TapsetParser_ErrorRunningSystemtap;
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, Messages.class);
+ }
- private Messages() {
- }
+ private Messages() {
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbeNodeData.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbeNodeData.java
index 20e7f050cc..0fd3204b42 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbeNodeData.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbeNodeData.java
@@ -15,35 +15,35 @@ import java.text.MessageFormat;
public class ProbeNodeData implements ISearchableNode {
- private final String name;
-
- @Override
- public boolean isRegexSearch() {
- return true;
- }
-
- /**
- * @return a regex to search a file with for the definition of this probe.
- */
- @Override
- public String getSearchToken() {
- return MessageFormat.format(ProbeParser.probeRegex, name);
- }
-
- @Override
- public String toString() {
- return getSearchToken();
- }
-
- /**
- * Create a new instance of probe node information.
- * @param line A line of text generated by running "stap -L" which
- * provides all information pertaining to a probe point, or at least
- * the probe's name.
- */
- public ProbeNodeData(String line) {
- int spaceIndex = line.indexOf(' ');
- name = (spaceIndex != -1 ? line.substring(0, spaceIndex) : line).trim();
- }
+ private final String name;
+
+ @Override
+ public boolean isRegexSearch() {
+ return true;
+ }
+
+ /**
+ * @return a regex to search a file with for the definition of this probe.
+ */
+ @Override
+ public String getSearchToken() {
+ return MessageFormat.format(ProbeParser.probeRegex, name);
+ }
+
+ @Override
+ public String toString() {
+ return getSearchToken();
+ }
+
+ /**
+ * Create a new instance of probe node information.
+ * @param line A line of text generated by running "stap -L" which
+ * provides all information pertaining to a probe point, or at least
+ * the probe's name.
+ */
+ public ProbeNodeData(String line) {
+ int spaceIndex = line.indexOf(' ');
+ name = (spaceIndex != -1 ? line.substring(0, spaceIndex) : line).trim();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbeParser.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbeParser.java
index 1ea2da3701..2acd6ba4e7 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbeParser.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbeParser.java
@@ -34,263 +34,263 @@ import org.eclipse.linuxtools.systemtap.structures.TreeNode;
*/
public class ProbeParser extends TapsetParser {
- static final String probeRegex = "(?s)(?<!\\w)probe\\s+{0}\\s*\\+?="; //$NON-NLS-1$
- private static final String tapsetProbeRegex = "probe {0} \\+?="; //$NON-NLS-1$
-
- private TreeNode probes;
- private TreeNode statics;
- private TreeNode aliases;
-
- static ProbeParser parser = null;
- public static ProbeParser getInstance(){
- if (parser != null) {
- return parser;
- }
- parser = new ProbeParser();
- return parser;
- }
-
- private ProbeParser() {
- super("Probe Parser"); //$NON-NLS-1$
- }
-
- /**
- * Returns the root node of the tree of the probe alias generated by
- * parseFiles. Probes are grouped by target location.
- * @return A tree of tapset probe aliases grouped by probe location.
- */
- public synchronized TreeNode getProbes() {
- return probes;
- }
-
- /**
- * This method will clean up everything from the run.
- */
- public void dispose() {
- probes.dispose();
- statics.dispose();
- aliases.dispose();
- }
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- // Create a new function tree each time, so as to not add duplicates.
- reset();
-
- addStaticProbes();
- if (cancelRequested){
- return new Status(IStatus.CANCEL, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
- }
- boolean cancelled = addProbeAliases(collect(null));
- constructRootTree();
- fireUpdateEvent(); //Inform listeners that everything is done
- return new Status(!cancelled ? IStatus.OK : IStatus.CANCEL, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
- }
-
- private void reset() {
- probes = new TreeNode("", false); //$NON-NLS-1$
- statics = new TreeNode(Messages.ProbeParser_staticProbes, false);
- aliases = new TreeNode(Messages.ProbeParser_aliasProbes, false);
- }
-
- private void constructRootTree() {
- statics.sortTree();
- aliases.sortTree();
- probes.add(statics);
- probes.add(aliases);
- }
-
- /**
- * Returns a String containing all of the content from the probe
- * point list, including variables and their type.
- *
- * stap -L
- * Will list all available probe points
- * @return the probe points consolidated into a single string
- */
- private String collect(String script) {
- String[] options;
- if(null == script) {
- script = "**"; //$NON-NLS-1$
- options = new String[] {"-L"}; //$NON-NLS-1$
- } else {
- options = null;
- }
-
- String s = runStap(options, script, false);
- if (s == null) {
- return ""; //$NON-NLS-1$
- }
-
- return s;
- }
-
- private boolean addStaticProbes() {
- String s = runStap(new String[]{"--dump-probe-types"}, null, false); //$NON-NLS-1$
- TreeNode group = null;
- try (Scanner st = new Scanner(s)) {
- while(st.hasNextLine()) {
- if (cancelRequested) {
- return false;
- }
- String tokenString = st.nextLine();
- String probeName = (new StringTokenizer(tokenString)).nextToken();
- group = addOrFindProbeGroup(extractProbeGroupName(probeName), group, statics);
- group.add(makeStaticProbeNode(probeName));
- }
- return true;
- }
- }
-
- /**
- * Parses the output generated from running stap -L. Pulls out all functions
- * and probe aliases from the provided string. Populates the probe tree.
- *
- * ProbeTree organized as:
- * Root->Named Groups->ProbePoints->Variables
- *
- * @param probeDump A list of probe points with the same formatting used by stap -L.
- * @return <code>false</code> if a cancellation prevented all probes from being added;
- * <code>true</code> otherwise.
- */
- private boolean addProbeAliases(String probeDump) {
- TreeNode group = null;
- try (Scanner st = new Scanner(probeDump)) {
- while(st.hasNextLine()) {
- if (cancelRequested) {
- return false;
- }
- String tokenString = st.nextLine();
- // If the token starts with '_' or '__' it is a private probe so
- // skip it.
- if (tokenString.startsWith("_")) { //$NON-NLS-1$
- continue;
- }
-
- StringTokenizer probeTokenizer = new StringTokenizer(tokenString);
- String probeName = probeTokenizer.nextToken();
-
- String groupName = extractProbeGroupName(tokenString);
- if (!isStaticProbeGroup(groupName)) {
- TreeNode probeNode = makeProbeAliasNode(probeName);
- group = addOrFindProbeGroup(groupName, group, aliases);
- group.add(probeNode);
- addAllVarNodesToProbeNode(probeTokenizer, probeNode);
- }
- }
- return true;
- }
- }
-
- /**
- * Find the appropriate parent group node for a probe alias to group probes by name.
- * If it doesn't yet exist, create it and add it to the view's tree.
- * @param probeLine The name of the probe group.
- * @param groupNode For optimization, pass an existing group node here, as it will be
- * used if the probe belongs in it. Otherwise, or if <code>null</code> is passed, a new one will be created.
- * @param category The parent tree node in which to put the group node.
- * @return The found or created group node that will be the parent of the probe's entry item in the view.
- */
- private TreeNode addOrFindProbeGroup(String groupName, TreeNode groupNode, TreeNode category) {
-
- // If the current probe belongs to a group other than
- // the most recent group. This should rarely be needed because the
- // probe list is sorted... mostly.
- if(groupNode == null || !groupNode.toString().equals(groupName)) {
- groupNode = category.getChildByName(groupName);
- }
-
- // Create a new group and add it
- if(groupNode == null) {
- groupNode = new TreeNode(groupName, true);
- category.add(groupNode);
- }
- return groupNode;
- }
-
- /**
- * @return the name of the group a probe belongs to, based on the probe's name.
- */
- private String extractProbeGroupName(String probeName) {
- int dotIndex = probeName.indexOf('.');
- int parenIndex = probeName.indexOf('(');
- if (dotIndex > 0 && parenIndex > 0) {
- return probeName.substring(0, Math.min(dotIndex, parenIndex));
- }
- if (dotIndex > 0) {
- return probeName.substring(0, dotIndex);
- }
- if (parenIndex > 0) {
- return probeName.substring(0, parenIndex);
- }
- return probeName;
- }
-
- private TreeNode makeStaticProbeNode(String probeName) {
- return new TreeNode(new ProbeNodeData(probeName), probeName, true);
- }
-
- private TreeNode makeProbeAliasNode(String probeName) {
- return new TreeDefinitionNode(new ProbeNodeData(probeName), probeName, findDefinitionOf(probeName), true);
- }
-
- private boolean isStaticProbeGroup(String groupName) {
- return statics.getChildByName(groupName) != null;
- }
-
- /**
- * Search the tapset content dump for the path of the file which defines the provided probe alias.
- * @param probeName The alias of the probe to find the definition file of.
- * @return The path of the probe's definition file, or <code>null</code> if a definition
- * file can't be found (which is the case for static probes).
- */
- private String findDefinitionOf(String probeName) {
- SharedParser sparser = SharedParser.getInstance();
- String tapsetContents = sparser.getTapsetContents();
- Matcher probeMatcher = Pattern.compile(MessageFormat.format(tapsetProbeRegex, Pattern.quote(probeName))).matcher(tapsetContents);
- if (!probeMatcher.find()) {
- return null;
- }
- int fileLocIndex = tapsetContents.substring(0, probeMatcher.start()).lastIndexOf(SharedParser.TAG_FILE);
- try (Scanner scanner = new Scanner(tapsetContents.substring(fileLocIndex))) {
- Matcher fileMatcher = sparser.filePattern.matcher(scanner.nextLine());
- return fileMatcher.matches()
- ? fileMatcher.group(1)
- : null;
- }
- }
-
- /**
- * Extracts the local variables from a (partially examined) probe alias token, and
- * adds them as child tree entries of their parent probe.
- */
- private void addAllVarNodesToProbeNode(StringTokenizer varTokenizer, TreeNode probeNode) {
- StringBuilder prev = new StringBuilder(""); //$NON-NLS-1$
- // the remaining tokens are variable names and variable types name:type.
- while(varTokenizer.hasMoreTokens()){
- String token = varTokenizer.nextToken();
-
- // Because some variable types contain spaces (var2:struct task_struct)
- // the only way to know if we have the entire string representing a
- // variable is if we reach the next token containing a ':' or we reach
- // the end of the stream.
- if (token.contains(":") && prev.length() > 0){ //$NON-NLS-1$
- prev.setLength(prev.length() - 1); // Remove the trailing space.
- addVarNodeToProbeNode(prev.toString(), probeNode);
- prev.setLength(0);
- }
- prev.append(token + " "); //$NON-NLS-1$
- }
-
- // Add the last token if there is one
- if (prev.length() > 0){
- prev.setLength(prev.length() - 1); // Remove the trailing space.
- addVarNodeToProbeNode(prev.toString(), probeNode);
- }
- }
-
- private void addVarNodeToProbeNode(String info, TreeNode probeNode) {
- probeNode.add(new TreeNode(new ProbevarNodeData(info), info, false));
- }
+ static final String probeRegex = "(?s)(?<!\\w)probe\\s+{0}\\s*\\+?="; //$NON-NLS-1$
+ private static final String tapsetProbeRegex = "probe {0} \\+?="; //$NON-NLS-1$
+
+ private TreeNode probes;
+ private TreeNode statics;
+ private TreeNode aliases;
+
+ static ProbeParser parser = null;
+ public static ProbeParser getInstance(){
+ if (parser != null) {
+ return parser;
+ }
+ parser = new ProbeParser();
+ return parser;
+ }
+
+ private ProbeParser() {
+ super("Probe Parser"); //$NON-NLS-1$
+ }
+
+ /**
+ * Returns the root node of the tree of the probe alias generated by
+ * parseFiles. Probes are grouped by target location.
+ * @return A tree of tapset probe aliases grouped by probe location.
+ */
+ public synchronized TreeNode getProbes() {
+ return probes;
+ }
+
+ /**
+ * This method will clean up everything from the run.
+ */
+ public void dispose() {
+ probes.dispose();
+ statics.dispose();
+ aliases.dispose();
+ }
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ // Create a new function tree each time, so as to not add duplicates.
+ reset();
+
+ addStaticProbes();
+ if (cancelRequested){
+ return new Status(IStatus.CANCEL, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
+ }
+ boolean cancelled = addProbeAliases(collect(null));
+ constructRootTree();
+ fireUpdateEvent(); //Inform listeners that everything is done
+ return new Status(!cancelled ? IStatus.OK : IStatus.CANCEL, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
+ }
+
+ private void reset() {
+ probes = new TreeNode("", false); //$NON-NLS-1$
+ statics = new TreeNode(Messages.ProbeParser_staticProbes, false);
+ aliases = new TreeNode(Messages.ProbeParser_aliasProbes, false);
+ }
+
+ private void constructRootTree() {
+ statics.sortTree();
+ aliases.sortTree();
+ probes.add(statics);
+ probes.add(aliases);
+ }
+
+ /**
+ * Returns a String containing all of the content from the probe
+ * point list, including variables and their type.
+ *
+ * stap -L
+ * Will list all available probe points
+ * @return the probe points consolidated into a single string
+ */
+ private String collect(String script) {
+ String[] options;
+ if(null == script) {
+ script = "**"; //$NON-NLS-1$
+ options = new String[] {"-L"}; //$NON-NLS-1$
+ } else {
+ options = null;
+ }
+
+ String s = runStap(options, script, false);
+ if (s == null) {
+ return ""; //$NON-NLS-1$
+ }
+
+ return s;
+ }
+
+ private boolean addStaticProbes() {
+ String s = runStap(new String[]{"--dump-probe-types"}, null, false); //$NON-NLS-1$
+ TreeNode group = null;
+ try (Scanner st = new Scanner(s)) {
+ while(st.hasNextLine()) {
+ if (cancelRequested) {
+ return false;
+ }
+ String tokenString = st.nextLine();
+ String probeName = (new StringTokenizer(tokenString)).nextToken();
+ group = addOrFindProbeGroup(extractProbeGroupName(probeName), group, statics);
+ group.add(makeStaticProbeNode(probeName));
+ }
+ return true;
+ }
+ }
+
+ /**
+ * Parses the output generated from running stap -L. Pulls out all functions
+ * and probe aliases from the provided string. Populates the probe tree.
+ *
+ * ProbeTree organized as:
+ * Root->Named Groups->ProbePoints->Variables
+ *
+ * @param probeDump A list of probe points with the same formatting used by stap -L.
+ * @return <code>false</code> if a cancellation prevented all probes from being added;
+ * <code>true</code> otherwise.
+ */
+ private boolean addProbeAliases(String probeDump) {
+ TreeNode group = null;
+ try (Scanner st = new Scanner(probeDump)) {
+ while(st.hasNextLine()) {
+ if (cancelRequested) {
+ return false;
+ }
+ String tokenString = st.nextLine();
+ // If the token starts with '_' or '__' it is a private probe so
+ // skip it.
+ if (tokenString.startsWith("_")) { //$NON-NLS-1$
+ continue;
+ }
+
+ StringTokenizer probeTokenizer = new StringTokenizer(tokenString);
+ String probeName = probeTokenizer.nextToken();
+
+ String groupName = extractProbeGroupName(tokenString);
+ if (!isStaticProbeGroup(groupName)) {
+ TreeNode probeNode = makeProbeAliasNode(probeName);
+ group = addOrFindProbeGroup(groupName, group, aliases);
+ group.add(probeNode);
+ addAllVarNodesToProbeNode(probeTokenizer, probeNode);
+ }
+ }
+ return true;
+ }
+ }
+
+ /**
+ * Find the appropriate parent group node for a probe alias to group probes by name.
+ * If it doesn't yet exist, create it and add it to the view's tree.
+ * @param probeLine The name of the probe group.
+ * @param groupNode For optimization, pass an existing group node here, as it will be
+ * used if the probe belongs in it. Otherwise, or if <code>null</code> is passed, a new one will be created.
+ * @param category The parent tree node in which to put the group node.
+ * @return The found or created group node that will be the parent of the probe's entry item in the view.
+ */
+ private TreeNode addOrFindProbeGroup(String groupName, TreeNode groupNode, TreeNode category) {
+
+ // If the current probe belongs to a group other than
+ // the most recent group. This should rarely be needed because the
+ // probe list is sorted... mostly.
+ if(groupNode == null || !groupNode.toString().equals(groupName)) {
+ groupNode = category.getChildByName(groupName);
+ }
+
+ // Create a new group and add it
+ if(groupNode == null) {
+ groupNode = new TreeNode(groupName, true);
+ category.add(groupNode);
+ }
+ return groupNode;
+ }
+
+ /**
+ * @return the name of the group a probe belongs to, based on the probe's name.
+ */
+ private String extractProbeGroupName(String probeName) {
+ int dotIndex = probeName.indexOf('.');
+ int parenIndex = probeName.indexOf('(');
+ if (dotIndex > 0 && parenIndex > 0) {
+ return probeName.substring(0, Math.min(dotIndex, parenIndex));
+ }
+ if (dotIndex > 0) {
+ return probeName.substring(0, dotIndex);
+ }
+ if (parenIndex > 0) {
+ return probeName.substring(0, parenIndex);
+ }
+ return probeName;
+ }
+
+ private TreeNode makeStaticProbeNode(String probeName) {
+ return new TreeNode(new ProbeNodeData(probeName), probeName, true);
+ }
+
+ private TreeNode makeProbeAliasNode(String probeName) {
+ return new TreeDefinitionNode(new ProbeNodeData(probeName), probeName, findDefinitionOf(probeName), true);
+ }
+
+ private boolean isStaticProbeGroup(String groupName) {
+ return statics.getChildByName(groupName) != null;
+ }
+
+ /**
+ * Search the tapset content dump for the path of the file which defines the provided probe alias.
+ * @param probeName The alias of the probe to find the definition file of.
+ * @return The path of the probe's definition file, or <code>null</code> if a definition
+ * file can't be found (which is the case for static probes).
+ */
+ private String findDefinitionOf(String probeName) {
+ SharedParser sparser = SharedParser.getInstance();
+ String tapsetContents = sparser.getTapsetContents();
+ Matcher probeMatcher = Pattern.compile(MessageFormat.format(tapsetProbeRegex, Pattern.quote(probeName))).matcher(tapsetContents);
+ if (!probeMatcher.find()) {
+ return null;
+ }
+ int fileLocIndex = tapsetContents.substring(0, probeMatcher.start()).lastIndexOf(SharedParser.TAG_FILE);
+ try (Scanner scanner = new Scanner(tapsetContents.substring(fileLocIndex))) {
+ Matcher fileMatcher = sparser.filePattern.matcher(scanner.nextLine());
+ return fileMatcher.matches()
+ ? fileMatcher.group(1)
+ : null;
+ }
+ }
+
+ /**
+ * Extracts the local variables from a (partially examined) probe alias token, and
+ * adds them as child tree entries of their parent probe.
+ */
+ private void addAllVarNodesToProbeNode(StringTokenizer varTokenizer, TreeNode probeNode) {
+ StringBuilder prev = new StringBuilder(""); //$NON-NLS-1$
+ // the remaining tokens are variable names and variable types name:type.
+ while(varTokenizer.hasMoreTokens()){
+ String token = varTokenizer.nextToken();
+
+ // Because some variable types contain spaces (var2:struct task_struct)
+ // the only way to know if we have the entire string representing a
+ // variable is if we reach the next token containing a ':' or we reach
+ // the end of the stream.
+ if (token.contains(":") && prev.length() > 0){ //$NON-NLS-1$
+ prev.setLength(prev.length() - 1); // Remove the trailing space.
+ addVarNodeToProbeNode(prev.toString(), probeNode);
+ prev.setLength(0);
+ }
+ prev.append(token + " "); //$NON-NLS-1$
+ }
+
+ // Add the last token if there is one
+ if (prev.length() > 0){
+ prev.setLength(prev.length() - 1); // Remove the trailing space.
+ addVarNodeToProbeNode(prev.toString(), probeNode);
+ }
+ }
+
+ private void addVarNodeToProbeNode(String info, TreeNode probeNode) {
+ probeNode.add(new TreeNode(new ProbevarNodeData(info), info, false));
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbevarNodeData.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbevarNodeData.java
index cb3efdb36a..bcb0208ead 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbevarNodeData.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/ProbevarNodeData.java
@@ -20,47 +20,47 @@ import java.util.List;
* @since 3.0
*/
public class ProbevarNodeData {
- private String text;
- private String name;
- private List<String> types;
+ private String text;
+ private String name;
+ private List<String> types;
- /**
- * @return The original line of text passed to this object, which contains the
- * variable's name and its full type.
- */
- @Override
- public String toString() {
- return text;
- }
+ /**
+ * @return The original line of text passed to this object, which contains the
+ * variable's name and its full type.
+ */
+ @Override
+ public String toString() {
+ return text;
+ }
- /**
- * @return The name of the variable.
- */
- public String getName() {
- return name;
- }
+ /**
+ * @return The name of the variable.
+ */
+ public String getName() {
+ return name;
+ }
- /**
- * @return A list of all tokens used to describe the variable's type.
- */
- public List<String> getTypes() {
- return types;
- }
+ /**
+ * @return A list of all tokens used to describe the variable's type.
+ */
+ public List<String> getTypes() {
+ return types;
+ }
- /**
- * Create a new instance of probe variable node information.
- * @param line A line of text generated by running "stap -L" which
- * provides all information pertaining to a probe point.
- */
- public ProbevarNodeData(String line) {
- text = line.trim();
- int colonIndex = text.indexOf(':');
- if (colonIndex == -1) {
- name = text;
- types = Collections.emptyList();
- } else {
- name = line.substring(0, colonIndex);
- types = Arrays.asList(text.substring(colonIndex+1).split(" ")); //$NON-NLS-1$
- }
- }
+ /**
+ * Create a new instance of probe variable node information.
+ * @param line A line of text generated by running "stap -L" which
+ * provides all information pertaining to a probe point.
+ */
+ public ProbevarNodeData(String line) {
+ text = line.trim();
+ int colonIndex = text.indexOf(':');
+ if (colonIndex == -1) {
+ name = text;
+ types = Collections.emptyList();
+ } else {
+ name = line.substring(0, colonIndex);
+ types = Arrays.asList(text.substring(colonIndex+1).split(" ")); //$NON-NLS-1$
+ }
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/SharedParser.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/SharedParser.java
index 0571f39d09..4c4dfeffd8 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/SharedParser.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/SharedParser.java
@@ -20,57 +20,57 @@ import org.eclipse.linuxtools.internal.systemtap.ui.ide.IDEPlugin;
public class SharedParser extends TapsetParser {
- static final String TAG_FILE = "# file"; //$NON-NLS-1$
- /**
- * A pattern that can be used to locate file paths listed in stap tapset dumps.
- */
- final Pattern filePattern = Pattern.compile("# file (/.*\\.stp)"); //$NON-NLS-1$
+ static final String TAG_FILE = "# file"; //$NON-NLS-1$
+ /**
+ * A pattern that can be used to locate file paths listed in stap tapset dumps.
+ */
+ final Pattern filePattern = Pattern.compile("# file (/.*\\.stp)"); //$NON-NLS-1$
- private String tapsetContents = null;
+ private String tapsetContents = null;
- static SharedParser parser = null;
- public static SharedParser getInstance(){
- if (parser != null) {
- return parser;
- }
- parser = new SharedParser();
- return parser;
- }
+ static SharedParser parser = null;
+ public static SharedParser getInstance(){
+ if (parser != null) {
+ return parser;
+ }
+ parser = new SharedParser();
+ return parser;
+ }
- private SharedParser() {
- super("Shared Parser"); //$NON-NLS-1$
- }
+ private SharedParser() {
+ super("Shared Parser"); //$NON-NLS-1$
+ }
- /**
- * Clear the cached tapset contents, so that the next call to {@link #getTapsetContents()}
- * will be guaranteed to use a new call of stap to gather up-to-date tapset contents.
- */
- synchronized void clearTapsetContents() {
- tapsetContents = null;
- }
+ /**
+ * Clear the cached tapset contents, so that the next call to {@link #getTapsetContents()}
+ * will be guaranteed to use a new call of stap to gather up-to-date tapset contents.
+ */
+ synchronized void clearTapsetContents() {
+ tapsetContents = null;
+ }
- /**
- * Get the contents of default & all imported tapsets. When calling this method
- * for the first time (or after changing the list of tapset directories), this will
- * run a dummy stap script to obtain the tapset contents, which will be cached into
- * memory. Subsequent calls will simply read the saved contents.
- * @return The string contents of tapsets, or <code>null</code> if there was an
- * error in obtaining this information.
- */
- synchronized String getTapsetContents() {
- if (tapsetContents == null) {
- run(null);
- }
- return tapsetContents;
- }
+ /**
+ * Get the contents of default & all imported tapsets. When calling this method
+ * for the first time (or after changing the list of tapset directories), this will
+ * run a dummy stap script to obtain the tapset contents, which will be cached into
+ * memory. Subsequent calls will simply read the saved contents.
+ * @return The string contents of tapsets, or <code>null</code> if there was an
+ * error in obtaining this information.
+ */
+ synchronized String getTapsetContents() {
+ if (tapsetContents == null) {
+ run(null);
+ }
+ return tapsetContents;
+ }
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- tapsetContents = runStap(new String[] {"-v", "-p1", "-e"}, "probe begin{}", false); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
- // Exclude the dump of the test script by excluding everything before the second pathname
- // (which is the first actual tapset file, not the input script).
- tapsetContents = tapsetContents.substring(tapsetContents.indexOf(TAG_FILE, tapsetContents.indexOf(TAG_FILE)+1));
- return new Status(IStatus.OK, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
- }
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ tapsetContents = runStap(new String[] {"-v", "-p1", "-e"}, "probe begin{}", false); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
+ // Exclude the dump of the test script by excluding everything before the second pathname
+ // (which is the first actual tapset file, not the input script).
+ tapsetContents = tapsetContents.substring(tapsetContents.indexOf(TAG_FILE, tapsetContents.indexOf(TAG_FILE)+1));
+ return new Status(IStatus.OK, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/StapErrorParser.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/StapErrorParser.java
index f0de0199a1..c8771976b3 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/StapErrorParser.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/StapErrorParser.java
@@ -22,66 +22,66 @@ import org.eclipse.linuxtools.systemtap.ui.consolelog.structures.IErrorParser;
* @author Ryan Morse
*/
public final class StapErrorParser implements IErrorParser {
- /**
- * Parses the error log passed in into a table of strings.
- * @param output The output from the stderr StreamGobbler.
- * @return A table of strings in the proper format to be displayed in the error log.
- */
- @Override
- public String[][] parseOutput(String output) {
- String[][] sErrors = null;
- ArrayList<String[]> errors = new ArrayList<>();
- int errorType = TYPE;
+ /**
+ * Parses the error log passed in into a table of strings.
+ * @param output The output from the stderr StreamGobbler.
+ * @return A table of strings in the proper format to be displayed in the error log.
+ */
+ @Override
+ public String[][] parseOutput(String output) {
+ String[][] sErrors = null;
+ ArrayList<String[]> errors = new ArrayList<>();
+ int errorType = TYPE;
- if(null != output) {
- String[] tokens = output.split("\\s"); //$NON-NLS-1$
- String[] row = null;
+ if(null != output) {
+ String[] tokens = output.split("\\s"); //$NON-NLS-1$
+ String[] row = null;
- for(int i=0; i<tokens.length; i++) {
- if(tokens[i].equals("error:")) { //$NON-NLS-1$
- row = new String[] {"", "", "", ""}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
- errors.add(row);
- row[TYPE] = tokens[i-1] + " " + tokens[i]; //$NON-NLS-1$
- errorType = ERROR;
- i++;
- } else if(tokens[i].equals("saw:")) { //$NON-NLS-1$
- errorType = SAW;
- i++;
- } else if(tokens[i].equals("at")) { //$NON-NLS-1$
- errorType = LOCATION;
- i++;
- } else if(tokens[i].equals("Pass")) { //$NON-NLS-1$
- errorType = PASS;
+ for(int i=0; i<tokens.length; i++) {
+ if(tokens[i].equals("error:")) { //$NON-NLS-1$
+ row = new String[] {"", "", "", ""}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
+ errors.add(row);
+ row[TYPE] = tokens[i-1] + " " + tokens[i]; //$NON-NLS-1$
+ errorType = ERROR;
+ i++;
+ } else if(tokens[i].equals("saw:")) { //$NON-NLS-1$
+ errorType = SAW;
+ i++;
+ } else if(tokens[i].equals("at")) { //$NON-NLS-1$
+ errorType = LOCATION;
+ i++;
+ } else if(tokens[i].equals("Pass")) { //$NON-NLS-1$
+ errorType = PASS;
- }
+ }
- if (null != row && errorType != PASS) {
- row[errorType] += tokens[i] + " "; //$NON-NLS-1$
- }
- }
+ if (null != row && errorType != PASS) {
+ row[errorType] += tokens[i] + " "; //$NON-NLS-1$
+ }
+ }
- sErrors = new String[errors.size()][4];
- System.arraycopy(errors.toArray(), 0, sErrors, 0, errors.size());
+ sErrors = new String[errors.size()][4];
+ System.arraycopy(errors.toArray(), 0, sErrors, 0, errors.size());
- for(int i=0; i<sErrors.length; i++)
- sErrors[i][LOCATION] = fixLocation(sErrors[i][LOCATION]);
- }
+ for(int i=0; i<sErrors.length; i++)
+ sErrors[i][LOCATION] = fixLocation(sErrors[i][LOCATION]);
+ }
- return sErrors;
- }
+ return sErrors;
+ }
- private static String fixLocation(String loc) {
- if(loc.contains(":")) { //$NON-NLS-1$
- loc = loc.substring(loc.indexOf(':')+1, loc.lastIndexOf(':'));
- return loc;
- } else {
- return ""; //$NON-NLS-1$
- }
- }
+ private static String fixLocation(String loc) {
+ if(loc.contains(":")) { //$NON-NLS-1$
+ loc = loc.substring(loc.indexOf(':')+1, loc.lastIndexOf(':'));
+ return loc;
+ } else {
+ return ""; //$NON-NLS-1$
+ }
+ }
- private static final int TYPE = 0;
- private static final int ERROR = 1;
- private static final int SAW = 2;
- private static final int LOCATION = 3;
- private static final int PASS = 4;
+ private static final int TYPE = 0;
+ private static final int ERROR = 1;
+ private static final int SAW = 2;
+ private static final int LOCATION = 3;
+ private static final int PASS = 4;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TapsetLibrary.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TapsetLibrary.java
index d56b9f20ba..c89c9857ff 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TapsetLibrary.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TapsetLibrary.java
@@ -43,372 +43,372 @@ import org.eclipse.ui.PlatformUI;
*/
public final class TapsetLibrary {
- private static TreeNode functionTree = null;
- private static TreeNode probeTree = null;
-
- private static FunctionParser functionParser = null;
- private static ProbeParser probeParser = null;
-
- public static TreeNode getProbes() {
- return probeTree;
- }
-
- public static TreeNode getStaticProbes() {
- return probeTree == null ? null : probeTree.getChildByName(Messages.ProbeParser_staticProbes);
- }
-
- public static TreeNode getProbeAliases() {
- return probeTree == null ? null : probeTree.getChildByName(Messages.ProbeParser_aliasProbes);
- }
-
- public static TreeNode getFunctions() {
- return functionTree;
- }
-
- private static HashMap<String, String> pages = new HashMap<>();
-
- /**
- * Returns the documentation for the given probe, function, or tapset.
- * @since 2.0
- */
- public static synchronized String getDocumentation(String element) {
- String documentation = pages.get(element);
- if (documentation == null) {
-
- // If the requested element is a probe variable
- // fetch the documentation for the parent probe then check the map
- if (element.matches("probe::.*::.*")) { //$NON-NLS-1$
- String probe = element.split("::")[1]; //$NON-NLS-1$
- getDocumentation("probe::" + probe); //$NON-NLS-1$
- return pages.get(element);
- }
-
- // Otherwise, get the documentation for the requested element.
- documentation = (new ManPage(element)).getStrippedTextPage().toString();
-
- // If the requested element is a probe and a documentation page was
- // found for it, parse the documentation for the variables if present.
- if (!documentation.startsWith("No manual entry for") && //$NON-NLS-1$
- element.startsWith("probe::")) { //$NON-NLS-1$
- // If this is a probe parse out the variables
- String[] sections = documentation.split("VALUES"); //$NON-NLS-1$
- if (sections.length > 1) {
- // Discard any other sections
- String variablesString = sections[1].split("CONTEXT|DESCRIPTION|SystemTap Tapset Reference")[0].trim(); //$NON-NLS-1$
- String[] variables = variablesString.split("\n"); //$NON-NLS-1$
- int i = 0;
- if (!variables[0].equals("None")) { //$NON-NLS-1$
- while ( i < variables.length) {
- String variableName = variables[i].trim();
- StringBuilder variableDocumentation = new StringBuilder();
- i++;
- while (i < variables.length && !variables[i].isEmpty()) {
- variableDocumentation.append(variables[i].trim());
- variableDocumentation.append("\n"); //$NON-NLS-1$
- i++;
- }
-
- pages.put(element + "::" + variableName, variableDocumentation.toString().trim()); //$NON-NLS-1$
- i++;
- }
- }
- }
- }
- }
- return documentation;
- }
-
- /**
- * Returns the documentation for the given element and caches the result. Use this
- * function if the given element is known to be a probe, function, or tapset.
- * @param element
- * @return
- * @since 2.0
- */
- public static synchronized String getAndCacheDocumentation(String element) {
- String doc = pages.get(element);
- if (doc == null) {
- doc = getDocumentation(element);
- pages.put(element, doc);
- }
- return doc;
- }
-
- private static IPropertyChangeListener propertyChangeListener = new IPropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getProperty().equals(IDEPreferenceConstants.P_TAPSETS)) {
- runStapParser();
- }
- }
- };
-
- /**
- * This method will attempt to get the most up-to-date information.
- * However, if the TapsetParser is running already it will quit,
- * assuming that new information will be available soon. By registering
- * a listener at that point the class can be notified when an update is
- * available.
- */
- public static void init() {
- if (null != functionParser && null != probeParser) {
- return;
- }
-
- IPreferenceStore preferenceStore = IDEPlugin.getDefault().getPreferenceStore();
- preferenceStore.addPropertyChangeListener(propertyChangeListener);
-
- if (preferenceStore.contains(IDEPreferenceConstants.P_STORED_TREE)
- && preferenceStore.getBoolean(IDEPreferenceConstants.P_STORED_TREE)
- && isTreeFileCurrent()) {
- readTreeFile();
- } else {
- runStapParser();
- }
- }
-
- /**
- * This method will create a new instance of the TapsetParser in order
- * to get the information directly from the files.
- */
- private static void runStapParser() {
- SharedParser.getInstance().clearTapsetContents();
-
- functionParser = FunctionParser.getInstance();
- functionParser.addListener(functionCompletionListener);
- functionParser.schedule();
-
- probeParser = ProbeParser.getInstance();
- probeParser.addListener(probeCompletionListener);
- probeParser.schedule();
- }
-
- /**
- * This method will get all of the tree information from
- * the TreeSettings xml file.
- */
- private static void readTreeFile() {
- functionTree = TreeSettings.getFunctionTree();
- probeTree = TreeSettings.getProbeTree();
- }
-
- /**
- * This method checks to see if the tapsets have changed
- * at all since the TreeSettings.xml file was created.
- * @return boolean indicating whether or not the TreeSettings.xml file has the most up-to-date version
- */
- private static boolean isTreeFileCurrent() {
- long treesDate = TreeSettings.getTreeFileDate();
-
- IPreferenceStore p = IDEPlugin.getDefault().getPreferenceStore();
- String[] tapsets = p.getString(IDEPreferenceConstants.P_TAPSETS).split(File.pathSeparator);
-
- File f = getTapsetLocation(p);
-
- if (!checkIsCurrentFolder(treesDate, f)) {
- return false;
- }
-
- for(int i=0; i<tapsets.length; i++) {
- f = new File(tapsets[i]);
- if (f.lastModified() > treesDate) {
- return false;
- }
- if (f.canRead() && !checkIsCurrentFolder(treesDate, f)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * This method attempts to locate the default tapset directory.
- * @param p Preference store where the tapset location might be stored
- * @return File representing the default tapset location.
- */
- public static File getTapsetLocation(IPreferenceStore p) {
- File f;
- String path = p.getString(PreferenceConstants.P_ENV[2][0]);
- if(path.trim().isEmpty()) {
- f = new File("/usr/share/systemtap/tapset"); //$NON-NLS-1$
- if(!f.exists()) {
- f = new File("/usr/local/share/systemtap/tapset"); //$NON-NLS-1$
- if(!f.exists()) {
- InputDialog i = new InputDialog(
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
- Localization.getString("TapsetBrowserView.TapsetLocation"), Localization.getString("TapsetBrowserView.WhereDefaultTapset"), "", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- i.open();
- p.setValue(PreferenceConstants.P_ENV[2][0], i.getValue());
- f = new File( i.getValue() );
- }
- }
- } else {
- f = new File( p.getString(path) );
- }
- IDESessionSettings.tapsetLocation = f.getAbsolutePath();
- return f;
- }
-
- /**
- * This method checks the provided time stap against the folders
- * time stamp. This is to see if the folder may have new data in it
- * @param time The current time stamp
- * @param folder The folder to check if it is newer the then time stamp
- * @return boolean indicating whether the time stamp is newer then the folder
- */
- private static boolean checkIsCurrentFolder(long time, File folder) {
- File[] fs = folder.listFiles();
-
- for(int i=0; i<fs.length; i++) {
- if (fs[i].lastModified() > time) {
- return false;
- }
-
- if (fs[i].isDirectory() && fs[i].canRead()
- && !checkIsCurrentFolder(time, fs[i])) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Adds a new listener to the TapsetParser
- * @param listener the listener to be added
- * @return boolean indicating whether or not the listener was added
- * @since 2.0
- */
- public static boolean addFunctionListener(IUpdateListener listener) {
- if(null == functionParser) {
- return false;
- }
- functionParser.addListener(listener);
- return true;
- }
-
- /**
- * @since 2.0
- */
- public static boolean addProbeListener(IUpdateListener listener) {
- if(null == probeParser) {
- return false;
- }
- probeParser.addListener(listener);
- return true;
- }
-
- private static Job cacheFunctionManpages = new Job(Localization.getString("TapsetLibrary.0")) { //$NON-NLS-1$
- private boolean cancelled;
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- TreeNode node = functionParser.getFunctions();
- int n = node.getChildCount();
- for (int i = 0; i < n && !this.cancelled; i++) {
- getAndCacheDocumentation("function::" + (node.getChildAt(i).toString())); //$NON-NLS-1$
- }
-
- return new Status(IStatus.OK, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$;
- }
-
- @Override
- protected void canceling() {
- this.cancelled = true;
- }
-
- };
-
- private static Job cacheProbeManpages = new Job(Localization.getString("TapsetLibrary.1")) { //$NON-NLS-1$
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- TreeNode node = probeParser.getProbes();
- int n = node.getChildCount();
- for (int i = 0; i < n; i++) {
- getAndCacheDocumentation("tapset::" + (node.getChildAt(i).toString())); //$NON-NLS-1$
- // No need to pre-cache probes; they can be fetched pretty quickly.
- }
-
- return new Status(IStatus.OK, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$;
- }
- };
-
- private static final IUpdateListener functionCompletionListener = new IUpdateListener() {
- @Override
- public void handleUpdateEvent() {
- functionTree = functionParser.getFunctions();
- cacheFunctionManpages.schedule();
- TreeSettings.setTrees(functionTree, probeTree);
- synchronized (functionParser) {
- functionParser.notifyAll();
- }
- }
- };
-
- private static final IUpdateListener probeCompletionListener = new IUpdateListener() {
- @Override
- public void handleUpdateEvent() {
- probeTree = probeParser.getProbes();
- cacheProbeManpages.schedule();
- synchronized (probeParser) {
- probeParser.notifyAll();
- }
- }
- };
-
- /**
- * Blocks the current thread until the parser has finished
- * parsing probes and functions.
- * @since 2.0
- */
- public static void waitForInitialization() {
- while (functionParser.getResult() == null) {
- try {
- synchronized (functionParser) {
- functionParser.wait(5000);
- }
- } catch (InterruptedException e) {
- break;
- }
- }
- while (probeParser.getResult() == null) {
- try {
- synchronized (probeParser) {
- probeParser.wait(5000);
- }
- } catch (InterruptedException e) {
- break;
- }
- }
- }
-
- /**
- * This method will stop services started by
- * {@link TapsetLibrary#init()} such as the {@link TapsetParser}
- * @since 1.2
- */
- public static void stop() {
- if(null != functionParser) {
- functionParser.cancel();
- cacheFunctionManpages.cancel();
- try {
- functionParser.join();
- } catch (InterruptedException e) {
- // The current thread was interrupted while waiting
- // for the parser thread to exit. Nothing to do
- // continue stopping.
- }
- }
- if(probeParser != null) {
- probeParser.cancel();
- cacheProbeManpages.cancel();
- try {
- probeParser.join();
- } catch (InterruptedException e) {
- // The current thread was interrupted while waiting
- // for the parser thread to exit. Nothing to do
- // continue stopping.
- }
- }
-
- }
+ private static TreeNode functionTree = null;
+ private static TreeNode probeTree = null;
+
+ private static FunctionParser functionParser = null;
+ private static ProbeParser probeParser = null;
+
+ public static TreeNode getProbes() {
+ return probeTree;
+ }
+
+ public static TreeNode getStaticProbes() {
+ return probeTree == null ? null : probeTree.getChildByName(Messages.ProbeParser_staticProbes);
+ }
+
+ public static TreeNode getProbeAliases() {
+ return probeTree == null ? null : probeTree.getChildByName(Messages.ProbeParser_aliasProbes);
+ }
+
+ public static TreeNode getFunctions() {
+ return functionTree;
+ }
+
+ private static HashMap<String, String> pages = new HashMap<>();
+
+ /**
+ * Returns the documentation for the given probe, function, or tapset.
+ * @since 2.0
+ */
+ public static synchronized String getDocumentation(String element) {
+ String documentation = pages.get(element);
+ if (documentation == null) {
+
+ // If the requested element is a probe variable
+ // fetch the documentation for the parent probe then check the map
+ if (element.matches("probe::.*::.*")) { //$NON-NLS-1$
+ String probe = element.split("::")[1]; //$NON-NLS-1$
+ getDocumentation("probe::" + probe); //$NON-NLS-1$
+ return pages.get(element);
+ }
+
+ // Otherwise, get the documentation for the requested element.
+ documentation = (new ManPage(element)).getStrippedTextPage().toString();
+
+ // If the requested element is a probe and a documentation page was
+ // found for it, parse the documentation for the variables if present.
+ if (!documentation.startsWith("No manual entry for") && //$NON-NLS-1$
+ element.startsWith("probe::")) { //$NON-NLS-1$
+ // If this is a probe parse out the variables
+ String[] sections = documentation.split("VALUES"); //$NON-NLS-1$
+ if (sections.length > 1) {
+ // Discard any other sections
+ String variablesString = sections[1].split("CONTEXT|DESCRIPTION|SystemTap Tapset Reference")[0].trim(); //$NON-NLS-1$
+ String[] variables = variablesString.split("\n"); //$NON-NLS-1$
+ int i = 0;
+ if (!variables[0].equals("None")) { //$NON-NLS-1$
+ while ( i < variables.length) {
+ String variableName = variables[i].trim();
+ StringBuilder variableDocumentation = new StringBuilder();
+ i++;
+ while (i < variables.length && !variables[i].isEmpty()) {
+ variableDocumentation.append(variables[i].trim());
+ variableDocumentation.append("\n"); //$NON-NLS-1$
+ i++;
+ }
+
+ pages.put(element + "::" + variableName, variableDocumentation.toString().trim()); //$NON-NLS-1$
+ i++;
+ }
+ }
+ }
+ }
+ }
+ return documentation;
+ }
+
+ /**
+ * Returns the documentation for the given element and caches the result. Use this
+ * function if the given element is known to be a probe, function, or tapset.
+ * @param element
+ * @return
+ * @since 2.0
+ */
+ public static synchronized String getAndCacheDocumentation(String element) {
+ String doc = pages.get(element);
+ if (doc == null) {
+ doc = getDocumentation(element);
+ pages.put(element, doc);
+ }
+ return doc;
+ }
+
+ private static IPropertyChangeListener propertyChangeListener = new IPropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ if (event.getProperty().equals(IDEPreferenceConstants.P_TAPSETS)) {
+ runStapParser();
+ }
+ }
+ };
+
+ /**
+ * This method will attempt to get the most up-to-date information.
+ * However, if the TapsetParser is running already it will quit,
+ * assuming that new information will be available soon. By registering
+ * a listener at that point the class can be notified when an update is
+ * available.
+ */
+ public static void init() {
+ if (null != functionParser && null != probeParser) {
+ return;
+ }
+
+ IPreferenceStore preferenceStore = IDEPlugin.getDefault().getPreferenceStore();
+ preferenceStore.addPropertyChangeListener(propertyChangeListener);
+
+ if (preferenceStore.contains(IDEPreferenceConstants.P_STORED_TREE)
+ && preferenceStore.getBoolean(IDEPreferenceConstants.P_STORED_TREE)
+ && isTreeFileCurrent()) {
+ readTreeFile();
+ } else {
+ runStapParser();
+ }
+ }
+
+ /**
+ * This method will create a new instance of the TapsetParser in order
+ * to get the information directly from the files.
+ */
+ private static void runStapParser() {
+ SharedParser.getInstance().clearTapsetContents();
+
+ functionParser = FunctionParser.getInstance();
+ functionParser.addListener(functionCompletionListener);
+ functionParser.schedule();
+
+ probeParser = ProbeParser.getInstance();
+ probeParser.addListener(probeCompletionListener);
+ probeParser.schedule();
+ }
+
+ /**
+ * This method will get all of the tree information from
+ * the TreeSettings xml file.
+ */
+ private static void readTreeFile() {
+ functionTree = TreeSettings.getFunctionTree();
+ probeTree = TreeSettings.getProbeTree();
+ }
+
+ /**
+ * This method checks to see if the tapsets have changed
+ * at all since the TreeSettings.xml file was created.
+ * @return boolean indicating whether or not the TreeSettings.xml file has the most up-to-date version
+ */
+ private static boolean isTreeFileCurrent() {
+ long treesDate = TreeSettings.getTreeFileDate();
+
+ IPreferenceStore p = IDEPlugin.getDefault().getPreferenceStore();
+ String[] tapsets = p.getString(IDEPreferenceConstants.P_TAPSETS).split(File.pathSeparator);
+
+ File f = getTapsetLocation(p);
+
+ if (!checkIsCurrentFolder(treesDate, f)) {
+ return false;
+ }
+
+ for(int i=0; i<tapsets.length; i++) {
+ f = new File(tapsets[i]);
+ if (f.lastModified() > treesDate) {
+ return false;
+ }
+ if (f.canRead() && !checkIsCurrentFolder(treesDate, f)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * This method attempts to locate the default tapset directory.
+ * @param p Preference store where the tapset location might be stored
+ * @return File representing the default tapset location.
+ */
+ public static File getTapsetLocation(IPreferenceStore p) {
+ File f;
+ String path = p.getString(PreferenceConstants.P_ENV[2][0]);
+ if(path.trim().isEmpty()) {
+ f = new File("/usr/share/systemtap/tapset"); //$NON-NLS-1$
+ if(!f.exists()) {
+ f = new File("/usr/local/share/systemtap/tapset"); //$NON-NLS-1$
+ if(!f.exists()) {
+ InputDialog i = new InputDialog(
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
+ Localization.getString("TapsetBrowserView.TapsetLocation"), Localization.getString("TapsetBrowserView.WhereDefaultTapset"), "", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ i.open();
+ p.setValue(PreferenceConstants.P_ENV[2][0], i.getValue());
+ f = new File( i.getValue() );
+ }
+ }
+ } else {
+ f = new File( p.getString(path) );
+ }
+ IDESessionSettings.tapsetLocation = f.getAbsolutePath();
+ return f;
+ }
+
+ /**
+ * This method checks the provided time stap against the folders
+ * time stamp. This is to see if the folder may have new data in it
+ * @param time The current time stamp
+ * @param folder The folder to check if it is newer the then time stamp
+ * @return boolean indicating whether the time stamp is newer then the folder
+ */
+ private static boolean checkIsCurrentFolder(long time, File folder) {
+ File[] fs = folder.listFiles();
+
+ for(int i=0; i<fs.length; i++) {
+ if (fs[i].lastModified() > time) {
+ return false;
+ }
+
+ if (fs[i].isDirectory() && fs[i].canRead()
+ && !checkIsCurrentFolder(time, fs[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Adds a new listener to the TapsetParser
+ * @param listener the listener to be added
+ * @return boolean indicating whether or not the listener was added
+ * @since 2.0
+ */
+ public static boolean addFunctionListener(IUpdateListener listener) {
+ if(null == functionParser) {
+ return false;
+ }
+ functionParser.addListener(listener);
+ return true;
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static boolean addProbeListener(IUpdateListener listener) {
+ if(null == probeParser) {
+ return false;
+ }
+ probeParser.addListener(listener);
+ return true;
+ }
+
+ private static Job cacheFunctionManpages = new Job(Localization.getString("TapsetLibrary.0")) { //$NON-NLS-1$
+ private boolean cancelled;
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ TreeNode node = functionParser.getFunctions();
+ int n = node.getChildCount();
+ for (int i = 0; i < n && !this.cancelled; i++) {
+ getAndCacheDocumentation("function::" + (node.getChildAt(i).toString())); //$NON-NLS-1$
+ }
+
+ return new Status(IStatus.OK, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$;
+ }
+
+ @Override
+ protected void canceling() {
+ this.cancelled = true;
+ }
+
+ };
+
+ private static Job cacheProbeManpages = new Job(Localization.getString("TapsetLibrary.1")) { //$NON-NLS-1$
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ TreeNode node = probeParser.getProbes();
+ int n = node.getChildCount();
+ for (int i = 0; i < n; i++) {
+ getAndCacheDocumentation("tapset::" + (node.getChildAt(i).toString())); //$NON-NLS-1$
+ // No need to pre-cache probes; they can be fetched pretty quickly.
+ }
+
+ return new Status(IStatus.OK, IDEPlugin.PLUGIN_ID, ""); //$NON-NLS-1$;
+ }
+ };
+
+ private static final IUpdateListener functionCompletionListener = new IUpdateListener() {
+ @Override
+ public void handleUpdateEvent() {
+ functionTree = functionParser.getFunctions();
+ cacheFunctionManpages.schedule();
+ TreeSettings.setTrees(functionTree, probeTree);
+ synchronized (functionParser) {
+ functionParser.notifyAll();
+ }
+ }
+ };
+
+ private static final IUpdateListener probeCompletionListener = new IUpdateListener() {
+ @Override
+ public void handleUpdateEvent() {
+ probeTree = probeParser.getProbes();
+ cacheProbeManpages.schedule();
+ synchronized (probeParser) {
+ probeParser.notifyAll();
+ }
+ }
+ };
+
+ /**
+ * Blocks the current thread until the parser has finished
+ * parsing probes and functions.
+ * @since 2.0
+ */
+ public static void waitForInitialization() {
+ while (functionParser.getResult() == null) {
+ try {
+ synchronized (functionParser) {
+ functionParser.wait(5000);
+ }
+ } catch (InterruptedException e) {
+ break;
+ }
+ }
+ while (probeParser.getResult() == null) {
+ try {
+ synchronized (probeParser) {
+ probeParser.wait(5000);
+ }
+ } catch (InterruptedException e) {
+ break;
+ }
+ }
+ }
+
+ /**
+ * This method will stop services started by
+ * {@link TapsetLibrary#init()} such as the {@link TapsetParser}
+ * @since 1.2
+ */
+ public static void stop() {
+ if(null != functionParser) {
+ functionParser.cancel();
+ cacheFunctionManpages.cancel();
+ try {
+ functionParser.join();
+ } catch (InterruptedException e) {
+ // The current thread was interrupted while waiting
+ // for the parser thread to exit. Nothing to do
+ // continue stopping.
+ }
+ }
+ if(probeParser != null) {
+ probeParser.cancel();
+ cacheProbeManpages.cancel();
+ try {
+ probeParser.join();
+ } catch (InterruptedException e) {
+ // The current thread was interrupted while waiting
+ // for the parser thread to exit. Nothing to do
+ // continue stopping.
+ }
+ }
+
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TapsetParser.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TapsetParser.java
index 5c291d9510..2675b32e12 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TapsetParser.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TapsetParser.java
@@ -48,151 +48,151 @@ import com.jcraft.jsch.JSchException;
*/
public abstract class TapsetParser extends Job {
- private ArrayList<IUpdateListener> listeners;
-
- protected boolean cancelRequested;
-
- protected TapsetParser(String jobTitle) {
- super(jobTitle);
- listeners = new ArrayList<>();
- cancelRequested = false;
- }
-
- @Override
- protected void canceling() {
- super.canceling();
- this.cancelRequested = true;
- }
-
- /**
- * This method will register a new listener with the parser
- * @param listener The listener that will receive updateEvents
- */
- public void addListener(IUpdateListener listener) {
- if (null != listener) {
- listeners.add(listener);
- }
- }
-
- /**
- * This method will unregister the listener with the parser
- * @param listener The listener that no longer wants to recieve update events
- */
- public void removeListener(IUpdateListener listener) {
- if (null != listener) {
- listeners.remove(listener);
- }
- }
-
- /**
- * This method will fire an updateEvent to all listeners.
- */
- protected void fireUpdateEvent() {
- for (IUpdateListener listener : listeners) {
- listener.handleUpdateEvent();
- }
- }
-
- /**
- * Runs the stap with the given options and returns the output generated
- * @param options String[] of any optional parameters to pass to stap
- * @param probe String containing the script to run stap on,
- * or <code>null</code> for scriptless commands
- * @param getErrors Set this to <code>true</code> if the script's error
- * stream contents should be returned instead of its standard output
- */
- protected String runStap(String[] options, String probe, boolean getErrors) {
- String[] args = null;
- String[] tapsets = IDEPlugin.getDefault().getPreferenceStore()
- .getString(IDEPreferenceConstants.P_TAPSETS).split(File.pathSeparator);
- boolean noTapsets = tapsets[0].trim().length() == 0;
- boolean noOptions = options[0].trim().length() == 0;
-
- int size = probe != null ? 2 : 1;
- if (tapsets.length > 0 && !noTapsets) {
- size += tapsets.length<<1;
- }
- if (options.length > 0 && !noOptions) {
- size += options.length;
- }
-
- args = new String[size];
- args[0] = "stap"; //$NON-NLS-1$
- if (probe != null) {
- args[size-1] = probe;
- }
-
- //Add extra tapset directories
- if (tapsets.length > 0 && !noTapsets) {
- for (int i = 0; i < tapsets.length; i++) {
- args[1 + 2*i] = "-I"; //$NON-NLS-1$
- args[2 + 2*i] = tapsets[i];
- }
- }
- if (options.length > 0 && !noOptions) {
- for (int i = 0, s = noTapsets ? 1 : 1 + tapsets.length*2; i<options.length; i++) {
- args[s + i] = options[i];
- }
- }
-
- try {
- if (IDEPlugin.getDefault().getPreferenceStore().getBoolean(IDEPreferenceConstants.P_REMOTE_PROBES)) {
- StringOutputStream str = new StringOutputStream();
- StringOutputStream strErr = new StringOutputStream();
-
- IPreferenceStore p = ConsoleLogPlugin.getDefault().getPreferenceStore();
- String user = p.getString(ConsoleLogPreferenceConstants.SCP_USER);
- String host = p.getString(ConsoleLogPreferenceConstants.HOST_NAME);
- String password = p.getString(ConsoleLogPreferenceConstants.SCP_PASSWORD);
-
- Channel channel = SystemtapProcessFactory.execRemoteAndWait(args,str, strErr, user, host, password);
- if (channel == null) {
- displayError(Messages.TapsetParser_CannotRunStapTitle, Messages.TapsetParser_CannotRunStapMessage);
- }
-
- return (!getErrors ? str : strErr).toString();
- } else {
- Process process = RuntimeProcessFactory.getFactory().exec(args, null, null);
- if(process == null){
- displayError(Messages.TapsetParser_CannotRunStapTitle, Messages.TapsetParser_CannotRunStapMessage);
- return null;
- }
-
- StringStreamGobbler gobbler = new StringStreamGobbler(process.getInputStream());
- StringStreamGobbler egobbler = null;
- gobbler.start();
- if (getErrors) {
- egobbler = new StringStreamGobbler(process.getErrorStream());
- egobbler.start();
- }
- process.waitFor();
- gobbler.stop();
- if (egobbler == null) {
- return gobbler.getOutput().toString();
- } else {
- egobbler.stop();
- return egobbler.getOutput().toString();
- }
- }
-
- } catch (JSchException|IOException e) {
- ExceptionErrorDialog.openError(Messages.TapsetParser_ErrorRunningSystemtap, e);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return null;
- }
-
- private void displayError(final String title, final String error) {
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- MessageDialog.openWarning(window.getShell(), title, error);
- }
- });
- }
+ private ArrayList<IUpdateListener> listeners;
+
+ protected boolean cancelRequested;
+
+ protected TapsetParser(String jobTitle) {
+ super(jobTitle);
+ listeners = new ArrayList<>();
+ cancelRequested = false;
+ }
+
+ @Override
+ protected void canceling() {
+ super.canceling();
+ this.cancelRequested = true;
+ }
+
+ /**
+ * This method will register a new listener with the parser
+ * @param listener The listener that will receive updateEvents
+ */
+ public void addListener(IUpdateListener listener) {
+ if (null != listener) {
+ listeners.add(listener);
+ }
+ }
+
+ /**
+ * This method will unregister the listener with the parser
+ * @param listener The listener that no longer wants to recieve update events
+ */
+ public void removeListener(IUpdateListener listener) {
+ if (null != listener) {
+ listeners.remove(listener);
+ }
+ }
+
+ /**
+ * This method will fire an updateEvent to all listeners.
+ */
+ protected void fireUpdateEvent() {
+ for (IUpdateListener listener : listeners) {
+ listener.handleUpdateEvent();
+ }
+ }
+
+ /**
+ * Runs the stap with the given options and returns the output generated
+ * @param options String[] of any optional parameters to pass to stap
+ * @param probe String containing the script to run stap on,
+ * or <code>null</code> for scriptless commands
+ * @param getErrors Set this to <code>true</code> if the script's error
+ * stream contents should be returned instead of its standard output
+ */
+ protected String runStap(String[] options, String probe, boolean getErrors) {
+ String[] args = null;
+ String[] tapsets = IDEPlugin.getDefault().getPreferenceStore()
+ .getString(IDEPreferenceConstants.P_TAPSETS).split(File.pathSeparator);
+ boolean noTapsets = tapsets[0].trim().length() == 0;
+ boolean noOptions = options[0].trim().length() == 0;
+
+ int size = probe != null ? 2 : 1;
+ if (tapsets.length > 0 && !noTapsets) {
+ size += tapsets.length<<1;
+ }
+ if (options.length > 0 && !noOptions) {
+ size += options.length;
+ }
+
+ args = new String[size];
+ args[0] = "stap"; //$NON-NLS-1$
+ if (probe != null) {
+ args[size-1] = probe;
+ }
+
+ //Add extra tapset directories
+ if (tapsets.length > 0 && !noTapsets) {
+ for (int i = 0; i < tapsets.length; i++) {
+ args[1 + 2*i] = "-I"; //$NON-NLS-1$
+ args[2 + 2*i] = tapsets[i];
+ }
+ }
+ if (options.length > 0 && !noOptions) {
+ for (int i = 0, s = noTapsets ? 1 : 1 + tapsets.length*2; i<options.length; i++) {
+ args[s + i] = options[i];
+ }
+ }
+
+ try {
+ if (IDEPlugin.getDefault().getPreferenceStore().getBoolean(IDEPreferenceConstants.P_REMOTE_PROBES)) {
+ StringOutputStream str = new StringOutputStream();
+ StringOutputStream strErr = new StringOutputStream();
+
+ IPreferenceStore p = ConsoleLogPlugin.getDefault().getPreferenceStore();
+ String user = p.getString(ConsoleLogPreferenceConstants.SCP_USER);
+ String host = p.getString(ConsoleLogPreferenceConstants.HOST_NAME);
+ String password = p.getString(ConsoleLogPreferenceConstants.SCP_PASSWORD);
+
+ Channel channel = SystemtapProcessFactory.execRemoteAndWait(args,str, strErr, user, host, password);
+ if (channel == null) {
+ displayError(Messages.TapsetParser_CannotRunStapTitle, Messages.TapsetParser_CannotRunStapMessage);
+ }
+
+ return (!getErrors ? str : strErr).toString();
+ } else {
+ Process process = RuntimeProcessFactory.getFactory().exec(args, null, null);
+ if(process == null){
+ displayError(Messages.TapsetParser_CannotRunStapTitle, Messages.TapsetParser_CannotRunStapMessage);
+ return null;
+ }
+
+ StringStreamGobbler gobbler = new StringStreamGobbler(process.getInputStream());
+ StringStreamGobbler egobbler = null;
+ gobbler.start();
+ if (getErrors) {
+ egobbler = new StringStreamGobbler(process.getErrorStream());
+ egobbler.start();
+ }
+ process.waitFor();
+ gobbler.stop();
+ if (egobbler == null) {
+ return gobbler.getOutput().toString();
+ } else {
+ egobbler.stop();
+ return egobbler.getOutput().toString();
+ }
+ }
+
+ } catch (JSchException|IOException e) {
+ ExceptionErrorDialog.openError(Messages.TapsetParser_ErrorRunningSystemtap, e);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+
+ private void displayError(final String title, final String error) {
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ MessageDialog.openWarning(window.getShell(), title, error);
+ }
+ });
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TreeSettings.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TreeSettings.java
index a7b03ba281..6053ae9051 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TreeSettings.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/structures/TreeSettings.java
@@ -33,244 +33,244 @@ import org.eclipse.ui.XMLMemento;
* @author Ryan Morse
*/
public final class TreeSettings {
- private TreeSettings() {
- }
- /**
- * Returns the modification date for the Tree File. Used to make sure that the cache is not out of
- * date.
- * @return The datestamp for the Tree file.
- */
- public static long getTreeFileDate() {
- if (!readData()) {
- return -1;
- }
- return treeFileDate;
- }
-
- /**
- * Allows access to the Tapset Function tree, which contains information about all
- * functions stored in the tapset library.
- * @return The <code>TreeNode</code> root of the Function tree.
- * @since 2.0
- */
- public static TreeNode getFunctionTree() {
- if (!readData()) {
- return null;
- }
- return functions;
- }
-
- /**
- * Allows access to the Tapset Probe Alias tree, which contains a list of all probe aliases
- * in the tapset library.
- * @return The <code>TreeNode</code> root of the Probe Alias tree.
- * @since 2.0
- */
- public static TreeNode getProbeTree() {
- if (!readData()) {
- return null;
- }
- return probes;
- }
-
- /**
- * Sets the Probe Alias and Function trees that are being cached to the trees given as arguments.
- * @param func The Function tree to store in cache.
- * @param probe The Probe Alias tree to store in cache.
- * @return True if the caching is successful.
- * @since 2.0
- */
- public static boolean setTrees(TreeNode func, TreeNode probe) {
- if (null == func || null == probe) {
- return false;
- }
- functions = func;
- probes = probe;
- return writeData();
- }
-
- /**
- * Reads the contents of the cache file into memory.
- * @return True if the read is successful.
- */
- private static boolean readData() {
- if (null == settingsFile && !openFile()) {
- return false;
- }
-
- try (FileReader reader = new FileReader(settingsFile)) {
- if(!reader.ready()) {
- reader.close();
- return false;
- }
-
- XMLMemento data = XMLMemento.createReadRoot(reader, "TreeSettings"); //$NON-NLS-1$
-
- IMemento child = data.getChild("functionTree"); //$NON-NLS-1$
- String s = child.getString("string"); //$NON-NLS-1$
- if ("<null>".equals(s)) { //$NON-NLS-1$
- s = null;
- }
- String d = child.getString("data"); //$NON-NLS-1$
- if ("<null>".equals(d)) { //$NON-NLS-1$
- d = null;
- }
-
- functions = new TreeNode(d, s, false);
- readTree(child, functions, 0);
-
- child = data.getChild("probeTree"); //$NON-NLS-1$
- s = child.getString("string"); //$NON-NLS-1$
- if ("<null>".equals(s)) { //$NON-NLS-1$
- s = null;
- }
- d = child.getString("data"); //$NON-NLS-1$
- if ("<null>".equals(d)) { //$NON-NLS-1$
- d = null;
- }
- probes = new TreeNode(d, s, false);
- readTree(child, probes, 0);
-
- child = data.getChild("modifiedDate"); //$NON-NLS-1$
- treeFileDate = Long.parseLong(child.getString("date")); //$NON-NLS-1$
- } catch(IOException|WorkbenchException fnfe) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Writes the tree data currently stored by this class to disk for later access.
- * @return True if the write is successful.
- */
- private static boolean writeData() {
- if (null == settingsFile && !openFile()) {
- return false;
- }
-
- try {
- XMLMemento data = XMLMemento.createWriteRoot("TreeSettings"); //$NON-NLS-1$
-
- IMemento child = data.createChild("functionTree"); //$NON-NLS-1$
- writeTree(child, functions, 0);
-
- child = data.createChild("probeTree"); //$NON-NLS-1$
- writeTree(child, probes, 0);
-
- child = data.createChild("modifiedDate"); //$NON-NLS-1$
- child.putString("date", (Long.valueOf(Calendar.getInstance().getTimeInMillis())).toString()); //$NON-NLS-1$
-
- FileWriter writer = new FileWriter(settingsFile);
- data.save(writer);
- } catch(FileNotFoundException fnfe) {
- return false;
- } catch(IOException e) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Writes the tree passed in to the <code>IMemento</code> argument, up to the specified depth.
- * @param child The <code>IMemento</code> to store the tree to.
- * @param tree The <code>TreeNode</code> to store.
- * @param depth The maximum depth level to write out.
- */
- private static void writeTree(IMemento child, TreeNode tree, int depth) {
- if (null == tree.toString()) {
- child.putString("string", "<null>"); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- child.putString("string", tree.toString()); //$NON-NLS-1$
- }
-
- if (null == tree.getData()) {
- child.putString("data", "<null>"); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- child.putString("data", tree.getData().toString()); //$NON-NLS-1$
- }
-
- if (tree instanceof TreeDefinitionNode) {
- if (null == ((TreeDefinitionNode) tree).getDefinition()) {
- child.putString("definition", "<null>"); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- child.putString(
- "definition", ((TreeDefinitionNode) tree).getDefinition()); //$NON-NLS-1$
- }
- }
-
- child.putInteger("click", (tree.isClickable()?1:0)); //$NON-NLS-1$
- for(int i=0; i<tree.getChildCount(); i++) {
- writeTree(child.createChild("level" + depth), tree.getChildAt(i), depth+1); //$NON-NLS-1$
- }
- }
-
- /**
- * Opposite action as writeTree. Reads the <code>IMemento</code> passed in into the <code>TreeNode</code>
- * up to the requested maximum depth.
- * @param data The <code>IMemento</code> to read the tree out of.
- * @param parent The <code>TreeNode</code> to store the tree in.
- * @param depth The maximum depth to read.
- */
- private static void readTree(IMemento data, TreeNode parent, int depth) {
- IMemento[] children = data.getChildren("level" + depth); //$NON-NLS-1$
-
- try {
- if(null != children) {
- for(int i=0; i<children.length; i++) {
- String s = children[i].getString("string"); //$NON-NLS-1$
- String d = children[i].getString("data"); //$NON-NLS-1$
- String def = children[i].getString("definition"); //$NON-NLS-1$
-
- boolean c = ((0==children[i].getInteger("click").intValue())?false:true); //$NON-NLS-1$
-
- if ("<null>".equals(s)) { //$NON-NLS-1$
- s = null;
- }
- if ("<null>".equals(d)) { //$NON-NLS-1$
- d = null;
- }
-
- TreeNode t;
- if(null == def) {
- t = new TreeNode(d, s, c);
- } else {
- if ("<null>".equals(def)) { //$NON-NLS-1$
- def = null;
- }
-
- t = new TreeDefinitionNode(d, s, def, c);
- }
- parent.add(t);
-
- readTree(children[i], t, depth+1);
- }
- }
- } catch(NullPointerException e) {
- }
- }
-
- private static boolean openFile() {
- settingsFile = new File(System.getenv("HOME") + "/.systemtapgui/" + fileName); //$NON-NLS-1$ //$NON-NLS-2$
-
- try {
- if (!settingsFile.exists()){
- // Create a new settings file-and its parent
- // directories- if one does not exist.
- settingsFile.getParentFile().mkdirs();
- settingsFile.createNewFile();
- }
- } catch(IOException ioe) {
- return false;
- }
-
- return true;
- }
-
- private static long treeFileDate;
- private static TreeNode functions;
- private static TreeNode probes;
- private static final String fileName = "/TreeSettings.xml"; //$NON-NLS-1$
- private static File settingsFile = null;
+ private TreeSettings() {
+ }
+ /**
+ * Returns the modification date for the Tree File. Used to make sure that the cache is not out of
+ * date.
+ * @return The datestamp for the Tree file.
+ */
+ public static long getTreeFileDate() {
+ if (!readData()) {
+ return -1;
+ }
+ return treeFileDate;
+ }
+
+ /**
+ * Allows access to the Tapset Function tree, which contains information about all
+ * functions stored in the tapset library.
+ * @return The <code>TreeNode</code> root of the Function tree.
+ * @since 2.0
+ */
+ public static TreeNode getFunctionTree() {
+ if (!readData()) {
+ return null;
+ }
+ return functions;
+ }
+
+ /**
+ * Allows access to the Tapset Probe Alias tree, which contains a list of all probe aliases
+ * in the tapset library.
+ * @return The <code>TreeNode</code> root of the Probe Alias tree.
+ * @since 2.0
+ */
+ public static TreeNode getProbeTree() {
+ if (!readData()) {
+ return null;
+ }
+ return probes;
+ }
+
+ /**
+ * Sets the Probe Alias and Function trees that are being cached to the trees given as arguments.
+ * @param func The Function tree to store in cache.
+ * @param probe The Probe Alias tree to store in cache.
+ * @return True if the caching is successful.
+ * @since 2.0
+ */
+ public static boolean setTrees(TreeNode func, TreeNode probe) {
+ if (null == func || null == probe) {
+ return false;
+ }
+ functions = func;
+ probes = probe;
+ return writeData();
+ }
+
+ /**
+ * Reads the contents of the cache file into memory.
+ * @return True if the read is successful.
+ */
+ private static boolean readData() {
+ if (null == settingsFile && !openFile()) {
+ return false;
+ }
+
+ try (FileReader reader = new FileReader(settingsFile)) {
+ if(!reader.ready()) {
+ reader.close();
+ return false;
+ }
+
+ XMLMemento data = XMLMemento.createReadRoot(reader, "TreeSettings"); //$NON-NLS-1$
+
+ IMemento child = data.getChild("functionTree"); //$NON-NLS-1$
+ String s = child.getString("string"); //$NON-NLS-1$
+ if ("<null>".equals(s)) { //$NON-NLS-1$
+ s = null;
+ }
+ String d = child.getString("data"); //$NON-NLS-1$
+ if ("<null>".equals(d)) { //$NON-NLS-1$
+ d = null;
+ }
+
+ functions = new TreeNode(d, s, false);
+ readTree(child, functions, 0);
+
+ child = data.getChild("probeTree"); //$NON-NLS-1$
+ s = child.getString("string"); //$NON-NLS-1$
+ if ("<null>".equals(s)) { //$NON-NLS-1$
+ s = null;
+ }
+ d = child.getString("data"); //$NON-NLS-1$
+ if ("<null>".equals(d)) { //$NON-NLS-1$
+ d = null;
+ }
+ probes = new TreeNode(d, s, false);
+ readTree(child, probes, 0);
+
+ child = data.getChild("modifiedDate"); //$NON-NLS-1$
+ treeFileDate = Long.parseLong(child.getString("date")); //$NON-NLS-1$
+ } catch(IOException|WorkbenchException fnfe) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Writes the tree data currently stored by this class to disk for later access.
+ * @return True if the write is successful.
+ */
+ private static boolean writeData() {
+ if (null == settingsFile && !openFile()) {
+ return false;
+ }
+
+ try {
+ XMLMemento data = XMLMemento.createWriteRoot("TreeSettings"); //$NON-NLS-1$
+
+ IMemento child = data.createChild("functionTree"); //$NON-NLS-1$
+ writeTree(child, functions, 0);
+
+ child = data.createChild("probeTree"); //$NON-NLS-1$
+ writeTree(child, probes, 0);
+
+ child = data.createChild("modifiedDate"); //$NON-NLS-1$
+ child.putString("date", (Long.valueOf(Calendar.getInstance().getTimeInMillis())).toString()); //$NON-NLS-1$
+
+ FileWriter writer = new FileWriter(settingsFile);
+ data.save(writer);
+ } catch(FileNotFoundException fnfe) {
+ return false;
+ } catch(IOException e) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Writes the tree passed in to the <code>IMemento</code> argument, up to the specified depth.
+ * @param child The <code>IMemento</code> to store the tree to.
+ * @param tree The <code>TreeNode</code> to store.
+ * @param depth The maximum depth level to write out.
+ */
+ private static void writeTree(IMemento child, TreeNode tree, int depth) {
+ if (null == tree.toString()) {
+ child.putString("string", "<null>"); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ child.putString("string", tree.toString()); //$NON-NLS-1$
+ }
+
+ if (null == tree.getData()) {
+ child.putString("data", "<null>"); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ child.putString("data", tree.getData().toString()); //$NON-NLS-1$
+ }
+
+ if (tree instanceof TreeDefinitionNode) {
+ if (null == ((TreeDefinitionNode) tree).getDefinition()) {
+ child.putString("definition", "<null>"); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ child.putString(
+ "definition", ((TreeDefinitionNode) tree).getDefinition()); //$NON-NLS-1$
+ }
+ }
+
+ child.putInteger("click", (tree.isClickable()?1:0)); //$NON-NLS-1$
+ for(int i=0; i<tree.getChildCount(); i++) {
+ writeTree(child.createChild("level" + depth), tree.getChildAt(i), depth+1); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Opposite action as writeTree. Reads the <code>IMemento</code> passed in into the <code>TreeNode</code>
+ * up to the requested maximum depth.
+ * @param data The <code>IMemento</code> to read the tree out of.
+ * @param parent The <code>TreeNode</code> to store the tree in.
+ * @param depth The maximum depth to read.
+ */
+ private static void readTree(IMemento data, TreeNode parent, int depth) {
+ IMemento[] children = data.getChildren("level" + depth); //$NON-NLS-1$
+
+ try {
+ if(null != children) {
+ for(int i=0; i<children.length; i++) {
+ String s = children[i].getString("string"); //$NON-NLS-1$
+ String d = children[i].getString("data"); //$NON-NLS-1$
+ String def = children[i].getString("definition"); //$NON-NLS-1$
+
+ boolean c = ((0==children[i].getInteger("click").intValue())?false:true); //$NON-NLS-1$
+
+ if ("<null>".equals(s)) { //$NON-NLS-1$
+ s = null;
+ }
+ if ("<null>".equals(d)) { //$NON-NLS-1$
+ d = null;
+ }
+
+ TreeNode t;
+ if(null == def) {
+ t = new TreeNode(d, s, c);
+ } else {
+ if ("<null>".equals(def)) { //$NON-NLS-1$
+ def = null;
+ }
+
+ t = new TreeDefinitionNode(d, s, def, c);
+ }
+ parent.add(t);
+
+ readTree(children[i], t, depth+1);
+ }
+ }
+ } catch(NullPointerException e) {
+ }
+ }
+
+ private static boolean openFile() {
+ settingsFile = new File(System.getenv("HOME") + "/.systemtapgui/" + fileName); //$NON-NLS-1$ //$NON-NLS-2$
+
+ try {
+ if (!settingsFile.exists()){
+ // Create a new settings file-and its parent
+ // directories- if one does not exist.
+ settingsFile.getParentFile().mkdirs();
+ settingsFile.createNewFile();
+ }
+ } catch(IOException ioe) {
+ return false;
+ }
+
+ return true;
+ }
+
+ private static long treeFileDate;
+ private static TreeNode functions;
+ private static TreeNode probes;
+ private static final String fileName = "/TreeSettings.xml"; //$NON-NLS-1$
+ private static File settingsFile = null;
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/BrowserView.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/BrowserView.java
index 7f67b04a24..dca0101c54 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/BrowserView.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/BrowserView.java
@@ -46,135 +46,135 @@ import org.eclipse.ui.part.ViewPart;
* @see org.eclipse.linuxtools.internal.systemtap.ui.ide.views.ProbeAliasBrowserView
*/
public abstract class BrowserView extends ViewPart {
- protected TreeViewer viewer;
-
- private CollapseAllHandler collapseHandler;
-
- public BrowserView() {
- super();
- }
-
- /**
- * Provides an interface for the TreeViewer to interact with the internal TreeNode data structure.
- * @author Ryan Morse
- *
- */
- static class ViewContentProvider implements ITreeContentProvider {
- @Override
- public void inputChanged(Viewer v, Object oldInput, Object newInput) {}
-
- @Override
- public void dispose() {}
-
- @Override
- public Object[] getElements(Object parent) {
- return getChildren(parent);
- }
-
- @Override
- public Object getParent(Object child) {
- return null;
- }
-
- @Override
- public Object[] getChildren(Object par) {
- TreeNode parent = ((TreeNode)par);
-
- Object[] children = new Object[parent.getChildCount()];
-
- for(int i=0; i<children.length; i++) {
- children[i] = parent.getChildAt(i);
- }
-
- return children;
- }
-
- @Override
- public boolean hasChildren(Object parent) {
- return ((TreeNode)parent).getChildCount() > 0;
- }
- }
-
- protected abstract Image getEntryImage(TreeNode treeObj);
-
- protected Image getGenericImage(TreeNode treeObj) {
- if (treeObj.getChildCount() == 0) {
- return IDEPlugin.getImageDescriptor("icons/vars/var_unk.gif").createImage(); //$NON-NLS-1$
- } else {
- return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
- }
- }
-
- /**
- * Provides the icon and text for each entry in the tapset tree.
- * @author Ryan Morse
- */
- protected class ViewLabelProvider extends LabelProvider {
- @Override
- public String getText(Object obj) {
- return obj.toString();
- }
-
- @Override
- public Image getImage(Object obj) {
- return getEntryImage((TreeNode) obj);
- }
- }
-
- @Override
- public void createPartControl(Composite parent) {
- parent.getShell().setCursor(parent.getShell().getDisplay().getSystemCursor(SWT.CURSOR_WAIT));
- PatternFilter filter = new PatternFilter();
- FilteredTree filteredTree = new FilteredTree(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL, filter, true);
- viewer = filteredTree.getViewer();
- viewer.setContentProvider(new ViewContentProvider());
- viewer.setLabelProvider(new ViewLabelProvider());
- IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class);
- collapseHandler = new CollapseAllHandler(getViewer());
- handlerService.activateHandler(CollapseAllHandler.COMMAND_ID, collapseHandler);
- }
-
- protected void registerContextMenu(String menuName) {
- Control control = this.viewer.getControl();
- MenuManager manager = new MenuManager(menuName);
- manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
- Menu menu = manager.createContextMenu(control);
- viewer.getControl().setMenu(menu);
-
- IWorkbenchPartSite partSite = getSite();
- partSite.registerContextMenu(manager, viewer);
- partSite.setSelectionProvider(viewer);
- }
-
- public TreeViewer getViewer() {
- return viewer;
- }
-
- @Override
- public void setFocus() {
- viewer.getControl().setFocus();
- }
-
- @Override
- public void dispose() {
- super.dispose();
- viewer = null;
- if(collapseHandler != null) {
- collapseHandler.dispose();
- }
- }
-
- abstract void refresh();
-
- protected class ViewUpdater implements IUpdateListener {
- @Override
- public void handleUpdateEvent() {
- viewer.getControl().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- refresh();
- }
- });
- }
- }
+ protected TreeViewer viewer;
+
+ private CollapseAllHandler collapseHandler;
+
+ public BrowserView() {
+ super();
+ }
+
+ /**
+ * Provides an interface for the TreeViewer to interact with the internal TreeNode data structure.
+ * @author Ryan Morse
+ *
+ */
+ static class ViewContentProvider implements ITreeContentProvider {
+ @Override
+ public void inputChanged(Viewer v, Object oldInput, Object newInput) {}
+
+ @Override
+ public void dispose() {}
+
+ @Override
+ public Object[] getElements(Object parent) {
+ return getChildren(parent);
+ }
+
+ @Override
+ public Object getParent(Object child) {
+ return null;
+ }
+
+ @Override
+ public Object[] getChildren(Object par) {
+ TreeNode parent = ((TreeNode)par);
+
+ Object[] children = new Object[parent.getChildCount()];
+
+ for(int i=0; i<children.length; i++) {
+ children[i] = parent.getChildAt(i);
+ }
+
+ return children;
+ }
+
+ @Override
+ public boolean hasChildren(Object parent) {
+ return ((TreeNode)parent).getChildCount() > 0;
+ }
+ }
+
+ protected abstract Image getEntryImage(TreeNode treeObj);
+
+ protected Image getGenericImage(TreeNode treeObj) {
+ if (treeObj.getChildCount() == 0) {
+ return IDEPlugin.getImageDescriptor("icons/vars/var_unk.gif").createImage(); //$NON-NLS-1$
+ } else {
+ return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
+ }
+ }
+
+ /**
+ * Provides the icon and text for each entry in the tapset tree.
+ * @author Ryan Morse
+ */
+ protected class ViewLabelProvider extends LabelProvider {
+ @Override
+ public String getText(Object obj) {
+ return obj.toString();
+ }
+
+ @Override
+ public Image getImage(Object obj) {
+ return getEntryImage((TreeNode) obj);
+ }
+ }
+
+ @Override
+ public void createPartControl(Composite parent) {
+ parent.getShell().setCursor(parent.getShell().getDisplay().getSystemCursor(SWT.CURSOR_WAIT));
+ PatternFilter filter = new PatternFilter();
+ FilteredTree filteredTree = new FilteredTree(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL, filter, true);
+ viewer = filteredTree.getViewer();
+ viewer.setContentProvider(new ViewContentProvider());
+ viewer.setLabelProvider(new ViewLabelProvider());
+ IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class);
+ collapseHandler = new CollapseAllHandler(getViewer());
+ handlerService.activateHandler(CollapseAllHandler.COMMAND_ID, collapseHandler);
+ }
+
+ protected void registerContextMenu(String menuName) {
+ Control control = this.viewer.getControl();
+ MenuManager manager = new MenuManager(menuName);
+ manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
+ Menu menu = manager.createContextMenu(control);
+ viewer.getControl().setMenu(menu);
+
+ IWorkbenchPartSite partSite = getSite();
+ partSite.registerContextMenu(manager, viewer);
+ partSite.setSelectionProvider(viewer);
+ }
+
+ public TreeViewer getViewer() {
+ return viewer;
+ }
+
+ @Override
+ public void setFocus() {
+ viewer.getControl().setFocus();
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ viewer = null;
+ if(collapseHandler != null) {
+ collapseHandler.dispose();
+ }
+ }
+
+ abstract void refresh();
+
+ protected class ViewUpdater implements IUpdateListener {
+ @Override
+ public void handleUpdateEvent() {
+ viewer.getControl().getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ refresh();
+ }
+ });
+ }
+ }
} \ No newline at end of file
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/FunctionBrowserView.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/FunctionBrowserView.java
index 2943bcd0de..fd7722247a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/FunctionBrowserView.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/FunctionBrowserView.java
@@ -28,99 +28,99 @@ import org.eclipse.swt.widgets.Composite;
* @author Henry Hughes
*/
public class FunctionBrowserView extends BrowserView {
- public static final String ID = "org.eclipse.linuxtools.internal.systemtap.ui.ide.views.FunctionBrowserView"; //$NON-NLS-1$
- private FunctionBrowserAction doubleClickAction;
- private TreeNode functions;
- private TreeNode localFunctions;
+ public static final String ID = "org.eclipse.linuxtools.internal.systemtap.ui.ide.views.FunctionBrowserView"; //$NON-NLS-1$
+ private FunctionBrowserAction doubleClickAction;
+ private TreeNode functions;
+ private TreeNode localFunctions;
- /**
- * Creates the UI on the given <code>Composite</code>
- */
- @Override
- public void createPartControl(Composite parent) {
- super.createPartControl(parent);
- TapsetLibrary.init();
- TapsetLibrary.addFunctionListener(new ViewUpdater());
- refresh();
- makeActions();
- }
+ /**
+ * Creates the UI on the given <code>Composite</code>
+ */
+ @Override
+ public void createPartControl(Composite parent) {
+ super.createPartControl(parent);
+ TapsetLibrary.init();
+ TapsetLibrary.addFunctionListener(new ViewUpdater());
+ refresh();
+ makeActions();
+ }
- @Override
- protected Image getEntryImage(TreeNode treeObj) {
- if (!(treeObj.getData() instanceof ISingleTypedNode)) {
- return IDEPlugin.getImageDescriptor("icons/vars/var_unk.gif").createImage(); //$NON-NLS-1$
- }
- String type = ((ISingleTypedNode) treeObj.getData()).getType();
- if (type == null) {
- return IDEPlugin.getImageDescriptor("icons/vars/var_void.gif").createImage(); //$NON-NLS-1$
- } else if (type.equals("long")) {//$NON-NLS-1$
- return IDEPlugin.getImageDescriptor("icons/vars/var_long.gif").createImage(); //$NON-NLS-1$
- } else if (type.equals("string")) {//$NON-NLS-1$
- return IDEPlugin.getImageDescriptor("icons/vars/var_str.gif").createImage(); //$NON-NLS-1$
- } else {
- return IDEPlugin.getImageDescriptor("icons/vars/var_unk.gif").createImage(); //$NON-NLS-1$
- }
- }
+ @Override
+ protected Image getEntryImage(TreeNode treeObj) {
+ if (!(treeObj.getData() instanceof ISingleTypedNode)) {
+ return IDEPlugin.getImageDescriptor("icons/vars/var_unk.gif").createImage(); //$NON-NLS-1$
+ }
+ String type = ((ISingleTypedNode) treeObj.getData()).getType();
+ if (type == null) {
+ return IDEPlugin.getImageDescriptor("icons/vars/var_void.gif").createImage(); //$NON-NLS-1$
+ } else if (type.equals("long")) {//$NON-NLS-1$
+ return IDEPlugin.getImageDescriptor("icons/vars/var_long.gif").createImage(); //$NON-NLS-1$
+ } else if (type.equals("string")) {//$NON-NLS-1$
+ return IDEPlugin.getImageDescriptor("icons/vars/var_str.gif").createImage(); //$NON-NLS-1$
+ } else {
+ return IDEPlugin.getImageDescriptor("icons/vars/var_unk.gif").createImage(); //$NON-NLS-1$
+ }
+ }
- /**
- * Refreshes the list of functions in the viewer.
- */
- @Override
- public void refresh() {
- functions = TapsetLibrary.getFunctions();
- if (functions != null){
- addLocalFunctions(localFunctions);
- }
- }
+ /**
+ * Refreshes the list of functions in the viewer.
+ */
+ @Override
+ public void refresh() {
+ functions = TapsetLibrary.getFunctions();
+ if (functions != null){
+ addLocalFunctions(localFunctions);
+ }
+ }
- /**
- * Adds the local functions specified in the argument to the viewer.
- * @param localFunctionTree A tree of the local functions.
- */
- public void addLocalFunctions(TreeNode localFunctionTree) {
- if(functions.getChildCount() > 0) {
- TreeNode localFuncs = functions.getChildAt(0);
+ /**
+ * Adds the local functions specified in the argument to the viewer.
+ * @param localFunctionTree A tree of the local functions.
+ */
+ public void addLocalFunctions(TreeNode localFunctionTree) {
+ if(functions.getChildCount() > 0) {
+ TreeNode localFuncs = functions.getChildAt(0);
- if("<local>".equals(localFuncs.toString())) { //$NON-NLS-1$
- functions.remove(0);
- }
+ if("<local>".equals(localFuncs.toString())) { //$NON-NLS-1$
+ functions.remove(0);
+ }
- if(null != localFunctions) {
- localFunctions = localFunctionTree;
- localFunctions.setDisplay("<local>"); //$NON-NLS-1$
- functions.addAt(localFunctions, 0);
- }
- }
- viewer.setInput(functions);
- }
+ if(null != localFunctions) {
+ localFunctions = localFunctionTree;
+ localFunctions.setDisplay("<local>"); //$NON-NLS-1$
+ functions.addAt(localFunctions, 0);
+ }
+ }
+ viewer.setInput(functions);
+ }
- /**
- * Wires up all of the actions for this browser, such as double and right click handlers.
- */
- private void makeActions() {
- doubleClickAction = new FunctionBrowserAction(getSite().getWorkbenchWindow(), this);
- viewer.addDoubleClickListener(doubleClickAction);
- registerContextMenu("functionPopup"); //$NON-NLS-1$
- }
+ /**
+ * Wires up all of the actions for this browser, such as double and right click handlers.
+ */
+ private void makeActions() {
+ doubleClickAction = new FunctionBrowserAction(getSite().getWorkbenchWindow(), this);
+ viewer.addDoubleClickListener(doubleClickAction);
+ registerContextMenu("functionPopup"); //$NON-NLS-1$
+ }
- @Override
- public void dispose() {
- super.dispose();
- if(null != viewer) {
- viewer.removeDoubleClickListener(doubleClickAction);
- }
- if(null != doubleClickAction) {
- doubleClickAction.dispose();
- }
- doubleClickAction = null;
- if(null != localFunctions) {
- localFunctions.dispose();
- }
- localFunctions = null;
- if(null != functions) {
- functions.dispose();
- }
- functions = null;
- TapsetLibrary.stop();
- }
+ @Override
+ public void dispose() {
+ super.dispose();
+ if(null != viewer) {
+ viewer.removeDoubleClickListener(doubleClickAction);
+ }
+ if(null != doubleClickAction) {
+ doubleClickAction.dispose();
+ }
+ doubleClickAction = null;
+ if(null != localFunctions) {
+ localFunctions.dispose();
+ }
+ localFunctions = null;
+ if(null != functions) {
+ functions.dispose();
+ }
+ functions = null;
+ TapsetLibrary.stop();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/KernelBrowserView.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/KernelBrowserView.java
index 4780864e39..5e191fdf9a 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/KernelBrowserView.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/KernelBrowserView.java
@@ -46,192 +46,192 @@ import org.eclipse.ui.progress.UIJob;
*/
public class KernelBrowserView extends BrowserView {
- private class KernelRefreshJob extends Job {
- private boolean remote;
- private URI kernelLocationURI;
- private IRemoteFileProxy proxy;
- private String kernelSource;
-
- public KernelRefreshJob(boolean remote, URI kernelLocationURI, IRemoteFileProxy proxy, String kernelSource) {
- super(Localization.getString("KernelBrowserView.RefreshingKernelSource")); //$NON-NLS-1$
- this.remote = remote;
- this.kernelLocationURI = kernelLocationURI;
- this.proxy = proxy;
- this.kernelSource = kernelSource;
- }
-
- @Override
- public IStatus run(IProgressMonitor monitor) {
- IPreferenceStore p = IDEPlugin.getDefault().getPreferenceStore();
- KernelSourceTree kst = new KernelSourceTree();
- String excluded[] = p.getString(IDEPreferenceConstants.P_EXCLUDED_KERNEL_SOURCE).split(File.pathSeparator);
- if (remote) {
- try {
- kst.buildKernelTree(kernelLocationURI, excluded, proxy, monitor);
- } catch (CoreException e) {
- ExceptionErrorDialog.openError(Localization.getString("KernelBrowserView.CouldNotInitializeTree"), e); //$NON-NLS-1$
- }
- } else {
- kst.buildKernelTree(kernelSource, excluded);
- }
- if (monitor.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
- UpdateKernelBrowserJob job = new UpdateKernelBrowserJob(kst);
- job.schedule();
- monitor.done();
- return Status.OK_STATUS;
- }
- }
-
- private class UpdateKernelBrowserJob extends UIJob {
- KernelSourceTree kst;
- public UpdateKernelBrowserJob(KernelSourceTree kst) {
- super(Localization.getString("KernelBrowserView.UpdateKernelBrowser")); //$NON-NLS-1$
- this.kst = kst;
- }
-
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- monitor.beginTask(Localization.getString("KernelBrowserView.UpdateKernelBrowser"), 100); //$NON-NLS-1$
- if (kst == null) {
- return Status.OK_STATUS;
- }
- viewer.setInput(kst.getTree());
- kst.dispose();
- monitor.done();
- return Status.OK_STATUS;
- }
- }
-
- public static final String ID = "org.eclipse.linuxtools.internal.systemtap.ui.ide.views.KernelBrowserView"; //$NON-NLS-1$
- private KernelSourceAction doubleClickAction;
-
- /**
- * Creates the UI on the given <code>Composite</code>
- */
- @Override
- public void createPartControl(Composite parent) {
- super.createPartControl(parent);
- refresh();
- makeActions();
- }
-
- /**
- * Wires up all of the actions for this browser, such as double and right click handlers.
- */
- private void makeActions() {
- doubleClickAction = new KernelSourceAction(getSite().getWorkbenchWindow(), this);
- viewer.addDoubleClickListener(doubleClickAction);
- IDEPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(propertyChangeListener);
- }
-
- @Override
- protected Image getEntryImage(TreeNode treeObj) {
- String item = treeObj.getData().toString();
- if(item.endsWith(".c")) { //$NON-NLS-1$
- return IDEPlugin.getImageDescriptor("icons/files/file_c.gif").createImage(); //$NON-NLS-1$
- }
- if(item.endsWith(".h")) { //$NON-NLS-1$
- return IDEPlugin.getImageDescriptor("icons/files/file_h.gif").createImage(); //$NON-NLS-1$
- }
- return getGenericImage(treeObj);
- }
-
- /**
- * Updates the kernel source displayed to the user with the new kernel source tree. Usually
- * a response to the user changing the preferences related to the kernel source location, requiring
- * that the application update the kernel source information.
- */
- @Override
- public void refresh() {
- IPreferenceStore p = IDEPlugin.getDefault().getPreferenceStore();
- String kernelSource = p.getString(IDEPreferenceConstants.P_KERNEL_SOURCE);
- if(null == kernelSource || kernelSource.length() < 1) {
- showBrowserErrorMessage(Localization.getString("KernelBrowserView.NoKernelSourceFound")); //$NON-NLS-1$
- return;
- }
-
- String localOrRemote = p.getString(IDEPreferenceConstants.P_REMOTE_LOCAL_KERNEL_SOURCE);
- URI kernelLocationURI = null;
- IRemoteFileProxy proxy = null;
- boolean remote = localOrRemote.equals(PathPreferencePage.REMOTE);
- if (remote) {
- boolean error = false;
- try {
- kernelLocationURI = IDEPlugin.getDefault().createRemoteUri(kernelSource);
- if (kernelLocationURI == null) {
- error = true;
- } else {
- proxy = RemoteProxyManager.getInstance().getFileProxy(kernelLocationURI);
- if (!validateProxy(proxy, kernelSource)) {
- error = true;
- }
- }
- } catch (CoreException e2) {
- error = true;
- }
- if (error) {
- showBrowserErrorMessage(Localization.getString("KernelBrowserView.KernelSourceDirNotFound")); //$NON-NLS-1$
- return;
- }
- }
-
- KernelRefreshJob refreshJob = new KernelRefreshJob(remote, kernelLocationURI, proxy, kernelSource);
- refreshJob.setUser(true);
- refreshJob.setPriority(Job.SHORT);
- refreshJob.schedule();
- }
-
- private boolean validateProxy(IRemoteFileProxy proxy, String kernelSource) {
- if (proxy == null) {
- return false;
- }
- IFileStore fs = proxy.getResource(kernelSource);
- if (fs == null) {
- return false;
- }
- IFileInfo info = fs.fetchInfo();
- if (info == null) {
- return false;
- }
- if (!info.exists()) {
- return false;
- }
- return true;
- }
-
- private void showBrowserErrorMessage(String message) {
- TreeNode t = new TreeNode("", "", false); //$NON-NLS-1$ //$NON-NLS-2$
- t.add(new TreeNode("", message, false)); //$NON-NLS-1$
- viewer.setInput(t);
- }
-
- /**
- * A <code>IPropertyChangeListener</code> that detects changes to the Kernel Source location
- * and runs the <code>updateKernelSourceTree</code> method.
- */
- private final IPropertyChangeListener propertyChangeListener = new IPropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if(event.getProperty().equals(IDEPreferenceConstants.P_KERNEL_SOURCE) ||
- event.getProperty().equals(IDEPreferenceConstants.P_REMOTE_LOCAL_KERNEL_SOURCE) ||
- event.getProperty().equals(IDEPreferenceConstants.P_EXCLUDED_KERNEL_SOURCE)) {
- refresh();
- }
- }
- };
-
- @Override
- public void dispose() {
- super.dispose();
- IDEPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(propertyChangeListener);
- if(null != viewer) {
- viewer.removeDoubleClickListener(doubleClickAction);
- }
- if(null != doubleClickAction) {
- doubleClickAction.dispose();
- }
- doubleClickAction = null;
- }
+ private class KernelRefreshJob extends Job {
+ private boolean remote;
+ private URI kernelLocationURI;
+ private IRemoteFileProxy proxy;
+ private String kernelSource;
+
+ public KernelRefreshJob(boolean remote, URI kernelLocationURI, IRemoteFileProxy proxy, String kernelSource) {
+ super(Localization.getString("KernelBrowserView.RefreshingKernelSource")); //$NON-NLS-1$
+ this.remote = remote;
+ this.kernelLocationURI = kernelLocationURI;
+ this.proxy = proxy;
+ this.kernelSource = kernelSource;
+ }
+
+ @Override
+ public IStatus run(IProgressMonitor monitor) {
+ IPreferenceStore p = IDEPlugin.getDefault().getPreferenceStore();
+ KernelSourceTree kst = new KernelSourceTree();
+ String excluded[] = p.getString(IDEPreferenceConstants.P_EXCLUDED_KERNEL_SOURCE).split(File.pathSeparator);
+ if (remote) {
+ try {
+ kst.buildKernelTree(kernelLocationURI, excluded, proxy, monitor);
+ } catch (CoreException e) {
+ ExceptionErrorDialog.openError(Localization.getString("KernelBrowserView.CouldNotInitializeTree"), e); //$NON-NLS-1$
+ }
+ } else {
+ kst.buildKernelTree(kernelSource, excluded);
+ }
+ if (monitor.isCanceled()) {
+ return Status.CANCEL_STATUS;
+ }
+ UpdateKernelBrowserJob job = new UpdateKernelBrowserJob(kst);
+ job.schedule();
+ monitor.done();
+ return Status.OK_STATUS;
+ }
+ }
+
+ private class UpdateKernelBrowserJob extends UIJob {
+ KernelSourceTree kst;
+ public UpdateKernelBrowserJob(KernelSourceTree kst) {
+ super(Localization.getString("KernelBrowserView.UpdateKernelBrowser")); //$NON-NLS-1$
+ this.kst = kst;
+ }
+
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ monitor.beginTask(Localization.getString("KernelBrowserView.UpdateKernelBrowser"), 100); //$NON-NLS-1$
+ if (kst == null) {
+ return Status.OK_STATUS;
+ }
+ viewer.setInput(kst.getTree());
+ kst.dispose();
+ monitor.done();
+ return Status.OK_STATUS;
+ }
+ }
+
+ public static final String ID = "org.eclipse.linuxtools.internal.systemtap.ui.ide.views.KernelBrowserView"; //$NON-NLS-1$
+ private KernelSourceAction doubleClickAction;
+
+ /**
+ * Creates the UI on the given <code>Composite</code>
+ */
+ @Override
+ public void createPartControl(Composite parent) {
+ super.createPartControl(parent);
+ refresh();
+ makeActions();
+ }
+
+ /**
+ * Wires up all of the actions for this browser, such as double and right click handlers.
+ */
+ private void makeActions() {
+ doubleClickAction = new KernelSourceAction(getSite().getWorkbenchWindow(), this);
+ viewer.addDoubleClickListener(doubleClickAction);
+ IDEPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(propertyChangeListener);
+ }
+
+ @Override
+ protected Image getEntryImage(TreeNode treeObj) {
+ String item = treeObj.getData().toString();
+ if(item.endsWith(".c")) { //$NON-NLS-1$
+ return IDEPlugin.getImageDescriptor("icons/files/file_c.gif").createImage(); //$NON-NLS-1$
+ }
+ if(item.endsWith(".h")) { //$NON-NLS-1$
+ return IDEPlugin.getImageDescriptor("icons/files/file_h.gif").createImage(); //$NON-NLS-1$
+ }
+ return getGenericImage(treeObj);
+ }
+
+ /**
+ * Updates the kernel source displayed to the user with the new kernel source tree. Usually
+ * a response to the user changing the preferences related to the kernel source location, requiring
+ * that the application update the kernel source information.
+ */
+ @Override
+ public void refresh() {
+ IPreferenceStore p = IDEPlugin.getDefault().getPreferenceStore();
+ String kernelSource = p.getString(IDEPreferenceConstants.P_KERNEL_SOURCE);
+ if(null == kernelSource || kernelSource.length() < 1) {
+ showBrowserErrorMessage(Localization.getString("KernelBrowserView.NoKernelSourceFound")); //$NON-NLS-1$
+ return;
+ }
+
+ String localOrRemote = p.getString(IDEPreferenceConstants.P_REMOTE_LOCAL_KERNEL_SOURCE);
+ URI kernelLocationURI = null;
+ IRemoteFileProxy proxy = null;
+ boolean remote = localOrRemote.equals(PathPreferencePage.REMOTE);
+ if (remote) {
+ boolean error = false;
+ try {
+ kernelLocationURI = IDEPlugin.getDefault().createRemoteUri(kernelSource);
+ if (kernelLocationURI == null) {
+ error = true;
+ } else {
+ proxy = RemoteProxyManager.getInstance().getFileProxy(kernelLocationURI);
+ if (!validateProxy(proxy, kernelSource)) {
+ error = true;
+ }
+ }
+ } catch (CoreException e2) {
+ error = true;
+ }
+ if (error) {
+ showBrowserErrorMessage(Localization.getString("KernelBrowserView.KernelSourceDirNotFound")); //$NON-NLS-1$
+ return;
+ }
+ }
+
+ KernelRefreshJob refreshJob = new KernelRefreshJob(remote, kernelLocationURI, proxy, kernelSource);
+ refreshJob.setUser(true);
+ refreshJob.setPriority(Job.SHORT);
+ refreshJob.schedule();
+ }
+
+ private boolean validateProxy(IRemoteFileProxy proxy, String kernelSource) {
+ if (proxy == null) {
+ return false;
+ }
+ IFileStore fs = proxy.getResource(kernelSource);
+ if (fs == null) {
+ return false;
+ }
+ IFileInfo info = fs.fetchInfo();
+ if (info == null) {
+ return false;
+ }
+ if (!info.exists()) {
+ return false;
+ }
+ return true;
+ }
+
+ private void showBrowserErrorMessage(String message) {
+ TreeNode t = new TreeNode("", "", false); //$NON-NLS-1$ //$NON-NLS-2$
+ t.add(new TreeNode("", message, false)); //$NON-NLS-1$
+ viewer.setInput(t);
+ }
+
+ /**
+ * A <code>IPropertyChangeListener</code> that detects changes to the Kernel Source location
+ * and runs the <code>updateKernelSourceTree</code> method.
+ */
+ private final IPropertyChangeListener propertyChangeListener = new IPropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ if(event.getProperty().equals(IDEPreferenceConstants.P_KERNEL_SOURCE) ||
+ event.getProperty().equals(IDEPreferenceConstants.P_REMOTE_LOCAL_KERNEL_SOURCE) ||
+ event.getProperty().equals(IDEPreferenceConstants.P_EXCLUDED_KERNEL_SOURCE)) {
+ refresh();
+ }
+ }
+ };
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ IDEPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(propertyChangeListener);
+ if(null != viewer) {
+ viewer.removeDoubleClickListener(doubleClickAction);
+ }
+ if(null != doubleClickAction) {
+ doubleClickAction.dispose();
+ }
+ doubleClickAction = null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/ProbeAliasBrowserView.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/ProbeAliasBrowserView.java
index 8ce45b93c3..fe8e358255 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/ProbeAliasBrowserView.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/views/ProbeAliasBrowserView.java
@@ -31,78 +31,78 @@ import org.eclipse.swt.widgets.Composite;
* @author Ryan Morse
*/
public class ProbeAliasBrowserView extends BrowserView {
- public static final String ID = "org.eclipse.linuxtools.internal.systemtap.ui.ide.views.ProbeAliasBrowserView"; //$NON-NLS-1$
- private ProbeAliasAction doubleClickAction;
+ public static final String ID = "org.eclipse.linuxtools.internal.systemtap.ui.ide.views.ProbeAliasBrowserView"; //$NON-NLS-1$
+ private ProbeAliasAction doubleClickAction;
- /**
- * Creates the UI on the given <code>Composite</code>
- */
- @Override
- public void createPartControl(Composite parent) {
- super.createPartControl(parent);
- TapsetLibrary.init();
- TapsetLibrary.addProbeListener(new ViewUpdater());
- refresh();
- makeActions();
- }
+ /**
+ * Creates the UI on the given <code>Composite</code>
+ */
+ @Override
+ public void createPartControl(Composite parent) {
+ super.createPartControl(parent);
+ TapsetLibrary.init();
+ TapsetLibrary.addProbeListener(new ViewUpdater());
+ refresh();
+ makeActions();
+ }
- @Override
- protected Image getEntryImage(TreeNode treeObj) {
- //Probe variables
- if (treeObj.getData() instanceof ProbevarNodeData) {
- List<String> varTypes = ((ProbevarNodeData) treeObj.getData()).getTypes();
- if (varTypes.get(varTypes.size()-1).endsWith("*")) { //Pointers //$NON-NLS-1$
- return IDEPlugin.getImageDescriptor("icons/vars/var_long.gif").createImage(); //$NON-NLS-1$
- }
- if (varTypes.contains("struct")) {//$NON-NLS-1$
- return IDEPlugin.getImageDescriptor("icons/vars/var_struct.gif").createImage(); //$NON-NLS-1$
- }
- if (varTypes.contains("string")) {//$NON-NLS-1$
- return IDEPlugin.getImageDescriptor("icons/vars/var_str.gif").createImage(); //$NON-NLS-1$
- }
- if (varTypes.contains("unknown")) {//$NON-NLS-1$
- return IDEPlugin.getImageDescriptor("icons/vars/var_unk.gif").createImage(); //$NON-NLS-1$
- }
- // All other types are displayed as long
- return IDEPlugin.getImageDescriptor("icons/vars/var_long.gif").createImage(); //$NON-NLS-1$
- }
+ @Override
+ protected Image getEntryImage(TreeNode treeObj) {
+ //Probe variables
+ if (treeObj.getData() instanceof ProbevarNodeData) {
+ List<String> varTypes = ((ProbevarNodeData) treeObj.getData()).getTypes();
+ if (varTypes.get(varTypes.size()-1).endsWith("*")) { //Pointers //$NON-NLS-1$
+ return IDEPlugin.getImageDescriptor("icons/vars/var_long.gif").createImage(); //$NON-NLS-1$
+ }
+ if (varTypes.contains("struct")) {//$NON-NLS-1$
+ return IDEPlugin.getImageDescriptor("icons/vars/var_struct.gif").createImage(); //$NON-NLS-1$
+ }
+ if (varTypes.contains("string")) {//$NON-NLS-1$
+ return IDEPlugin.getImageDescriptor("icons/vars/var_str.gif").createImage(); //$NON-NLS-1$
+ }
+ if (varTypes.contains("unknown")) {//$NON-NLS-1$
+ return IDEPlugin.getImageDescriptor("icons/vars/var_unk.gif").createImage(); //$NON-NLS-1$
+ }
+ // All other types are displayed as long
+ return IDEPlugin.getImageDescriptor("icons/vars/var_long.gif").createImage(); //$NON-NLS-1$
+ }
- //Non-variable icons
- if (treeObj.getData() instanceof ProbeNodeData) {
- return IDEPlugin.getImageDescriptor("icons/misc/probe_obj.gif").createImage(); //$NON-NLS-1$
- }
- return getGenericImage(treeObj);
- }
+ //Non-variable icons
+ if (treeObj.getData() instanceof ProbeNodeData) {
+ return IDEPlugin.getImageDescriptor("icons/misc/probe_obj.gif").createImage(); //$NON-NLS-1$
+ }
+ return getGenericImage(treeObj);
+ }
- /**
- * Refreshes the list of probe aliases in the viewer.
- */
- @Override
- public void refresh() {
- TreeNode probes = TapsetLibrary.getProbes();
- if (probes != null){
- super.viewer.setInput(probes);
- }
- }
+ /**
+ * Refreshes the list of probe aliases in the viewer.
+ */
+ @Override
+ public void refresh() {
+ TreeNode probes = TapsetLibrary.getProbes();
+ if (probes != null){
+ super.viewer.setInput(probes);
+ }
+ }
- /**
- * Wires up all of the actions for this browser, such as double and right click handlers.
- */
- private void makeActions() {
- doubleClickAction = new ProbeAliasAction(getSite().getWorkbenchWindow(), this);
- viewer.addDoubleClickListener(doubleClickAction);
- registerContextMenu("probePopup"); //$NON-NLS-1$
- }
+ /**
+ * Wires up all of the actions for this browser, such as double and right click handlers.
+ */
+ private void makeActions() {
+ doubleClickAction = new ProbeAliasAction(getSite().getWorkbenchWindow(), this);
+ viewer.addDoubleClickListener(doubleClickAction);
+ registerContextMenu("probePopup"); //$NON-NLS-1$
+ }
- @Override
- public void dispose() {
- super.dispose();
- if (null != viewer) {
- viewer.removeDoubleClickListener(doubleClickAction);
- }
- if (null != doubleClickAction) {
- doubleClickAction.dispose();
- }
- doubleClickAction = null;
- }
+ @Override
+ public void dispose() {
+ super.dispose();
+ if (null != viewer) {
+ viewer.removeDoubleClickListener(doubleClickAction);
+ }
+ if (null != doubleClickAction) {
+ doubleClickAction.dispose();
+ }
+ doubleClickAction = null;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/wizards/StapNewWizard.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/wizards/StapNewWizard.java
index 0de1de2566..4c220dcdbc 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/wizards/StapNewWizard.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/wizards/StapNewWizard.java
@@ -45,100 +45,100 @@ import org.eclipse.ui.ide.IDE;
*/
public class StapNewWizard extends Wizard implements INewWizard {
- private StapNewWizardPage page;
- private ISelection selection;
- private static final ResourceBundle resourceBundle = ResourceBundle.getBundle("org.eclipse.linuxtools.internal.systemtap.ui.ide.wizards.stap_strings"); //$NON-NLS-1$
+ private StapNewWizardPage page;
+ private ISelection selection;
+ private static final ResourceBundle resourceBundle = ResourceBundle.getBundle("org.eclipse.linuxtools.internal.systemtap.ui.ide.wizards.stap_strings"); //$NON-NLS-1$
- /**
- * Constructor for StapNewWizard.
- */
- public StapNewWizard() {
- super();
- setNeedsProgressMonitor(true);
- }
+ /**
+ * Constructor for StapNewWizard.
+ */
+ public StapNewWizard() {
+ super();
+ setNeedsProgressMonitor(true);
+ }
- /**
- * Adding the page to the wizard.
- */
+ /**
+ * Adding the page to the wizard.
+ */
- @Override
- public void addPages() {
- page = new StapNewWizardPage(selection);
- addPage(page);
- }
+ @Override
+ public void addPages() {
+ page = new StapNewWizardPage(selection);
+ addPage(page);
+ }
- /**
- * This method is called when 'Finish' button is pressed in
- * the wizard. We will create an operation and run it
- * using wizard as execution context.
- */
- @Override
- public boolean performFinish() {
- final String containerName = page.getContainerName();
- final String fileName = page.getFileName();
- IRunnableWithProgress op = new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor) throws InvocationTargetException {
- try {
- doFinish(containerName, fileName, monitor);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
- };
- try {
- getContainer().run(true, false, op);
- } catch (InterruptedException e) {
- MessageDialog.openError(getShell(), "Error", e.getLocalizedMessage()); //$NON-NLS-1$
- return false;
- } catch (InvocationTargetException e) {
- Throwable realException = e.getTargetException();
- MessageDialog.openError(getShell(), "Error", realException.getMessage()); //$NON-NLS-1$
- return false;
- }
- return true;
- }
+ /**
+ * This method is called when 'Finish' button is pressed in
+ * the wizard. We will create an operation and run it
+ * using wizard as execution context.
+ */
+ @Override
+ public boolean performFinish() {
+ final String containerName = page.getContainerName();
+ final String fileName = page.getFileName();
+ IRunnableWithProgress op = new IRunnableWithProgress() {
+ @Override
+ public void run(IProgressMonitor monitor) throws InvocationTargetException {
+ try {
+ doFinish(containerName, fileName, monitor);
+ } catch (CoreException e) {
+ throw new InvocationTargetException(e);
+ } finally {
+ monitor.done();
+ }
+ }
+ };
+ try {
+ getContainer().run(true, false, op);
+ } catch (InterruptedException e) {
+ MessageDialog.openError(getShell(), "Error", e.getLocalizedMessage()); //$NON-NLS-1$
+ return false;
+ } catch (InvocationTargetException e) {
+ Throwable realException = e.getTargetException();
+ MessageDialog.openError(getShell(), "Error", realException.getMessage()); //$NON-NLS-1$
+ return false;
+ }
+ return true;
+ }
- /**
- * The worker method. It will find the container, create the
- * file if missing or just replace its contents, and open
- * the editor on the newly created file.
- */
+ /**
+ * The worker method. It will find the container, create the
+ * file if missing or just replace its contents, and open
+ * the editor on the newly created file.
+ */
- private void doFinish(String containerName, String fileName, IProgressMonitor monitor) throws CoreException {
- // create a .stp file
+ private void doFinish(String containerName, String fileName, IProgressMonitor monitor) throws CoreException {
+ // create a .stp file
- monitor.beginTask(resourceBundle.getString("StapNewWizard.BeginTask") + fileName, 2); //$NON-NLS-1$
- final IContainer newResource = (IContainer) ResourcesPlugin.getWorkspace().getRoot().findMember(containerName);
- final IFile newFile = newResource.getFile(new Path(fileName));
- String envString = "#!/usr/bin/env stap"; //$NON-NLS-1$
- newFile.create(new ByteArrayInputStream(envString.getBytes()) , true, monitor);
- monitor.worked(1);
- monitor.setTaskName(resourceBundle.getString("StapNewWizard.SetTask")); //$NON-NLS-1$
- getShell().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- try {
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getWorkbench()
- .showPerspective(IDEPerspective.ID, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
- IDE.openEditor(page, newFile);
- } catch (WorkbenchException e1) {
- // ignore, the file is created but opening the editor failed
- }
- }
- });
- monitor.worked(1);
- }
+ monitor.beginTask(resourceBundle.getString("StapNewWizard.BeginTask") + fileName, 2); //$NON-NLS-1$
+ final IContainer newResource = (IContainer) ResourcesPlugin.getWorkspace().getRoot().findMember(containerName);
+ final IFile newFile = newResource.getFile(new Path(fileName));
+ String envString = "#!/usr/bin/env stap"; //$NON-NLS-1$
+ newFile.create(new ByteArrayInputStream(envString.getBytes()) , true, monitor);
+ monitor.worked(1);
+ monitor.setTaskName(resourceBundle.getString("StapNewWizard.SetTask")); //$NON-NLS-1$
+ getShell().getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getWorkbench()
+ .showPerspective(IDEPerspective.ID, PlatformUI.getWorkbench().getActiveWorkbenchWindow());
+ IDE.openEditor(page, newFile);
+ } catch (WorkbenchException e1) {
+ // ignore, the file is created but opening the editor failed
+ }
+ }
+ });
+ monitor.worked(1);
+ }
- /**
- * We will accept the selection in the workbench to see if
- * we can initialize from it.
- * @see INewWizard#init(IWorkbench, IStructuredSelection)
- */
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- this.selection = selection;
- }
+ /**
+ * We will accept the selection in the workbench to see if
+ * we can initialize from it.
+ * @see INewWizard#init(IWorkbench, IStructuredSelection)
+ */
+ @Override
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ this.selection = selection;
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/wizards/StapNewWizardPage.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/wizards/StapNewWizardPage.java
index d71aa13eb6..986a884d5c 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/wizards/StapNewWizardPage.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.ide/src/org/eclipse/linuxtools/internal/systemtap/ui/ide/wizards/StapNewWizardPage.java
@@ -41,162 +41,162 @@ import org.eclipse.ui.dialogs.ContainerSelectionDialog;
*/
public class StapNewWizardPage extends WizardPage {
- private Text fileText;
-
- private Text containerText;
-
- private ISelection selection;
-
- private static final ResourceBundle resourceBundle = ResourceBundle.getBundle("org.eclipse.linuxtools.internal.systemtap.ui.ide.wizards.stap_strings"); //$NON-NLS-1$
-
- /**
- * Constructor for StapNewWizardPage.
- *
- * @param pageName
- */
- public StapNewWizardPage(ISelection selection) {
- super(resourceBundle.getString("StapNewWizardPage.WizardPage")); //$NON-NLS-1$
- setTitle(resourceBundle.getString("StapNewWizardPage.Title")); //$NON-NLS-1$
- setDescription(resourceBundle.getString("StapNewWizardPage.setDescription")); //$NON-NLS-1$
- this.selection = selection;
- }
-
- /**
- * @see WizardPage#createControl(Composite)
- */
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- container.setLayout(layout);
- layout.numColumns = 3;
- layout.verticalSpacing = 9;
-
- Label label = new Label(container, SWT.NULL);
- label.setText(resourceBundle.getString("StapNewWizardPage.ScriptName")); //$NON-NLS-1$
-
- fileText = new Text(container, SWT.BORDER | SWT.SINGLE);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- fileText.setLayoutData(gd);
- fileText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- dialogChanged();
- }
- });
- new Label(container, SWT.NULL); // XXX just create a new layout with different width
-
- label = new Label(container, SWT.NULL);
- label.setText(resourceBundle.getString("StapNewWizardPage.Project")); //$NON-NLS-1$
-
- containerText = new Text(container, SWT.BORDER | SWT.SINGLE);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- containerText.setLayoutData(gd);
- containerText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- dialogChanged();
- }
- });
-
- Button button = new Button(container, SWT.PUSH);
- button.setText(resourceBundle.getString("StapNewWizardPage.Browse")); //$NON-NLS-1$
- button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleBrowse();
- }
- });
- initialize();
- dialogChanged();
- setControl(container);
- }
-
- /**
- * Tests if the current workbench selection is a suitable container to use.
- */
-
- private void initialize() {
- if (selection != null && selection.isEmpty() == false
- && selection instanceof IStructuredSelection) {
- IStructuredSelection ssel = (IStructuredSelection) selection;
- if (ssel.size() > 1) {
- return;
- }
- Object obj = ssel.getFirstElement();
- if (obj instanceof IResource) {
- IContainer container;
- if (obj instanceof IContainer) {
- container = (IContainer) obj;
- } else {
- container = ((IResource) obj).getParent();
- }
- containerText.setText(container.getFullPath().toString());
- }
- }
- fileText.setText(".stp"); //$NON-NLS-1$
- }
-
- /**
- * Uses the standard container selection dialog to choose the new value for
- * the container field.
- */
- private void handleBrowse() {
- ContainerSelectionDialog dialog = new ContainerSelectionDialog(
- getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, resourceBundle.getString("StapNewWizardPage.SelectProjectMessage")); //$NON-NLS-1$
- if (dialog.open() == Window.OK) {
- Object[] result = dialog.getResult();
- if (result.length == 1) {
- containerText.setText(((Path) result[0]).toString());
- }
- }
- }
-
- /**
- * Ensures that both text fields are set.
- */
-
- private void dialogChanged() {
- IPath container = Path.fromOSString(getContainerName());
- String fileName = getFileName();
- if (fileName.length() == 0 || fileName.equals(".stp")) { //$NON-NLS-1$
- updateStatus(resourceBundle.getString("StapNewWizardPage.UpdateStatus1")); //$NON-NLS-1$
- return;
- }
- if (getContainerName().length() == 0) {
- updateStatus(resourceBundle.getString("StapNewWizardPage.UpdateStatus2")); //$NON-NLS-1$
- return;
- }
- if (container == null
- || !container.isValidPath(getContainerName())) {
- updateStatus(resourceBundle.getString("StapNewWizardPage.UpdateStatus3")); //$NON-NLS-1$
- return;
- }
- if (fileName.replace('\\', '/').indexOf('/', 1) > 0) {
- updateStatus(resourceBundle.getString("StapNewWizardPage.UpdateStatus4")); //$NON-NLS-1$
- return;
- }
- int dotLoc = fileName.lastIndexOf('.');
- if (dotLoc != -1) {
- String ext = fileName.substring(dotLoc + 1);
- if (ext.equalsIgnoreCase("stp") == false) { //$NON-NLS-1$
- updateStatus(resourceBundle.getString("StapNewWizardPage.UpdateStatus.5")); //$NON-NLS-1$
- return;
- }
- }
- updateStatus(null);
- }
-
- private void updateStatus(String message) {
- setErrorMessage(message);
- setPageComplete(message == null);
- }
-
- public String getContainerName() {
- return containerText.getText();
- }
-
- public String getFileName() {
- return fileText.getText();
- }
+ private Text fileText;
+
+ private Text containerText;
+
+ private ISelection selection;
+
+ private static final ResourceBundle resourceBundle = ResourceBundle.getBundle("org.eclipse.linuxtools.internal.systemtap.ui.ide.wizards.stap_strings"); //$NON-NLS-1$
+
+ /**
+ * Constructor for StapNewWizardPage.
+ *
+ * @param pageName
+ */
+ public StapNewWizardPage(ISelection selection) {
+ super(resourceBundle.getString("StapNewWizardPage.WizardPage")); //$NON-NLS-1$
+ setTitle(resourceBundle.getString("StapNewWizardPage.Title")); //$NON-NLS-1$
+ setDescription(resourceBundle.getString("StapNewWizardPage.setDescription")); //$NON-NLS-1$
+ this.selection = selection;
+ }
+
+ /**
+ * @see WizardPage#createControl(Composite)
+ */
+ @Override
+ public void createControl(Composite parent) {
+ Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 3;
+ layout.verticalSpacing = 9;
+
+ Label label = new Label(container, SWT.NULL);
+ label.setText(resourceBundle.getString("StapNewWizardPage.ScriptName")); //$NON-NLS-1$
+
+ fileText = new Text(container, SWT.BORDER | SWT.SINGLE);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+ fileText.setLayoutData(gd);
+ fileText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ dialogChanged();
+ }
+ });
+ new Label(container, SWT.NULL); // XXX just create a new layout with different width
+
+ label = new Label(container, SWT.NULL);
+ label.setText(resourceBundle.getString("StapNewWizardPage.Project")); //$NON-NLS-1$
+
+ containerText = new Text(container, SWT.BORDER | SWT.SINGLE);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ containerText.setLayoutData(gd);
+ containerText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ dialogChanged();
+ }
+ });
+
+ Button button = new Button(container, SWT.PUSH);
+ button.setText(resourceBundle.getString("StapNewWizardPage.Browse")); //$NON-NLS-1$
+ button.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ handleBrowse();
+ }
+ });
+ initialize();
+ dialogChanged();
+ setControl(container);
+ }
+
+ /**
+ * Tests if the current workbench selection is a suitable container to use.
+ */
+
+ private void initialize() {
+ if (selection != null && selection.isEmpty() == false
+ && selection instanceof IStructuredSelection) {
+ IStructuredSelection ssel = (IStructuredSelection) selection;
+ if (ssel.size() > 1) {
+ return;
+ }
+ Object obj = ssel.getFirstElement();
+ if (obj instanceof IResource) {
+ IContainer container;
+ if (obj instanceof IContainer) {
+ container = (IContainer) obj;
+ } else {
+ container = ((IResource) obj).getParent();
+ }
+ containerText.setText(container.getFullPath().toString());
+ }
+ }
+ fileText.setText(".stp"); //$NON-NLS-1$
+ }
+
+ /**
+ * Uses the standard container selection dialog to choose the new value for
+ * the container field.
+ */
+ private void handleBrowse() {
+ ContainerSelectionDialog dialog = new ContainerSelectionDialog(
+ getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, resourceBundle.getString("StapNewWizardPage.SelectProjectMessage")); //$NON-NLS-1$
+ if (dialog.open() == Window.OK) {
+ Object[] result = dialog.getResult();
+ if (result.length == 1) {
+ containerText.setText(((Path) result[0]).toString());
+ }
+ }
+ }
+
+ /**
+ * Ensures that both text fields are set.
+ */
+
+ private void dialogChanged() {
+ IPath container = Path.fromOSString(getContainerName());
+ String fileName = getFileName();
+ if (fileName.length() == 0 || fileName.equals(".stp")) { //$NON-NLS-1$
+ updateStatus(resourceBundle.getString("StapNewWizardPage.UpdateStatus1")); //$NON-NLS-1$
+ return;
+ }
+ if (getContainerName().length() == 0) {
+ updateStatus(resourceBundle.getString("StapNewWizardPage.UpdateStatus2")); //$NON-NLS-1$
+ return;
+ }
+ if (container == null
+ || !container.isValidPath(getContainerName())) {
+ updateStatus(resourceBundle.getString("StapNewWizardPage.UpdateStatus3")); //$NON-NLS-1$
+ return;
+ }
+ if (fileName.replace('\\', '/').indexOf('/', 1) > 0) {
+ updateStatus(resourceBundle.getString("StapNewWizardPage.UpdateStatus4")); //$NON-NLS-1$
+ return;
+ }
+ int dotLoc = fileName.lastIndexOf('.');
+ if (dotLoc != -1) {
+ String ext = fileName.substring(dotLoc + 1);
+ if (ext.equalsIgnoreCase("stp") == false) { //$NON-NLS-1$
+ updateStatus(resourceBundle.getString("StapNewWizardPage.UpdateStatus.5")); //$NON-NLS-1$
+ return;
+ }
+ }
+ updateStatus(null);
+ }
+
+ private void updateStatus(String message) {
+ setErrorMessage(message);
+ setPageComplete(message == null);
+ }
+
+ public String getContainerName() {
+ return containerText.getText();
+ }
+
+ public String getFileName() {
+ return fileText.getText();
+ }
}
diff --git a/systemtap/org.eclipse.linuxtools.systemtap.ui.tests/src/org/eclipse/linuxtools/systemtap/ui/tests/SystemtapTest.java b/systemtap/org.eclipse.linuxtools.systemtap.ui.tests/src/org/eclipse/linuxtools/systemtap/ui/tests/SystemtapTest.java
index a7f617bbd7..c2d413942b 100644
--- a/systemtap/org.eclipse.linuxtools.systemtap.ui.tests/src/org/eclipse/linuxtools/systemtap/ui/tests/SystemtapTest.java
+++ b/systemtap/org.eclipse.linuxtools.systemtap.ui.tests/src/org/eclipse/linuxtools/systemtap/ui/tests/SystemtapTest.java
@@ -19,22 +19,22 @@ import org.junit.BeforeClass;
* Generic utilities for systemtap tests.
*/
public class SystemtapTest {
- public static boolean stapInstalled;
+ public static boolean stapInstalled;
- @BeforeClass
- public static void checkStapInstalled() throws IOException {
- stapInstalled = SystemtapTest.stapInstalled();
- }
+ @BeforeClass
+ public static void checkStapInstalled() throws IOException {
+ stapInstalled = SystemtapTest.stapInstalled();
+ }
- /**
- * Check that stap is installed
- *
- * @return true if stap is installed, false otherwise.
- * @throws IOException
- */
- protected static boolean stapInstalled() throws IOException {
- Process process = RuntimeProcessFactory.getFactory().exec(
- new String[] { "stap", "-V" }, null); //$NON-NLS-1$ //$NON-NLS-2$
- return (process != null);
- }
+ /**
+ * Check that stap is installed
+ *
+ * @return true if stap is installed, false otherwise.
+ * @throws IOException
+ */
+ protected static boolean stapInstalled() throws IOException {
+ Process process = RuntimeProcessFactory.getFactory().exec(
+ new String[] { "stap", "-V" }, null); //$NON-NLS-1$ //$NON-NLS-2$
+ return (process != null);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind-feature/pom.xml b/valgrind/org.eclipse.linuxtools.valgrind-feature/pom.xml
index fbda4ceb49..e557635785 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind-feature/pom.xml
+++ b/valgrind/org.eclipse.linuxtools.valgrind-feature/pom.xml
@@ -22,7 +22,7 @@
<packaging>eclipse-feature</packaging>
<name>Linux Tools Valgrind Tools Integration Feature</name>
-
+
<build>
<plugins>
<plugin>
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/AbstractCachegrindTest.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/AbstractCachegrindTest.java
index ef1f8a4b77..6d99fceeae 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/AbstractCachegrindTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/AbstractCachegrindTest.java
@@ -18,29 +18,29 @@ import org.eclipse.linuxtools.internal.valgrind.tests.AbstractValgrindTest;
public abstract class AbstractCachegrindTest extends AbstractValgrindTest {
- @Override
- protected String getToolID() {
- return CachegrindPlugin.TOOL_ID;
- }
+ @Override
+ protected String getToolID() {
+ return CachegrindPlugin.TOOL_ID;
+ }
- protected CachegrindFile getFileByName(CachegrindOutput output, String name) {
- CachegrindFile file = null;
- for (CachegrindFile f : output.getFiles()) {
- if (f.getName().equals(name)) {
- file = f;
- }
- }
- return file;
- }
+ protected CachegrindFile getFileByName(CachegrindOutput output, String name) {
+ CachegrindFile file = null;
+ for (CachegrindFile f : output.getFiles()) {
+ if (f.getName().equals(name)) {
+ file = f;
+ }
+ }
+ return file;
+ }
- protected CachegrindFunction getFunctionByName(CachegrindFile file, String name) {
- CachegrindFunction function = null;
- for (CachegrindFunction f : file.getFunctions()) {
- if (f.getName().equals(name)) {
- function = f;
- }
- }
- return function;
- }
+ protected CachegrindFunction getFunctionByName(CachegrindFile file, String name) {
+ CachegrindFunction function = null;
+ for (CachegrindFunction f : file.getFunctions()) {
+ if (f.getName().equals(name)) {
+ function = f;
+ }
+ }
+ return function;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/AllTests.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/AllTests.java
index 93c7b4909b..f4558f1e74 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/AllTests.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/AllTests.java
@@ -15,8 +15,8 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ BasicCachegrindTest.class, CModelLabelsTest.class,
- DoubleClickTest.class, LaunchConfigTabTest.class,
- MultiProcessTest.class, ExpandCollapseTest.class, ShortcutTest.class })
+ DoubleClickTest.class, LaunchConfigTabTest.class,
+ MultiProcessTest.class, ExpandCollapseTest.class, ShortcutTest.class })
public class AllTests {
// suite class
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/BasicCachegrindTest.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/BasicCachegrindTest.java
index 7298b8e840..99f64944f5 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/BasicCachegrindTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/BasicCachegrindTest.java
@@ -25,52 +25,52 @@ import org.junit.Test;
public class BasicCachegrindTest extends AbstractCachegrindTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
- @Test
- public void testNumPIDs() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testNumPIDs"); //$NON-NLS-1$
+ @Test
+ public void testNumPIDs() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testNumPIDs"); //$NON-NLS-1$
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
- .getDefault().getView().getDynamicView();
- assertEquals(1, view.getOutputs().length);
- }
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
+ .getDefault().getView().getDynamicView();
+ assertEquals(1, view.getOutputs().length);
+ }
- @Test
- public void testFileNames() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testFileNames"); //$NON-NLS-1$
+ @Test
+ public void testFileNames() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testFileNames"); //$NON-NLS-1$
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
- .getDefault().getView().getDynamicView();
- CachegrindOutput output = view.getOutputs()[0];
- CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- assertNotNull(file);
- file = getFileByName(output, "cpptest.h"); //$NON-NLS-1$
- assertNotNull(file);
- }
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
+ .getDefault().getView().getDynamicView();
+ CachegrindOutput output = view.getOutputs()[0];
+ CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ assertNotNull(file);
+ file = getFileByName(output, "cpptest.h"); //$NON-NLS-1$
+ assertNotNull(file);
+ }
- @Test
- public void testNumFunctions() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testNumFunctions"); //$NON-NLS-1$
+ @Test
+ public void testNumFunctions() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testNumFunctions"); //$NON-NLS-1$
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
- .getDefault().getView().getDynamicView();
- CachegrindOutput output = view.getOutputs()[0];
- CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- assertNotNull(file);
- assertEquals(8, file.getFunctions().length);
- }
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
+ .getDefault().getView().getDynamicView();
+ CachegrindOutput output = view.getOutputs()[0];
+ CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ assertNotNull(file);
+ assertEquals(8, file.getFunctions().length);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/CModelLabelsTest.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/CModelLabelsTest.java
index 443e474d1f..582345c639 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/CModelLabelsTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/CModelLabelsTest.java
@@ -37,114 +37,114 @@ import org.junit.Test;
public class CModelLabelsTest extends AbstractCachegrindTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
- @Test
- public void testFileLabelsCPP() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testFileLabelsCPP"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- CachegrindOutput output = view.getOutputs()[0];
- CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
-
- assertTrue(file.getModel() instanceof ITranslationUnit);
-
- checkLabelProvider(file);
- }
- @Test
- public void testFileLabelsH() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testFileLabelsH"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- CachegrindOutput output = view.getOutputs()[0];
- CachegrindFile file = getFileByName(output, "cpptest.h"); //$NON-NLS-1$
-
- assertTrue(file.getModel() instanceof ITranslationUnit);
- assertTrue(((ITranslationUnit) file.getModel()).isHeaderUnit());
-
- checkLabelProvider(file);
- }
- @Test
- public void testFunctionLabel() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testFunctionLabel"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- CachegrindOutput output = view.getOutputs()[0];
- CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- CachegrindFunction func = getFunctionByName(file, "main"); //$NON-NLS-1$
-
- assertTrue(func.getModel() instanceof IFunction);
-
- checkLabelProvider(func, file);
- }
- @Test
- public void testMethodLabel() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testMethodLabel"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- CachegrindOutput output = view.getOutputs()[0];
- CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- CachegrindFunction func = getFunctionByName(file, "A::A()"); //$NON-NLS-1$
-
- assertTrue(func.getModel() instanceof IMethod);
-
- checkLabelProvider(func, file);
- }
- @Test
- public void testNestedMethodLabel() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testNestedMethodLabel"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- CachegrindOutput output = view.getOutputs()[0];
- CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- CachegrindFunction func = getFunctionByName(file, "A::B::e()"); //$NON-NLS-1$
-
- assertTrue(func.getModel() instanceof IMethod);
-
- checkLabelProvider(func, file);
- }
-
- private static void checkLabelProvider(CachegrindFile file) {
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- TreeViewer viewer = view.getViewer();
-
- TreePath path = new TreePath(new Object[] { view.getOutputs()[0], file });
- checkLabelProvider(viewer, path, file);
- }
-
- private static void checkLabelProvider(CachegrindFunction func, CachegrindFile file) {
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- TreeViewer viewer = view.getViewer();
-
- TreePath path = new TreePath(new Object[] { view.getOutputs()[0], file, func });
- checkLabelProvider(viewer, path, func);
- }
-
- private static void checkLabelProvider(TreeViewer viewer, TreePath path, ICachegrindElement element) {
- // expand only the interesting item
- viewer.expandToLevel(element, AbstractTreeViewer.ALL_LEVELS);
- TreeSelection selection = new TreeSelection(path);
- viewer.setSelection(selection);
- TreeItem item = viewer.getTree().getSelection()[0];
-
- // ensure the CElementLabelProvider is called correctly
- CElementLabelProvider provider = ((CachegrindLabelProvider) viewer.getLabelProvider(0)).getCLabelProvider();
- assertEquals(provider.getText(element.getModel()), item.getText());
- assertEquals(provider.getImage(element.getModel()), item.getImage());
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+ @Test
+ public void testFileLabelsCPP() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testFileLabelsCPP"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ CachegrindOutput output = view.getOutputs()[0];
+ CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+
+ assertTrue(file.getModel() instanceof ITranslationUnit);
+
+ checkLabelProvider(file);
+ }
+ @Test
+ public void testFileLabelsH() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testFileLabelsH"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ CachegrindOutput output = view.getOutputs()[0];
+ CachegrindFile file = getFileByName(output, "cpptest.h"); //$NON-NLS-1$
+
+ assertTrue(file.getModel() instanceof ITranslationUnit);
+ assertTrue(((ITranslationUnit) file.getModel()).isHeaderUnit());
+
+ checkLabelProvider(file);
+ }
+ @Test
+ public void testFunctionLabel() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testFunctionLabel"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ CachegrindOutput output = view.getOutputs()[0];
+ CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ CachegrindFunction func = getFunctionByName(file, "main"); //$NON-NLS-1$
+
+ assertTrue(func.getModel() instanceof IFunction);
+
+ checkLabelProvider(func, file);
+ }
+ @Test
+ public void testMethodLabel() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testMethodLabel"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ CachegrindOutput output = view.getOutputs()[0];
+ CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ CachegrindFunction func = getFunctionByName(file, "A::A()"); //$NON-NLS-1$
+
+ assertTrue(func.getModel() instanceof IMethod);
+
+ checkLabelProvider(func, file);
+ }
+ @Test
+ public void testNestedMethodLabel() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testNestedMethodLabel"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ CachegrindOutput output = view.getOutputs()[0];
+ CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ CachegrindFunction func = getFunctionByName(file, "A::B::e()"); //$NON-NLS-1$
+
+ assertTrue(func.getModel() instanceof IMethod);
+
+ checkLabelProvider(func, file);
+ }
+
+ private static void checkLabelProvider(CachegrindFile file) {
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ TreeViewer viewer = view.getViewer();
+
+ TreePath path = new TreePath(new Object[] { view.getOutputs()[0], file });
+ checkLabelProvider(viewer, path, file);
+ }
+
+ private static void checkLabelProvider(CachegrindFunction func, CachegrindFile file) {
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ TreeViewer viewer = view.getViewer();
+
+ TreePath path = new TreePath(new Object[] { view.getOutputs()[0], file, func });
+ checkLabelProvider(viewer, path, func);
+ }
+
+ private static void checkLabelProvider(TreeViewer viewer, TreePath path, ICachegrindElement element) {
+ // expand only the interesting item
+ viewer.expandToLevel(element, AbstractTreeViewer.ALL_LEVELS);
+ TreeSelection selection = new TreeSelection(path);
+ viewer.setSelection(selection);
+ TreeItem item = viewer.getTree().getSelection()[0];
+
+ // ensure the CElementLabelProvider is called correctly
+ CElementLabelProvider provider = ((CachegrindLabelProvider) viewer.getLabelProvider(0)).getCLabelProvider();
+ assertEquals(provider.getText(element.getModel()), item.getText());
+ assertEquals(provider.getImage(element.getModel()), item.getImage());
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/DoubleClickTest.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/DoubleClickTest.java
index 1c5ea00f55..9b1b74eebd 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/DoubleClickTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/DoubleClickTest.java
@@ -43,104 +43,104 @@ import org.junit.Before;
import org.junit.Test;
public class DoubleClickTest extends AbstractCachegrindTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
-
- private static void doDoubleClick(TreePath path) {
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- TreeViewer treeViewer = view.getViewer();
-
- ICachegrindElement element = (ICachegrindElement) path.getLastSegment();
- treeViewer.expandToLevel(element, AbstractTreeViewer.ALL_LEVELS);
- TreeSelection selection = new TreeSelection(path);
-
- IDoubleClickListener listener = view.getDoubleClickListener();
- listener.doubleClick(new DoubleClickEvent(treeViewer, selection));
- }
- @Test
- public void testDoubleClickFile() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testDoubleClickFile"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- CachegrindOutput output = view.getOutputs()[0];
- CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- TreePath path = new TreePath(new Object[] { output, file });
-
- doDoubleClick(path);
-
- checkFile(file);
- }
- @Test
- public void testDoubleClickFunction() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testDoubleClickFunction"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- CachegrindOutput output = view.getOutputs()[0];
- CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- CachegrindFunction func = getFunctionByName(file, "main"); //$NON-NLS-1$
- TreePath path = new TreePath(new Object[] { output, file, func });
-
- doDoubleClick(path);
-
- // check file in editor
- IEditorPart editor = checkFile(file);
-
- // check line number
- ITextEditor textEditor = (ITextEditor) editor;
-
- ISelection selection = textEditor.getSelectionProvider().getSelection();
- TextSelection textSelection = (TextSelection) selection;
- int line = textSelection.getStartLine() + 1; // zero-indexed
-
- int expectedLine = ((IFunction) func.getModel()).getSourceRange().getStartLine();
- assertEquals(expectedLine, line);
- }
- @Test
- public void testDoubleClickLine() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testDoubleClickFunction"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- CachegrindOutput output = view.getOutputs()[0];
- CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- CachegrindFunction func = getFunctionByName(file, "main"); //$NON-NLS-1$
- CachegrindLine line = func.getLines()[0];
- TreePath path = new TreePath(new Object[] { output, file, func });
-
- doDoubleClick(path);
-
- // check file in editor
- IEditorPart editor = checkFile(file);
-
- // check line number
- ITextEditor textEditor = (ITextEditor) editor;
-
- ISelection selection = textEditor.getSelectionProvider().getSelection();
- TextSelection textSelection = (TextSelection) selection;
- int actualLine = textSelection.getStartLine() + 1; // zero-indexed
-
- assertEquals(line.getLine(), actualLine);
- }
-
- private IEditorPart checkFile(CachegrindFile file) {
- IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- IEditorInput input = editor.getEditorInput();
- IFileEditorInput fileInput = (IFileEditorInput) input;
- IResource expectedResource = proj.getProject().findMember(file.getName());
- File expectedFile = expectedResource.getLocation().toFile();
- File actualFile = fileInput.getFile().getLocation().toFile();
- assertEquals(expectedFile, actualFile);
- return editor;
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ private static void doDoubleClick(TreePath path) {
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ TreeViewer treeViewer = view.getViewer();
+
+ ICachegrindElement element = (ICachegrindElement) path.getLastSegment();
+ treeViewer.expandToLevel(element, AbstractTreeViewer.ALL_LEVELS);
+ TreeSelection selection = new TreeSelection(path);
+
+ IDoubleClickListener listener = view.getDoubleClickListener();
+ listener.doubleClick(new DoubleClickEvent(treeViewer, selection));
+ }
+ @Test
+ public void testDoubleClickFile() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testDoubleClickFile"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ CachegrindOutput output = view.getOutputs()[0];
+ CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ TreePath path = new TreePath(new Object[] { output, file });
+
+ doDoubleClick(path);
+
+ checkFile(file);
+ }
+ @Test
+ public void testDoubleClickFunction() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testDoubleClickFunction"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ CachegrindOutput output = view.getOutputs()[0];
+ CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ CachegrindFunction func = getFunctionByName(file, "main"); //$NON-NLS-1$
+ TreePath path = new TreePath(new Object[] { output, file, func });
+
+ doDoubleClick(path);
+
+ // check file in editor
+ IEditorPart editor = checkFile(file);
+
+ // check line number
+ ITextEditor textEditor = (ITextEditor) editor;
+
+ ISelection selection = textEditor.getSelectionProvider().getSelection();
+ TextSelection textSelection = (TextSelection) selection;
+ int line = textSelection.getStartLine() + 1; // zero-indexed
+
+ int expectedLine = ((IFunction) func.getModel()).getSourceRange().getStartLine();
+ assertEquals(expectedLine, line);
+ }
+ @Test
+ public void testDoubleClickLine() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testDoubleClickFunction"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ CachegrindOutput output = view.getOutputs()[0];
+ CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ CachegrindFunction func = getFunctionByName(file, "main"); //$NON-NLS-1$
+ CachegrindLine line = func.getLines()[0];
+ TreePath path = new TreePath(new Object[] { output, file, func });
+
+ doDoubleClick(path);
+
+ // check file in editor
+ IEditorPart editor = checkFile(file);
+
+ // check line number
+ ITextEditor textEditor = (ITextEditor) editor;
+
+ ISelection selection = textEditor.getSelectionProvider().getSelection();
+ TextSelection textSelection = (TextSelection) selection;
+ int actualLine = textSelection.getStartLine() + 1; // zero-indexed
+
+ assertEquals(line.getLine(), actualLine);
+ }
+
+ private IEditorPart checkFile(CachegrindFile file) {
+ IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
+ IEditorInput input = editor.getEditorInput();
+ IFileEditorInput fileInput = (IFileEditorInput) input;
+ IResource expectedResource = proj.getProject().findMember(file.getName());
+ File expectedFile = expectedResource.getLocation().toFile();
+ File actualFile = fileInput.getFile().getLocation().toFile();
+ assertEquals(expectedFile, actualFile);
+ return editor;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ExpandCollapseTest.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ExpandCollapseTest.java
index bed1490867..8a44766f32 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ExpandCollapseTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ExpandCollapseTest.java
@@ -30,68 +30,68 @@ import org.junit.Test;
public class ExpandCollapseTest extends AbstractCachegrindTest {
- private TreeViewer viewer;
- private Menu contextMenu;
+ private TreeViewer viewer;
+ private Menu contextMenu;
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
- @Test
- public void testExpand() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testDefaults"); //$NON-NLS-1$
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+ @Test
+ public void testExpand() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testDefaults"); //$NON-NLS-1$
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- viewer = view.getViewer();
- contextMenu = viewer.getTree().getMenu();
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ viewer = view.getViewer();
+ contextMenu = viewer.getTree().getMenu();
- // Select first snapshot and expand it
- CachegrindOutput[] outputs = (CachegrindOutput[]) viewer.getInput();
- CachegrindOutput output = outputs[0];
- TreeSelection selection = new TreeSelection(new TreePath(new Object[] { output }));
- viewer.setSelection(selection);
- contextMenu.notifyListeners(SWT.Show, null);
- contextMenu.getItem(0).notifyListeners(SWT.Selection, null);
+ // Select first snapshot and expand it
+ CachegrindOutput[] outputs = (CachegrindOutput[]) viewer.getInput();
+ CachegrindOutput output = outputs[0];
+ TreeSelection selection = new TreeSelection(new TreePath(new Object[] { output }));
+ viewer.setSelection(selection);
+ contextMenu.notifyListeners(SWT.Show, null);
+ contextMenu.getItem(0).notifyListeners(SWT.Selection, null);
- checkExpanded(output, true);
- }
- @Test
- public void testCollapse() throws Exception {
- // Expand the element first
- testExpand();
+ checkExpanded(output, true);
+ }
+ @Test
+ public void testCollapse() throws Exception {
+ // Expand the element first
+ testExpand();
- // Then collapse it
- CachegrindOutput[] outputs = (CachegrindOutput[]) viewer.getInput();
- CachegrindOutput output = outputs[0];
- TreeSelection selection = new TreeSelection(new TreePath(new Object[] { output }));
- viewer.setSelection(selection);
- contextMenu.notifyListeners(SWT.Show, null);
- contextMenu.getItem(1).notifyListeners(SWT.Selection, null);
+ // Then collapse it
+ CachegrindOutput[] outputs = (CachegrindOutput[]) viewer.getInput();
+ CachegrindOutput output = outputs[0];
+ TreeSelection selection = new TreeSelection(new TreePath(new Object[] { output }));
+ viewer.setSelection(selection);
+ contextMenu.notifyListeners(SWT.Show, null);
+ contextMenu.getItem(1).notifyListeners(SWT.Selection, null);
- checkExpanded(output, false);
- }
+ checkExpanded(output, false);
+ }
- private void checkExpanded(ICachegrindElement element, boolean expanded) {
- if (element.getChildren() != null && element.getChildren().length > 0) {
- // only applicable to internal nodes
- if (expanded) {
- assertTrue(viewer.getExpandedState(element));
- }
- else {
- assertFalse(viewer.getExpandedState(element));
- }
- for (ICachegrindElement child : element.getChildren()) {
- checkExpanded(child, expanded);
- }
- }
- }
+ private void checkExpanded(ICachegrindElement element, boolean expanded) {
+ if (element.getChildren() != null && element.getChildren().length > 0) {
+ // only applicable to internal nodes
+ if (expanded) {
+ assertTrue(viewer.getExpandedState(element));
+ }
+ else {
+ assertFalse(viewer.getExpandedState(element));
+ }
+ for (ICachegrindElement child : element.getChildren()) {
+ checkExpanded(child, expanded);
+ }
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/LaunchConfigTabTest.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/LaunchConfigTabTest.java
index 9c544328e8..a9209ef82f 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/LaunchConfigTabTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/LaunchConfigTabTest.java
@@ -35,161 +35,161 @@ import org.junit.Test;
public class LaunchConfigTabTest extends AbstractCachegrindTest {
- private ILaunchConfiguration config;
- private Shell testShell;
- private ValgrindOptionsTab tab;
- private CachegrindToolPage dynamicTab;
-
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
-
- config = createConfiguration(proj.getProject());
-
- testShell = new Shell(Display.getDefault());
- testShell.setLayout(new GridLayout());
- tab = new ValgrindOptionsTab();
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- tab.dispose();
- testShell.dispose();
- deleteProject(proj);
- super.tearDown();
- }
-
- private ILaunchConfigurationWorkingCopy initConfig() throws CoreException {
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- tab.setDefaults(wc);
- tab.createControl(testShell);
- tab.initializeFrom(config);
- int ix = Arrays.asList(tab.getTools()).indexOf(CachegrindPlugin.TOOL_ID);
- tab.getToolsCombo().select(ix);
- ILaunchConfigurationTab dynamicTab = tab.getDynamicTab();
- this.dynamicTab = (CachegrindToolPage) dynamicTab;
- return wc;
- }
-
- private ILaunch saveAndLaunch(ILaunchConfigurationWorkingCopy wc,
- String testName) throws Exception {
- tab.performApply(wc);
- config = wc.doSave();
- return doLaunch(config, testName);
- }
- @Test
- public void testDefaults() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- ILaunch launch = saveAndLaunch(wc, "testDefaults"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--tool=cachegrind")); //$NON-NLS-1$
- assertFalse(cmd.contains("--xml=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("-q")); //$NON-NLS-1$
- assertTrue(cmd.contains("--trace-children=no")); //$NON-NLS-1$
- assertTrue(cmd.contains("--child-silent-after-fork=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--demangle=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--num-callers=12")); //$NON-NLS-1$
- assertTrue(cmd.contains("--error-limit=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--show-below-main=no")); //$NON-NLS-1$
- assertFalse(cmd.contains("--suppressions")); //$NON-NLS-1$
- assertTrue(cmd.contains("--max-stackframe=2000000")); //$NON-NLS-1$
- assertTrue(cmd.contains("--run-libc-freeres=yes")); //$NON-NLS-1$
-
- assertTrue(cmd.contains("--cache-sim=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--branch-sim=no")); //$NON-NLS-1$
- }
- @Test
- public void testNoSim() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getCacheButton().setSelection(false);
- tab.performApply(wc);
- wc.doSave();
-
- assertFalse(tab.isValid(config));
- }
- @Test
- public void testBranchSim() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getBranchButton().setSelection(true);
- tab.performApply(wc);
- wc.doSave();
-
- ILaunch launch = saveAndLaunch(wc, "testBranchSim"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--branch-sim=yes")); //$NON-NLS-1$
- }
- @Test
- public void testI1Cache() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
-
- assertFalse(dynamicTab.getI1SizeSpinner().isEnabled());
- dynamicTab.getI1Button().setSelection(true);
- dynamicTab.getI1Button().notifyListeners(SWT.Selection, null);
- assertTrue(dynamicTab.getI1SizeSpinner().isEnabled());
-
- dynamicTab.getI1SizeSpinner().setSelection(16384);
- dynamicTab.getI1AssocSpinner().setSelection(1);
- dynamicTab.getI1LineSizeSpinner().setSelection(16);
-
- tab.performApply(wc);
- wc.doSave();
-
- ILaunch launch = saveAndLaunch(wc, "testI1Cache"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertTrue(cmd.contains("--I1=16384,1,16")); //$NON-NLS-1$
- }
- @Test
- public void testD1Cache() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
-
- assertFalse(dynamicTab.getD1SizeSpinner().isEnabled());
- dynamicTab.getD1Button().setSelection(true);
- dynamicTab.getD1Button().notifyListeners(SWT.Selection, null);
- assertTrue(dynamicTab.getD1SizeSpinner().isEnabled());
-
- dynamicTab.getD1SizeSpinner().setSelection(16384);
- dynamicTab.getD1AssocSpinner().setSelection(1);
- dynamicTab.getD1LineSizeSpinner().setSelection(16);
-
- tab.performApply(wc);
- wc.doSave();
-
- ILaunch launch = saveAndLaunch(wc, "testD1Cache"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertTrue(cmd.contains("--D1=16384,1,16")); //$NON-NLS-1$
- }
- @Test
- public void testL2Cache() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
-
- assertFalse(dynamicTab.getL2SizeSpinner().isEnabled());
- dynamicTab.getL2Button().setSelection(true);
- dynamicTab.getL2Button().notifyListeners(SWT.Selection, null);
- assertTrue(dynamicTab.getL2SizeSpinner().isEnabled());
-
- dynamicTab.getL2SizeSpinner().setSelection(16384);
- dynamicTab.getL2AssocSpinner().setSelection(1);
- dynamicTab.getL2LineSizeSpinner().setSelection(16);
-
- tab.performApply(wc);
- wc.doSave();
-
- ILaunch launch = saveAndLaunch(wc, "testL2Cache"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertTrue(cmd.contains("--L2=16384,1,16")); //$NON-NLS-1$
- }
+ private ILaunchConfiguration config;
+ private Shell testShell;
+ private ValgrindOptionsTab tab;
+ private CachegrindToolPage dynamicTab;
+
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
+
+ config = createConfiguration(proj.getProject());
+
+ testShell = new Shell(Display.getDefault());
+ testShell.setLayout(new GridLayout());
+ tab = new ValgrindOptionsTab();
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ tab.dispose();
+ testShell.dispose();
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ private ILaunchConfigurationWorkingCopy initConfig() throws CoreException {
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ tab.setDefaults(wc);
+ tab.createControl(testShell);
+ tab.initializeFrom(config);
+ int ix = Arrays.asList(tab.getTools()).indexOf(CachegrindPlugin.TOOL_ID);
+ tab.getToolsCombo().select(ix);
+ ILaunchConfigurationTab dynamicTab = tab.getDynamicTab();
+ this.dynamicTab = (CachegrindToolPage) dynamicTab;
+ return wc;
+ }
+
+ private ILaunch saveAndLaunch(ILaunchConfigurationWorkingCopy wc,
+ String testName) throws Exception {
+ tab.performApply(wc);
+ config = wc.doSave();
+ return doLaunch(config, testName);
+ }
+ @Test
+ public void testDefaults() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ ILaunch launch = saveAndLaunch(wc, "testDefaults"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--tool=cachegrind")); //$NON-NLS-1$
+ assertFalse(cmd.contains("--xml=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("-q")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--trace-children=no")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--child-silent-after-fork=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--demangle=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--num-callers=12")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--error-limit=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--show-below-main=no")); //$NON-NLS-1$
+ assertFalse(cmd.contains("--suppressions")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--max-stackframe=2000000")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--run-libc-freeres=yes")); //$NON-NLS-1$
+
+ assertTrue(cmd.contains("--cache-sim=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--branch-sim=no")); //$NON-NLS-1$
+ }
+ @Test
+ public void testNoSim() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getCacheButton().setSelection(false);
+ tab.performApply(wc);
+ wc.doSave();
+
+ assertFalse(tab.isValid(config));
+ }
+ @Test
+ public void testBranchSim() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getBranchButton().setSelection(true);
+ tab.performApply(wc);
+ wc.doSave();
+
+ ILaunch launch = saveAndLaunch(wc, "testBranchSim"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--branch-sim=yes")); //$NON-NLS-1$
+ }
+ @Test
+ public void testI1Cache() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+
+ assertFalse(dynamicTab.getI1SizeSpinner().isEnabled());
+ dynamicTab.getI1Button().setSelection(true);
+ dynamicTab.getI1Button().notifyListeners(SWT.Selection, null);
+ assertTrue(dynamicTab.getI1SizeSpinner().isEnabled());
+
+ dynamicTab.getI1SizeSpinner().setSelection(16384);
+ dynamicTab.getI1AssocSpinner().setSelection(1);
+ dynamicTab.getI1LineSizeSpinner().setSelection(16);
+
+ tab.performApply(wc);
+ wc.doSave();
+
+ ILaunch launch = saveAndLaunch(wc, "testI1Cache"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertTrue(cmd.contains("--I1=16384,1,16")); //$NON-NLS-1$
+ }
+ @Test
+ public void testD1Cache() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+
+ assertFalse(dynamicTab.getD1SizeSpinner().isEnabled());
+ dynamicTab.getD1Button().setSelection(true);
+ dynamicTab.getD1Button().notifyListeners(SWT.Selection, null);
+ assertTrue(dynamicTab.getD1SizeSpinner().isEnabled());
+
+ dynamicTab.getD1SizeSpinner().setSelection(16384);
+ dynamicTab.getD1AssocSpinner().setSelection(1);
+ dynamicTab.getD1LineSizeSpinner().setSelection(16);
+
+ tab.performApply(wc);
+ wc.doSave();
+
+ ILaunch launch = saveAndLaunch(wc, "testD1Cache"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertTrue(cmd.contains("--D1=16384,1,16")); //$NON-NLS-1$
+ }
+ @Test
+ public void testL2Cache() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+
+ assertFalse(dynamicTab.getL2SizeSpinner().isEnabled());
+ dynamicTab.getL2Button().setSelection(true);
+ dynamicTab.getL2Button().notifyListeners(SWT.Selection, null);
+ assertTrue(dynamicTab.getL2SizeSpinner().isEnabled());
+
+ dynamicTab.getL2SizeSpinner().setSelection(16384);
+ dynamicTab.getL2AssocSpinner().setSelection(1);
+ dynamicTab.getL2LineSizeSpinner().setSelection(16);
+
+ tab.performApply(wc);
+ wc.doSave();
+
+ ILaunch launch = saveAndLaunch(wc, "testL2Cache"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertTrue(cmd.contains("--L2=16384,1,16")); //$NON-NLS-1$
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/MultiProcessTest.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/MultiProcessTest.java
index 90ad7f2b9d..fb9c921989 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/MultiProcessTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/MultiProcessTest.java
@@ -27,105 +27,105 @@ import org.junit.Before;
import org.junit.Test;
public class MultiProcessTest extends AbstractCachegrindTest {
- private ICProject refProj;
-
- @Before
- public void prep() throws Exception {
- refProj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
- proj = createProjectAndBuild("multiProcTest"); //$NON-NLS-1$
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- deleteProject(refProj);
- super.tearDown();
- }
-
- @Test
- public void testNoExec() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testNoExec"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
- .getDefault().getView().getDynamicView();
- assertEquals(1, view.getOutputs().length);
- }
-
- @Test
- public void testNumPids() throws Exception {
- ILaunchConfigurationWorkingCopy config = createConfiguration(
- proj.getProject()).getWorkingCopy();
- config.setAttribute(
- LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
- config.doSave();
- doLaunch(config, "testExec"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
- .getDefault().getView().getDynamicView();
- assertEquals(2, view.getOutputs().length);
- }
-
- @Test
- public void testFileNames() throws Exception {
- ILaunchConfigurationWorkingCopy config = createConfiguration(
- proj.getProject()).getWorkingCopy();
- config.setAttribute(
- LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
- config.doSave();
- doLaunch(config, "testExec"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
- .getDefault().getView().getDynamicView();
-
- int pidIx = 0;
- CachegrindOutput output = view.getOutputs()[pidIx];
- CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- if (file == null) {
- pidIx = 1;
- output = view.getOutputs()[pidIx];
- file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- }
- assertNotNull(file);
- file = getFileByName(output, "cpptest.h"); //$NON-NLS-1$
- assertNotNull(file);
-
- // test other pid
- pidIx = (pidIx + 1) % 2;
- output = view.getOutputs()[pidIx];
- file = getFileByName(output, "parent.cpp"); //$NON-NLS-1$
- assertNotNull(file);
- }
-
- @Test
- public void testNumFunctions() throws Exception {
- ILaunchConfigurationWorkingCopy config = createConfiguration(
- proj.getProject()).getWorkingCopy();
- config.setAttribute(
- LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
- config.doSave();
- doLaunch(config, "testExec"); //$NON-NLS-1$
-
- CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
- .getDefault().getView().getDynamicView();
-
- int pidIx = 0;
- CachegrindOutput output = view.getOutputs()[pidIx];
- CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- if (file == null) {
- pidIx = 1;
- output = view.getOutputs()[pidIx];
- file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
- }
- assertNotNull(file);
- assertEquals(8, file.getFunctions().length);
-
- // test other pid
- pidIx = (pidIx + 1) % 2;
- output = view.getOutputs()[pidIx];
- file = getFileByName(output, "parent.cpp"); //$NON-NLS-1$
- assertNotNull(file);
- assertEquals(6, file.getFunctions().length);
- }
+ private ICProject refProj;
+
+ @Before
+ public void prep() throws Exception {
+ refProj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
+ proj = createProjectAndBuild("multiProcTest"); //$NON-NLS-1$
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ deleteProject(refProj);
+ super.tearDown();
+ }
+
+ @Test
+ public void testNoExec() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testNoExec"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
+ .getDefault().getView().getDynamicView();
+ assertEquals(1, view.getOutputs().length);
+ }
+
+ @Test
+ public void testNumPids() throws Exception {
+ ILaunchConfigurationWorkingCopy config = createConfiguration(
+ proj.getProject()).getWorkingCopy();
+ config.setAttribute(
+ LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
+ config.doSave();
+ doLaunch(config, "testExec"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
+ .getDefault().getView().getDynamicView();
+ assertEquals(2, view.getOutputs().length);
+ }
+
+ @Test
+ public void testFileNames() throws Exception {
+ ILaunchConfigurationWorkingCopy config = createConfiguration(
+ proj.getProject()).getWorkingCopy();
+ config.setAttribute(
+ LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
+ config.doSave();
+ doLaunch(config, "testExec"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
+ .getDefault().getView().getDynamicView();
+
+ int pidIx = 0;
+ CachegrindOutput output = view.getOutputs()[pidIx];
+ CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ if (file == null) {
+ pidIx = 1;
+ output = view.getOutputs()[pidIx];
+ file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ }
+ assertNotNull(file);
+ file = getFileByName(output, "cpptest.h"); //$NON-NLS-1$
+ assertNotNull(file);
+
+ // test other pid
+ pidIx = (pidIx + 1) % 2;
+ output = view.getOutputs()[pidIx];
+ file = getFileByName(output, "parent.cpp"); //$NON-NLS-1$
+ assertNotNull(file);
+ }
+
+ @Test
+ public void testNumFunctions() throws Exception {
+ ILaunchConfigurationWorkingCopy config = createConfiguration(
+ proj.getProject()).getWorkingCopy();
+ config.setAttribute(
+ LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
+ config.doSave();
+ doLaunch(config, "testExec"); //$NON-NLS-1$
+
+ CachegrindViewPart view = (CachegrindViewPart) ValgrindUIPlugin
+ .getDefault().getView().getDynamicView();
+
+ int pidIx = 0;
+ CachegrindOutput output = view.getOutputs()[pidIx];
+ CachegrindFile file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ if (file == null) {
+ pidIx = 1;
+ output = view.getOutputs()[pidIx];
+ file = getFileByName(output, "cpptest.cpp"); //$NON-NLS-1$
+ }
+ assertNotNull(file);
+ assertEquals(8, file.getFunctions().length);
+
+ // test other pid
+ pidIx = (pidIx + 1) % 2;
+ output = view.getOutputs()[pidIx];
+ file = getFileByName(output, "parent.cpp"); //$NON-NLS-1$
+ assertNotNull(file);
+ assertEquals(6, file.getFunctions().length);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ShortcutTest.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ShortcutTest.java
index 275eff355b..580602450d 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ShortcutTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ShortcutTest.java
@@ -31,67 +31,67 @@ import org.junit.Test;
public class ShortcutTest extends AbstractCachegrindTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
-
- @Test
- public void testShortcutSelection() throws Exception {
- ValgrindTestCachegrindLaunchShortcut shortcut = new ValgrindTestCachegrindLaunchShortcut();
-
- shortcut.launch(new StructuredSelection(proj.getProject()),
- ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration config = shortcut.getConfig();
-
- compareWithDefaults(config);
- }
-
- @Test
- public void testShortcutEditor() throws Exception {
- ValgrindTestCachegrindLaunchShortcut shortcut = new ValgrindTestCachegrindLaunchShortcut();
-
- IWorkbenchPage page = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- IFile file = proj.getProject().getFile("test.c"); //$NON-NLS-1$
- IEditorPart editor = IDE.openEditor(page, file);
-
- assertNotNull(editor);
-
- shortcut.launch(editor, ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration config = shortcut.getConfig();
-
- compareWithDefaults(config);
- }
-
- @Test
- public void testShortcutExistingConfig() throws Exception {
- ILaunchConfiguration prev = createConfiguration(proj.getProject());
-
- ValgrindTestCachegrindLaunchShortcut shortcut = new ValgrindTestCachegrindLaunchShortcut();
- shortcut.launch(new StructuredSelection(proj.getProject()),
- ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration current = shortcut.getConfig();
-
- assertEquals(prev, current);
- }
-
- private void compareWithDefaults(ILaunchConfiguration config)
- throws CoreException {
- // tests launch in foreground, this is not typical
- ILaunchConfiguration defaults = createConfiguration(proj.getProject());
- ILaunchConfigurationWorkingCopy wc = defaults.getWorkingCopy();
- wc.removeAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND);
- wc.doSave();
-
- // Compare launch config with defaults
- assertEquals(config.getAttributes(), defaults.getAttributes());
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ @Test
+ public void testShortcutSelection() throws Exception {
+ ValgrindTestCachegrindLaunchShortcut shortcut = new ValgrindTestCachegrindLaunchShortcut();
+
+ shortcut.launch(new StructuredSelection(proj.getProject()),
+ ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration config = shortcut.getConfig();
+
+ compareWithDefaults(config);
+ }
+
+ @Test
+ public void testShortcutEditor() throws Exception {
+ ValgrindTestCachegrindLaunchShortcut shortcut = new ValgrindTestCachegrindLaunchShortcut();
+
+ IWorkbenchPage page = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
+ IFile file = proj.getProject().getFile("test.c"); //$NON-NLS-1$
+ IEditorPart editor = IDE.openEditor(page, file);
+
+ assertNotNull(editor);
+
+ shortcut.launch(editor, ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration config = shortcut.getConfig();
+
+ compareWithDefaults(config);
+ }
+
+ @Test
+ public void testShortcutExistingConfig() throws Exception {
+ ILaunchConfiguration prev = createConfiguration(proj.getProject());
+
+ ValgrindTestCachegrindLaunchShortcut shortcut = new ValgrindTestCachegrindLaunchShortcut();
+ shortcut.launch(new StructuredSelection(proj.getProject()),
+ ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration current = shortcut.getConfig();
+
+ assertEquals(prev, current);
+ }
+
+ private void compareWithDefaults(ILaunchConfiguration config)
+ throws CoreException {
+ // tests launch in foreground, this is not typical
+ ILaunchConfiguration defaults = createConfiguration(proj.getProject());
+ ILaunchConfigurationWorkingCopy wc = defaults.getWorkingCopy();
+ wc.removeAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND);
+ wc.doSave();
+
+ // Compare launch config with defaults
+ assertEquals(config.getAttributes(), defaults.getAttributes());
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ValgrindTestCachegrindLaunchShortcut.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ValgrindTestCachegrindLaunchShortcut.java
index de0bd94a11..97abafcebc 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ValgrindTestCachegrindLaunchShortcut.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind.tests/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/tests/ValgrindTestCachegrindLaunchShortcut.java
@@ -17,14 +17,14 @@ import org.eclipse.linuxtools.internal.valgrind.cachegrind.CachegrindLaunchShort
public class ValgrindTestCachegrindLaunchShortcut extends CachegrindLaunchShortcut {
- private ILaunchConfiguration config;
+ private ILaunchConfiguration config;
- @Override
- public void launch(IBinary bin, String mode) {
- config = findLaunchConfiguration(bin, mode);
- }
-
- public ILaunchConfiguration getConfig() {
- return config;
- }
+ @Override
+ public void launch(IBinary bin, String mode) {
+ config = findLaunchConfiguration(bin, mode);
+ }
+
+ public ILaunchConfiguration getConfig() {
+ return config;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/plugin.xml b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/plugin.xml
index 208976b252..2b8d6059b2 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/plugin.xml
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/plugin.xml
@@ -30,6 +30,6 @@
tabgroup="org.eclipse.linuxtools.internal.valgrind.cachegrind.CachegrindLaunchConfigurationTabGroup"
type="timing">
</provider>
- </extension>
+ </extension>
</plugin>
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindCommandConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindCommandConstants.java
index 3c7b5656ee..3dda853822 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindCommandConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindCommandConstants.java
@@ -11,11 +11,11 @@
package org.eclipse.linuxtools.internal.valgrind.cachegrind;
public final class CachegrindCommandConstants {
- // Valgrind program arguments
- public static final String OPT_CACHEGRIND_OUTFILE = "--cachegrind-out-file"; //$NON-NLS-1$
- public static final String OPT_I1 = "--I1"; //$NON-NLS-1$
- public static final String OPT_D1 = "--D1"; //$NON-NLS-1$
- public static final String OPT_L2 = "--L2"; //$NON-NLS-1$
- public static final String OPT_CACHE_SIM = "--cache-sim"; //$NON-NLS-1$
- public static final String OPT_BRANCH_SIM = "--branch-sim"; //$NON-NLS-1$
+ // Valgrind program arguments
+ public static final String OPT_CACHEGRIND_OUTFILE = "--cachegrind-out-file"; //$NON-NLS-1$
+ public static final String OPT_I1 = "--I1"; //$NON-NLS-1$
+ public static final String OPT_D1 = "--D1"; //$NON-NLS-1$
+ public static final String OPT_L2 = "--L2"; //$NON-NLS-1$
+ public static final String OPT_CACHE_SIM = "--cache-sim"; //$NON-NLS-1$
+ public static final String OPT_BRANCH_SIM = "--branch-sim"; //$NON-NLS-1$
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLabelProvider.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLabelProvider.java
index 42a8fe603a..ae6122c5e6 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLabelProvider.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLabelProvider.java
@@ -32,81 +32,81 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
public class CachegrindLabelProvider extends CellLabelProvider {
- private static final String NAME_NOT_FOUND_SYMBOL = "???"; //$NON-NLS-1$
+ private static final String NAME_NOT_FOUND_SYMBOL = "???"; //$NON-NLS-1$
- protected CElementLabelProvider cLabelProvider = new CElementLabelProvider(CElementLabelProvider.SHOW_SMALL_ICONS | CElementLabelProvider.SHOW_PARAMETERS | CElementLabelProvider.SHOW_RETURN_TYPE) {
- @Override
- public int getTextFlags() {
- return super.getTextFlags() |CElementBaseLabels.M_FULLY_QUALIFIED;
- }
- };
+ protected CElementLabelProvider cLabelProvider = new CElementLabelProvider(CElementLabelProvider.SHOW_SMALL_ICONS | CElementLabelProvider.SHOW_PARAMETERS | CElementLabelProvider.SHOW_RETURN_TYPE) {
+ @Override
+ public int getTextFlags() {
+ return super.getTextFlags() |CElementBaseLabels.M_FULLY_QUALIFIED;
+ }
+ };
- protected DecimalFormat df = new DecimalFormat("#,##0"); //$NON-NLS-1$
+ protected DecimalFormat df = new DecimalFormat("#,##0"); //$NON-NLS-1$
- private static final Image FUNC_IMG = AbstractUIPlugin.imageDescriptorFromPlugin(CachegrindPlugin.PLUGIN_ID, "icons/function_obj.gif").createImage(); //$NON-NLS-1$
+ private static final Image FUNC_IMG = AbstractUIPlugin.imageDescriptorFromPlugin(CachegrindPlugin.PLUGIN_ID, "icons/function_obj.gif").createImage(); //$NON-NLS-1$
- @Override
- public void update(ViewerCell cell) {
- ICachegrindElement element = ((ICachegrindElement) cell.getElement());
- int index = cell.getColumnIndex();
+ @Override
+ public void update(ViewerCell cell) {
+ ICachegrindElement element = ((ICachegrindElement) cell.getElement());
+ int index = cell.getColumnIndex();
- if (index == 0) {
- if (element instanceof CachegrindFile) {
- // Try to use the CElementLabelProvider
- IAdaptable model = ((CachegrindFile) element).getModel();
- if (model != null) {
- cell.setText(cLabelProvider.getText(model));
- cell.setImage(cLabelProvider.getImage(model));
- } else { // Fall back
- String name = ((CachegrindFile) element).getName();
- cell.setText(name);
- cell.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE));
- }
- } else if (element instanceof CachegrindFunction) {
- // Try to use the CElementLabelProvider
- IAdaptable model = ((CachegrindFunction) element).getModel();
- if (model != null) {
- cell.setText(cLabelProvider.getText(model));
- cell.setImage(cLabelProvider.getImage(model));
- } else { // Fall back
- String name = ((CachegrindFunction) element).getName();
- cell.setText(name);
- cell.setImage(FUNC_IMG);
- }
- } else if (element instanceof CachegrindLine) {
- cell.setText(NLS.bind(Messages.getString("CachegrindViewPart.line"), ((CachegrindLine) element).getLine())); //$NON-NLS-1$
- cell.setImage(DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_INSTRUCTION_POINTER_TOP));
- } else if (element instanceof CachegrindOutput) {
- cell.setText(NLS.bind(Messages.getString("CachegrindViewPart.Total_PID"), ((CachegrindOutput) element).getPid())); //$NON-NLS-1$
- cell.setImage(DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_REGISTER));
- }
- } else if (element instanceof CachegrindFunction) {
- cell.setText(df.format(((CachegrindFunction) element).getTotals()[index - 1]));
- } else if (element instanceof CachegrindLine) {
- cell.setText(df.format(((CachegrindLine) element).getValues()[index - 1]));
- } else if (element instanceof CachegrindOutput) {
- cell.setText(df.format(((CachegrindOutput) element).getSummary()[index - 1]));
- }
- }
+ if (index == 0) {
+ if (element instanceof CachegrindFile) {
+ // Try to use the CElementLabelProvider
+ IAdaptable model = ((CachegrindFile) element).getModel();
+ if (model != null) {
+ cell.setText(cLabelProvider.getText(model));
+ cell.setImage(cLabelProvider.getImage(model));
+ } else { // Fall back
+ String name = ((CachegrindFile) element).getName();
+ cell.setText(name);
+ cell.setImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE));
+ }
+ } else if (element instanceof CachegrindFunction) {
+ // Try to use the CElementLabelProvider
+ IAdaptable model = ((CachegrindFunction) element).getModel();
+ if (model != null) {
+ cell.setText(cLabelProvider.getText(model));
+ cell.setImage(cLabelProvider.getImage(model));
+ } else { // Fall back
+ String name = ((CachegrindFunction) element).getName();
+ cell.setText(name);
+ cell.setImage(FUNC_IMG);
+ }
+ } else if (element instanceof CachegrindLine) {
+ cell.setText(NLS.bind(Messages.getString("CachegrindViewPart.line"), ((CachegrindLine) element).getLine())); //$NON-NLS-1$
+ cell.setImage(DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_INSTRUCTION_POINTER_TOP));
+ } else if (element instanceof CachegrindOutput) {
+ cell.setText(NLS.bind(Messages.getString("CachegrindViewPart.Total_PID"), ((CachegrindOutput) element).getPid())); //$NON-NLS-1$
+ cell.setImage(DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_REGISTER));
+ }
+ } else if (element instanceof CachegrindFunction) {
+ cell.setText(df.format(((CachegrindFunction) element).getTotals()[index - 1]));
+ } else if (element instanceof CachegrindLine) {
+ cell.setText(df.format(((CachegrindLine) element).getValues()[index - 1]));
+ } else if (element instanceof CachegrindOutput) {
+ cell.setText(df.format(((CachegrindOutput) element).getSummary()[index - 1]));
+ }
+ }
- public CElementLabelProvider getCLabelProvider() {
- return cLabelProvider;
- }
+ public CElementLabelProvider getCLabelProvider() {
+ return cLabelProvider;
+ }
- @Override
- public String getToolTipText(Object element) {
- String tooltip = null;
- if(element instanceof CachegrindFile){
- if(((CachegrindFile)element).getName().contains(NAME_NOT_FOUND_SYMBOL)){
- tooltip = Messages.getString("CachegrindViewPart.Tooltip_no_debug_info"); //$NON-NLS-1$
- }
- }
+ @Override
+ public String getToolTipText(Object element) {
+ String tooltip = null;
+ if(element instanceof CachegrindFile){
+ if(((CachegrindFile)element).getName().contains(NAME_NOT_FOUND_SYMBOL)){
+ tooltip = Messages.getString("CachegrindViewPart.Tooltip_no_debug_info"); //$NON-NLS-1$
+ }
+ }
- if(element instanceof CachegrindFunction){
- if(((CachegrindFunction)element).getName().contains(NAME_NOT_FOUND_SYMBOL)){
- tooltip = Messages.getString("CachegrindViewPart.Tooltip_no_debug_info"); //$NON-NLS-1$
- }
- }
- return tooltip;
- }
+ if(element instanceof CachegrindFunction){
+ if(((CachegrindFunction)element).getName().contains(NAME_NOT_FOUND_SYMBOL)){
+ tooltip = Messages.getString("CachegrindViewPart.Tooltip_no_debug_info"); //$NON-NLS-1$
+ }
+ }
+ return tooltip;
+ }
} \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchConfigurationTabGroup.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchConfigurationTabGroup.java
index 4eeb20c280..343236b818 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchConfigurationTabGroup.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchConfigurationTabGroup.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Red Hat Inc. - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.cachegrind;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
@@ -15,13 +15,13 @@ import org.eclipse.linuxtools.internal.valgrind.launch.ValgrindSingleToolOptions
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTabGroup;
public class CachegrindLaunchConfigurationTabGroup extends
- ProfileLaunchConfigurationTabGroup {
+ ProfileLaunchConfigurationTabGroup {
+
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ return new AbstractLaunchConfigurationTab[] {
+ new ValgrindSingleToolOptionsTab(CachegrindPlugin.TOOL_ID),
+ };
+ }
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- return new AbstractLaunchConfigurationTab[] {
- new ValgrindSingleToolOptionsTab(CachegrindPlugin.TOOL_ID),
- };
- }
-
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchConstants.java
index d7062754b8..78343f3c8c 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchConstants.java
@@ -11,34 +11,34 @@
package org.eclipse.linuxtools.internal.valgrind.cachegrind;
public final class CachegrindLaunchConstants {
- // LaunchConfiguration attributes
- public static final String ATTR_CACHEGRIND_CACHE_SIM = CachegrindPlugin.PLUGIN_ID + ".CACHE_SIM"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_BRANCH_SIM = CachegrindPlugin.PLUGIN_ID + ".BRANCH_SIM"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_I1 = CachegrindPlugin.PLUGIN_ID + ".I1"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_I1_SIZE = CachegrindPlugin.PLUGIN_ID + ".I1_SIZE"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_I1_ASSOC = CachegrindPlugin.PLUGIN_ID + ".I1_ASSOC"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_I1_LSIZE = CachegrindPlugin.PLUGIN_ID + ".I1_LSIZE"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_D1 = CachegrindPlugin.PLUGIN_ID + ".D1"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_D1_SIZE = CachegrindPlugin.PLUGIN_ID + ".D1_SIZE"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_D1_ASSOC = CachegrindPlugin.PLUGIN_ID + ".D1_ASSOC"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_D1_LSIZE = CachegrindPlugin.PLUGIN_ID + ".D1_LSIZE"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_L2 = CachegrindPlugin.PLUGIN_ID + ".L2"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_L2_SIZE = CachegrindPlugin.PLUGIN_ID + ".L2_SIZE"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_L2_ASSOC = CachegrindPlugin.PLUGIN_ID + ".L2_ASSOC"; //$NON-NLS-1$
- public static final String ATTR_CACHEGRIND_L2_LSIZE = CachegrindPlugin.PLUGIN_ID + ".L2_LSIZE"; //$NON-NLS-1$
-
- public static final boolean DEFAULT_CACHEGRIND_CACHE_SIM = true;
- public static final boolean DEFAULT_CACHEGRIND_BRANCH_SIM = false;
- public static final boolean DEFAULT_CACHEGRIND_I1 = false;
- public static final int DEFAULT_CACHEGRIND_I1_SIZE = 0;
- public static final int DEFAULT_CACHEGRIND_I1_ASSOC = 0;
- public static final int DEFAULT_CACHEGRIND_I1_LSIZE = 0;
- public static final boolean DEFAULT_CACHEGRIND_D1 = false;
- public static final int DEFAULT_CACHEGRIND_D1_SIZE = 0;
- public static final int DEFAULT_CACHEGRIND_D1_ASSOC = 0;
- public static final int DEFAULT_CACHEGRIND_D1_LSIZE = 0;
- public static final boolean DEFAULT_CACHEGRIND_L2 = false;
- public static final int DEFAULT_CACHEGRIND_L2_SIZE = 0;
- public static final int DEFAULT_CACHEGRIND_L2_ASSOC = 0;
- public static final int DEFAULT_CACHEGRIND_L2_LSIZE = 0;
+ // LaunchConfiguration attributes
+ public static final String ATTR_CACHEGRIND_CACHE_SIM = CachegrindPlugin.PLUGIN_ID + ".CACHE_SIM"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_BRANCH_SIM = CachegrindPlugin.PLUGIN_ID + ".BRANCH_SIM"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_I1 = CachegrindPlugin.PLUGIN_ID + ".I1"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_I1_SIZE = CachegrindPlugin.PLUGIN_ID + ".I1_SIZE"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_I1_ASSOC = CachegrindPlugin.PLUGIN_ID + ".I1_ASSOC"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_I1_LSIZE = CachegrindPlugin.PLUGIN_ID + ".I1_LSIZE"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_D1 = CachegrindPlugin.PLUGIN_ID + ".D1"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_D1_SIZE = CachegrindPlugin.PLUGIN_ID + ".D1_SIZE"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_D1_ASSOC = CachegrindPlugin.PLUGIN_ID + ".D1_ASSOC"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_D1_LSIZE = CachegrindPlugin.PLUGIN_ID + ".D1_LSIZE"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_L2 = CachegrindPlugin.PLUGIN_ID + ".L2"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_L2_SIZE = CachegrindPlugin.PLUGIN_ID + ".L2_SIZE"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_L2_ASSOC = CachegrindPlugin.PLUGIN_ID + ".L2_ASSOC"; //$NON-NLS-1$
+ public static final String ATTR_CACHEGRIND_L2_LSIZE = CachegrindPlugin.PLUGIN_ID + ".L2_LSIZE"; //$NON-NLS-1$
+
+ public static final boolean DEFAULT_CACHEGRIND_CACHE_SIM = true;
+ public static final boolean DEFAULT_CACHEGRIND_BRANCH_SIM = false;
+ public static final boolean DEFAULT_CACHEGRIND_I1 = false;
+ public static final int DEFAULT_CACHEGRIND_I1_SIZE = 0;
+ public static final int DEFAULT_CACHEGRIND_I1_ASSOC = 0;
+ public static final int DEFAULT_CACHEGRIND_I1_LSIZE = 0;
+ public static final boolean DEFAULT_CACHEGRIND_D1 = false;
+ public static final int DEFAULT_CACHEGRIND_D1_SIZE = 0;
+ public static final int DEFAULT_CACHEGRIND_D1_ASSOC = 0;
+ public static final int DEFAULT_CACHEGRIND_D1_LSIZE = 0;
+ public static final boolean DEFAULT_CACHEGRIND_L2 = false;
+ public static final int DEFAULT_CACHEGRIND_L2_SIZE = 0;
+ public static final int DEFAULT_CACHEGRIND_L2_ASSOC = 0;
+ public static final int DEFAULT_CACHEGRIND_L2_LSIZE = 0;
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchDelegate.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchDelegate.java
index b490c1b725..227b220901 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchDelegate.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchDelegate.java
@@ -30,105 +30,105 @@ import org.eclipse.linuxtools.valgrind.ui.IValgrindToolView;
import org.osgi.framework.Version;
public class CachegrindLaunchDelegate implements IValgrindLaunchDelegate {
- protected static final String OUT_PREFIX = "cachegrind_"; //$NON-NLS-1$
- protected static final String OUT_FILE = OUT_PREFIX + "%p.txt"; //$NON-NLS-1$
- protected static final FileFilter CACHEGRIND_FILTER = new FileFilter() {
- @Override
- public boolean accept(File pathname) {
- return pathname.getName().startsWith(OUT_PREFIX);
- }
- };
-
- private static final String COMMA = ","; //$NON-NLS-1$
- private static final String EQUALS = "="; //$NON-NLS-1$
- private static final String NO = "no"; //$NON-NLS-1$
- private static final String YES = "yes"; //$NON-NLS-1$
- private CachegrindOutput[] outputs;
-
- @Override
- public void handleLaunch(ILaunchConfiguration config, ILaunch launch, IPath logDir, IProgressMonitor monitor) throws CoreException {
- try {
- monitor.beginTask(Messages.getString("CachegrindLaunchDelegate.Parsing_Cachegrind_Output"), 3); //$NON-NLS-1$
-
- File[] cachegrindOutputs = logDir.toFile().listFiles(CACHEGRIND_FILTER);
-
- if (cachegrindOutputs.length > 0) {
- parseOutput(cachegrindOutputs, monitor);
- }
- } catch (IOException e) {
- e.printStackTrace();
- abort(Messages.getString("CachegrindLaunchDelegate.Error_parsing_output"), e, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); //$NON-NLS-1$
- } finally {
- monitor.done();
- }
- }
+ protected static final String OUT_PREFIX = "cachegrind_"; //$NON-NLS-1$
+ protected static final String OUT_FILE = OUT_PREFIX + "%p.txt"; //$NON-NLS-1$
+ protected static final FileFilter CACHEGRIND_FILTER = new FileFilter() {
+ @Override
+ public boolean accept(File pathname) {
+ return pathname.getName().startsWith(OUT_PREFIX);
+ }
+ };
- private void parseOutput(File[] cachegrindOutputs, IProgressMonitor monitor) throws IOException {
- outputs = new CachegrindOutput[cachegrindOutputs.length];
-
- for (int i = 0; i < cachegrindOutputs.length; i++) {
- outputs[i] = new CachegrindOutput();
- CachegrindParser.getParser().parse(outputs[i], cachegrindOutputs[i]);
- }
- monitor.worked(2);
- }
-
- @Override
- public String[] getCommandArray(ILaunchConfiguration config, Version ver, IPath logDir) throws CoreException {
- ArrayList<String> opts = new ArrayList<>();
-
- opts.add(CachegrindCommandConstants.OPT_CACHEGRIND_OUTFILE + EQUALS + logDir.append(OUT_FILE).toOSString());
- opts.add(CachegrindCommandConstants.OPT_CACHE_SIM + EQUALS + (config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_CACHE_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_CACHE_SIM) ? YES : NO));
- opts.add(CachegrindCommandConstants.OPT_BRANCH_SIM + EQUALS + (config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_BRANCH_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_BRANCH_SIM) ? YES : NO));
- if (config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1)) {
- opts.add(CachegrindCommandConstants.OPT_I1 + EQUALS + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_SIZE)
- + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_ASSOC)
- + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_LSIZE));
- }
- if (config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1)) {
- opts.add(CachegrindCommandConstants.OPT_D1 + EQUALS + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_SIZE)
- + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_ASSOC)
- + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_LSIZE));
- }
- if (config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2)) {
- opts.add(CachegrindCommandConstants.OPT_L2 + EQUALS + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_SIZE)
- + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_ASSOC)
- + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_LSIZE));
- }
- return opts.toArray(new String[opts.size()]);
- }
-
- @Override
- public void initializeView(IValgrindToolView view, String contentDescription, IProgressMonitor monitor)
- throws CoreException {
- if (outputs != null && view instanceof CachegrindViewPart) {
- ((CachegrindViewPart) view).setOutputs(outputs);
- }
- monitor.worked(1);
- }
+ private static final String COMMA = ","; //$NON-NLS-1$
+ private static final String EQUALS = "="; //$NON-NLS-1$
+ private static final String NO = "no"; //$NON-NLS-1$
+ private static final String YES = "yes"; //$NON-NLS-1$
+ private CachegrindOutput[] outputs;
- /**
- * Throws a core exception with an error status object built from the given
- * message, lower level exception, and error code.
- *
- * @param message
- * the status message
- * @param exception
- * lower level exception associated with the error, or
- * <code>null</code> if none
- * @param code
- * error code
- */
- private void abort(String message, Throwable exception, int code) throws CoreException {
- IStatus status;
- if (exception != null) {
- MultiStatus multiStatus = new MultiStatus(CachegrindPlugin.PLUGIN_ID, code, message, exception);
- multiStatus.add(new Status(IStatus.ERROR, CachegrindPlugin.PLUGIN_ID, code, exception.getLocalizedMessage(), exception));
- status= multiStatus;
- } else {
- status= new Status(IStatus.ERROR, CachegrindPlugin.PLUGIN_ID, code, message, null);
- }
- throw new CoreException(status);
- }
+ @Override
+ public void handleLaunch(ILaunchConfiguration config, ILaunch launch, IPath logDir, IProgressMonitor monitor) throws CoreException {
+ try {
+ monitor.beginTask(Messages.getString("CachegrindLaunchDelegate.Parsing_Cachegrind_Output"), 3); //$NON-NLS-1$
+
+ File[] cachegrindOutputs = logDir.toFile().listFiles(CACHEGRIND_FILTER);
+
+ if (cachegrindOutputs.length > 0) {
+ parseOutput(cachegrindOutputs, monitor);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ abort(Messages.getString("CachegrindLaunchDelegate.Error_parsing_output"), e, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); //$NON-NLS-1$
+ } finally {
+ monitor.done();
+ }
+ }
+
+ private void parseOutput(File[] cachegrindOutputs, IProgressMonitor monitor) throws IOException {
+ outputs = new CachegrindOutput[cachegrindOutputs.length];
+
+ for (int i = 0; i < cachegrindOutputs.length; i++) {
+ outputs[i] = new CachegrindOutput();
+ CachegrindParser.getParser().parse(outputs[i], cachegrindOutputs[i]);
+ }
+ monitor.worked(2);
+ }
+
+ @Override
+ public String[] getCommandArray(ILaunchConfiguration config, Version ver, IPath logDir) throws CoreException {
+ ArrayList<String> opts = new ArrayList<>();
+
+ opts.add(CachegrindCommandConstants.OPT_CACHEGRIND_OUTFILE + EQUALS + logDir.append(OUT_FILE).toOSString());
+ opts.add(CachegrindCommandConstants.OPT_CACHE_SIM + EQUALS + (config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_CACHE_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_CACHE_SIM) ? YES : NO));
+ opts.add(CachegrindCommandConstants.OPT_BRANCH_SIM + EQUALS + (config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_BRANCH_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_BRANCH_SIM) ? YES : NO));
+ if (config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1)) {
+ opts.add(CachegrindCommandConstants.OPT_I1 + EQUALS + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_SIZE)
+ + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_ASSOC)
+ + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_LSIZE));
+ }
+ if (config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1)) {
+ opts.add(CachegrindCommandConstants.OPT_D1 + EQUALS + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_SIZE)
+ + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_ASSOC)
+ + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_LSIZE));
+ }
+ if (config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2)) {
+ opts.add(CachegrindCommandConstants.OPT_L2 + EQUALS + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_SIZE)
+ + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_ASSOC)
+ + COMMA + config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_LSIZE));
+ }
+ return opts.toArray(new String[opts.size()]);
+ }
+
+ @Override
+ public void initializeView(IValgrindToolView view, String contentDescription, IProgressMonitor monitor)
+ throws CoreException {
+ if (outputs != null && view instanceof CachegrindViewPart) {
+ ((CachegrindViewPart) view).setOutputs(outputs);
+ }
+ monitor.worked(1);
+ }
+
+ /**
+ * Throws a core exception with an error status object built from the given
+ * message, lower level exception, and error code.
+ *
+ * @param message
+ * the status message
+ * @param exception
+ * lower level exception associated with the error, or
+ * <code>null</code> if none
+ * @param code
+ * error code
+ */
+ private void abort(String message, Throwable exception, int code) throws CoreException {
+ IStatus status;
+ if (exception != null) {
+ MultiStatus multiStatus = new MultiStatus(CachegrindPlugin.PLUGIN_ID, code, message, exception);
+ multiStatus.add(new Status(IStatus.ERROR, CachegrindPlugin.PLUGIN_ID, code, exception.getLocalizedMessage(), exception));
+ status= multiStatus;
+ } else {
+ status= new Status(IStatus.ERROR, CachegrindPlugin.PLUGIN_ID, code, message, null);
+ }
+ throw new CoreException(status);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchShortcut.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchShortcut.java
index 470e0df677..1f6fcab837 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchShortcut.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindLaunchShortcut.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Red Hat Inc - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.cachegrind;
import org.eclipse.core.runtime.CoreException;
@@ -21,22 +21,22 @@ import org.eclipse.linuxtools.profiling.launch.ProfileLaunchShortcut;
public class CachegrindLaunchShortcut extends ProfileLaunchShortcut {
- @Override
- protected void setDefaultProfileAttributes(
- ILaunchConfigurationWorkingCopy wc) throws CoreException {
- ValgrindOptionsTab tab = new ValgrindOptionsTab();
- tab.setDefaults(wc);
- ILaunchConfigurationTab defaultTab = ValgrindLaunchPlugin.getDefault().getToolPage(CachegrindPlugin.TOOL_ID);
- defaultTab.setDefaults(wc);
- }
+ @Override
+ protected void setDefaultProfileAttributes(
+ ILaunchConfigurationWorkingCopy wc) throws CoreException {
+ ValgrindOptionsTab tab = new ValgrindOptionsTab();
+ tab.setDefaults(wc);
+ ILaunchConfigurationTab defaultTab = ValgrindLaunchPlugin.getDefault().getToolPage(CachegrindPlugin.TOOL_ID);
+ defaultTab.setDefaults(wc);
+ }
- /**
- * Method getValgrindLaunchConfigType.
- * @return ILaunchConfigurationType
- */
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(ValgrindLaunchPlugin.LAUNCH_ID);
- }
+ /**
+ * Method getValgrindLaunchConfigType.
+ * @return ILaunchConfigurationType
+ */
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(ValgrindLaunchPlugin.LAUNCH_ID);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindParser.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindParser.java
index a7a579d99c..25721da973 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindParser.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindParser.java
@@ -23,104 +23,104 @@ import org.eclipse.linuxtools.internal.valgrind.cachegrind.model.CachegrindOutpu
import org.eclipse.linuxtools.valgrind.core.ValgrindParserUtils;
public final class CachegrindParser {
- private static final String COLON = ":"; //$NON-NLS-1$
- private static final String SPACE = " "; //$NON-NLS-1$
- private static final String EQUALS = "="; //$NON-NLS-1$
+ private static final String COLON = ":"; //$NON-NLS-1$
+ private static final String SPACE = " "; //$NON-NLS-1$
+ private static final String EQUALS = "="; //$NON-NLS-1$
- private static final String CMD = "cmd"; //$NON-NLS-1$
- private static final String DESC = "desc"; //$NON-NLS-1$
- private static final String FL = "fl"; //$NON-NLS-1$
- private static final String FN = "fn"; //$NON-NLS-1$
- private static final String EVENTS = "events"; //$NON-NLS-1$
- private static final String SUMMARY = "summary"; //$NON-NLS-1$
+ private static final String CMD = "cmd"; //$NON-NLS-1$
+ private static final String DESC = "desc"; //$NON-NLS-1$
+ private static final String FL = "fl"; //$NON-NLS-1$
+ private static final String FN = "fn"; //$NON-NLS-1$
+ private static final String EVENTS = "events"; //$NON-NLS-1$
+ private static final String SUMMARY = "summary"; //$NON-NLS-1$
- private static final String COMMA = ","; //$NON-NLS-1$
+ private static final String COMMA = ","; //$NON-NLS-1$
- protected static CachegrindParser instance;
+ protected static CachegrindParser instance;
- private CachegrindParser() {
- }
+ private CachegrindParser() {
+ }
- public static CachegrindParser getParser() {
- if (instance == null) {
- instance = new CachegrindParser();
- }
- return instance;
- }
+ public static CachegrindParser getParser() {
+ if (instance == null) {
+ instance = new CachegrindParser();
+ }
+ return instance;
+ }
- public void parse(CachegrindOutput output, File cgOut) throws IOException {
- try (BufferedReader br = new BufferedReader(new FileReader(cgOut))) {
- output.setPid(ValgrindParserUtils.parsePID(cgOut.getName(), CachegrindLaunchDelegate.OUT_PREFIX));
+ public void parse(CachegrindOutput output, File cgOut) throws IOException {
+ try (BufferedReader br = new BufferedReader(new FileReader(cgOut))) {
+ output.setPid(ValgrindParserUtils.parsePID(cgOut.getName(), CachegrindLaunchDelegate.OUT_PREFIX));
- String line;
- CachegrindFile curFl = null;
- CachegrindFunction curFn = null;
- while ((line = br.readLine()) != null) {
- if (line.startsWith(EVENTS + COLON)) {
- output.setEvents(ValgrindParserUtils.parseStrValue(line, COLON + SPACE).split(SPACE));
- } else if (line.startsWith(CMD + COLON)) {
- //continue
- } else if (line.startsWith(DESC + COLON)) {
- CachegrindDescription description = parseDescription(line);
- output.addDescription(description);
- } else if (line.startsWith(FL + EQUALS)) {
- curFl = new CachegrindFile(output, ValgrindParserUtils.parseStrValue(line, EQUALS));
- output.addFile(curFl);
- } else if (line.startsWith(FN + EQUALS)) {
- if (curFl != null) {
- curFn = new CachegrindFunction(curFl, ValgrindParserUtils.parseStrValue(line, EQUALS));
- curFl.addFunction(curFn);
- } else {
- ValgrindParserUtils.fail(line);
- }
- } else if (line.startsWith(SUMMARY + COLON)) {
- long[] summary = parseData(line, ValgrindParserUtils.parseStrValue(line, COLON + SPACE).split(SPACE));
- output.setSummary(summary);
- }
- else { // line data
- String[] tokens = line.split(SPACE, 2);
- if (ValgrindParserUtils.isNumber(tokens[0])) {
- int lineNo = Integer.parseInt(tokens[0]);
+ String line;
+ CachegrindFile curFl = null;
+ CachegrindFunction curFn = null;
+ while ((line = br.readLine()) != null) {
+ if (line.startsWith(EVENTS + COLON)) {
+ output.setEvents(ValgrindParserUtils.parseStrValue(line, COLON + SPACE).split(SPACE));
+ } else if (line.startsWith(CMD + COLON)) {
+ //continue
+ } else if (line.startsWith(DESC + COLON)) {
+ CachegrindDescription description = parseDescription(line);
+ output.addDescription(description);
+ } else if (line.startsWith(FL + EQUALS)) {
+ curFl = new CachegrindFile(output, ValgrindParserUtils.parseStrValue(line, EQUALS));
+ output.addFile(curFl);
+ } else if (line.startsWith(FN + EQUALS)) {
+ if (curFl != null) {
+ curFn = new CachegrindFunction(curFl, ValgrindParserUtils.parseStrValue(line, EQUALS));
+ curFl.addFunction(curFn);
+ } else {
+ ValgrindParserUtils.fail(line);
+ }
+ } else if (line.startsWith(SUMMARY + COLON)) {
+ long[] summary = parseData(line, ValgrindParserUtils.parseStrValue(line, COLON + SPACE).split(SPACE));
+ output.setSummary(summary);
+ }
+ else { // line data
+ String[] tokens = line.split(SPACE, 2);
+ if (ValgrindParserUtils.isNumber(tokens[0])) {
+ int lineNo = Integer.parseInt(tokens[0]);
- long[] data = parseData(line, tokens[1].split(SPACE));
- if (curFn != null) {
- curFn.addLine(new CachegrindLine(curFn, lineNo, data));
- } else {
- ValgrindParserUtils.fail(line);
- }
- } else {
- ValgrindParserUtils.fail(line);
- }
- }
- }
- }
- }
+ long[] data = parseData(line, tokens[1].split(SPACE));
+ if (curFn != null) {
+ curFn.addLine(new CachegrindLine(curFn, lineNo, data));
+ } else {
+ ValgrindParserUtils.fail(line);
+ }
+ } else {
+ ValgrindParserUtils.fail(line);
+ }
+ }
+ }
+ }
+ }
- private long[] parseData(String line, String[] data) throws IOException {
- long[] result = new long[data.length];
- for (int i = 0; i < data.length; i++) {
- if (!ValgrindParserUtils.isNumber(data[i])) {
- ValgrindParserUtils.fail(line);
- }
- result[i] = Long.parseLong(data[i]);
- }
- return result;
- }
+ private long[] parseData(String line, String[] data) throws IOException {
+ long[] result = new long[data.length];
+ for (int i = 0; i < data.length; i++) {
+ if (!ValgrindParserUtils.isNumber(data[i])) {
+ ValgrindParserUtils.fail(line);
+ }
+ result[i] = Long.parseLong(data[i]);
+ }
+ return result;
+ }
- private CachegrindDescription parseDescription(String line) throws IOException {
- CachegrindDescription desc = null;
- String[] tokens = line.split(COLON + "\\s+"); //$NON-NLS-1$
- if (tokens.length == 3) {
- String name = tokens[1];
- tokens = tokens[2].split(COMMA + SPACE);
- if (tokens.length == 3) {
- desc = new CachegrindDescription(name);
- } else {
- ValgrindParserUtils.fail(line);
- }
- } else {
- ValgrindParserUtils.fail(line);
- }
- return desc;
- }
+ private CachegrindDescription parseDescription(String line) throws IOException {
+ CachegrindDescription desc = null;
+ String[] tokens = line.split(COLON + "\\s+"); //$NON-NLS-1$
+ if (tokens.length == 3) {
+ String name = tokens[1];
+ tokens = tokens[2].split(COMMA + SPACE);
+ if (tokens.length == 3) {
+ desc = new CachegrindDescription(name);
+ } else {
+ ValgrindParserUtils.fail(line);
+ }
+ } else {
+ ValgrindParserUtils.fail(line);
+ }
+ return desc;
+ }
} \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindPlugin.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindPlugin.java
index d09523760b..19b32ee5e8 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindPlugin.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindPlugin.java
@@ -15,8 +15,8 @@ package org.eclipse.linuxtools.internal.valgrind.cachegrind;
*/
public class CachegrindPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.cachegrind"; //$NON-NLS-1$
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.cachegrind"; //$NON-NLS-1$
- public static final String TOOL_ID = "org.eclipse.linuxtools.valgrind.launch.cachegrind"; //$NON-NLS-1$
+ public static final String TOOL_ID = "org.eclipse.linuxtools.valgrind.launch.cachegrind"; //$NON-NLS-1$
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindToolPage.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindToolPage.java
index 416a9278f1..39b9865068 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindToolPage.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindToolPage.java
@@ -32,354 +32,354 @@ import org.eclipse.swt.widgets.Spinner;
import org.osgi.framework.Version;
public class CachegrindToolPage extends AbstractLaunchConfigurationTab
- implements IValgrindToolPage {
- // Cachegrind controls
- private Button cacheButton;
- private Button branchButton;
- private Spinner i1SizeSpinner;
- private Spinner i1AssocSpinner;
- private Spinner i1LineSizeSpinner;
- private Button i1Button;
- private Spinner d1SizeSpinner;
- private Spinner d1AssocSpinner;
- private Spinner d1LineSizeSpinner;
- private Button d1Button;
- private Spinner l2SizeSpinner;
- private Spinner l2AssocSpinner;
- private Spinner l2LineSizeSpinner;
- private Button l2Button;
-
- private boolean isInitializing = false;
- private SelectionListener selectListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
- private ModifyListener modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
-
- @Override
- public void createControl(Composite parent) {
- Composite top = new Composite(parent, SWT.NONE);
- top.setLayout(new GridLayout());
- top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- // Event options
- cacheButton = new Button(top, SWT.CHECK);
- cacheButton.setText(Messages.getString("CachegrindToolPage.Profile_Cache")); //$NON-NLS-1$
- cacheButton.addSelectionListener(selectListener);
-
- branchButton = new Button(top, SWT.CHECK);
- branchButton.setText(Messages.getString("CachegrindToolPage.Profile_Branch")); //$NON-NLS-1$
- branchButton.addSelectionListener(selectListener);
-
- createVerticalSpacer(top, 1);
-
- Group cacheGroup = new Group(top, SWT.SHADOW_OUT);
- cacheGroup.setLayout(new GridLayout(2, false));
- cacheGroup.setText(Messages.getString("CachegrindToolPage.Manually_Set_Cache")); //$NON-NLS-1$
-
- // I1 Cache
- i1Button = new Button(cacheGroup, SWT.CHECK);
- i1Button.setText(Messages.getString("CachegrindToolPage.I1_Cache")); //$NON-NLS-1$
- i1Button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- checkI1Enablement();
- updateLaunchConfigurationDialog();
- }
- });
-
- Composite i1Top = new Composite(cacheGroup, SWT.BORDER);
- GridLayout i1Layout = new GridLayout(6, false);
- i1Layout.horizontalSpacing = 10;
- i1Top.setLayout(i1Layout);
-
- Label i1SizeLabel = new Label(i1Top, SWT.NONE);
- i1SizeLabel.setText(Messages.getString("CachegrindToolPage.Size")); //$NON-NLS-1$
-
- i1SizeSpinner = new Spinner(i1Top, SWT.BORDER);
- i1SizeSpinner.setMaximum(Integer.MAX_VALUE);
- i1SizeSpinner.addModifyListener(modifyListener);
-
- Label i1AssocLabel = new Label(i1Top, SWT.NONE);
- i1AssocLabel.setText(Messages.getString("CachegrindToolPage.Assoc")); //$NON-NLS-1$
-
- i1AssocSpinner = new Spinner(i1Top, SWT.BORDER);
- i1AssocSpinner.setMaximum(Integer.MAX_VALUE);
- i1AssocSpinner.addModifyListener(modifyListener);
-
- Label i1LineSizeLabel = new Label(i1Top, SWT.NONE);
- i1LineSizeLabel.setText(Messages.getString("CachegrindToolPage.Line_Size")); //$NON-NLS-1$
-
- i1LineSizeSpinner = new Spinner(i1Top, SWT.BORDER);
- i1LineSizeSpinner.setMaximum(Integer.MAX_VALUE);
- i1LineSizeSpinner.addModifyListener(modifyListener);
-
- // D1 Cache
- d1Button = new Button(cacheGroup, SWT.CHECK);
- d1Button.setText(Messages.getString("CachegrindToolPage.D1_Cache")); //$NON-NLS-1$
- d1Button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- checkD1Enablement();
- updateLaunchConfigurationDialog();
- }
- });
-
- Composite d1Top = new Composite(cacheGroup, SWT.BORDER);
- GridLayout d1Layout = new GridLayout(6, false);
- d1Layout.horizontalSpacing = 10;
- d1Top.setLayout(d1Layout);
-
- Label d1SizeLabel = new Label(d1Top, SWT.NONE);
- d1SizeLabel.setText(Messages.getString("CachegrindToolPage.Size")); //$NON-NLS-1$
-
- d1SizeSpinner = new Spinner(d1Top, SWT.BORDER);
- d1SizeSpinner.setMaximum(Integer.MAX_VALUE);
- d1SizeSpinner.addModifyListener(modifyListener);
-
- Label d1AssocLabel = new Label(d1Top, SWT.NONE);
- d1AssocLabel.setText(Messages.getString("CachegrindToolPage.Assoc")); //$NON-NLS-1$
-
- d1AssocSpinner = new Spinner(d1Top, SWT.BORDER);
- d1AssocSpinner.setMaximum(Integer.MAX_VALUE);
- d1AssocSpinner.addModifyListener(modifyListener);
-
- Label d1LineSizeLabel = new Label(d1Top, SWT.NONE);
- d1LineSizeLabel.setText(Messages.getString("CachegrindToolPage.Line_Size")); //$NON-NLS-1$
-
- d1LineSizeSpinner = new Spinner(d1Top, SWT.BORDER);
- d1LineSizeSpinner.setMaximum(Integer.MAX_VALUE);
- d1LineSizeSpinner.addModifyListener(modifyListener);
-
- // D1 Cache
- l2Button = new Button(cacheGroup, SWT.CHECK);
- l2Button.setText(Messages.getString("CachegrindToolPage.L2_Cache")); //$NON-NLS-1$
- l2Button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- checkL2Enablement();
- updateLaunchConfigurationDialog();
- }
- });
-
- Composite l2Top = new Composite(cacheGroup, SWT.BORDER);
- GridLayout l2Layout = new GridLayout(6, false);
- l2Layout.horizontalSpacing = 10;
- l2Top.setLayout(l2Layout);
-
- Label l2SizeLabel = new Label(l2Top, SWT.NONE);
- l2SizeLabel.setText(Messages.getString("CachegrindToolPage.Size")); //$NON-NLS-1$
-
- l2SizeSpinner = new Spinner(l2Top, SWT.BORDER);
- l2SizeSpinner.setMaximum(Integer.MAX_VALUE);
- l2SizeSpinner.addModifyListener(modifyListener);
-
- Label l2AssocLabel = new Label(l2Top, SWT.NONE);
- l2AssocLabel.setText(Messages.getString("CachegrindToolPage.Assoc")); //$NON-NLS-1$
-
- l2AssocSpinner = new Spinner(l2Top, SWT.BORDER);
- l2AssocSpinner.setMaximum(Integer.MAX_VALUE);
- l2AssocSpinner.addModifyListener(modifyListener);
-
- Label l2LineSizeLabel = new Label(l2Top, SWT.NONE);
- l2LineSizeLabel.setText(Messages.getString("CachegrindToolPage.Line_Size")); //$NON-NLS-1$
-
- l2LineSizeSpinner = new Spinner(l2Top, SWT.BORDER);
- l2LineSizeSpinner.setMaximum(Integer.MAX_VALUE);
- l2LineSizeSpinner.addModifyListener(modifyListener);
- }
-
- @Override
- public String getName() {
- return Messages.getString("CachegrindToolPage.Cachegrind_Options"); //$NON-NLS-1$
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration config) {
- isInitializing = true;
-
- try
- {
- cacheButton.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_CACHE_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_CACHE_SIM));
- branchButton.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_BRANCH_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_BRANCH_SIM));
-
- i1Button.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1));
- i1SizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_SIZE));
- i1AssocSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_ASSOC));
- i1LineSizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_LSIZE));
- checkI1Enablement();
-
- d1Button.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1));
- d1SizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_SIZE));
- d1AssocSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_ASSOC));
- d1LineSizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_LSIZE));
- checkD1Enablement();
-
- l2Button.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2));
- l2SizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_SIZE));
- l2AssocSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_ASSOC));
- l2LineSizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_LSIZE));
- checkL2Enablement();
-
- } catch (CoreException e) {
- e.printStackTrace();
- }
- isInitializing = false;
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy config) {
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_CACHE_SIM, cacheButton.getSelection());
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_BRANCH_SIM, branchButton.getSelection());
-
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1, i1Button.getSelection());
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_SIZE, i1SizeSpinner.getSelection());
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_ASSOC, i1AssocSpinner.getSelection());
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_LSIZE, i1LineSizeSpinner.getSelection());
-
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1, d1Button.getSelection());
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_SIZE, d1SizeSpinner.getSelection());
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_ASSOC, d1AssocSpinner.getSelection());
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_LSIZE, d1LineSizeSpinner.getSelection());
-
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2, l2Button.getSelection());
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_SIZE, l2SizeSpinner.getSelection());
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_ASSOC, l2AssocSpinner.getSelection());
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_LSIZE, l2LineSizeSpinner.getSelection());
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy config) {
- config.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, CachegrindPlugin.TOOL_ID);
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_CACHE_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_CACHE_SIM);
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_BRANCH_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_BRANCH_SIM);
-
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1);
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_SIZE);
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_ASSOC);
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_LSIZE);
-
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1);
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_SIZE);
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_ASSOC);
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_LSIZE);
-
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2);
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_SIZE);
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_ASSOC);
- config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_LSIZE);
- }
-
- @Override
- public boolean isValid(ILaunchConfiguration launchConfig) {
- setErrorMessage(null);
-
- boolean result = false;
- try {
- result = launchConfig.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_CACHE_SIM, true)
- || launchConfig.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_BRANCH_SIM, false);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- if (!result) {
- setErrorMessage(Messages.getString("CachegrindToolPage.At_least_one_of")); //$NON-NLS-1$
- }
- return result;
- }
-
- @Override
- public void setValgrindVersion(Version ver) {
- // Not used
- }
-
- @Override
- protected void updateLaunchConfigurationDialog() {
- if (!isInitializing) {
- super.updateLaunchConfigurationDialog();
- }
- }
-
- private void checkI1Enablement() {
- boolean checked = i1Button.getSelection();
- i1SizeSpinner.setEnabled(checked);
- i1AssocSpinner.setEnabled(checked);
- i1LineSizeSpinner.setEnabled(checked);
- }
-
- private void checkD1Enablement() {
- boolean checked = d1Button.getSelection();
- d1SizeSpinner.setEnabled(checked);
- d1AssocSpinner.setEnabled(checked);
- d1LineSizeSpinner.setEnabled(checked);
- }
-
- private void checkL2Enablement() {
- boolean checked = l2Button.getSelection();
- l2SizeSpinner.setEnabled(checked);
- l2AssocSpinner.setEnabled(checked);
- l2LineSizeSpinner.setEnabled(checked);
- }
-
- public Button getCacheButton() {
- return cacheButton;
- }
-
- public Button getBranchButton() {
- return branchButton;
- }
-
- public Spinner getI1SizeSpinner() {
- return i1SizeSpinner;
- }
-
- public Spinner getI1AssocSpinner() {
- return i1AssocSpinner;
- }
-
- public Spinner getI1LineSizeSpinner() {
- return i1LineSizeSpinner;
- }
-
- public Button getI1Button() {
- return i1Button;
- }
-
- public Spinner getD1SizeSpinner() {
- return d1SizeSpinner;
- }
-
- public Spinner getD1AssocSpinner() {
- return d1AssocSpinner;
- }
-
- public Spinner getD1LineSizeSpinner() {
- return d1LineSizeSpinner;
- }
-
- public Button getD1Button() {
- return d1Button;
- }
-
- public Spinner getL2SizeSpinner() {
- return l2SizeSpinner;
- }
-
- public Spinner getL2AssocSpinner() {
- return l2AssocSpinner;
- }
-
- public Spinner getL2LineSizeSpinner() {
- return l2LineSizeSpinner;
- }
-
- public Button getL2Button() {
- return l2Button;
- }
+ implements IValgrindToolPage {
+ // Cachegrind controls
+ private Button cacheButton;
+ private Button branchButton;
+ private Spinner i1SizeSpinner;
+ private Spinner i1AssocSpinner;
+ private Spinner i1LineSizeSpinner;
+ private Button i1Button;
+ private Spinner d1SizeSpinner;
+ private Spinner d1AssocSpinner;
+ private Spinner d1LineSizeSpinner;
+ private Button d1Button;
+ private Spinner l2SizeSpinner;
+ private Spinner l2AssocSpinner;
+ private Spinner l2LineSizeSpinner;
+ private Button l2Button;
+
+ private boolean isInitializing = false;
+ private SelectionListener selectListener = new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+ private ModifyListener modifyListener = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ @Override
+ public void createControl(Composite parent) {
+ Composite top = new Composite(parent, SWT.NONE);
+ top.setLayout(new GridLayout());
+ top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ // Event options
+ cacheButton = new Button(top, SWT.CHECK);
+ cacheButton.setText(Messages.getString("CachegrindToolPage.Profile_Cache")); //$NON-NLS-1$
+ cacheButton.addSelectionListener(selectListener);
+
+ branchButton = new Button(top, SWT.CHECK);
+ branchButton.setText(Messages.getString("CachegrindToolPage.Profile_Branch")); //$NON-NLS-1$
+ branchButton.addSelectionListener(selectListener);
+
+ createVerticalSpacer(top, 1);
+
+ Group cacheGroup = new Group(top, SWT.SHADOW_OUT);
+ cacheGroup.setLayout(new GridLayout(2, false));
+ cacheGroup.setText(Messages.getString("CachegrindToolPage.Manually_Set_Cache")); //$NON-NLS-1$
+
+ // I1 Cache
+ i1Button = new Button(cacheGroup, SWT.CHECK);
+ i1Button.setText(Messages.getString("CachegrindToolPage.I1_Cache")); //$NON-NLS-1$
+ i1Button.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ checkI1Enablement();
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ Composite i1Top = new Composite(cacheGroup, SWT.BORDER);
+ GridLayout i1Layout = new GridLayout(6, false);
+ i1Layout.horizontalSpacing = 10;
+ i1Top.setLayout(i1Layout);
+
+ Label i1SizeLabel = new Label(i1Top, SWT.NONE);
+ i1SizeLabel.setText(Messages.getString("CachegrindToolPage.Size")); //$NON-NLS-1$
+
+ i1SizeSpinner = new Spinner(i1Top, SWT.BORDER);
+ i1SizeSpinner.setMaximum(Integer.MAX_VALUE);
+ i1SizeSpinner.addModifyListener(modifyListener);
+
+ Label i1AssocLabel = new Label(i1Top, SWT.NONE);
+ i1AssocLabel.setText(Messages.getString("CachegrindToolPage.Assoc")); //$NON-NLS-1$
+
+ i1AssocSpinner = new Spinner(i1Top, SWT.BORDER);
+ i1AssocSpinner.setMaximum(Integer.MAX_VALUE);
+ i1AssocSpinner.addModifyListener(modifyListener);
+
+ Label i1LineSizeLabel = new Label(i1Top, SWT.NONE);
+ i1LineSizeLabel.setText(Messages.getString("CachegrindToolPage.Line_Size")); //$NON-NLS-1$
+
+ i1LineSizeSpinner = new Spinner(i1Top, SWT.BORDER);
+ i1LineSizeSpinner.setMaximum(Integer.MAX_VALUE);
+ i1LineSizeSpinner.addModifyListener(modifyListener);
+
+ // D1 Cache
+ d1Button = new Button(cacheGroup, SWT.CHECK);
+ d1Button.setText(Messages.getString("CachegrindToolPage.D1_Cache")); //$NON-NLS-1$
+ d1Button.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ checkD1Enablement();
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ Composite d1Top = new Composite(cacheGroup, SWT.BORDER);
+ GridLayout d1Layout = new GridLayout(6, false);
+ d1Layout.horizontalSpacing = 10;
+ d1Top.setLayout(d1Layout);
+
+ Label d1SizeLabel = new Label(d1Top, SWT.NONE);
+ d1SizeLabel.setText(Messages.getString("CachegrindToolPage.Size")); //$NON-NLS-1$
+
+ d1SizeSpinner = new Spinner(d1Top, SWT.BORDER);
+ d1SizeSpinner.setMaximum(Integer.MAX_VALUE);
+ d1SizeSpinner.addModifyListener(modifyListener);
+
+ Label d1AssocLabel = new Label(d1Top, SWT.NONE);
+ d1AssocLabel.setText(Messages.getString("CachegrindToolPage.Assoc")); //$NON-NLS-1$
+
+ d1AssocSpinner = new Spinner(d1Top, SWT.BORDER);
+ d1AssocSpinner.setMaximum(Integer.MAX_VALUE);
+ d1AssocSpinner.addModifyListener(modifyListener);
+
+ Label d1LineSizeLabel = new Label(d1Top, SWT.NONE);
+ d1LineSizeLabel.setText(Messages.getString("CachegrindToolPage.Line_Size")); //$NON-NLS-1$
+
+ d1LineSizeSpinner = new Spinner(d1Top, SWT.BORDER);
+ d1LineSizeSpinner.setMaximum(Integer.MAX_VALUE);
+ d1LineSizeSpinner.addModifyListener(modifyListener);
+
+ // D1 Cache
+ l2Button = new Button(cacheGroup, SWT.CHECK);
+ l2Button.setText(Messages.getString("CachegrindToolPage.L2_Cache")); //$NON-NLS-1$
+ l2Button.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ checkL2Enablement();
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ Composite l2Top = new Composite(cacheGroup, SWT.BORDER);
+ GridLayout l2Layout = new GridLayout(6, false);
+ l2Layout.horizontalSpacing = 10;
+ l2Top.setLayout(l2Layout);
+
+ Label l2SizeLabel = new Label(l2Top, SWT.NONE);
+ l2SizeLabel.setText(Messages.getString("CachegrindToolPage.Size")); //$NON-NLS-1$
+
+ l2SizeSpinner = new Spinner(l2Top, SWT.BORDER);
+ l2SizeSpinner.setMaximum(Integer.MAX_VALUE);
+ l2SizeSpinner.addModifyListener(modifyListener);
+
+ Label l2AssocLabel = new Label(l2Top, SWT.NONE);
+ l2AssocLabel.setText(Messages.getString("CachegrindToolPage.Assoc")); //$NON-NLS-1$
+
+ l2AssocSpinner = new Spinner(l2Top, SWT.BORDER);
+ l2AssocSpinner.setMaximum(Integer.MAX_VALUE);
+ l2AssocSpinner.addModifyListener(modifyListener);
+
+ Label l2LineSizeLabel = new Label(l2Top, SWT.NONE);
+ l2LineSizeLabel.setText(Messages.getString("CachegrindToolPage.Line_Size")); //$NON-NLS-1$
+
+ l2LineSizeSpinner = new Spinner(l2Top, SWT.BORDER);
+ l2LineSizeSpinner.setMaximum(Integer.MAX_VALUE);
+ l2LineSizeSpinner.addModifyListener(modifyListener);
+ }
+
+ @Override
+ public String getName() {
+ return Messages.getString("CachegrindToolPage.Cachegrind_Options"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration config) {
+ isInitializing = true;
+
+ try
+ {
+ cacheButton.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_CACHE_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_CACHE_SIM));
+ branchButton.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_BRANCH_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_BRANCH_SIM));
+
+ i1Button.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1));
+ i1SizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_SIZE));
+ i1AssocSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_ASSOC));
+ i1LineSizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_LSIZE));
+ checkI1Enablement();
+
+ d1Button.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1));
+ d1SizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_SIZE));
+ d1AssocSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_ASSOC));
+ d1LineSizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_LSIZE));
+ checkD1Enablement();
+
+ l2Button.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2));
+ l2SizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_SIZE));
+ l2AssocSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_ASSOC));
+ l2LineSizeSpinner.setSelection(config.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_LSIZE));
+ checkL2Enablement();
+
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ isInitializing = false;
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy config) {
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_CACHE_SIM, cacheButton.getSelection());
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_BRANCH_SIM, branchButton.getSelection());
+
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1, i1Button.getSelection());
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_SIZE, i1SizeSpinner.getSelection());
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_ASSOC, i1AssocSpinner.getSelection());
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_LSIZE, i1LineSizeSpinner.getSelection());
+
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1, d1Button.getSelection());
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_SIZE, d1SizeSpinner.getSelection());
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_ASSOC, d1AssocSpinner.getSelection());
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_LSIZE, d1LineSizeSpinner.getSelection());
+
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2, l2Button.getSelection());
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_SIZE, l2SizeSpinner.getSelection());
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_ASSOC, l2AssocSpinner.getSelection());
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_LSIZE, l2LineSizeSpinner.getSelection());
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy config) {
+ config.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, CachegrindPlugin.TOOL_ID);
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_CACHE_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_CACHE_SIM);
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_BRANCH_SIM, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_BRANCH_SIM);
+
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1);
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_SIZE);
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_ASSOC);
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_I1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_I1_LSIZE);
+
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1);
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_SIZE);
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_ASSOC);
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_D1_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_D1_LSIZE);
+
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2);
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_SIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_SIZE);
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_ASSOC, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_ASSOC);
+ config.setAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_L2_LSIZE, CachegrindLaunchConstants.DEFAULT_CACHEGRIND_L2_LSIZE);
+ }
+
+ @Override
+ public boolean isValid(ILaunchConfiguration launchConfig) {
+ setErrorMessage(null);
+
+ boolean result = false;
+ try {
+ result = launchConfig.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_CACHE_SIM, true)
+ || launchConfig.getAttribute(CachegrindLaunchConstants.ATTR_CACHEGRIND_BRANCH_SIM, false);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ if (!result) {
+ setErrorMessage(Messages.getString("CachegrindToolPage.At_least_one_of")); //$NON-NLS-1$
+ }
+ return result;
+ }
+
+ @Override
+ public void setValgrindVersion(Version ver) {
+ // Not used
+ }
+
+ @Override
+ protected void updateLaunchConfigurationDialog() {
+ if (!isInitializing) {
+ super.updateLaunchConfigurationDialog();
+ }
+ }
+
+ private void checkI1Enablement() {
+ boolean checked = i1Button.getSelection();
+ i1SizeSpinner.setEnabled(checked);
+ i1AssocSpinner.setEnabled(checked);
+ i1LineSizeSpinner.setEnabled(checked);
+ }
+
+ private void checkD1Enablement() {
+ boolean checked = d1Button.getSelection();
+ d1SizeSpinner.setEnabled(checked);
+ d1AssocSpinner.setEnabled(checked);
+ d1LineSizeSpinner.setEnabled(checked);
+ }
+
+ private void checkL2Enablement() {
+ boolean checked = l2Button.getSelection();
+ l2SizeSpinner.setEnabled(checked);
+ l2AssocSpinner.setEnabled(checked);
+ l2LineSizeSpinner.setEnabled(checked);
+ }
+
+ public Button getCacheButton() {
+ return cacheButton;
+ }
+
+ public Button getBranchButton() {
+ return branchButton;
+ }
+
+ public Spinner getI1SizeSpinner() {
+ return i1SizeSpinner;
+ }
+
+ public Spinner getI1AssocSpinner() {
+ return i1AssocSpinner;
+ }
+
+ public Spinner getI1LineSizeSpinner() {
+ return i1LineSizeSpinner;
+ }
+
+ public Button getI1Button() {
+ return i1Button;
+ }
+
+ public Spinner getD1SizeSpinner() {
+ return d1SizeSpinner;
+ }
+
+ public Spinner getD1AssocSpinner() {
+ return d1AssocSpinner;
+ }
+
+ public Spinner getD1LineSizeSpinner() {
+ return d1LineSizeSpinner;
+ }
+
+ public Button getD1Button() {
+ return d1Button;
+ }
+
+ public Spinner getL2SizeSpinner() {
+ return l2SizeSpinner;
+ }
+
+ public Spinner getL2AssocSpinner() {
+ return l2AssocSpinner;
+ }
+
+ public Spinner getL2LineSizeSpinner() {
+ return l2LineSizeSpinner;
+ }
+
+ public Button getL2Button() {
+ return l2Button;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindViewPart.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindViewPart.java
index f9f21a06be..8bc2920013 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindViewPart.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/CachegrindViewPart.java
@@ -54,301 +54,301 @@ import org.eclipse.ui.part.ViewPart;
public class CachegrindViewPart extends ViewPart implements IValgrindToolView {
- private CachegrindOutput[] outputs;
- private TreeViewer viewer;
-
- private static final int COLUMN_SIZE = 75;
- private CachegrindLabelProvider labelProvider;
- private CachegrindTreeContentProvider contentProvider;
- private IDoubleClickListener doubleClickListener;
- private ExpandAction expandAction;
- private CollapseAction collapseAction;
-
- // Events - Cache
- private static final String IR = "Ir"; //$NON-NLS-1$
- private static final String I1MR = "I1mr"; //$NON-NLS-1$
- private static final String I2MR = "I2mr"; //$NON-NLS-1$
- private static final String DR = "Dr"; //$NON-NLS-1$
- private static final String D1MR = "D1mr"; //$NON-NLS-1$
- private static final String D2MR = "D2mr"; //$NON-NLS-1$
- private static final String DW = "Dw"; //$NON-NLS-1$
- private static final String D1MW = "D1mw"; //$NON-NLS-1$
- private static final String D2MW = "D2mw"; //$NON-NLS-1$
-
- // Events - Branch
- private static final String BC = "Bc"; //$NON-NLS-1$
- private static final String BCM = "Bcm"; //$NON-NLS-1$
- private static final String BI = "Bi"; //$NON-NLS-1$
- private static final String BIM = "Bim"; //$NON-NLS-1$
-
- @Override
- public void createPartControl(Composite parent) {
- Composite top = new Composite(parent, SWT.NONE);
- GridLayout topLayout = new GridLayout();
- topLayout.marginHeight = topLayout.marginWidth = 0;
- top.setLayout(topLayout);
- top.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- viewer = new TreeViewer(top, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL
- | SWT.FULL_SELECTION);
-
- labelProvider = new CachegrindLabelProvider();
- ColumnViewerToolTipSupport.enableFor(viewer);
-
- Tree tree = viewer.getTree();
- tree.setHeaderVisible(true);
- tree.setLinesVisible(true);
- tree.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- TreeViewerColumn column = new TreeViewerColumn(viewer, SWT.NONE);
- column.getColumn().setText(Messages.getString("CachegrindViewPart.Location")); //$NON-NLS-1$
- column.getColumn().setWidth(COLUMN_SIZE * 4);
- column.getColumn().setResizable(true);
- column.getColumn().addSelectionListener(getHeaderListener());
- column.setLabelProvider(labelProvider);
-
- contentProvider = new CachegrindTreeContentProvider();
- viewer.setContentProvider(contentProvider);
- viewer.setLabelProvider(labelProvider);
- viewer.setAutoExpandLevel(2);
- doubleClickListener = new IDoubleClickListener() {
- @Override
- public void doubleClick(DoubleClickEvent event) {
- Object selection = ((StructuredSelection) event.getSelection()).getFirstElement();
- String path = null;
- int line = 0;
- if (selection instanceof CachegrindFile) {
- path = ((CachegrindFile) selection).getPath();
- } else if (selection instanceof CachegrindLine) {
- CachegrindLine element = (CachegrindLine) selection;
- CachegrindFile file = (CachegrindFile) element.getParent().getParent();
- path = file.getPath();
- line = element.getLine();
- } else if (selection instanceof CachegrindFunction) {
- CachegrindFunction function = (CachegrindFunction) selection;
- path = ((CachegrindFile) function.getParent()).getPath();
- if (function.getModel() instanceof ISourceReference) {
- ISourceReference model = (ISourceReference) function.getModel();
- try {
- ISourceRange sr = model.getSourceRange();
- if (sr != null) {
- line = sr.getStartLine();
- }
- } catch (CModelException e) {
- e.printStackTrace();
- }
- }
- }
- if (path != null) {
- try {
- ProfileUIUtils.openEditorAndSelect(path, line);
- } catch (PartInitException|BadLocationException e) {
- e.printStackTrace();
- }
- }
- }
- };
- viewer.addDoubleClickListener(doubleClickListener);
-
- expandAction = new ExpandAction(viewer);
- collapseAction = new CollapseAction(viewer);
-
- MenuManager manager = new MenuManager();
- manager.addMenuListener(new IMenuListener() {
- @Override
- public void menuAboutToShow(IMenuManager manager) {
- ITreeSelection selection = (ITreeSelection) viewer.getSelection();
- ICachegrindElement element = (ICachegrindElement) selection.getFirstElement();
- if (contentProvider.hasChildren(element)) {
- manager.add(expandAction);
- manager.add(collapseAction);
- }
- }
- });
-
- manager.setRemoveAllWhenShown(true);
- Menu contextMenu = manager.createContextMenu(viewer.getTree());
- viewer.getControl().setMenu(contextMenu);
- }
-
- @Override
- public void setFocus() {
- viewer.getTree().setFocus();
- }
-
- @Override
- public IAction[] getToolbarActions() {
- return null;
- }
-
- @Override
- public void refreshView() {
- if (outputs != null && outputs.length > 0) {
- String[] events = outputs[0].getEvents();
- for (int i = 0; i < events.length; i++) {
- TreeViewerColumn column = new TreeViewerColumn(viewer, SWT.NONE);
- column.getColumn().setText(events[i]);
- column.getColumn().setWidth(COLUMN_SIZE);
- column.getColumn().setToolTipText(getFullEventName(events[i]));
- column.getColumn().setResizable(true);
- column.getColumn().addSelectionListener(getHeaderListener());
- column.setLabelProvider(labelProvider);
- }
- viewer.setInput(outputs);
- viewer.getTree().layout(true);
- }
- }
-
- public void setOutputs(CachegrindOutput[] outputs) {
- this.outputs = outputs;
- }
-
- public CachegrindOutput[] getOutputs() {
- return outputs;
- }
-
- public TreeViewer getViewer() {
- return viewer;
- }
-
- public IDoubleClickListener getDoubleClickListener() {
- return doubleClickListener;
- }
-
- private SelectionListener getHeaderListener() {
- return new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- TreeColumn column = (TreeColumn) e.widget;
- Tree tree = viewer.getTree();
- if (column.equals(tree.getSortColumn())) {
- int direction = tree.getSortDirection() == SWT.UP ? SWT.DOWN
- : SWT.UP;
- tree.setSortDirection(direction);
- } else {
- tree.setSortDirection(SWT.UP);
- }
- tree.setSortColumn(column);
- viewer.setComparator(new ViewerComparator() {
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- Tree tree = ((TreeViewer) viewer).getTree();
- int direction = tree.getSortDirection();
- ICachegrindElement o1 = (ICachegrindElement) e1;
- ICachegrindElement o2 = (ICachegrindElement) e2;
- long result = 0;
-
- int sortIndex = Arrays.asList(tree.getColumns()).indexOf(tree.getSortColumn());
- if (sortIndex == 0) { // use compareTo
- result = o1.compareTo(o2);
- }
- else {
- long[] v1 = null;
- long[] v2 = null;
- if (o1 instanceof CachegrindFunction && o2 instanceof CachegrindFunction) {
- v1 = ((CachegrindFunction) o1).getTotals();
- v2 = ((CachegrindFunction) o2).getTotals();
- }
- else if (o1 instanceof CachegrindLine && o2 instanceof CachegrindLine) {
- v1 = ((CachegrindLine) o1).getValues();
- v2 = ((CachegrindLine) o2).getValues();
- }
- else if (o1 instanceof CachegrindOutput && o2 instanceof CachegrindOutput) {
- v1 = ((CachegrindOutput) o1).getSummary();
- v2 = ((CachegrindOutput) o2).getSummary();
- }
-
- if (v1 != null && v2 != null) {
- result = v1[sortIndex - 1] - v2[sortIndex - 1];
- }
- }
-
- // ascending or descending
- result = direction == SWT.UP ? result : -result;
-
- // overflow check
- if (result > Integer.MAX_VALUE) {
- result = Integer.MAX_VALUE;
- } else if (result < Integer.MIN_VALUE) {
- result = Integer.MIN_VALUE;
- }
-
- return (int) result;
- }
- });
- }
- };
- }
-
- private String getFullEventName(String event) {
- String result = event;
- if (event.equals(IR)) {
- result = Messages.getString("CachegrindViewPart.Ir_long"); //$NON-NLS-1$
- } else if (event.equals(I1MR)) {
- result = Messages.getString("CachegrindViewPart.I1mr_long"); //$NON-NLS-1$
- } else if (event.equals(I2MR)) {
- result = Messages.getString("CachegrindViewPart.I2mr_long"); //$NON-NLS-1$
- } else if (event.equals(DR)) {
- result = Messages.getString("CachegrindViewPart.Dr_long"); //$NON-NLS-1$
- } else if (event.equals(D1MR)) {
- result = Messages.getString("CachegrindViewPart.D1mr_long"); //$NON-NLS-1$
- } else if (event.equals(D2MR)) {
- result = Messages.getString("CachegrindViewPart.D2mr_long"); //$NON-NLS-1$
- } else if (event.equals(DW)) {
- result = Messages.getString("CachegrindViewPart.Dw_long"); //$NON-NLS-1$
- } else if (event.equals(D1MW)) {
- result = Messages.getString("CachegrindViewPart.D1mw_long"); //$NON-NLS-1$
- } else if (event.equals(D2MW)) {
- result = Messages.getString("CachegrindViewPart.D2mw_long"); //$NON-NLS-1$
- } else if (event.equals(BC)) {
- result = Messages.getString("CachegrindViewPart.Bc_long"); //$NON-NLS-1$
- } else if (event.equals(BCM)) {
- result = Messages.getString("CachegrindViewPart.Bcm_long"); //$NON-NLS-1$
- } else if (event.equals(BI)) {
- result = Messages.getString("CachegrindViewPart.Bi_long"); //$NON-NLS-1$
- } else if (event.equals(BIM)) {
- result = Messages.getString("CachegrindViewPart.Bim_long"); //$NON-NLS-1$
- }
- return result;
- }
-
- protected static class CachegrindTreeContentProvider implements ITreeContentProvider {
-
- @Override
- public Object[] getChildren(Object parentElement) {
- Object[] result = null;
- if (parentElement instanceof CachegrindOutput[]) {
- result = (CachegrindOutput[]) parentElement;
- }
- else if (parentElement instanceof ICachegrindElement) {
- result = ((ICachegrindElement) parentElement).getChildren();
- }
- return result;
- }
-
- @Override
- public Object getParent(Object element) {
- return ((ICachegrindElement) element).getParent();
- }
-
- @Override
- public boolean hasChildren(Object element) {
- ICachegrindElement[] children = (ICachegrindElement[]) getChildren(element);
- return children != null && children.length > 0;
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- }
+ private CachegrindOutput[] outputs;
+ private TreeViewer viewer;
+
+ private static final int COLUMN_SIZE = 75;
+ private CachegrindLabelProvider labelProvider;
+ private CachegrindTreeContentProvider contentProvider;
+ private IDoubleClickListener doubleClickListener;
+ private ExpandAction expandAction;
+ private CollapseAction collapseAction;
+
+ // Events - Cache
+ private static final String IR = "Ir"; //$NON-NLS-1$
+ private static final String I1MR = "I1mr"; //$NON-NLS-1$
+ private static final String I2MR = "I2mr"; //$NON-NLS-1$
+ private static final String DR = "Dr"; //$NON-NLS-1$
+ private static final String D1MR = "D1mr"; //$NON-NLS-1$
+ private static final String D2MR = "D2mr"; //$NON-NLS-1$
+ private static final String DW = "Dw"; //$NON-NLS-1$
+ private static final String D1MW = "D1mw"; //$NON-NLS-1$
+ private static final String D2MW = "D2mw"; //$NON-NLS-1$
+
+ // Events - Branch
+ private static final String BC = "Bc"; //$NON-NLS-1$
+ private static final String BCM = "Bcm"; //$NON-NLS-1$
+ private static final String BI = "Bi"; //$NON-NLS-1$
+ private static final String BIM = "Bim"; //$NON-NLS-1$
+
+ @Override
+ public void createPartControl(Composite parent) {
+ Composite top = new Composite(parent, SWT.NONE);
+ GridLayout topLayout = new GridLayout();
+ topLayout.marginHeight = topLayout.marginWidth = 0;
+ top.setLayout(topLayout);
+ top.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ viewer = new TreeViewer(top, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL
+ | SWT.FULL_SELECTION);
+
+ labelProvider = new CachegrindLabelProvider();
+ ColumnViewerToolTipSupport.enableFor(viewer);
+
+ Tree tree = viewer.getTree();
+ tree.setHeaderVisible(true);
+ tree.setLinesVisible(true);
+ tree.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ TreeViewerColumn column = new TreeViewerColumn(viewer, SWT.NONE);
+ column.getColumn().setText(Messages.getString("CachegrindViewPart.Location")); //$NON-NLS-1$
+ column.getColumn().setWidth(COLUMN_SIZE * 4);
+ column.getColumn().setResizable(true);
+ column.getColumn().addSelectionListener(getHeaderListener());
+ column.setLabelProvider(labelProvider);
+
+ contentProvider = new CachegrindTreeContentProvider();
+ viewer.setContentProvider(contentProvider);
+ viewer.setLabelProvider(labelProvider);
+ viewer.setAutoExpandLevel(2);
+ doubleClickListener = new IDoubleClickListener() {
+ @Override
+ public void doubleClick(DoubleClickEvent event) {
+ Object selection = ((StructuredSelection) event.getSelection()).getFirstElement();
+ String path = null;
+ int line = 0;
+ if (selection instanceof CachegrindFile) {
+ path = ((CachegrindFile) selection).getPath();
+ } else if (selection instanceof CachegrindLine) {
+ CachegrindLine element = (CachegrindLine) selection;
+ CachegrindFile file = (CachegrindFile) element.getParent().getParent();
+ path = file.getPath();
+ line = element.getLine();
+ } else if (selection instanceof CachegrindFunction) {
+ CachegrindFunction function = (CachegrindFunction) selection;
+ path = ((CachegrindFile) function.getParent()).getPath();
+ if (function.getModel() instanceof ISourceReference) {
+ ISourceReference model = (ISourceReference) function.getModel();
+ try {
+ ISourceRange sr = model.getSourceRange();
+ if (sr != null) {
+ line = sr.getStartLine();
+ }
+ } catch (CModelException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ if (path != null) {
+ try {
+ ProfileUIUtils.openEditorAndSelect(path, line);
+ } catch (PartInitException|BadLocationException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ };
+ viewer.addDoubleClickListener(doubleClickListener);
+
+ expandAction = new ExpandAction(viewer);
+ collapseAction = new CollapseAction(viewer);
+
+ MenuManager manager = new MenuManager();
+ manager.addMenuListener(new IMenuListener() {
+ @Override
+ public void menuAboutToShow(IMenuManager manager) {
+ ITreeSelection selection = (ITreeSelection) viewer.getSelection();
+ ICachegrindElement element = (ICachegrindElement) selection.getFirstElement();
+ if (contentProvider.hasChildren(element)) {
+ manager.add(expandAction);
+ manager.add(collapseAction);
+ }
+ }
+ });
+
+ manager.setRemoveAllWhenShown(true);
+ Menu contextMenu = manager.createContextMenu(viewer.getTree());
+ viewer.getControl().setMenu(contextMenu);
+ }
+
+ @Override
+ public void setFocus() {
+ viewer.getTree().setFocus();
+ }
+
+ @Override
+ public IAction[] getToolbarActions() {
+ return null;
+ }
+
+ @Override
+ public void refreshView() {
+ if (outputs != null && outputs.length > 0) {
+ String[] events = outputs[0].getEvents();
+ for (int i = 0; i < events.length; i++) {
+ TreeViewerColumn column = new TreeViewerColumn(viewer, SWT.NONE);
+ column.getColumn().setText(events[i]);
+ column.getColumn().setWidth(COLUMN_SIZE);
+ column.getColumn().setToolTipText(getFullEventName(events[i]));
+ column.getColumn().setResizable(true);
+ column.getColumn().addSelectionListener(getHeaderListener());
+ column.setLabelProvider(labelProvider);
+ }
+ viewer.setInput(outputs);
+ viewer.getTree().layout(true);
+ }
+ }
+
+ public void setOutputs(CachegrindOutput[] outputs) {
+ this.outputs = outputs;
+ }
+
+ public CachegrindOutput[] getOutputs() {
+ return outputs;
+ }
+
+ public TreeViewer getViewer() {
+ return viewer;
+ }
+
+ public IDoubleClickListener getDoubleClickListener() {
+ return doubleClickListener;
+ }
+
+ private SelectionListener getHeaderListener() {
+ return new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ TreeColumn column = (TreeColumn) e.widget;
+ Tree tree = viewer.getTree();
+ if (column.equals(tree.getSortColumn())) {
+ int direction = tree.getSortDirection() == SWT.UP ? SWT.DOWN
+ : SWT.UP;
+ tree.setSortDirection(direction);
+ } else {
+ tree.setSortDirection(SWT.UP);
+ }
+ tree.setSortColumn(column);
+ viewer.setComparator(new ViewerComparator() {
+ @Override
+ public int compare(Viewer viewer, Object e1, Object e2) {
+ Tree tree = ((TreeViewer) viewer).getTree();
+ int direction = tree.getSortDirection();
+ ICachegrindElement o1 = (ICachegrindElement) e1;
+ ICachegrindElement o2 = (ICachegrindElement) e2;
+ long result = 0;
+
+ int sortIndex = Arrays.asList(tree.getColumns()).indexOf(tree.getSortColumn());
+ if (sortIndex == 0) { // use compareTo
+ result = o1.compareTo(o2);
+ }
+ else {
+ long[] v1 = null;
+ long[] v2 = null;
+ if (o1 instanceof CachegrindFunction && o2 instanceof CachegrindFunction) {
+ v1 = ((CachegrindFunction) o1).getTotals();
+ v2 = ((CachegrindFunction) o2).getTotals();
+ }
+ else if (o1 instanceof CachegrindLine && o2 instanceof CachegrindLine) {
+ v1 = ((CachegrindLine) o1).getValues();
+ v2 = ((CachegrindLine) o2).getValues();
+ }
+ else if (o1 instanceof CachegrindOutput && o2 instanceof CachegrindOutput) {
+ v1 = ((CachegrindOutput) o1).getSummary();
+ v2 = ((CachegrindOutput) o2).getSummary();
+ }
+
+ if (v1 != null && v2 != null) {
+ result = v1[sortIndex - 1] - v2[sortIndex - 1];
+ }
+ }
+
+ // ascending or descending
+ result = direction == SWT.UP ? result : -result;
+
+ // overflow check
+ if (result > Integer.MAX_VALUE) {
+ result = Integer.MAX_VALUE;
+ } else if (result < Integer.MIN_VALUE) {
+ result = Integer.MIN_VALUE;
+ }
+
+ return (int) result;
+ }
+ });
+ }
+ };
+ }
+
+ private String getFullEventName(String event) {
+ String result = event;
+ if (event.equals(IR)) {
+ result = Messages.getString("CachegrindViewPart.Ir_long"); //$NON-NLS-1$
+ } else if (event.equals(I1MR)) {
+ result = Messages.getString("CachegrindViewPart.I1mr_long"); //$NON-NLS-1$
+ } else if (event.equals(I2MR)) {
+ result = Messages.getString("CachegrindViewPart.I2mr_long"); //$NON-NLS-1$
+ } else if (event.equals(DR)) {
+ result = Messages.getString("CachegrindViewPart.Dr_long"); //$NON-NLS-1$
+ } else if (event.equals(D1MR)) {
+ result = Messages.getString("CachegrindViewPart.D1mr_long"); //$NON-NLS-1$
+ } else if (event.equals(D2MR)) {
+ result = Messages.getString("CachegrindViewPart.D2mr_long"); //$NON-NLS-1$
+ } else if (event.equals(DW)) {
+ result = Messages.getString("CachegrindViewPart.Dw_long"); //$NON-NLS-1$
+ } else if (event.equals(D1MW)) {
+ result = Messages.getString("CachegrindViewPart.D1mw_long"); //$NON-NLS-1$
+ } else if (event.equals(D2MW)) {
+ result = Messages.getString("CachegrindViewPart.D2mw_long"); //$NON-NLS-1$
+ } else if (event.equals(BC)) {
+ result = Messages.getString("CachegrindViewPart.Bc_long"); //$NON-NLS-1$
+ } else if (event.equals(BCM)) {
+ result = Messages.getString("CachegrindViewPart.Bcm_long"); //$NON-NLS-1$
+ } else if (event.equals(BI)) {
+ result = Messages.getString("CachegrindViewPart.Bi_long"); //$NON-NLS-1$
+ } else if (event.equals(BIM)) {
+ result = Messages.getString("CachegrindViewPart.Bim_long"); //$NON-NLS-1$
+ }
+ return result;
+ }
+
+ protected static class CachegrindTreeContentProvider implements ITreeContentProvider {
+
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ Object[] result = null;
+ if (parentElement instanceof CachegrindOutput[]) {
+ result = (CachegrindOutput[]) parentElement;
+ }
+ else if (parentElement instanceof ICachegrindElement) {
+ result = ((ICachegrindElement) parentElement).getChildren();
+ }
+ return result;
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ return ((ICachegrindElement) element).getParent();
+ }
+
+ @Override
+ public boolean hasChildren(Object element) {
+ ICachegrindElement[] children = (ICachegrindElement[]) getChildren(element);
+ return children != null && children.length > 0;
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ return getChildren(inputElement);
+ }
+
+ @Override
+ public void dispose() {
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/Messages.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/Messages.java
index 4806dfbbbf..68a6e6bac0 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/Messages.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/Messages.java
@@ -14,19 +14,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.cachegrind.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.cachegrind.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindDescription.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindDescription.java
index c5bea07793..561dc582c3 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindDescription.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindDescription.java
@@ -11,23 +11,23 @@
package org.eclipse.linuxtools.internal.valgrind.cachegrind.model;
public class CachegrindDescription {
- private String name;
-
- public CachegrindDescription(String name) {
- this.name = name;
- }
-
- @Override
- public boolean equals(Object obj) {
- return obj instanceof CachegrindDescription && name.equals(((CachegrindDescription) obj).getName());
- }
-
- @Override
- public int hashCode() {
- return name.hashCode();
- }
-
- public String getName() {
- return name;
- }
+ private String name;
+
+ public CachegrindDescription(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return obj instanceof CachegrindDescription && name.equals(((CachegrindDescription) obj).getName());
+ }
+
+ @Override
+ public int hashCode() {
+ return name.hashCode();
+ }
+
+ public String getName() {
+ return name;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindFile.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindFile.java
index 78f56bc09c..06e2764f2c 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindFile.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindFile.java
@@ -20,74 +20,74 @@ import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
public class CachegrindFile implements ICachegrindElement {
- private static final String UNKNOWN_FILE = "???"; //$NON-NLS-1$
-
-
- private CachegrindOutput parent;
- private String path;
- private List<CachegrindFunction> functions;
-
- private IAdaptable model;
-
- public CachegrindFile(CachegrindOutput parent, String path) {
- this.parent = parent;
- this.path = path;
- functions = new ArrayList<>();
-
- IPath pathObj = Path.fromOSString(path);
- if (path.equals(UNKNOWN_FILE)) {
- model = null;
- }
- else {
- model = CoreModel.getDefault().create(pathObj);
- if (model == null) {
- model = ResourcesPlugin.getWorkspace().getRoot().getFile(pathObj);
- }
- }
- }
-
- public void addFunction(CachegrindFunction func) {
- functions.add(func);
- }
-
- public CachegrindFunction[] getFunctions() {
- return functions.toArray(new CachegrindFunction[functions.size()]);
- }
-
- @Override
- public ICachegrindElement[] getChildren() {
- return getFunctions();
- }
-
- @Override
- public IAdaptable getModel() {
- return model;
- }
-
- public String getPath() {
- return path;
- }
-
- public String getName() {
- String name = path;
- if (Path.ROOT.isValidPath(path)) {
- name = Path.fromOSString(path).lastSegment();
- }
- return name;
- }
-
- @Override
- public ICachegrindElement getParent() {
- return parent;
- }
-
- @Override
- public int compareTo(ICachegrindElement o) {
- int result = 0;
- if (o instanceof CachegrindFile) {
- result = getName().compareTo(((CachegrindFile) o).getName());
- }
- return result;
- }
+ private static final String UNKNOWN_FILE = "???"; //$NON-NLS-1$
+
+
+ private CachegrindOutput parent;
+ private String path;
+ private List<CachegrindFunction> functions;
+
+ private IAdaptable model;
+
+ public CachegrindFile(CachegrindOutput parent, String path) {
+ this.parent = parent;
+ this.path = path;
+ functions = new ArrayList<>();
+
+ IPath pathObj = Path.fromOSString(path);
+ if (path.equals(UNKNOWN_FILE)) {
+ model = null;
+ }
+ else {
+ model = CoreModel.getDefault().create(pathObj);
+ if (model == null) {
+ model = ResourcesPlugin.getWorkspace().getRoot().getFile(pathObj);
+ }
+ }
+ }
+
+ public void addFunction(CachegrindFunction func) {
+ functions.add(func);
+ }
+
+ public CachegrindFunction[] getFunctions() {
+ return functions.toArray(new CachegrindFunction[functions.size()]);
+ }
+
+ @Override
+ public ICachegrindElement[] getChildren() {
+ return getFunctions();
+ }
+
+ @Override
+ public IAdaptable getModel() {
+ return model;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public String getName() {
+ String name = path;
+ if (Path.ROOT.isValidPath(path)) {
+ name = Path.fromOSString(path).lastSegment();
+ }
+ return name;
+ }
+
+ @Override
+ public ICachegrindElement getParent() {
+ return parent;
+ }
+
+ @Override
+ public int compareTo(ICachegrindElement o) {
+ int result = 0;
+ if (o instanceof CachegrindFile) {
+ result = getName().compareTo(((CachegrindFile) o).getName());
+ }
+ return result;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindFunction.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindFunction.java
index 06361d9296..3c83263544 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindFunction.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindFunction.java
@@ -24,121 +24,121 @@ import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
public class CachegrindFunction implements ICachegrindElement {
- private CachegrindFile parent;
- private String name;
- private List<CachegrindLine> lines;
- private long[] totals;
-
- private IAdaptable model;
-
- private static final String SCOPE_RESOLUTION = "::"; //$NON-NLS-1$
-
- public CachegrindFunction(CachegrindFile parent, String name) {
- this.parent = parent;
- this.name = name;
- lines = new ArrayList<>();
-
- IAdaptable pModel = parent.getModel();
- if (pModel instanceof ICElement) {
- ICElement element = (ICElement) pModel;
- try {
- if (element instanceof ITranslationUnit) {
- // Cachegrind labels parameter types for C++ methods
- int paramIndex = name.indexOf('(');
- if (paramIndex >= 0) {
- name = name.substring(0, paramIndex);
- }
-
- model = findElement(name, (IParent) element);
- if (model == null) {
- while (name.contains(SCOPE_RESOLUTION)) {
- String[] parts = name.split(SCOPE_RESOLUTION, 2);
- String structureName = parts[0];
- name = parts[1];
-
- List<ICElement> dom = ((IParent) element).getChildrenOfType(ICElement.C_CLASS);
- dom.addAll(((IParent) element).getChildrenOfType(ICElement.C_STRUCT));
- dom.addAll(((IParent) element).getChildrenOfType(ICElement.C_UNION));
- for (int i = 0; i < dom.size(); i++) {
- ICElement e = dom.get(i);
- if (e instanceof IStructure && e.getElementName().equals(structureName)) {
- element = e;
- }
- }
- }
- model = findElement(name, (IParent) element);
- }
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
-
- private ICElement findElement(String name, IParent parent)
- throws CModelException {
- ICElement element = null;
- List<ICElement> dom = parent.getChildrenOfType(ICElement.C_FUNCTION);
- dom.addAll(parent.getChildrenOfType(ICElement.C_METHOD));
- for (int i = 0; i < dom.size(); i++) {
- ICElement func = dom.get(i);
- if ((func instanceof IFunction || func instanceof IMethod) && func.getElementName().equals(name)) {
- element = func;
- }
- }
- return element;
- }
-
- public void addLine(CachegrindLine line) {
- long[] values = line.getValues();
- if (totals == null) {
- totals = new long[values.length];
- }
- for (int i = 0; i < values.length; i++) {
- totals[i] += values[i];
- }
- lines.add(line);
- }
-
- public String getName() {
- return name;
- }
-
- @Override
- public IAdaptable getModel() {
- return model;
- }
-
- public long[] getTotals() {
- return totals;
- }
-
- public CachegrindLine[] getLines() {
- return lines.toArray(new CachegrindLine[lines.size()]);
- }
-
- @Override
- public ICachegrindElement[] getChildren() {
- ICachegrindElement[] children = null;
- // if there is only a summary don't return any children
- if (lines.get(0).getLine() > 0) {
- children = getLines();
- }
- return children;
- }
-
- @Override
- public ICachegrindElement getParent() {
- return parent;
- }
-
- @Override
- public int compareTo(ICachegrindElement o) {
- int result = 0;
- if (o instanceof CachegrindFunction) {
- result = name.compareTo(((CachegrindFunction) o).getName());
- }
- return result;
- }
+ private CachegrindFile parent;
+ private String name;
+ private List<CachegrindLine> lines;
+ private long[] totals;
+
+ private IAdaptable model;
+
+ private static final String SCOPE_RESOLUTION = "::"; //$NON-NLS-1$
+
+ public CachegrindFunction(CachegrindFile parent, String name) {
+ this.parent = parent;
+ this.name = name;
+ lines = new ArrayList<>();
+
+ IAdaptable pModel = parent.getModel();
+ if (pModel instanceof ICElement) {
+ ICElement element = (ICElement) pModel;
+ try {
+ if (element instanceof ITranslationUnit) {
+ // Cachegrind labels parameter types for C++ methods
+ int paramIndex = name.indexOf('(');
+ if (paramIndex >= 0) {
+ name = name.substring(0, paramIndex);
+ }
+
+ model = findElement(name, (IParent) element);
+ if (model == null) {
+ while (name.contains(SCOPE_RESOLUTION)) {
+ String[] parts = name.split(SCOPE_RESOLUTION, 2);
+ String structureName = parts[0];
+ name = parts[1];
+
+ List<ICElement> dom = ((IParent) element).getChildrenOfType(ICElement.C_CLASS);
+ dom.addAll(((IParent) element).getChildrenOfType(ICElement.C_STRUCT));
+ dom.addAll(((IParent) element).getChildrenOfType(ICElement.C_UNION));
+ for (int i = 0; i < dom.size(); i++) {
+ ICElement e = dom.get(i);
+ if (e instanceof IStructure && e.getElementName().equals(structureName)) {
+ element = e;
+ }
+ }
+ }
+ model = findElement(name, (IParent) element);
+ }
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private ICElement findElement(String name, IParent parent)
+ throws CModelException {
+ ICElement element = null;
+ List<ICElement> dom = parent.getChildrenOfType(ICElement.C_FUNCTION);
+ dom.addAll(parent.getChildrenOfType(ICElement.C_METHOD));
+ for (int i = 0; i < dom.size(); i++) {
+ ICElement func = dom.get(i);
+ if ((func instanceof IFunction || func instanceof IMethod) && func.getElementName().equals(name)) {
+ element = func;
+ }
+ }
+ return element;
+ }
+
+ public void addLine(CachegrindLine line) {
+ long[] values = line.getValues();
+ if (totals == null) {
+ totals = new long[values.length];
+ }
+ for (int i = 0; i < values.length; i++) {
+ totals[i] += values[i];
+ }
+ lines.add(line);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public IAdaptable getModel() {
+ return model;
+ }
+
+ public long[] getTotals() {
+ return totals;
+ }
+
+ public CachegrindLine[] getLines() {
+ return lines.toArray(new CachegrindLine[lines.size()]);
+ }
+
+ @Override
+ public ICachegrindElement[] getChildren() {
+ ICachegrindElement[] children = null;
+ // if there is only a summary don't return any children
+ if (lines.get(0).getLine() > 0) {
+ children = getLines();
+ }
+ return children;
+ }
+
+ @Override
+ public ICachegrindElement getParent() {
+ return parent;
+ }
+
+ @Override
+ public int compareTo(ICachegrindElement o) {
+ int result = 0;
+ if (o instanceof CachegrindFunction) {
+ result = name.compareTo(((CachegrindFunction) o).getName());
+ }
+ return result;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindLine.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindLine.java
index 32d6999bc8..6cb063bc74 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindLine.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindLine.java
@@ -14,46 +14,46 @@ import org.eclipse.core.runtime.IAdaptable;
public class CachegrindLine implements ICachegrindElement {
- private CachegrindFunction parent;
- private int line;
- private long[] values;
-
- public CachegrindLine(CachegrindFunction parent, int line, long[] values) {
- this.parent = parent;
- this.line = line;
- this.values = values;
- }
-
- @Override
- public ICachegrindElement[] getChildren() {
- return null;
- }
-
- public int getLine() {
- return line;
- }
-
- public long[] getValues() {
- return values;
- }
-
- @Override
- public ICachegrindElement getParent() {
- return parent;
- }
-
- @Override
- public int compareTo(ICachegrindElement o) {
- int result = 0;
- if (o instanceof CachegrindLine) {
- result = line - ((CachegrindLine) o).getLine();
- }
- return result;
- }
-
- @Override
- public IAdaptable getModel() {
- return null;
- }
-
+ private CachegrindFunction parent;
+ private int line;
+ private long[] values;
+
+ public CachegrindLine(CachegrindFunction parent, int line, long[] values) {
+ this.parent = parent;
+ this.line = line;
+ this.values = values;
+ }
+
+ @Override
+ public ICachegrindElement[] getChildren() {
+ return null;
+ }
+
+ public int getLine() {
+ return line;
+ }
+
+ public long[] getValues() {
+ return values;
+ }
+
+ @Override
+ public ICachegrindElement getParent() {
+ return parent;
+ }
+
+ @Override
+ public int compareTo(ICachegrindElement o) {
+ int result = 0;
+ if (o instanceof CachegrindLine) {
+ result = line - ((CachegrindLine) o).getLine();
+ }
+ return result;
+ }
+
+ @Override
+ public IAdaptable getModel() {
+ return null;
+ }
+
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindOutput.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindOutput.java
index 7ad55ad5f7..55d4a10c2e 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindOutput.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/CachegrindOutput.java
@@ -16,75 +16,75 @@ import java.util.List;
import org.eclipse.core.runtime.IAdaptable;
public class CachegrindOutput implements ICachegrindElement {
- private List<CachegrindDescription> descriptions;
- private List<CachegrindFile> files;
- private Integer pid;
- private String[] events;
- private long[] summary;
-
- public CachegrindOutput() {
- descriptions = new ArrayList<>();
- files = new ArrayList<>();
- }
-
- public void addDescription(CachegrindDescription desc) {
- descriptions.add(desc);
- }
-
- public void addFile(CachegrindFile file) {
- files.add(file);
- }
-
- public void setEvents(String[] events) {
- this.events = events;
- }
-
- public void setSummary(long[] summary) {
- this.summary = summary;
- }
-
- public void setPid(Integer pid) {
- this.pid = pid;
- }
-
- public String[] getEvents() {
- return events;
- }
-
- public CachegrindFile[] getFiles() {
- return files.toArray(new CachegrindFile[files.size()]);
- }
-
- public long[] getSummary() {
- return summary;
- }
-
- @Override
- public ICachegrindElement[] getChildren() {
- return getFiles();
- }
-
- @Override
- public ICachegrindElement getParent() {
- return null;
- }
-
- public Integer getPid() {
- return pid;
- }
-
- @Override
- public int compareTo(ICachegrindElement o) {
- int result = 0;
- if (o instanceof CachegrindOutput) {
- result = pid - ((CachegrindOutput) o).getPid();
- }
- return result;
- }
-
- @Override
- public IAdaptable getModel() {
- return null;
- }
-
+ private List<CachegrindDescription> descriptions;
+ private List<CachegrindFile> files;
+ private Integer pid;
+ private String[] events;
+ private long[] summary;
+
+ public CachegrindOutput() {
+ descriptions = new ArrayList<>();
+ files = new ArrayList<>();
+ }
+
+ public void addDescription(CachegrindDescription desc) {
+ descriptions.add(desc);
+ }
+
+ public void addFile(CachegrindFile file) {
+ files.add(file);
+ }
+
+ public void setEvents(String[] events) {
+ this.events = events;
+ }
+
+ public void setSummary(long[] summary) {
+ this.summary = summary;
+ }
+
+ public void setPid(Integer pid) {
+ this.pid = pid;
+ }
+
+ public String[] getEvents() {
+ return events;
+ }
+
+ public CachegrindFile[] getFiles() {
+ return files.toArray(new CachegrindFile[files.size()]);
+ }
+
+ public long[] getSummary() {
+ return summary;
+ }
+
+ @Override
+ public ICachegrindElement[] getChildren() {
+ return getFiles();
+ }
+
+ @Override
+ public ICachegrindElement getParent() {
+ return null;
+ }
+
+ public Integer getPid() {
+ return pid;
+ }
+
+ @Override
+ public int compareTo(ICachegrindElement o) {
+ int result = 0;
+ if (o instanceof CachegrindOutput) {
+ result = pid - ((CachegrindOutput) o).getPid();
+ }
+ return result;
+ }
+
+ @Override
+ public IAdaptable getModel() {
+ return null;
+ }
+
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/ICachegrindElement.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/ICachegrindElement.java
index 9208fdbdec..10369347c5 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/ICachegrindElement.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/ICachegrindElement.java
@@ -13,9 +13,9 @@ package org.eclipse.linuxtools.internal.valgrind.cachegrind.model;
import org.eclipse.core.runtime.IAdaptable;
public interface ICachegrindElement extends Comparable<ICachegrindElement> {
-
- ICachegrindElement getParent();
- ICachegrindElement[] getChildren();
- IAdaptable getModel();
-
+
+ ICachegrindElement getParent();
+ ICachegrindElement[] getChildren();
+ IAdaptable getModel();
+
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/Messages.java b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/Messages.java
index d01fb95402..fe8add94e3 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/Messages.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.cachegrind/src/org/eclipse/linuxtools/internal/valgrind/cachegrind/model/Messages.java
@@ -14,19 +14,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.cachegrind.model.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.cachegrind.model.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/AbstractValgrindMessage.java b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/AbstractValgrindMessage.java
index 7f6ca2ef2d..6ee72a4d33 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/AbstractValgrindMessage.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/AbstractValgrindMessage.java
@@ -17,45 +17,45 @@ import org.eclipse.linuxtools.valgrind.core.IValgrindMessage;
public class AbstractValgrindMessage implements IValgrindMessage {
- private IValgrindMessage parent;
- private ILaunch launch;
- private ArrayList<IValgrindMessage> children;
- private String text;
-
- public AbstractValgrindMessage(IValgrindMessage parent, String text, ILaunch launch) {
- children = new ArrayList<>();
- this.parent = parent;
- this.text = text;
- this.launch = launch;
-
- if (parent != null) {
- parent.addChild(this);
- }
- }
-
- @Override
- public void addChild(IValgrindMessage message) {
- children.add(message);
- }
-
- @Override
- public ILaunch getLaunch() {
- return launch;
- }
-
- @Override
- public IValgrindMessage getParent() {
- return parent;
- }
-
- @Override
- public IValgrindMessage[] getChildren() {
- return children.toArray(new IValgrindMessage[children.size()]);
- }
-
- @Override
- public String getText() {
- return text;
- }
+ private IValgrindMessage parent;
+ private ILaunch launch;
+ private ArrayList<IValgrindMessage> children;
+ private String text;
+
+ public AbstractValgrindMessage(IValgrindMessage parent, String text, ILaunch launch) {
+ children = new ArrayList<>();
+ this.parent = parent;
+ this.text = text;
+ this.launch = launch;
+
+ if (parent != null) {
+ parent.addChild(this);
+ }
+ }
+
+ @Override
+ public void addChild(IValgrindMessage message) {
+ children.add(message);
+ }
+
+ @Override
+ public ILaunch getLaunch() {
+ return launch;
+ }
+
+ @Override
+ public IValgrindMessage getParent() {
+ return parent;
+ }
+
+ @Override
+ public IValgrindMessage[] getChildren() {
+ return children.toArray(new IValgrindMessage[children.size()]);
+ }
+
+ @Override
+ public String getText() {
+ return text;
+ }
} \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/Messages.java b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/Messages.java
index 6b9f954f03..901763cb38 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/Messages.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/Messages.java
@@ -7,26 +7,26 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.core;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.core.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.core.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/PluginConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/PluginConstants.java
index 4678a45171..b421a0b0b8 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/PluginConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/PluginConstants.java
@@ -11,6 +11,6 @@
package org.eclipse.linuxtools.internal.valgrind.core;
public interface PluginConstants {
- // IDs for important plugins
- String CORE_PLUGIN_ID = "org.eclipse.linuxtools.valgrind.core"; //$NON-NLS-1$
+ // IDs for important plugins
+ String CORE_PLUGIN_ID = "org.eclipse.linuxtools.valgrind.core"; //$NON-NLS-1$
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindCommand.java b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindCommand.java
index f7e4d6ea4e..4ceb55e401 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindCommand.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindCommand.java
@@ -21,88 +21,88 @@ import org.eclipse.linuxtools.tools.launch.core.factory.RuntimeProcessFactory;
import org.eclipse.linuxtools.valgrind.core.CommandLineConstants;
public class ValgrindCommand {
- protected static final String WHICH_CMD = "which"; //$NON-NLS-1$
- protected static final String VALGRIND_CMD = "valgrind"; //$NON-NLS-1$
+ protected static final String WHICH_CMD = "which"; //$NON-NLS-1$
+ protected static final String VALGRIND_CMD = "valgrind"; //$NON-NLS-1$
- protected Process process;
- protected String[] args;
+ protected Process process;
+ protected String[] args;
- public String getValgrindCommand() {
- return VALGRIND_CMD;
- }
+ public String getValgrindCommand() {
+ return VALGRIND_CMD;
+ }
- public String whichVersion(IProject project) throws IOException {
- StringBuffer out = new StringBuffer();
- String version = ""; //$NON-NLS-1$
- Process p = RuntimeProcessFactory.getFactory().exec(new String[] { VALGRIND_CMD, CommandLineConstants.OPT_VERSION }, project);
- try {
- readIntoBuffer(out, p);
- version = out.toString().trim();
- } catch(IOException e) {
- e.printStackTrace();
- }
- return version;
- }
+ public String whichVersion(IProject project) throws IOException {
+ StringBuffer out = new StringBuffer();
+ String version = ""; //$NON-NLS-1$
+ Process p = RuntimeProcessFactory.getFactory().exec(new String[] { VALGRIND_CMD, CommandLineConstants.OPT_VERSION }, project);
+ try {
+ readIntoBuffer(out, p);
+ version = out.toString().trim();
+ } catch(IOException e) {
+ e.printStackTrace();
+ }
+ return version;
+ }
- public void execute(String[] commandArray, Object env, File wd, boolean usePty, IProject project) throws IOException {
- args = commandArray;
- try {
- process = startProcess(commandArray, env, wd, usePty, project);
- } catch (IOException e) {
- if (process != null) {
- process.destroy();
- }
- throw e;
- }
- }
+ public void execute(String[] commandArray, Object env, File wd, boolean usePty, IProject project) throws IOException {
+ args = commandArray;
+ try {
+ process = startProcess(commandArray, env, wd, usePty, project);
+ } catch (IOException e) {
+ if (process != null) {
+ process.destroy();
+ }
+ throw e;
+ }
+ }
- public Process getProcess() {
- return process;
- }
+ public Process getProcess() {
+ return process;
+ }
- public String getCommandLine() {
- StringBuffer ret = new StringBuffer();
- for (String arg : args) {
- ret.append(arg).append(" "); //$NON-NLS-1$
- }
- return ret.toString().trim();
- }
+ public String getCommandLine() {
+ StringBuffer ret = new StringBuffer();
+ for (String arg : args) {
+ ret.append(arg).append(" "); //$NON-NLS-1$
+ }
+ return ret.toString().trim();
+ }
- private Process startProcess(String[] commandArray, Object env, File workDir, boolean usePty, IProject project) throws IOException {
- if (workDir == null) {
- return CdtSpawnerProcessFactory.getFactory().exec(commandArray, (String[]) env, project);
- }
- if (PTY.isSupported() && usePty) {
- return CdtSpawnerProcessFactory.getFactory().exec(commandArray, (String[]) env, workDir, new PTY(), project);
- } else {
- return CdtSpawnerProcessFactory.getFactory().exec(commandArray, (String[]) env, workDir, project);
- }
- }
+ private Process startProcess(String[] commandArray, Object env, File workDir, boolean usePty, IProject project) throws IOException {
+ if (workDir == null) {
+ return CdtSpawnerProcessFactory.getFactory().exec(commandArray, (String[]) env, project);
+ }
+ if (PTY.isSupported() && usePty) {
+ return CdtSpawnerProcessFactory.getFactory().exec(commandArray, (String[]) env, workDir, new PTY(), project);
+ } else {
+ return CdtSpawnerProcessFactory.getFactory().exec(commandArray, (String[]) env, workDir, project);
+ }
+ }
- private void readIntoBuffer(StringBuffer out, Process p) throws IOException {
- boolean success;
- InputStream in, err, input;
- if (p == null ) {
- throw new IOException("Null Process object: unabled to read input into buffer"); //$NON-NLS-1$
- }
- try {
- //We need to get the inputs before calling waitFor
- input = p.getInputStream();
- err = p.getErrorStream();
- if (success = (p.waitFor() == 0)) {
- in = input;
- } else {
- in = err;
- }
- int ch;
- while ((ch = in.read()) != -1) {
- out.append((char) ch);
- }
- if (!success) {
- throw new IOException(out.toString());
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
+ private void readIntoBuffer(StringBuffer out, Process p) throws IOException {
+ boolean success;
+ InputStream in, err, input;
+ if (p == null ) {
+ throw new IOException("Null Process object: unabled to read input into buffer"); //$NON-NLS-1$
+ }
+ try {
+ //We need to get the inputs before calling waitFor
+ input = p.getInputStream();
+ err = p.getErrorStream();
+ if (success = (p.waitFor() == 0)) {
+ in = input;
+ } else {
+ in = err;
+ }
+ int ch;
+ while ((ch = in.read()) != -1) {
+ out.append((char) ch);
+ }
+ if (!success) {
+ throw new IOException(out.toString());
+ }
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindCoreParser.java b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindCoreParser.java
index 7717d7becb..766cf759d0 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindCoreParser.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindCoreParser.java
@@ -24,90 +24,90 @@ import org.eclipse.linuxtools.valgrind.core.IValgrindMessage;
import org.eclipse.linuxtools.valgrind.core.ValgrindParserUtils;
public class ValgrindCoreParser {
- private static final String AT = "at"; //$NON-NLS-1$
- private static final String BY = "by"; //$NON-NLS-1$
+ private static final String AT = "at"; //$NON-NLS-1$
+ private static final String BY = "by"; //$NON-NLS-1$
- private List<IValgrindMessage> messages;
- private int pid;
- private ILaunch launch;
+ private List<IValgrindMessage> messages;
+ private int pid;
+ private ILaunch launch;
- public ValgrindCoreParser(File inputFile, ILaunch launch) throws IOException {
- this.launch = launch;
- // keep track of nested messages and their corresponding indents
- Stack<IValgrindMessage> messageStack = new Stack<>();
- Stack<Integer> indentStack = new Stack<>();
- messages = new ArrayList<>();
+ public ValgrindCoreParser(File inputFile, ILaunch launch) throws IOException {
+ this.launch = launch;
+ // keep track of nested messages and their corresponding indents
+ Stack<IValgrindMessage> messageStack = new Stack<>();
+ Stack<Integer> indentStack = new Stack<>();
+ messages = new ArrayList<>();
- try (BufferedReader br = new BufferedReader(new FileReader(inputFile))) {
- pid = ValgrindParserUtils.parsePID(inputFile.getName(), CommandLineConstants.LOG_PREFIX);
- String line;
- while ((line = br.readLine()) != null) {
- // remove PID string
- // might encounter warnings also #325130
- // fixed #423371 - handle timestamp (e.g. ==00:00:00:01.175 52756728==)
- line = line.replaceFirst("==([\\d:\\.]+\\s)?\\d+==|\\*\\*\\d+\\*\\*", ""); //$NON-NLS-1$ //$NON-NLS-2$
+ try (BufferedReader br = new BufferedReader(new FileReader(inputFile))) {
+ pid = ValgrindParserUtils.parsePID(inputFile.getName(), CommandLineConstants.LOG_PREFIX);
+ String line;
+ while ((line = br.readLine()) != null) {
+ // remove PID string
+ // might encounter warnings also #325130
+ // fixed #423371 - handle timestamp (e.g. ==00:00:00:01.175 52756728==)
+ line = line.replaceFirst("==([\\d:\\.]+\\s)?\\d+==|\\*\\*\\d+\\*\\*", ""); //$NON-NLS-1$ //$NON-NLS-2$
- int indent;
- for (indent = 0; indent < line.length()
- && line.charAt(indent) == ' '; indent++){}
+ int indent;
+ for (indent = 0; indent < line.length()
+ && line.charAt(indent) == ' '; indent++){}
- line = line.trim();
- if (!line.isEmpty()) {
- /*
- * indent == 1 -> top level message
- * indent > 1 -> child message
- * indent == 0 -> should not occur
- */
- if (indent == 1) {
- // top-level message, clear stacks
- IValgrindMessage message = getMessage(null, line);
- messages.add(message);
- messageStack.clear();
- messageStack.push(message);
- indentStack.clear();
- indentStack.push(indent);
- }
- else if (indent > 1) {
- /**
- * We assume that an indented child message has a
- * parent, but this may not be the case.
- * See BZ #360225
- */
- if (indentStack.isEmpty()){
- // pretend this is a top level message
- IValgrindMessage message = getMessage(null, line);
- messages.add(message);
- messageStack.clear();
- messageStack.push(message);
- indentStack.clear();
- indentStack.push(1);
- }else{
- // find this message's parent
- while (indent <= indentStack.peek()) {
- messageStack.pop();
- indentStack.pop();
- }
-
- messageStack.push(getMessage(messageStack.peek(), line));
- indentStack.push(indent);
- }
- }
- }
- }
- }
- }
+ line = line.trim();
+ if (!line.isEmpty()) {
+ /*
+ * indent == 1 -> top level message
+ * indent > 1 -> child message
+ * indent == 0 -> should not occur
+ */
+ if (indent == 1) {
+ // top-level message, clear stacks
+ IValgrindMessage message = getMessage(null, line);
+ messages.add(message);
+ messageStack.clear();
+ messageStack.push(message);
+ indentStack.clear();
+ indentStack.push(indent);
+ }
+ else if (indent > 1) {
+ /**
+ * We assume that an indented child message has a
+ * parent, but this may not be the case.
+ * See BZ #360225
+ */
+ if (indentStack.isEmpty()){
+ // pretend this is a top level message
+ IValgrindMessage message = getMessage(null, line);
+ messages.add(message);
+ messageStack.clear();
+ messageStack.push(message);
+ indentStack.clear();
+ indentStack.push(1);
+ }else{
+ // find this message's parent
+ while (indent <= indentStack.peek()) {
+ messageStack.pop();
+ indentStack.pop();
+ }
- private IValgrindMessage getMessage(IValgrindMessage message, String line) {
- if (line.startsWith(AT) || line.startsWith(BY)) {
- Object[] parsed = ValgrindParserUtils.parseFilename(line);
- String filename = (String) parsed[0];
- int lineNo = (Integer) parsed[1];
- return new ValgrindStackFrame(message, line, launch, filename, lineNo);
- }
- return new ValgrindError(message, line, launch, pid);
- }
-
- public IValgrindMessage[] getMessages() {
- return messages.toArray(new IValgrindMessage[messages.size()]);
- }
+ messageStack.push(getMessage(messageStack.peek(), line));
+ indentStack.push(indent);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private IValgrindMessage getMessage(IValgrindMessage message, String line) {
+ if (line.startsWith(AT) || line.startsWith(BY)) {
+ Object[] parsed = ValgrindParserUtils.parseFilename(line);
+ String filename = (String) parsed[0];
+ int lineNo = (Integer) parsed[1];
+ return new ValgrindStackFrame(message, line, launch, filename, lineNo);
+ }
+ return new ValgrindError(message, line, launch, pid);
+ }
+
+ public IValgrindMessage[] getMessages() {
+ return messages.toArray(new IValgrindMessage[messages.size()]);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindError.java b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindError.java
index fcd33df24d..5043f48725 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindError.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindError.java
@@ -15,15 +15,15 @@ import org.eclipse.linuxtools.valgrind.core.IValgrindMessage;
public class ValgrindError extends AbstractValgrindMessage {
- protected int pid;
-
- public ValgrindError(IValgrindMessage message, String text, ILaunch launch, int pid) {
- super(message, text, launch);
- this.pid = pid;
- }
-
- @Override
- public String getText() {
- return super.getText() + " [PID: " + pid + "]"; //$NON-NLS-1$ //$NON-NLS-2$
- }
+ protected int pid;
+
+ public ValgrindError(IValgrindMessage message, String text, ILaunch launch, int pid) {
+ super(message, text, launch);
+ this.pid = pid;
+ }
+
+ @Override
+ public String getText() {
+ return super.getText() + " [PID: " + pid + "]"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindInfo.java b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindInfo.java
index c0c1af8f42..33afc3adeb 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindInfo.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindInfo.java
@@ -16,8 +16,8 @@ import org.eclipse.linuxtools.valgrind.core.IValgrindMessage;
public class ValgrindInfo extends AbstractValgrindMessage {
- public ValgrindInfo(IValgrindMessage parent, String text, ILaunch launch) {
- super(parent, text, launch);
- }
+ public ValgrindInfo(IValgrindMessage parent, String text, ILaunch launch) {
+ super(parent, text, launch);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindStackFrame.java b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindStackFrame.java
index 56f1bca42a..d29281a036 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindStackFrame.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/internal/valgrind/core/ValgrindStackFrame.java
@@ -7,28 +7,28 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.core;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.linuxtools.valgrind.core.IValgrindMessage;
public class ValgrindStackFrame extends AbstractValgrindMessage {
- protected String file;
- protected int line;
-
- public ValgrindStackFrame(IValgrindMessage message, String text, ILaunch launch, String file, int line) {
- super(message, text, launch);
- this.file = file;
- this.line = line;
- }
-
- public String getFile() {
- return file;
- }
-
- public int getLine() {
- return line;
- }
-
+ protected String file;
+ protected int line;
+
+ public ValgrindStackFrame(IValgrindMessage message, String text, ILaunch launch, String file, int line) {
+ super(message, text, launch);
+ this.file = file;
+ this.line = line;
+ }
+
+ public String getFile() {
+ return file;
+ }
+
+ public int getLine() {
+ return line;
+ }
+
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/CommandLineConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/CommandLineConstants.java
index 292e7fba48..8e099c8663 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/CommandLineConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/CommandLineConstants.java
@@ -11,30 +11,30 @@
package org.eclipse.linuxtools.valgrind.core;
public interface CommandLineConstants {
- String OPT_TOOL = "--tool"; //$NON-NLS-1$
+ String OPT_TOOL = "--tool"; //$NON-NLS-1$
- String OPT_XML = "--xml"; //$NON-NLS-1$
- String OPT_LOGFILE = "--log-file"; //$NON-NLS-1$
- String OPT_QUIET = "-q"; //$NON-NLS-1$
- String OPT_VERSION = "--version"; //$NON-NLS-1$
+ String OPT_XML = "--xml"; //$NON-NLS-1$
+ String OPT_LOGFILE = "--log-file"; //$NON-NLS-1$
+ String OPT_QUIET = "-q"; //$NON-NLS-1$
+ String OPT_VERSION = "--version"; //$NON-NLS-1$
- String OPT_TRACECHILD = "--trace-children"; //$NON-NLS-1$
- String OPT_CHILDSILENT = "--child-silent-after-fork"; //$NON-NLS-1$
- String OPT_TRACKFDS = "--track-fds"; //$NON-NLS-1$
- String OPT_TIMESTAMP = "--time-stamp"; //$NON-NLS-1$
- String OPT_FREERES = "--run-libc-freeres"; //$NON-NLS-1$
- String OPT_DEMANGLE = "--demangle"; //$NON-NLS-1$
- String OPT_NUMCALLERS = "--num-callers"; //$NON-NLS-1$
- String OPT_ERRLIMIT = "--error-limit"; //$NON-NLS-1$
- String OPT_BELOWMAIN = "--show-below-main"; //$NON-NLS-1$
- String OPT_MAXFRAME = "--max-stackframe"; //$NON-NLS-1$
- String OPT_SUPPFILE = "--suppressions"; //$NON-NLS-1$
+ String OPT_TRACECHILD = "--trace-children"; //$NON-NLS-1$
+ String OPT_CHILDSILENT = "--child-silent-after-fork"; //$NON-NLS-1$
+ String OPT_TRACKFDS = "--track-fds"; //$NON-NLS-1$
+ String OPT_TIMESTAMP = "--time-stamp"; //$NON-NLS-1$
+ String OPT_FREERES = "--run-libc-freeres"; //$NON-NLS-1$
+ String OPT_DEMANGLE = "--demangle"; //$NON-NLS-1$
+ String OPT_NUMCALLERS = "--num-callers"; //$NON-NLS-1$
+ String OPT_ERRLIMIT = "--error-limit"; //$NON-NLS-1$
+ String OPT_BELOWMAIN = "--show-below-main"; //$NON-NLS-1$
+ String OPT_MAXFRAME = "--max-stackframe"; //$NON-NLS-1$
+ String OPT_SUPPFILE = "--suppressions"; //$NON-NLS-1$
- // 3.4.0 specific
- String OPT_MAINSTACK = "--main-stacksize"; //$NON-NLS-1$
+ // 3.4.0 specific
+ String OPT_MAINSTACK = "--main-stacksize"; //$NON-NLS-1$
- // 3.6.0 specific
- String OPT_DSYMUTIL = "--dsymutil"; //$NON-NLS-1$
+ // 3.6.0 specific
+ String OPT_DSYMUTIL = "--dsymutil"; //$NON-NLS-1$
- String LOG_PREFIX = "valgrind_"; //$NON-NLS-1$
+ String LOG_PREFIX = "valgrind_"; //$NON-NLS-1$
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/IValgrindMessage.java b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/IValgrindMessage.java
index 5ac9a694e8..4cbc75a21a 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/IValgrindMessage.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/IValgrindMessage.java
@@ -14,14 +14,14 @@ import org.eclipse.debug.core.ILaunch;
public interface IValgrindMessage {
- IValgrindMessage getParent();
+ IValgrindMessage getParent();
- IValgrindMessage[] getChildren();
+ IValgrindMessage[] getChildren();
- String getText();
-
- ILaunch getLaunch();
+ String getText();
- void addChild(IValgrindMessage child);
+ ILaunch getLaunch();
+
+ void addChild(IValgrindMessage child);
} \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/ValgrindParserUtils.java b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/ValgrindParserUtils.java
index f0f5da6fac..7e435780dd 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/ValgrindParserUtils.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.core/src/org/eclipse/linuxtools/valgrind/core/ValgrindParserUtils.java
@@ -20,130 +20,130 @@ import org.eclipse.osgi.util.NLS;
* parsers.
*/
public final class ValgrindParserUtils {
- private static final String DOT = "."; //$NON-NLS-1$
- private static final String EMPTY_STRING = ""; //$NON-NLS-1$
+ private static final String DOT = "."; //$NON-NLS-1$
+ private static final String EMPTY_STRING = ""; //$NON-NLS-1$
- /**
- * Retrieves ARGUMENT portion of [OPTION][DELIMITER][ARGUMENT]
- * where ARGUMENT is a Long
- * @param line - the line to parse
- * @param delim - the DELIMITER to separate on
- * @return Long value of ARGUMENT
- * @throws IOException
- */
- public static Long parseLongValue(String line, String delim)
- throws IOException {
- Long result = null;
- String[] parts = line.split(delim, 2);
- if (parts.length > 1 && isNumber(parts[1])) {
- result = Long.parseLong(parts[1]);
- } else {
- fail(line);
- }
- return result;
- }
+ /**
+ * Retrieves ARGUMENT portion of [OPTION][DELIMITER][ARGUMENT]
+ * where ARGUMENT is a Long
+ * @param line - the line to parse
+ * @param delim - the DELIMITER to separate on
+ * @return Long value of ARGUMENT
+ * @throws IOException
+ */
+ public static Long parseLongValue(String line, String delim)
+ throws IOException {
+ Long result = null;
+ String[] parts = line.split(delim, 2);
+ if (parts.length > 1 && isNumber(parts[1])) {
+ result = Long.parseLong(parts[1]);
+ } else {
+ fail(line);
+ }
+ return result;
+ }
- /**
- * Retrieves ARGUMENT portion of [OPTION][DELIMITER][ARGUMENT]
- * where ARGUMENT is a String
- * @param line - the line to parse
- * @param delim - the DELIMITER to separate fields
- * @return String value of ARGUMENT
- * @throws IOException
- */
- public static String parseStrValue(String line, String delim)
- throws IOException {
- String result = null;
- String[] parts = line.split(delim, 2);
- if (parts.length > 1) {
- result = parts[1];
- } else {
- fail(line);
- }
- return result;
- }
-
- /**
- * Retrieves PID from filename with format [PREFIX][PID].[EXTENSION]
- * @param filename - the file name to parse
- * @param prefix - the prefix of the filename up to the PID
- * @return - the PID portion of the filename as an Integer
- * @throws IOException
- */
- public static Integer parsePID(String filename, String prefix) throws IOException {
- String pidstr = filename.substring(prefix.length(), filename.lastIndexOf(DOT));
- if (isNumber(pidstr)) {
- return Integer.valueOf(pidstr);
- } else {
- throw new IOException("Cannot parse PID from output file"); //$NON-NLS-1$
- }
- }
+ /**
+ * Retrieves ARGUMENT portion of [OPTION][DELIMITER][ARGUMENT]
+ * where ARGUMENT is a String
+ * @param line - the line to parse
+ * @param delim - the DELIMITER to separate fields
+ * @return String value of ARGUMENT
+ * @throws IOException
+ */
+ public static String parseStrValue(String line, String delim)
+ throws IOException {
+ String result = null;
+ String[] parts = line.split(delim, 2);
+ if (parts.length > 1) {
+ result = parts[1];
+ } else {
+ fail(line);
+ }
+ return result;
+ }
- /**
- * Throws an IOException indicating parsing failed on a given line
- * @param line - line that parsing failed
- * @throws IOException
- */
- public static void fail(String line) throws IOException {
- throw new IOException(NLS.bind(Messages.getString("AbstractValgrindTextParser.Parsing_output_failed"), line)); //$NON-NLS-1$
- }
+ /**
+ * Retrieves PID from filename with format [PREFIX][PID].[EXTENSION]
+ * @param filename - the file name to parse
+ * @param prefix - the prefix of the filename up to the PID
+ * @return - the PID portion of the filename as an Integer
+ * @throws IOException
+ */
+ public static Integer parsePID(String filename, String prefix) throws IOException {
+ String pidstr = filename.substring(prefix.length(), filename.lastIndexOf(DOT));
+ if (isNumber(pidstr)) {
+ return Integer.valueOf(pidstr);
+ } else {
+ throw new IOException("Cannot parse PID from output file"); //$NON-NLS-1$
+ }
+ }
- /**
- * Determines if argument is a number
- * @param string - argument to test
- * @return - true if argument is a number
- */
- public static boolean isNumber(String string) {
- boolean result = true;
- char[] chars = string.toCharArray();
- for (int i = 0; i < chars.length; i++) {
- if (!Character.isDigit(chars[i])) {
- result = false;
- }
- }
- return result;
- }
+ /**
+ * Throws an IOException indicating parsing failed on a given line
+ * @param line - line that parsing failed
+ * @throws IOException
+ */
+ public static void fail(String line) throws IOException {
+ throw new IOException(NLS.bind(Messages.getString("AbstractValgrindTextParser.Parsing_output_failed"), line)); //$NON-NLS-1$
+ }
- /**
- * Parses string ending with format ([FILE]:[LINE MODULE])
- * Assumes syntax is: "\(.*:[0-9]+(\s.+)?\)$"
- * @param line - String with the above criteria
- * @return a tuple of [String filename, Integer line]
- */
- public static Object[] parseFilename(String line) {
- String filename = null;
- int lineNo = 0;
-
- int ix = line.lastIndexOf('(');
- if (ix >= 0) {
- String part = line.substring(ix, line.length());
- part = part.substring(1, part.length() - 1); // remove leading and trailing parentheses
- if ((ix = part.lastIndexOf(':')) >= 0) {
- String strLineNo = part.substring(ix + 1);
- if (isNumber(strLineNo)) {
- lineNo = Integer.parseInt(strLineNo);
- filename = part.substring(0, ix);
- } else {
- // handle format: (FILE:LINE MODULE)
- int ix1 = strLineNo.indexOf(' ');
- if (ix1 > 0) {
- strLineNo = strLineNo.substring(0, ix1);
- if (isNumber(strLineNo)) {
- lineNo = Integer.parseInt(strLineNo);
- filename = part.substring(0, ix);
- }
- }
- }
- } else {
- // check for "in " token (lib, with symbol)
- part = part.replaceFirst("^in ", EMPTY_STRING); //$NON-NLS-1$
- // check for "within " token (lib, without symbol)
- part = part.replaceFirst("^within ", EMPTY_STRING); //$NON-NLS-1$
- filename = part; // library, no line number
- }
- }
-
- return new Object[] { filename, lineNo };
- }
+ /**
+ * Determines if argument is a number
+ * @param string - argument to test
+ * @return - true if argument is a number
+ */
+ public static boolean isNumber(String string) {
+ boolean result = true;
+ char[] chars = string.toCharArray();
+ for (int i = 0; i < chars.length; i++) {
+ if (!Character.isDigit(chars[i])) {
+ result = false;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Parses string ending with format ([FILE]:[LINE MODULE])
+ * Assumes syntax is: "\(.*:[0-9]+(\s.+)?\)$"
+ * @param line - String with the above criteria
+ * @return a tuple of [String filename, Integer line]
+ */
+ public static Object[] parseFilename(String line) {
+ String filename = null;
+ int lineNo = 0;
+
+ int ix = line.lastIndexOf('(');
+ if (ix >= 0) {
+ String part = line.substring(ix, line.length());
+ part = part.substring(1, part.length() - 1); // remove leading and trailing parentheses
+ if ((ix = part.lastIndexOf(':')) >= 0) {
+ String strLineNo = part.substring(ix + 1);
+ if (isNumber(strLineNo)) {
+ lineNo = Integer.parseInt(strLineNo);
+ filename = part.substring(0, ix);
+ } else {
+ // handle format: (FILE:LINE MODULE)
+ int ix1 = strLineNo.indexOf(' ');
+ if (ix1 > 0) {
+ strLineNo = strLineNo.substring(0, ix1);
+ if (isNumber(strLineNo)) {
+ lineNo = Integer.parseInt(strLineNo);
+ filename = part.substring(0, ix);
+ }
+ }
+ }
+ } else {
+ // check for "in " token (lib, with symbol)
+ part = part.replaceFirst("^in ", EMPTY_STRING); //$NON-NLS-1$
+ // check for "within " token (lib, without symbol)
+ part = part.replaceFirst("^within ", EMPTY_STRING); //$NON-NLS-1$
+ filename = part; // library, no line number
+ }
+ }
+
+ return new Object[] { filename, lineNo };
+ }
} \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.doc/build-helper.xml b/valgrind/org.eclipse.linuxtools.valgrind.doc/build-helper.xml
index edb8d3f84c..e1650e595c 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.doc/build-helper.xml
+++ b/valgrind/org.eclipse.linuxtools.valgrind.doc/build-helper.xml
@@ -1,60 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="org.eclipse.linuxtools.valgrind.doc" default="all">
- <description>
+ <description>
Generate Eclipse help content for the Linux Tools Valgrind user guide
</description>
- <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
+ <property name="help.doc.url.base" value="http://wiki.eclipse.org" />
- <path id="wikitext.tasks.classpath">
- <!-- Replace dir with the dir you have wikitext installed into.-->
- <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
- <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
- </fileset>
- </path>
+ <path id="wikitext.tasks.classpath">
+ <!-- Replace dir with the dir you have wikitext installed into.-->
+ <fileset dir="/usr/share/eclipse/dropins/mylyn/eclipse/plugins">
+ <include name="org.eclipse.mylyn.wikitext.*core*.jar" />
+ </fileset>
+ </path>
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
- <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/wikitext/core/util/anttask/tasks.properties" />
+ <taskdef classpathref="wikitext.tasks.classpath" resource="org/eclipse/mylyn/internal/wikitext/mediawiki/core/tasks/tasks.properties" />
- <target name="all" description="Generate Eclipse help content for the Linux Tools Valgrind user guide">
- <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="Valgrind User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*, Infobox">
+ <target name="all" description="Generate Eclipse help content for the Linux Tools Valgrind user guide">
+ <mediawiki-to-eclipse-help wikiBaseUrl="${help.doc.url.base}" title="Valgrind User Guide" formatoutput="true" dest="." templateExcludes="*eclipseproject*, Infobox">
- <path name="Linux_Tools_Project/Valgrind/User_Guide" title="Valgrind User Guide" generateToc="false" />
- <stylesheet url="book.css" />
- <pageAppendum>
- = Updating This Document =
+ <path name="Linux_Tools_Project/Valgrind/User_Guide" title="Valgrind User Guide" generateToc="false" />
+ <stylesheet url="book.css" />
+ <pageAppendum>
+ = Updating This Document =
- This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
- http://wiki.eclipse.org/Linux_Tools_Project/Valgrind/User_Guide .
- </pageAppendum>
- </mediawiki-to-eclipse-help>
- <antcall target="test" />
- </target>
+ This document is maintained in a collaborative wiki. If you wish to update or modify this document please visit
+ http://wiki.eclipse.org/Linux_Tools_Project/Valgrind/User_Guide .
+ </pageAppendum>
+ </mediawiki-to-eclipse-help>
+ <antcall target="test" />
+ </target>
- <target name="test" description="verify that all of the HTML files are well-formed XML">
- <echo level="info">
+ <target name="test" description="verify that all of the HTML files are well-formed XML">
+ <echo level="info">
Validating help content XML and HTML files: The Eclipse help system expects well-formed XML
-
+
If validation fails it is because either:
-
+
* the userguide source code is poorly formed, or
* the WikiText MediaWiki parser has a bug
-
+
Problems with userguide source are usually caused by improper use of HTML markup in the MediaWiki source,
or inadvertently starting a line with a space character (in MediaWiki this starts a preformatted block)
- </echo>
-
- <!--
- Don't bother with DTD validation: we only care if the files are well-formed.
- We therefore provide an empty DTD
- -->
- <echo file="tmp/__empty.dtd" message="" />
- <xmlvalidate lenient="true">
- <fileset dir="Linux_Tools_Project">
- <include name="**/*.html" />
- </fileset>
- <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
- </xmlvalidate>
- <delete dir="tmp" />
- </target>
+ </echo>
+
+ <!--
+ Don't bother with DTD validation: we only care if the files are well-formed.
+ We therefore provide an empty DTD
+ -->
+ <echo file="tmp/__empty.dtd" message="" />
+ <xmlvalidate lenient="true">
+ <fileset dir="Linux_Tools_Project">
+ <include name="**/*.html" />
+ </fileset>
+ <dtd publicid="-//W3C//DTD XHTML 1.0 Transitional//EN" location="${basedir}/tmp/__empty.dtd" />
+ </xmlvalidate>
+ <delete dir="tmp" />
+ </target>
</project>
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.doc/toc-doc.xml b/valgrind/org.eclipse.linuxtools.valgrind.doc/toc-doc.xml
index 56fd4f24fe..0eabae91c1 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.doc/toc-doc.xml
+++ b/valgrind/org.eclipse.linuxtools.valgrind.doc/toc-doc.xml
@@ -1,5 +1,5 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/Valgrind/User_Guide/User-Guide.html" label="Valgrind User Guide">
-<link toc="toc.xml" />
+<link toc="toc.xml" />
<topic href="doc/notices.html" label="Legal"> </topic>
</toc>
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.doc/toc.xml b/valgrind/org.eclipse.linuxtools.valgrind.doc/toc.xml
index 700fcc83ad..2bd170f7c0 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.doc/toc.xml
+++ b/valgrind/org.eclipse.linuxtools.valgrind.doc/toc.xml
@@ -1,41 +1,41 @@
<?xml version='1.0' encoding='utf-8' ?>
<toc topic="Linux_Tools_Project/Valgrind/User_Guide/User-Guide.html" label="Valgrind User Guide">
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/User-Guide.html" label="Valgrind User Guide">
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/User-Guide.html" label="Overview"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Installing.html" label="Installing"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html" label="General Usage">
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#Configuring_a_Profile_Run" label="Configuring a Profile Run">
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#General_Options" label="General Options"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#Suppressions" label="Suppressions"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#Exporting_Valgrind_Data" label="Exporting Valgrind Data"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#Other_Operating_Systems" label="Other Operating Systems">
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#Mac_OS_X_10.6" label="Mac OS X 10.6"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#x86_64_Mac_OS" label="x86_64 Mac OS"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#All_Mac_OS" label="All Mac OS"></topic>
- </topic>
- </topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Memcheck.html" label="Using Memcheck">
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Memcheck.html#Analyzing_Memcheck_Profile_Results" label="Analyzing Memcheck Profile Results"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Memcheck.html#Configuring_a_Memcheck_Profile_Run" label="Configuring a Memcheck Profile Run"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Massif.html" label="Using Massif">
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Massif.html#Analyzing_Massif_Profile_Results" label="Analyzing Massif Profile Results"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Massif.html#Configuring_a_Massif_Profile_Run" label="Configuring a Massif Profile Run"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Cachegrind.html" label="Using Cachegrind">
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Cachegrind.html#Analyzing_Cachegrind_Profile_Results" label="Analyzing Cachegrind Profile Results"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Cachegrind.html#Configuring_a_Cachegrind_Profile_Run" label="Configuring a Cachegrind Profile Run"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Helgrind.html" label="Using Helgrind">
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Helgrind.html#Analyzing_Helgrind_Profile_Results" label="Analyzing Helgrind Profile Results"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Helgrind.html#Configuring_a_Helgrind_Profile_Run" label="Configuring a Helgrind Profile Run"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Remote-Valgrind.html" label="Remote Valgrind"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Special-Cases.html" label="Special Cases">
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Special-Cases.html#Encountering_Errors" label="Encountering Errors"></topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Special-Cases.html#Profiling_Child_Processes" label="Profiling Child Processes"></topic>
- </topic>
- <topic href="Linux_Tools_Project/Valgrind/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
- </topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/User-Guide.html" label="Valgrind User Guide">
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/User-Guide.html" label="Overview"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Installing.html" label="Installing"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html" label="General Usage">
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#Configuring_a_Profile_Run" label="Configuring a Profile Run">
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#General_Options" label="General Options"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#Suppressions" label="Suppressions"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#Exporting_Valgrind_Data" label="Exporting Valgrind Data"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#Other_Operating_Systems" label="Other Operating Systems">
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#Mac_OS_X_10.6" label="Mac OS X 10.6"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#x86_64_Mac_OS" label="x86_64 Mac OS"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/General-Usage.html#All_Mac_OS" label="All Mac OS"></topic>
+ </topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Memcheck.html" label="Using Memcheck">
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Memcheck.html#Analyzing_Memcheck_Profile_Results" label="Analyzing Memcheck Profile Results"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Memcheck.html#Configuring_a_Memcheck_Profile_Run" label="Configuring a Memcheck Profile Run"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Massif.html" label="Using Massif">
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Massif.html#Analyzing_Massif_Profile_Results" label="Analyzing Massif Profile Results"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Massif.html#Configuring_a_Massif_Profile_Run" label="Configuring a Massif Profile Run"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Cachegrind.html" label="Using Cachegrind">
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Cachegrind.html#Analyzing_Cachegrind_Profile_Results" label="Analyzing Cachegrind Profile Results"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Cachegrind.html#Configuring_a_Cachegrind_Profile_Run" label="Configuring a Cachegrind Profile Run"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Helgrind.html" label="Using Helgrind">
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Helgrind.html#Analyzing_Helgrind_Profile_Results" label="Analyzing Helgrind Profile Results"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Using-Helgrind.html#Configuring_a_Helgrind_Profile_Run" label="Configuring a Helgrind Profile Run"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Remote-Valgrind.html" label="Remote Valgrind"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Special-Cases.html" label="Special Cases">
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Special-Cases.html#Encountering_Errors" label="Encountering Errors"></topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Special-Cases.html#Profiling_Child_Processes" label="Profiling Child Processes"></topic>
+ </topic>
+ <topic href="Linux_Tools_Project/Valgrind/User_Guide/Updating-This-Document.html" label="Updating This Document"></topic>
+ </topic>
</toc> \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/AbstractHelgrindTest.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/AbstractHelgrindTest.java
index 7b25a5f96a..1a7c2152a2 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/AbstractHelgrindTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/AbstractHelgrindTest.java
@@ -15,8 +15,8 @@ import org.eclipse.linuxtools.internal.valgrind.tests.AbstractValgrindTest;
public abstract class AbstractHelgrindTest extends AbstractValgrindTest {
- @Override
- protected String getToolID() {
- return HelgrindPlugin.TOOL_ID;
- }
+ @Override
+ protected String getToolID() {
+ return HelgrindPlugin.TOOL_ID;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/BasicHelgrindTest.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/BasicHelgrindTest.java
index f360e73fbc..8b7ec4dfbe 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/BasicHelgrindTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/BasicHelgrindTest.java
@@ -26,24 +26,24 @@ import org.junit.Test;
public class BasicHelgrindTest extends AbstractHelgrindTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
- @Test
- public void testNumErrors() throws CoreException, URISyntaxException, IOException {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testHelgrindGeneric"); //$NON-NLS-1$
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+ @Test
+ public void testNumErrors() throws CoreException, URISyntaxException, IOException {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testHelgrindGeneric"); //$NON-NLS-1$
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- assertEquals(1, view.getMessages().length);
- assertEquals(view.getMessages()[0].getText(), Messages.getString("ValgrindOutputView.No_output")); //$NON-NLS-1$
- }
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ assertEquals(1, view.getMessages().length);
+ assertEquals(view.getMessages()[0].getText(), Messages.getString("ValgrindOutputView.No_output")); //$NON-NLS-1$
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/LaunchConfigTabTest.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/LaunchConfigTabTest.java
index 237ffcfe85..a34ebd23ab 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/LaunchConfigTabTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/LaunchConfigTabTest.java
@@ -34,126 +34,126 @@ import org.junit.Test;
public class LaunchConfigTabTest extends AbstractHelgrindTest {
- private ILaunchConfiguration config;
- private Shell testShell;
- private ValgrindOptionsTab tab;
- private HelgrindToolPage dynamicTab;
-
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
-
- config = createConfiguration(proj.getProject());
-
- testShell = new Shell(Display.getDefault());
- testShell.setLayout(new GridLayout());
- tab = new ValgrindOptionsTab();
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- tab.dispose();
- testShell.dispose();
- deleteProject(proj);
- super.tearDown();
- }
-
- private ILaunchConfigurationWorkingCopy initConfig() throws CoreException {
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- tab.setDefaults(wc);
- tab.createControl(testShell);
- tab.initializeFrom(config);
- int ix = Arrays.asList(tab.getTools()).indexOf(HelgrindPlugin.TOOL_ID);
- tab.getToolsCombo().select(ix);
- ILaunchConfigurationTab dynamicTab = tab.getDynamicTab();
- this.dynamicTab = (HelgrindToolPage) dynamicTab;
- return wc;
- }
-
- private ILaunch saveAndLaunch(ILaunchConfigurationWorkingCopy wc,
- String testName) throws CoreException, URISyntaxException, IOException {
- tab.performApply(wc);
- config = wc.doSave();
-
- ILaunch launch = doLaunch(config, testName);
- return launch;
- }
-
- @Test
- public void testDefaults() throws CoreException, URISyntaxException, IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- ILaunch launch = saveAndLaunch(wc, "testHelgrindGeneric"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--tool=helgrind")); //$NON-NLS-1$
- assertFalse(cmd.contains("--xml=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("-q")); //$NON-NLS-1$
- assertTrue(cmd.contains("--track-lockorders=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--history-level=full")); //$NON-NLS-1$
- assertTrue(cmd.contains("--conflict-cache-size=1000000")); //$NON-NLS-1$
- }
-
- @Test
- public void testTrackLockorders() throws CoreException, URISyntaxException, IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getLockordersButton().setSelection(false);
- tab.performApply(wc);
- wc.doSave();
-
- ILaunch launch = saveAndLaunch(wc, "testHelgrindGeneric"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--track-lockorders=no")); //$NON-NLS-1$
- }
-
- @Test
- public void testHistoryNone() throws CoreException, URISyntaxException, IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getHistoryCombo().setText("none");
- tab.performApply(wc);
- wc.doSave();
-
- ILaunch launch = saveAndLaunch(wc, "testHelgrindGeneric"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--history-level=none")); //$NON-NLS-1$
- }
-
- @Test
- public void testHistoryApprox() throws CoreException, URISyntaxException, IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getHistoryCombo().setText("approx");
- tab.performApply(wc);
- wc.doSave();
-
- ILaunch launch = saveAndLaunch(wc, "testHelgrindGeneric"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--history-level=approx")); //$NON-NLS-1$
- }
-
- @Test
- public void testConflictCacheSize() throws CoreException, URISyntaxException, IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
-
- dynamicTab.getCacheSizeSpinner().setSelection(123456);
- tab.performApply(wc);
- wc.doSave();
-
- ILaunch launch = saveAndLaunch(wc, "testHelgrindGeneric"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--conflict-cache-size=123456")); //$NON-NLS-1$
- }
+ private ILaunchConfiguration config;
+ private Shell testShell;
+ private ValgrindOptionsTab tab;
+ private HelgrindToolPage dynamicTab;
+
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("cpptest"); //$NON-NLS-1$
+
+ config = createConfiguration(proj.getProject());
+
+ testShell = new Shell(Display.getDefault());
+ testShell.setLayout(new GridLayout());
+ tab = new ValgrindOptionsTab();
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ tab.dispose();
+ testShell.dispose();
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ private ILaunchConfigurationWorkingCopy initConfig() throws CoreException {
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ tab.setDefaults(wc);
+ tab.createControl(testShell);
+ tab.initializeFrom(config);
+ int ix = Arrays.asList(tab.getTools()).indexOf(HelgrindPlugin.TOOL_ID);
+ tab.getToolsCombo().select(ix);
+ ILaunchConfigurationTab dynamicTab = tab.getDynamicTab();
+ this.dynamicTab = (HelgrindToolPage) dynamicTab;
+ return wc;
+ }
+
+ private ILaunch saveAndLaunch(ILaunchConfigurationWorkingCopy wc,
+ String testName) throws CoreException, URISyntaxException, IOException {
+ tab.performApply(wc);
+ config = wc.doSave();
+
+ ILaunch launch = doLaunch(config, testName);
+ return launch;
+ }
+
+ @Test
+ public void testDefaults() throws CoreException, URISyntaxException, IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ ILaunch launch = saveAndLaunch(wc, "testHelgrindGeneric"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--tool=helgrind")); //$NON-NLS-1$
+ assertFalse(cmd.contains("--xml=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("-q")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--track-lockorders=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--history-level=full")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--conflict-cache-size=1000000")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testTrackLockorders() throws CoreException, URISyntaxException, IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getLockordersButton().setSelection(false);
+ tab.performApply(wc);
+ wc.doSave();
+
+ ILaunch launch = saveAndLaunch(wc, "testHelgrindGeneric"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--track-lockorders=no")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testHistoryNone() throws CoreException, URISyntaxException, IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getHistoryCombo().setText("none");
+ tab.performApply(wc);
+ wc.doSave();
+
+ ILaunch launch = saveAndLaunch(wc, "testHelgrindGeneric"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--history-level=none")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testHistoryApprox() throws CoreException, URISyntaxException, IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getHistoryCombo().setText("approx");
+ tab.performApply(wc);
+ wc.doSave();
+
+ ILaunch launch = saveAndLaunch(wc, "testHelgrindGeneric"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--history-level=approx")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testConflictCacheSize() throws CoreException, URISyntaxException, IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+
+ dynamicTab.getCacheSizeSpinner().setSelection(123456);
+ tab.performApply(wc);
+ wc.doSave();
+
+ ILaunch launch = saveAndLaunch(wc, "testHelgrindGeneric"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--conflict-cache-size=123456")); //$NON-NLS-1$
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/ShortcutTest.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/ShortcutTest.java
index 8f0541fad5..0f3c4e1b6d 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/ShortcutTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/ShortcutTest.java
@@ -30,61 +30,61 @@ import org.junit.Test;
public class ShortcutTest extends AbstractHelgrindTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
- @Test
- public void testShortcutSelection() throws CoreException {
- ValgrindTestHelgrindLaunchShortcut shortcut = new ValgrindTestHelgrindLaunchShortcut();
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+ @Test
+ public void testShortcutSelection() throws CoreException {
+ ValgrindTestHelgrindLaunchShortcut shortcut = new ValgrindTestHelgrindLaunchShortcut();
- shortcut.launch(new StructuredSelection(proj.getProject()), ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration config = shortcut.getConfig();
+ shortcut.launch(new StructuredSelection(proj.getProject()), ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration config = shortcut.getConfig();
- compareWithDefaults(config);
- }
- @Test
- public void testShortcutEditor() throws CoreException {
- ValgrindTestHelgrindLaunchShortcut shortcut = new ValgrindTestHelgrindLaunchShortcut();
+ compareWithDefaults(config);
+ }
+ @Test
+ public void testShortcutEditor() throws CoreException {
+ ValgrindTestHelgrindLaunchShortcut shortcut = new ValgrindTestHelgrindLaunchShortcut();
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- IFile file = proj.getProject().getFile("test.c"); //$NON-NLS-1$
- IEditorPart editor = IDE.openEditor(page, file);
+ IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
+ IFile file = proj.getProject().getFile("test.c"); //$NON-NLS-1$
+ IEditorPart editor = IDE.openEditor(page, file);
- assertNotNull(editor);
+ assertNotNull(editor);
- shortcut.launch(editor, ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration config = shortcut.getConfig();
+ shortcut.launch(editor, ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration config = shortcut.getConfig();
- compareWithDefaults(config);
- }
- @Test
- public void testShortcutExistingConfig() throws CoreException {
- ILaunchConfiguration prev = createConfiguration(proj.getProject());
+ compareWithDefaults(config);
+ }
+ @Test
+ public void testShortcutExistingConfig() throws CoreException {
+ ILaunchConfiguration prev = createConfiguration(proj.getProject());
- ValgrindTestHelgrindLaunchShortcut shortcut = new ValgrindTestHelgrindLaunchShortcut();
- shortcut.launch(new StructuredSelection(proj.getProject()), ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration current = shortcut.getConfig();
+ ValgrindTestHelgrindLaunchShortcut shortcut = new ValgrindTestHelgrindLaunchShortcut();
+ shortcut.launch(new StructuredSelection(proj.getProject()), ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration current = shortcut.getConfig();
- assertEquals(prev, current);
- }
+ assertEquals(prev, current);
+ }
- private void compareWithDefaults(ILaunchConfiguration config)
- throws CoreException {
- // tests launch in foreground, this is not typical
- ILaunchConfiguration defaults = createConfiguration(proj.getProject());
- ILaunchConfigurationWorkingCopy wc = defaults.getWorkingCopy();
- wc.removeAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND);
- wc.doSave();
+ private void compareWithDefaults(ILaunchConfiguration config)
+ throws CoreException {
+ // tests launch in foreground, this is not typical
+ ILaunchConfiguration defaults = createConfiguration(proj.getProject());
+ ILaunchConfigurationWorkingCopy wc = defaults.getWorkingCopy();
+ wc.removeAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND);
+ wc.doSave();
- // Compare launch config with defaults
- assertEquals(config.getAttributes(), defaults.getAttributes());
- }
+ // Compare launch config with defaults
+ assertEquals(config.getAttributes(), defaults.getAttributes());
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/ValgrindTestHelgrindLaunchShortcut.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/ValgrindTestHelgrindLaunchShortcut.java
index 21c6096464..16659775ce 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/ValgrindTestHelgrindLaunchShortcut.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/helgrind/tests/ValgrindTestHelgrindLaunchShortcut.java
@@ -17,14 +17,14 @@ import org.eclipse.linuxtools.internal.valgrind.helgrind.HelgrindLaunchShortcut;
public class ValgrindTestHelgrindLaunchShortcut extends HelgrindLaunchShortcut {
- private ILaunchConfiguration config;
+ private ILaunchConfiguration config;
- @Override
- public void launch(IBinary bin, String mode) {
- config = findLaunchConfiguration(bin, mode);
- }
-
- public ILaunchConfiguration getConfig() {
- return config;
- }
+ @Override
+ public void launch(IBinary bin, String mode) {
+ config = findLaunchConfiguration(bin, mode);
+ }
+
+ public ILaunchConfiguration getConfig() {
+ return config;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/plugin.xml b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/plugin.xml
index a9474f90d2..0967eb4ae2 100755
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/plugin.xml
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/plugin.xml
@@ -30,6 +30,6 @@
tabgroup="org.eclipse.linuxtools.internal.valgrind.helgrind.HelgrindLaunchConfigurationTabGroup"
type="memory">
</provider>
- </extension>
+ </extension>
</plugin>
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindCommandConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindCommandConstants.java
index 3895221706..e5209f9934 100755
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindCommandConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindCommandConstants.java
@@ -19,10 +19,10 @@ package org.eclipse.linuxtools.internal.valgrind.helgrind;
* none: only show trace for one thread in a race (fastest)
* --conflict-cache-size=N size of 'full' history cache [1000000]
*/
-public final class HelgrindCommandConstants
+public final class HelgrindCommandConstants
{
- public static final String OPT_TRACK_LOCKORDERS = "--track-lockorders"; //$NON-NLS-1$
- public static final String OPT_HISTORY_LEVEL = "--history-level"; //$NON-NLS-1$
- public static final String OPT_CONFLICT_CACHE_SIZE = "--conflict-cache-size"; //$NON-NLS-1$
+ public static final String OPT_TRACK_LOCKORDERS = "--track-lockorders"; //$NON-NLS-1$
+ public static final String OPT_HISTORY_LEVEL = "--history-level"; //$NON-NLS-1$
+ public static final String OPT_CONFLICT_CACHE_SIZE = "--conflict-cache-size"; //$NON-NLS-1$
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchConfigurationTabGroup.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchConfigurationTabGroup.java
index 5ac58bbacf..15f01ffbe3 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchConfigurationTabGroup.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchConfigurationTabGroup.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Red Hat Inc. - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.helgrind;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
@@ -15,13 +15,13 @@ import org.eclipse.linuxtools.internal.valgrind.launch.ValgrindSingleToolOptions
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTabGroup;
public class HelgrindLaunchConfigurationTabGroup extends
- ProfileLaunchConfigurationTabGroup {
+ ProfileLaunchConfigurationTabGroup {
+
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ return new AbstractLaunchConfigurationTab[] {
+ new ValgrindSingleToolOptionsTab(HelgrindPlugin.TOOL_ID)
+ };
+ }
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- return new AbstractLaunchConfigurationTab[] {
- new ValgrindSingleToolOptionsTab(HelgrindPlugin.TOOL_ID)
- };
- }
-
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchDelegate.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchDelegate.java
index bd2448fb7f..23c6e14e36 100755
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchDelegate.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchDelegate.java
@@ -24,25 +24,25 @@ import org.eclipse.linuxtools.valgrind.ui.IValgrindToolView;
import org.osgi.framework.Version;
public class HelgrindLaunchDelegate implements IValgrindLaunchDelegate {
- private static final String EQUALS = "="; //$NON-NLS-1$
- private static final String NO = "no"; //$NON-NLS-1$
- private static final String YES = "yes"; //$NON-NLS-1$
-
- @Override
- public void handleLaunch(ILaunchConfiguration config, ILaunch launch, IPath outDir, IProgressMonitor monitor) {
- }
-
- @Override
- public String[] getCommandArray(ILaunchConfiguration config, Version ver, IPath logDir) throws CoreException {
- ArrayList<String> opts = new ArrayList<>();
-
- opts.add(HelgrindCommandConstants.OPT_TRACK_LOCKORDERS + EQUALS + (config.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_LOCKORDERS, HelgrindLaunchConstants.DEFAULT_HELGRIND_LOCKORDERS) ? YES : NO));
- opts.add(HelgrindCommandConstants.OPT_HISTORY_LEVEL + EQUALS + config.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_HISTORYLEVEL, HelgrindLaunchConstants.DEFAULT_HELGRIND_HISTORYLEVEL));
- opts.add(HelgrindCommandConstants.OPT_CONFLICT_CACHE_SIZE + EQUALS + config.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_CACHESIZE, HelgrindLaunchConstants.DEFAULT_HELGRIND_CACHESIZE));
- return opts.toArray(new String[opts.size()]);
- }
-
- @Override
- public void initializeView(IValgrindToolView view, String contentDescription, IProgressMonitor monitor) {
- }
+ private static final String EQUALS = "="; //$NON-NLS-1$
+ private static final String NO = "no"; //$NON-NLS-1$
+ private static final String YES = "yes"; //$NON-NLS-1$
+
+ @Override
+ public void handleLaunch(ILaunchConfiguration config, ILaunch launch, IPath outDir, IProgressMonitor monitor) {
+ }
+
+ @Override
+ public String[] getCommandArray(ILaunchConfiguration config, Version ver, IPath logDir) throws CoreException {
+ ArrayList<String> opts = new ArrayList<>();
+
+ opts.add(HelgrindCommandConstants.OPT_TRACK_LOCKORDERS + EQUALS + (config.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_LOCKORDERS, HelgrindLaunchConstants.DEFAULT_HELGRIND_LOCKORDERS) ? YES : NO));
+ opts.add(HelgrindCommandConstants.OPT_HISTORY_LEVEL + EQUALS + config.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_HISTORYLEVEL, HelgrindLaunchConstants.DEFAULT_HELGRIND_HISTORYLEVEL));
+ opts.add(HelgrindCommandConstants.OPT_CONFLICT_CACHE_SIZE + EQUALS + config.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_CACHESIZE, HelgrindLaunchConstants.DEFAULT_HELGRIND_CACHESIZE));
+ return opts.toArray(new String[opts.size()]);
+ }
+
+ @Override
+ public void initializeView(IValgrindToolView view, String contentDescription, IProgressMonitor monitor) {
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchShortcut.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchShortcut.java
index e314698a9d..99e77c3203 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchShortcut.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindLaunchShortcut.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Red Hat Inc - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.helgrind;
import org.eclipse.core.runtime.CoreException;
@@ -21,22 +21,22 @@ import org.eclipse.linuxtools.profiling.launch.ProfileLaunchShortcut;
public class HelgrindLaunchShortcut extends ProfileLaunchShortcut {
- @Override
- protected void setDefaultProfileAttributes(
- ILaunchConfigurationWorkingCopy wc) throws CoreException {
- ValgrindOptionsTab tab = new ValgrindOptionsTab();
- tab.setDefaults(wc);
- ILaunchConfigurationTab defaultTab = ValgrindLaunchPlugin.getDefault().getToolPage(HelgrindPlugin.TOOL_ID);
- defaultTab.setDefaults(wc);
- }
+ @Override
+ protected void setDefaultProfileAttributes(
+ ILaunchConfigurationWorkingCopy wc) throws CoreException {
+ ValgrindOptionsTab tab = new ValgrindOptionsTab();
+ tab.setDefaults(wc);
+ ILaunchConfigurationTab defaultTab = ValgrindLaunchPlugin.getDefault().getToolPage(HelgrindPlugin.TOOL_ID);
+ defaultTab.setDefaults(wc);
+ }
- /**
- * Method getValgrindLaunchConfigType.
- * @return ILaunchConfigurationType
- */
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(ValgrindLaunchPlugin.LAUNCH_ID);
- }
+ /**
+ * Method getValgrindLaunchConfigType.
+ * @return ILaunchConfigurationType
+ */
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(ValgrindLaunchPlugin.LAUNCH_ID);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindPlugin.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindPlugin.java
index 758231a3ca..401f4e818c 100755
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindPlugin.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindPlugin.java
@@ -17,8 +17,8 @@ package org.eclipse.linuxtools.internal.valgrind.helgrind;
*/
public class HelgrindPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.helgrind"; //$NON-NLS-1$
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.helgrind"; //$NON-NLS-1$
- public static final String TOOL_ID = "org.eclipse.linuxtools.valgrind.launch.helgrind"; //$NON-NLS-1$
+ public static final String TOOL_ID = "org.eclipse.linuxtools.valgrind.launch.helgrind"; //$NON-NLS-1$
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindToolPage.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindToolPage.java
index cc56aebf10..2a28b67a34 100755
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindToolPage.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindToolPage.java
@@ -34,120 +34,120 @@ import org.eclipse.swt.widgets.Spinner;
import org.osgi.framework.Version;
public class HelgrindToolPage extends AbstractLaunchConfigurationTab implements IValgrindToolPage {
- // HELGRIND controls
- private Button lockordersButton;
- private Combo historyCombo;
- private Spinner cacheSizeSpinner;
-
-
- private boolean isInitializing = false;
-
- private SelectionListener selectListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
- private ModifyListener modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
-
- @Override
- public void createControl(Composite parent) {
- Composite top = new Composite(parent, SWT.NONE);
- GridLayout helgrindLayout = new GridLayout(2, true);
- top.setLayout(helgrindLayout);
- top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- lockordersButton = new Button(top, SWT.CHECK);
- lockordersButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- lockordersButton.setText(Messages.getString("HelgrindToolPage.track_lockorders")); //$NON-NLS-1$
- lockordersButton.addSelectionListener(selectListener);
-
- Composite historyTop = new Composite(top, SWT.NONE);
- historyTop.setLayout(new GridLayout(2, false));
- historyTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Label historyLabel = new Label(historyTop, SWT.NONE);
- historyLabel.setText(Messages.getString("HelgrindToolPage.history_level")); //$NON-NLS-1$
- historyCombo = new Combo(historyTop, SWT.READ_ONLY);
- String[] historyOpts = { HelgrindLaunchConstants.HISTORY_FULL, HelgrindLaunchConstants.HISTORY_APPROX, HelgrindLaunchConstants.HISTORY_NONE };
- historyCombo.setItems(historyOpts);
- historyCombo.addSelectionListener(selectListener);
-
- Composite conflictCacheSizeTop = new Composite(top, SWT.NONE);
- conflictCacheSizeTop.setLayout(new GridLayout(2, false));
- conflictCacheSizeTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Label cacheSizeLabel = new Label(conflictCacheSizeTop, SWT.NONE);
- cacheSizeLabel.setText(Messages.getString("HelgrindToolPage.cache_size")); //$NON-NLS-1$
- cacheSizeSpinner = new Spinner(conflictCacheSizeTop, SWT.BORDER);
- cacheSizeSpinner.setMaximum(Integer.MAX_VALUE);
- cacheSizeSpinner.addModifyListener(modifyListener);
- }
-
- @Override
- public String getName() {
- return Messages.getString("HelgrindToolPage.Helgrind_Options"); //$NON-NLS-1$
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration configuration) {
- isInitializing = true;
- try {
- lockordersButton.setSelection(configuration.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_LOCKORDERS, HelgrindLaunchConstants.DEFAULT_HELGRIND_LOCKORDERS));
- historyCombo.setText(configuration.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_HISTORYLEVEL, HelgrindLaunchConstants.DEFAULT_HELGRIND_HISTORYLEVEL));
- cacheSizeSpinner.setSelection(configuration.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_CACHESIZE, HelgrindLaunchConstants.DEFAULT_HELGRIND_CACHESIZE));
- } catch (CoreException e) {
- }
- isInitializing = false;
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_LOCKORDERS, lockordersButton.getSelection());
- configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_HISTORYLEVEL, historyCombo.getText());
- configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_CACHESIZE, cacheSizeSpinner.getSelection());
- }
-
- @Override
- public boolean isValid(ILaunchConfiguration launchConfig) {
- setErrorMessage(null);
- return true;
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, HelgrindPlugin.TOOL_ID);
- configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_LOCKORDERS, HelgrindLaunchConstants.DEFAULT_HELGRIND_LOCKORDERS);
- configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_HISTORYLEVEL, HelgrindLaunchConstants.DEFAULT_HELGRIND_HISTORYLEVEL);
- configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_CACHESIZE, HelgrindLaunchConstants.DEFAULT_HELGRIND_CACHESIZE);
- }
-
- @Override
- public void setValgrindVersion(Version ver) {
- // no constraints
- }
-
- @Override
- protected void updateLaunchConfigurationDialog() {
- if (!isInitializing) {
- super.updateLaunchConfigurationDialog();
- }
- }
-
- public Button getLockordersButton() {
- return lockordersButton;
- }
-
- public Spinner getCacheSizeSpinner() {
- return cacheSizeSpinner;
- }
-
- public Combo getHistoryCombo() {
- return historyCombo;
- }
+ // HELGRIND controls
+ private Button lockordersButton;
+ private Combo historyCombo;
+ private Spinner cacheSizeSpinner;
+
+
+ private boolean isInitializing = false;
+
+ private SelectionListener selectListener = new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+ private ModifyListener modifyListener = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ @Override
+ public void createControl(Composite parent) {
+ Composite top = new Composite(parent, SWT.NONE);
+ GridLayout helgrindLayout = new GridLayout(2, true);
+ top.setLayout(helgrindLayout);
+ top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ lockordersButton = new Button(top, SWT.CHECK);
+ lockordersButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ lockordersButton.setText(Messages.getString("HelgrindToolPage.track_lockorders")); //$NON-NLS-1$
+ lockordersButton.addSelectionListener(selectListener);
+
+ Composite historyTop = new Composite(top, SWT.NONE);
+ historyTop.setLayout(new GridLayout(2, false));
+ historyTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ Label historyLabel = new Label(historyTop, SWT.NONE);
+ historyLabel.setText(Messages.getString("HelgrindToolPage.history_level")); //$NON-NLS-1$
+ historyCombo = new Combo(historyTop, SWT.READ_ONLY);
+ String[] historyOpts = { HelgrindLaunchConstants.HISTORY_FULL, HelgrindLaunchConstants.HISTORY_APPROX, HelgrindLaunchConstants.HISTORY_NONE };
+ historyCombo.setItems(historyOpts);
+ historyCombo.addSelectionListener(selectListener);
+
+ Composite conflictCacheSizeTop = new Composite(top, SWT.NONE);
+ conflictCacheSizeTop.setLayout(new GridLayout(2, false));
+ conflictCacheSizeTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ Label cacheSizeLabel = new Label(conflictCacheSizeTop, SWT.NONE);
+ cacheSizeLabel.setText(Messages.getString("HelgrindToolPage.cache_size")); //$NON-NLS-1$
+ cacheSizeSpinner = new Spinner(conflictCacheSizeTop, SWT.BORDER);
+ cacheSizeSpinner.setMaximum(Integer.MAX_VALUE);
+ cacheSizeSpinner.addModifyListener(modifyListener);
+ }
+
+ @Override
+ public String getName() {
+ return Messages.getString("HelgrindToolPage.Helgrind_Options"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration configuration) {
+ isInitializing = true;
+ try {
+ lockordersButton.setSelection(configuration.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_LOCKORDERS, HelgrindLaunchConstants.DEFAULT_HELGRIND_LOCKORDERS));
+ historyCombo.setText(configuration.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_HISTORYLEVEL, HelgrindLaunchConstants.DEFAULT_HELGRIND_HISTORYLEVEL));
+ cacheSizeSpinner.setSelection(configuration.getAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_CACHESIZE, HelgrindLaunchConstants.DEFAULT_HELGRIND_CACHESIZE));
+ } catch (CoreException e) {
+ }
+ isInitializing = false;
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_LOCKORDERS, lockordersButton.getSelection());
+ configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_HISTORYLEVEL, historyCombo.getText());
+ configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_CACHESIZE, cacheSizeSpinner.getSelection());
+ }
+
+ @Override
+ public boolean isValid(ILaunchConfiguration launchConfig) {
+ setErrorMessage(null);
+ return true;
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, HelgrindPlugin.TOOL_ID);
+ configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_LOCKORDERS, HelgrindLaunchConstants.DEFAULT_HELGRIND_LOCKORDERS);
+ configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_HISTORYLEVEL, HelgrindLaunchConstants.DEFAULT_HELGRIND_HISTORYLEVEL);
+ configuration.setAttribute(HelgrindLaunchConstants.ATTR_HELGRIND_CACHESIZE, HelgrindLaunchConstants.DEFAULT_HELGRIND_CACHESIZE);
+ }
+
+ @Override
+ public void setValgrindVersion(Version ver) {
+ // no constraints
+ }
+
+ @Override
+ protected void updateLaunchConfigurationDialog() {
+ if (!isInitializing) {
+ super.updateLaunchConfigurationDialog();
+ }
+ }
+
+ public Button getLockordersButton() {
+ return lockordersButton;
+ }
+
+ public Spinner getCacheSizeSpinner() {
+ return cacheSizeSpinner;
+ }
+
+ public Combo getHistoryCombo() {
+ return historyCombo;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindViewPart.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindViewPart.java
index d5f7ad7339..b6adf792da 100755
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindViewPart.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/HelgrindViewPart.java
@@ -18,21 +18,21 @@ import org.eclipse.ui.part.ViewPart;
public class HelgrindViewPart extends ViewPart implements IValgrindToolView {
- @Override
- public void createPartControl(Composite parent) {
- }
-
- @Override
- public void setFocus() {
- }
-
- @Override
- public void refreshView() {
- }
-
- @Override
- public IAction[] getToolbarActions() {
- return null;
- }
-
+ @Override
+ public void createPartControl(Composite parent) {
+ }
+
+ @Override
+ public void setFocus() {
+ }
+
+ @Override
+ public void refreshView() {
+ }
+
+ @Override
+ public IAction[] getToolbarActions() {
+ return null;
+ }
+
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/Messages.java b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/Messages.java
index 6803d070d4..33b3c33e20 100755
--- a/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/Messages.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.helgrind/src/org/eclipse/linuxtools/internal/valgrind/helgrind/Messages.java
@@ -15,19 +15,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.helgrind.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.helgrind.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ClearMarkersHandler.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ClearMarkersHandler.java
index 578b978c7a..79b6ef98bb 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ClearMarkersHandler.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ClearMarkersHandler.java
@@ -21,22 +21,22 @@ import org.eclipse.swt.widgets.Display;
public class ClearMarkersHandler extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) {
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- try {
- root.deleteMarkers(ValgrindLaunchPlugin.MARKER_TYPE, true, IResource.DEPTH_INFINITE);
- } catch (CoreException e) {
- // do nothing for now
- }
- // Clear Valgrind view
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- ValgrindUIPlugin.getDefault().resetView();
- }
- });
- return null;
- }
+ @Override
+ public Object execute(ExecutionEvent event) {
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ try {
+ root.deleteMarkers(ValgrindLaunchPlugin.MARKER_TYPE, true, IResource.DEPTH_INFINITE);
+ } catch (CoreException e) {
+ // do nothing for now
+ }
+ // Clear Valgrind view
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ ValgrindUIPlugin.getDefault().resetView();
+ }
+ });
+ return null;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ExportHandler.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ExportHandler.java
index 3686f4b97d..da01b3eff3 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ExportHandler.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ExportHandler.java
@@ -20,21 +20,21 @@ import org.eclipse.ui.PlatformUI;
public class ExportHandler extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
- IWorkbenchWizard wizard = new ValgrindExportWizard();
- wizard.init(PlatformUI.getWorkbench(), null);
+ @Override
+ public Object execute(ExecutionEvent event) {
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
+ IWorkbenchWizard wizard = new ValgrindExportWizard();
+ wizard.init(PlatformUI.getWorkbench(), null);
- WizardDialog dialog = new WizardDialog(parent, wizard);
- dialog.open();
- }
- });
+ WizardDialog dialog = new WizardDialog(parent, wizard);
+ dialog.open();
+ }
+ });
- return null;
- }
+ return null;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ExportWizardConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ExportWizardConstants.java
index 59819a9222..e7b7861926 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ExportWizardConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ExportWizardConstants.java
@@ -7,13 +7,13 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.launch;
public final class ExportWizardConstants {
- public static final String WIZARD_TITLE = Messages.getString("ExportWizardConstants.Wizard_title"); //$NON-NLS-1$
- public static final String WIZARD_WINDOW_TITLE = Messages.getString("ExportWizardConstants.Window_title"); //$NON-NLS-1$
- public static final String WIZARD_DESCRIPTION = Messages.getString("ExportWizardConstants.Wizard_desc"); //$NON-NLS-1$
+ public static final String WIZARD_TITLE = Messages.getString("ExportWizardConstants.Wizard_title"); //$NON-NLS-1$
+ public static final String WIZARD_WINDOW_TITLE = Messages.getString("ExportWizardConstants.Window_title"); //$NON-NLS-1$
+ public static final String WIZARD_DESCRIPTION = Messages.getString("ExportWizardConstants.Wizard_desc"); //$NON-NLS-1$
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/LaunchConfigurationConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/LaunchConfigurationConstants.java
index c05b619b1b..8f9e744455 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/LaunchConfigurationConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/LaunchConfigurationConstants.java
@@ -16,45 +16,45 @@ import java.util.List;
public final class LaunchConfigurationConstants {
- // LaunchConfiguration constants
- private static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.launch"; //$NON-NLS-1$
-
- public static final String ATTR_TOOL = PLUGIN_ID + ".TOOL"; //$NON-NLS-1$
- public static final String ATTR_INTERNAL_OUTPUT_DIR = PLUGIN_ID + ".OUTPUT_DIR"; //$NON-NLS-1$
-
- public static final String ATTR_GENERAL_TRACECHILD = PLUGIN_ID + ".GENERAL_TRACECHILD"; //$NON-NLS-1$
- public static final String ATTR_GENERAL_CHILDSILENT = PLUGIN_ID + ".GENERAL_CHILDSILENT"; //$NON-NLS-1$
- public static final String ATTR_GENERAL_FREERES = PLUGIN_ID + ".GENERAL_FREERES"; //$NON-NLS-1$
- public static final String ATTR_GENERAL_DEMANGLE = PLUGIN_ID + ".GENERAL_DEMANGLE"; //$NON-NLS-1$
- public static final String ATTR_GENERAL_NUMCALLERS = PLUGIN_ID + ".GENERAL_NUMCALLERS"; //$NON-NLS-1$
- public static final String ATTR_GENERAL_ERRLIMIT = PLUGIN_ID + ".GENERAL_ERRLIMIT"; //$NON-NLS-1$
- public static final String ATTR_GENERAL_BELOWMAIN = PLUGIN_ID + ".GENERAL_BELOWMAIN"; //$NON-NLS-1$
- public static final String ATTR_GENERAL_MAXFRAME = PLUGIN_ID + ".GENERAL_MAXFRAME"; //$NON-NLS-1$
- public static final String ATTR_GENERAL_SUPPFILES = PLUGIN_ID + ".GENERAL_SUPPFILES"; //$NON-NLS-1$
-
- // 3.4.0 specific
- public static final String ATTR_GENERAL_MAINSTACK_BOOL = PLUGIN_ID + ".GENERAL_MAINSTACK_BOOL"; //$NON-NLS-1$
- public static final String ATTR_GENERAL_MAINSTACK = PLUGIN_ID + ".GENERAL_MAINSTACK"; //$NON-NLS-1$
-
- // 3.6.0 specific
- public static final String ATTR_GENERAL_DSYMUTIL = PLUGIN_ID + ".GENERAL_DSYMUTIL"; //$NON-NLS-1$
-
- public static final String DEFAULT_TOOL = PLUGIN_ID + ".memcheck"; //$NON-NLS-1$
-
- public static final boolean DEFAULT_GENERAL_TRACECHILD = false;
- public static final boolean DEFAULT_GENERAL_CHILDSILENT = true; // necessary for parsing
- public static final boolean DEFAULT_GENERAL_FREERES = true;
- public static final boolean DEFAULT_GENERAL_DEMANGLE = true;
- public static final int DEFAULT_GENERAL_NUMCALLERS = 12;
- public static final boolean DEFAULT_GENERAL_ERRLIMIT = true;
- public static final boolean DEFAULT_GENERAL_BELOWMAIN = false;
- public static final int DEFAULT_GENERAL_MAXFRAME = 2000000;
- public static final List<String> DEFAULT_GENERAL_SUPPFILES = Collections.emptyList();
-
- // 3.4.0 specific
- public static final boolean DEFAULT_GENERAL_MAINSTACK_BOOL = false;
- public static final int DEFAULT_GENERAL_MAINSTACK = 0;
-
- // 3.6.0 specific
- public static final boolean DEFAULT_GENERAL_DSYMUTIL = true; // necessary for OS X, Bug #333640
+ // LaunchConfiguration constants
+ private static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.launch"; //$NON-NLS-1$
+
+ public static final String ATTR_TOOL = PLUGIN_ID + ".TOOL"; //$NON-NLS-1$
+ public static final String ATTR_INTERNAL_OUTPUT_DIR = PLUGIN_ID + ".OUTPUT_DIR"; //$NON-NLS-1$
+
+ public static final String ATTR_GENERAL_TRACECHILD = PLUGIN_ID + ".GENERAL_TRACECHILD"; //$NON-NLS-1$
+ public static final String ATTR_GENERAL_CHILDSILENT = PLUGIN_ID + ".GENERAL_CHILDSILENT"; //$NON-NLS-1$
+ public static final String ATTR_GENERAL_FREERES = PLUGIN_ID + ".GENERAL_FREERES"; //$NON-NLS-1$
+ public static final String ATTR_GENERAL_DEMANGLE = PLUGIN_ID + ".GENERAL_DEMANGLE"; //$NON-NLS-1$
+ public static final String ATTR_GENERAL_NUMCALLERS = PLUGIN_ID + ".GENERAL_NUMCALLERS"; //$NON-NLS-1$
+ public static final String ATTR_GENERAL_ERRLIMIT = PLUGIN_ID + ".GENERAL_ERRLIMIT"; //$NON-NLS-1$
+ public static final String ATTR_GENERAL_BELOWMAIN = PLUGIN_ID + ".GENERAL_BELOWMAIN"; //$NON-NLS-1$
+ public static final String ATTR_GENERAL_MAXFRAME = PLUGIN_ID + ".GENERAL_MAXFRAME"; //$NON-NLS-1$
+ public static final String ATTR_GENERAL_SUPPFILES = PLUGIN_ID + ".GENERAL_SUPPFILES"; //$NON-NLS-1$
+
+ // 3.4.0 specific
+ public static final String ATTR_GENERAL_MAINSTACK_BOOL = PLUGIN_ID + ".GENERAL_MAINSTACK_BOOL"; //$NON-NLS-1$
+ public static final String ATTR_GENERAL_MAINSTACK = PLUGIN_ID + ".GENERAL_MAINSTACK"; //$NON-NLS-1$
+
+ // 3.6.0 specific
+ public static final String ATTR_GENERAL_DSYMUTIL = PLUGIN_ID + ".GENERAL_DSYMUTIL"; //$NON-NLS-1$
+
+ public static final String DEFAULT_TOOL = PLUGIN_ID + ".memcheck"; //$NON-NLS-1$
+
+ public static final boolean DEFAULT_GENERAL_TRACECHILD = false;
+ public static final boolean DEFAULT_GENERAL_CHILDSILENT = true; // necessary for parsing
+ public static final boolean DEFAULT_GENERAL_FREERES = true;
+ public static final boolean DEFAULT_GENERAL_DEMANGLE = true;
+ public static final int DEFAULT_GENERAL_NUMCALLERS = 12;
+ public static final boolean DEFAULT_GENERAL_ERRLIMIT = true;
+ public static final boolean DEFAULT_GENERAL_BELOWMAIN = false;
+ public static final int DEFAULT_GENERAL_MAXFRAME = 2000000;
+ public static final List<String> DEFAULT_GENERAL_SUPPFILES = Collections.emptyList();
+
+ // 3.4.0 specific
+ public static final boolean DEFAULT_GENERAL_MAINSTACK_BOOL = false;
+ public static final int DEFAULT_GENERAL_MAINSTACK = 0;
+
+ // 3.6.0 specific
+ public static final boolean DEFAULT_GENERAL_DSYMUTIL = true; // necessary for OS X, Bug #333640
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/Messages.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/Messages.java
index d319d4d1ee..d7d441bfa3 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/Messages.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/Messages.java
@@ -7,26 +7,26 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.launch;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.launch.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.launch.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ProjectBuildListener.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ProjectBuildListener.java
index 93771e8419..ca380a65ac 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ProjectBuildListener.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ProjectBuildListener.java
@@ -29,88 +29,88 @@ import org.eclipse.swt.widgets.Display;
*/
public class ProjectBuildListener implements IResourceChangeListener {
- // project to keep track of
- private IProject project;
+ // project to keep track of
+ private IProject project;
- public ProjectBuildListener(IProject targetProject) {
- project = targetProject;
- }
+ public ProjectBuildListener(IProject targetProject) {
+ project = targetProject;
+ }
- @Override
- public void resourceChanged(IResourceChangeEvent event) {
- if (project != null && isPostBuildEvent(event)) {
+ @Override
+ public void resourceChanged(IResourceChangeEvent event) {
+ if (project != null && isPostBuildEvent(event)) {
- // find the project from event delta and delete its markers
- IResourceDelta delta = event.getDelta();
- IResourceDelta[] childrenDelta = delta.getAffectedChildren(IResourceDelta.CHANGED);
- for (IResourceDelta childDelta : childrenDelta) {
- if (isProjectDelta(childDelta, project)) {
+ // find the project from event delta and delete its markers
+ IResourceDelta delta = event.getDelta();
+ IResourceDelta[] childrenDelta = delta.getAffectedChildren(IResourceDelta.CHANGED);
+ for (IResourceDelta childDelta : childrenDelta) {
+ if (isProjectDelta(childDelta, project)) {
- // clear markers and de-register this listener
- clearProjectMarkers(project);
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
- }
- }
- }
- }
+ // clear markers and de-register this listener
+ clearProjectMarkers(project);
+ ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
+ }
+ }
+ }
+ }
- /**
- * Check if {@link IResourceDelta} represents a change in the specified {@link IProject}..
- *
- * @param delta IResourceDelta resource delta to check
- * @param project IProject project to compare against
- * @return boolean true if IResourceDelta is a project and equals the
- */
- private boolean isProjectDelta(IResourceDelta delta, IProject project){
- if(delta != null){
- IResource resource = delta.getResource();
- return delta.getKind() == IResourceDelta.CHANGED
- && resource != null
- && resource.getType() == IResource.PROJECT
- && resource.equals(project);
- }
- return false;
- }
+ /**
+ * Check if {@link IResourceDelta} represents a change in the specified {@link IProject}..
+ *
+ * @param delta IResourceDelta resource delta to check
+ * @param project IProject project to compare against
+ * @return boolean true if IResourceDelta is a project and equals the
+ */
+ private boolean isProjectDelta(IResourceDelta delta, IProject project){
+ if(delta != null){
+ IResource resource = delta.getResource();
+ return delta.getKind() == IResourceDelta.CHANGED
+ && resource != null
+ && resource.getType() == IResource.PROJECT
+ && resource.equals(project);
+ }
+ return false;
+ }
- /**
- * Check if {@link IResourceChangeEvent} is a post-build event.
- *
- * @param event IResourceChangeEvent event to check
- * @return boolean true if IResourceChangeEvent is a post-build event, false
- * otherwise
- */
- private boolean isPostBuildEvent(IResourceChangeEvent event) {
- if(event != null){
- int buildKind = event.getBuildKind();
- return event.getType() == IResourceChangeEvent.POST_BUILD
- && (buildKind == IncrementalProjectBuilder.FULL_BUILD
- || buildKind == IncrementalProjectBuilder.INCREMENTAL_BUILD
- || buildKind == IncrementalProjectBuilder.CLEAN_BUILD);
- }
- return false;
- }
+ /**
+ * Check if {@link IResourceChangeEvent} is a post-build event.
+ *
+ * @param event IResourceChangeEvent event to check
+ * @return boolean true if IResourceChangeEvent is a post-build event, false
+ * otherwise
+ */
+ private boolean isPostBuildEvent(IResourceChangeEvent event) {
+ if(event != null){
+ int buildKind = event.getBuildKind();
+ return event.getType() == IResourceChangeEvent.POST_BUILD
+ && (buildKind == IncrementalProjectBuilder.FULL_BUILD
+ || buildKind == IncrementalProjectBuilder.INCREMENTAL_BUILD
+ || buildKind == IncrementalProjectBuilder.CLEAN_BUILD);
+ }
+ return false;
+ }
- /**
- * Clear markers of specified project.
- *
- * @param project IProject project to clear markers from
- */
- private void clearProjectMarkers(IProject project) {
- try {
+ /**
+ * Clear markers of specified project.
+ *
+ * @param project IProject project to clear markers from
+ */
+ private void clearProjectMarkers(IProject project) {
+ try {
- // remove project markers
- project.deleteMarkers(ValgrindLaunchPlugin.MARKER_TYPE, true,IResource.DEPTH_INFINITE);
+ // remove project markers
+ project.deleteMarkers(ValgrindLaunchPlugin.MARKER_TYPE, true,IResource.DEPTH_INFINITE);
- // clear valgrind error view
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- ValgrindUIPlugin.getDefault().resetView();
- }
- });
- } catch (CoreException e) {
- Status status = new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, e.getMessage());
- ValgrindLaunchPlugin.getDefault().getLog().log(status);
- }
- }
+ // clear valgrind error view
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ ValgrindUIPlugin.getDefault().resetView();
+ }
+ });
+ } catch (CoreException e) {
+ Status status = new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, e.getMessage());
+ ValgrindLaunchPlugin.getDefault().getLog().log(status);
+ }
+ }
} \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindExportWizard.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindExportWizard.java
index e97e07d1a7..928f560e97 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindExportWizard.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindExportWizard.java
@@ -33,67 +33,67 @@ import org.eclipse.ui.progress.IProgressService;
public class ValgrindExportWizard extends Wizard implements IExportWizard {
- private ValgrindExportWizardPage exportPage;
+ private ValgrindExportWizardPage exportPage;
- @Override
- public boolean performFinish() {
- final File[] logs = exportPage.getSelectedFiles();
- final IPath outputPath = exportPage.getOutputPath();
+ @Override
+ public boolean performFinish() {
+ final File[] logs = exportPage.getSelectedFiles();
+ final IPath outputPath = exportPage.getOutputPath();
- IProgressService ps = PlatformUI.getWorkbench().getProgressService();
- try {
- ps.busyCursorWhile(new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor)
- throws InvocationTargetException {
- if (logs.length > 0) {
- File outputDir = outputPath.toFile();
- monitor.beginTask(
- NLS.bind(
- Messages.getString("ValgrindExportWizard.Export_task"), outputPath.toOSString()), logs.length); //$NON-NLS-1$
- for (File log : logs) {
- monitor.subTask(NLS.bind(
- Messages.getString("ValgrindExportWizard.Export_subtask"), log.getName())); //$NON-NLS-1$
+ IProgressService ps = PlatformUI.getWorkbench().getProgressService();
+ try {
+ ps.busyCursorWhile(new IRunnableWithProgress() {
+ @Override
+ public void run(IProgressMonitor monitor)
+ throws InvocationTargetException {
+ if (logs.length > 0) {
+ File outputDir = outputPath.toFile();
+ monitor.beginTask(
+ NLS.bind(
+ Messages.getString("ValgrindExportWizard.Export_task"), outputPath.toOSString()), logs.length); //$NON-NLS-1$
+ for (File log : logs) {
+ monitor.subTask(NLS.bind(
+ Messages.getString("ValgrindExportWizard.Export_subtask"), log.getName())); //$NON-NLS-1$
- File outLog = new File(outputDir, log.getName());
- try (FileInputStream fis = new FileInputStream(log);
- FileChannel inChan = fis.getChannel();
- FileOutputStream fos = new FileOutputStream(
- outLog);
- FileChannel outChan = fos.getChannel()) {
- outChan.transferFrom(inChan, 0, inChan.size());
- } catch (IOException e) {
- throw new InvocationTargetException(e);
- }
- monitor.worked(1);
- }
- monitor.done();
- }
- }
+ File outLog = new File(outputDir, log.getName());
+ try (FileInputStream fis = new FileInputStream(log);
+ FileChannel inChan = fis.getChannel();
+ FileOutputStream fos = new FileOutputStream(
+ outLog);
+ FileChannel outChan = fos.getChannel()) {
+ outChan.transferFrom(inChan, 0, inChan.size());
+ } catch (IOException e) {
+ throw new InvocationTargetException(e);
+ }
+ monitor.worked(1);
+ }
+ monitor.done();
+ }
+ }
- });
+ });
- } catch (InvocationTargetException e) {
- IStatus status = new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, Messages.getString("ValgrindExportWizard.Export_fail"), e); //$NON-NLS-1$
- ErrorDialog.openError(getShell(), ExportWizardConstants.WIZARD_TITLE, null, status);
- e.printStackTrace();
- return false;
- } catch (InterruptedException e) {
- }
+ } catch (InvocationTargetException e) {
+ IStatus status = new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, Messages.getString("ValgrindExportWizard.Export_fail"), e); //$NON-NLS-1$
+ ErrorDialog.openError(getShell(), ExportWizardConstants.WIZARD_TITLE, null, status);
+ e.printStackTrace();
+ return false;
+ } catch (InterruptedException e) {
+ }
- return true;
- }
+ return true;
+ }
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- setWindowTitle(ExportWizardConstants.WIZARD_WINDOW_TITLE);
- exportPage = getWizardPage();
- exportPage.setDescription(ExportWizardConstants.WIZARD_DESCRIPTION);
- addPage(exportPage);
- }
+ @Override
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ setWindowTitle(ExportWizardConstants.WIZARD_WINDOW_TITLE);
+ exportPage = getWizardPage();
+ exportPage.setDescription(ExportWizardConstants.WIZARD_DESCRIPTION);
+ addPage(exportPage);
+ }
- private ValgrindExportWizardPage getWizardPage() {
- return new ValgrindExportWizardPage(Messages.getString("ValgrindExportWizard.Page_name"), ExportWizardConstants.WIZARD_TITLE, null); //$NON-NLS-1$
- }
+ private ValgrindExportWizardPage getWizardPage() {
+ return new ValgrindExportWizardPage(Messages.getString("ValgrindExportWizard.Page_name"), ExportWizardConstants.WIZARD_TITLE, null); //$NON-NLS-1$
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindExportWizardPage.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindExportWizardPage.java
index 74df5ea749..3aa82f1575 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindExportWizardPage.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindExportWizardPage.java
@@ -43,187 +43,187 @@ import org.eclipse.ui.PlatformUI;
public class ValgrindExportWizardPage extends WizardPage {
- private IPath outputPath;
- private CheckboxTableViewer viewer;
- private Text destText;
-
- protected ValgrindExportWizardPage(String pageName, String title, ImageDescriptor titleImage) {
- super(pageName, title, titleImage);
- }
-
-
- @Override
- public void createControl(Composite parent) {
- Composite top = new Composite(parent, SWT.NONE);
- top.setLayout(new GridLayout());
- top.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- IPath logPath = null;
-
- // Retrieve location of Valgrind logs from launch configuration
- ILaunchConfiguration config = getPlugin().getCurrentLaunchConfiguration();
- if (config != null && config.exists()) {
- String strpath;
- try {
- strpath = config.getAttribute(LaunchConfigurationConstants.ATTR_INTERNAL_OUTPUT_DIR, (String) null);
- if (strpath != null) {
- logPath = Path.fromPortableString(strpath);
- }
- } catch (CoreException e) {
- setErrorMessage(e.getLocalizedMessage());
- e.printStackTrace();
- }
- }
-
- Label selectFilesLabel = new Label(top, SWT.NONE);
- selectFilesLabel.setText(Messages.getString("ValgrindExportWizardPage.Viewer_label")); //$NON-NLS-1$
-
- viewer = CheckboxTableViewer.newCheckList(top, SWT.BORDER);
- viewer.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));
- viewer.setContentProvider(new ArrayContentProvider());
- viewer.setLabelProvider(new LabelProvider() {
- @Override
- public String getText(Object element) {
- return ((File) element).getName();
- }
-
- @Override
- public Image getImage(Object element) {
- return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE);
- }
- });
-
- Composite selectAllNoneTop = new Composite(top, SWT.NONE);
- selectAllNoneTop.setLayout(new GridLayout(2, true));
- selectAllNoneTop.setLayoutData(new GridData(SWT.TRAIL, SWT.DEFAULT, false, false));
-
- Button selectAllButton = new Button(selectAllNoneTop, SWT.NONE);
- selectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- selectAllButton.setText(Messages.getString("ValgrindExportWizardPage.Select_all")); //$NON-NLS-1$
- selectAllButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- viewer.setAllChecked(true);
- }
- });
-
- Button deselectAllButton = new Button(selectAllNoneTop, SWT.NONE);
- deselectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- deselectAllButton.setText(Messages.getString("ValgrindExportWizardPage.Deselect_all")); //$NON-NLS-1$
- deselectAllButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- viewer.setAllChecked(false);
- }
- });
-
- createDestinationGroup(top);
-
- if (logPath != null) {
- // List all output files in our output directory from the recent launch
- File logs[] = logPath.toFile().listFiles(new FileFilter() {
- @Override
- public boolean accept(File pathname) {
- return pathname.isFile();
- }
- });
- viewer.setInput(logs);
- viewer.setAllChecked(true);
- }
-
- // catch any errors so far
- setPageComplete(isValid());
-
- setControl(top);
- }
-
- public IPath getOutputPath() {
- return outputPath;
- }
-
- public File[] getSelectedFiles() {
- Object[] selected = viewer.getCheckedElements();
- File[] files = new File[selected.length];
- System.arraycopy(selected, 0, files, 0, selected.length);
- return files;
- }
-
- private void createDestinationGroup(Composite top) {
- Group destGroup = new Group(top, SWT.SHADOW_OUT);
- destGroup.setText(Messages.getString("ValgrindExportWizardPage.Destination_group")); //$NON-NLS-1$
- destGroup.setLayout(new GridLayout(2, false));
- destGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- destText = new Text(destGroup, SWT.BORDER);
- destText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- destText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- setPageComplete(isValid());
- }
- });
-
- Button browseButton = new Button(destGroup, SWT.PUSH);
- browseButton.setText(Messages.getString("ValgrindExportWizardPage.Browse")); //$NON-NLS-1$
- browseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- // Prompt for output directory
- Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
- DirectoryDialog dialog = new DirectoryDialog(parent);
- dialog.setText(Messages.getString("ValgrindLaunchConfigurationDelegate.Select_Destination")); //$NON-NLS-1$
- String strpath = dialog.open();
- if (strpath != null) {
- destText.setText(strpath);
- }
- }
- });
- }
-
- private boolean isValid() {
- boolean valid = false;
- int length = -1;
-
- setErrorMessage(null);
- setMessage(null);
-
- Object obj = viewer.getInput();
- // Check if there are no launch files (either null because directory is missing
- // or 0 files are found in directory)
- if (obj instanceof File[])
- length = ((File[])obj).length;
- if (viewer.getInput() == null || length == 0) {
- setErrorMessage(Messages.getString("ValgrindExportWizardPage.Err_No_Valgrind_run")); //$NON-NLS-1$
- }
- else if (destText.getText().equals("")) { //$NON-NLS-1$
- setMessage(Messages.getString("ValgrindExportWizardPage.Msg_Select_destination")); //$NON-NLS-1$
- }
- else {
- IPath path = Path.fromOSString(destText.getText());
- if (!path.toFile().exists()) {
- setErrorMessage(NLS.bind(Messages.getString("ValgrindExportWizardPage.Err_Dir_not_exist"), path.toOSString())); //$NON-NLS-1$
- }
- else if (!path.toFile().isDirectory()) {
- setErrorMessage(NLS.bind(Messages.getString("ValgrindExportWizardPage.Err_Not_dir"), path.toOSString())); //$NON-NLS-1$
- }
- else {
- outputPath = path;
- valid = true;
- }
- }
-
- return valid;
- }
-
- private ValgrindLaunchPlugin getPlugin() {
- return ValgrindLaunchPlugin.getDefault();
- }
-
- public CheckboxTableViewer getViewer() {
- return viewer;
- }
-
- public Text getDestText() {
- return destText;
- }
+ private IPath outputPath;
+ private CheckboxTableViewer viewer;
+ private Text destText;
+
+ protected ValgrindExportWizardPage(String pageName, String title, ImageDescriptor titleImage) {
+ super(pageName, title, titleImage);
+ }
+
+
+ @Override
+ public void createControl(Composite parent) {
+ Composite top = new Composite(parent, SWT.NONE);
+ top.setLayout(new GridLayout());
+ top.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ IPath logPath = null;
+
+ // Retrieve location of Valgrind logs from launch configuration
+ ILaunchConfiguration config = getPlugin().getCurrentLaunchConfiguration();
+ if (config != null && config.exists()) {
+ String strpath;
+ try {
+ strpath = config.getAttribute(LaunchConfigurationConstants.ATTR_INTERNAL_OUTPUT_DIR, (String) null);
+ if (strpath != null) {
+ logPath = Path.fromPortableString(strpath);
+ }
+ } catch (CoreException e) {
+ setErrorMessage(e.getLocalizedMessage());
+ e.printStackTrace();
+ }
+ }
+
+ Label selectFilesLabel = new Label(top, SWT.NONE);
+ selectFilesLabel.setText(Messages.getString("ValgrindExportWizardPage.Viewer_label")); //$NON-NLS-1$
+
+ viewer = CheckboxTableViewer.newCheckList(top, SWT.BORDER);
+ viewer.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));
+ viewer.setContentProvider(new ArrayContentProvider());
+ viewer.setLabelProvider(new LabelProvider() {
+ @Override
+ public String getText(Object element) {
+ return ((File) element).getName();
+ }
+
+ @Override
+ public Image getImage(Object element) {
+ return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE);
+ }
+ });
+
+ Composite selectAllNoneTop = new Composite(top, SWT.NONE);
+ selectAllNoneTop.setLayout(new GridLayout(2, true));
+ selectAllNoneTop.setLayoutData(new GridData(SWT.TRAIL, SWT.DEFAULT, false, false));
+
+ Button selectAllButton = new Button(selectAllNoneTop, SWT.NONE);
+ selectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ selectAllButton.setText(Messages.getString("ValgrindExportWizardPage.Select_all")); //$NON-NLS-1$
+ selectAllButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ viewer.setAllChecked(true);
+ }
+ });
+
+ Button deselectAllButton = new Button(selectAllNoneTop, SWT.NONE);
+ deselectAllButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ deselectAllButton.setText(Messages.getString("ValgrindExportWizardPage.Deselect_all")); //$NON-NLS-1$
+ deselectAllButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ viewer.setAllChecked(false);
+ }
+ });
+
+ createDestinationGroup(top);
+
+ if (logPath != null) {
+ // List all output files in our output directory from the recent launch
+ File logs[] = logPath.toFile().listFiles(new FileFilter() {
+ @Override
+ public boolean accept(File pathname) {
+ return pathname.isFile();
+ }
+ });
+ viewer.setInput(logs);
+ viewer.setAllChecked(true);
+ }
+
+ // catch any errors so far
+ setPageComplete(isValid());
+
+ setControl(top);
+ }
+
+ public IPath getOutputPath() {
+ return outputPath;
+ }
+
+ public File[] getSelectedFiles() {
+ Object[] selected = viewer.getCheckedElements();
+ File[] files = new File[selected.length];
+ System.arraycopy(selected, 0, files, 0, selected.length);
+ return files;
+ }
+
+ private void createDestinationGroup(Composite top) {
+ Group destGroup = new Group(top, SWT.SHADOW_OUT);
+ destGroup.setText(Messages.getString("ValgrindExportWizardPage.Destination_group")); //$NON-NLS-1$
+ destGroup.setLayout(new GridLayout(2, false));
+ destGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ destText = new Text(destGroup, SWT.BORDER);
+ destText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ destText.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ setPageComplete(isValid());
+ }
+ });
+
+ Button browseButton = new Button(destGroup, SWT.PUSH);
+ browseButton.setText(Messages.getString("ValgrindExportWizardPage.Browse")); //$NON-NLS-1$
+ browseButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ // Prompt for output directory
+ Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
+ DirectoryDialog dialog = new DirectoryDialog(parent);
+ dialog.setText(Messages.getString("ValgrindLaunchConfigurationDelegate.Select_Destination")); //$NON-NLS-1$
+ String strpath = dialog.open();
+ if (strpath != null) {
+ destText.setText(strpath);
+ }
+ }
+ });
+ }
+
+ private boolean isValid() {
+ boolean valid = false;
+ int length = -1;
+
+ setErrorMessage(null);
+ setMessage(null);
+
+ Object obj = viewer.getInput();
+ // Check if there are no launch files (either null because directory is missing
+ // or 0 files are found in directory)
+ if (obj instanceof File[])
+ length = ((File[])obj).length;
+ if (viewer.getInput() == null || length == 0) {
+ setErrorMessage(Messages.getString("ValgrindExportWizardPage.Err_No_Valgrind_run")); //$NON-NLS-1$
+ }
+ else if (destText.getText().equals("")) { //$NON-NLS-1$
+ setMessage(Messages.getString("ValgrindExportWizardPage.Msg_Select_destination")); //$NON-NLS-1$
+ }
+ else {
+ IPath path = Path.fromOSString(destText.getText());
+ if (!path.toFile().exists()) {
+ setErrorMessage(NLS.bind(Messages.getString("ValgrindExportWizardPage.Err_Dir_not_exist"), path.toOSString())); //$NON-NLS-1$
+ }
+ else if (!path.toFile().isDirectory()) {
+ setErrorMessage(NLS.bind(Messages.getString("ValgrindExportWizardPage.Err_Not_dir"), path.toOSString())); //$NON-NLS-1$
+ }
+ else {
+ outputPath = path;
+ valid = true;
+ }
+ }
+
+ return valid;
+ }
+
+ private ValgrindLaunchPlugin getPlugin() {
+ return ValgrindLaunchPlugin.getDefault();
+ }
+
+ public CheckboxTableViewer getViewer() {
+ return viewer;
+ }
+
+ public Text getDestText() {
+ return destText;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchConfigurationDelegate.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchConfigurationDelegate.java
index 5bffa2dbf4..56e0f8ee21 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchConfigurationDelegate.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchConfigurationDelegate.java
@@ -62,327 +62,327 @@ import org.osgi.framework.Version;
public class ValgrindLaunchConfigurationDelegate extends AbstractCLaunchDelegate {
- private static final String NO = "no"; //$NON-NLS-1$
- private static final String YES = "yes"; //$NON-NLS-1$
- private static final String EQUALS = "="; //$NON-NLS-1$
-
- private static final String LOG_FILE = CommandLineConstants.LOG_PREFIX + "%p.txt"; //$NON-NLS-1$
- private static final FileFilter LOG_FILTER = new FileFilter() {
- @Override
- public boolean accept(File pathname) {
- return pathname.getName().startsWith(CommandLineConstants.LOG_PREFIX);
- }
- };
-
- protected String toolID;
- protected ValgrindCommand command;
- protected IPath outputPath;
- protected IValgrindLaunchDelegate dynamicDelegate;
- protected ILaunchConfiguration config;
- protected ILaunch launch;
- protected IProcess process;
- protected String launchStr;
- protected Version valgrindVersion; // null if not used
-
- @Override
- public void launch(ILaunchConfiguration config, String mode,
- ILaunch launch, IProgressMonitor m) throws CoreException {
- if (m == null) {
- m = new NullProgressMonitor();
- }
-
- SubMonitor monitor = SubMonitor.convert(m, Messages.getString("ValgrindLaunchConfigurationDelegate.Profiling_Local_CCPP_Application"), 10); //$NON-NLS-1$
- // check for cancellation
- if (monitor.isCanceled()) {
- return;
- }
-
- this.config = config;
- this.launch = launch;
- try {
- IProject project = CDebugUtils.verifyCProject(config).getProject();
- command = getValgrindCommand();
-
- // remove any output from previous run
- ValgrindUIPlugin.getDefault().resetView();
- // reset stored launch data
- getPlugin().setCurrentLaunchConfiguration(null);
- getPlugin().setCurrentLaunch(null);
-
- String valgrindCommand= getValgrindCommand().getValgrindCommand();
- // also ensure Valgrind version is usable
- valgrindVersion = getPlugin().getValgrindVersion(project);
-
- monitor.worked(1);
- IPath exePath = CDebugUtils.verifyProgramPath(config);
- String[] arguments = getProgramArgumentsArray(config);
- File workDir = getWorkingDirectory(config);
- if (workDir == null) {
- workDir = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // set output directory in config
- IValgrindOutputDirectoryProvider provider = getPlugin().getOutputDirectoryProvider();
- setOutputPath(config, provider.getOutputPath());
- outputPath = verifyOutputPath(config);
- // create/empty output directory
- createDirectory(outputPath);
-
- // tool that was launched
- toolID = getTool(config);
- // ask tool extension for arguments
- dynamicDelegate = getDynamicDelegate(toolID);
- String[] opts = getValgrindArgumentsArray(config);
-
- // set the default source locator if required
- setDefaultSourceLocator(launch, config);
-
- ArrayList<String> cmdLine = new ArrayList<>(1 + arguments.length);
- cmdLine.add(valgrindCommand);
- cmdLine.addAll(Arrays.asList(opts));
- cmdLine.add(exePath.toOSString());
- cmdLine.addAll(Arrays.asList(arguments));
- String[] commandArray = cmdLine.toArray(new String[cmdLine.size()]);
- boolean usePty = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL, ICDTLaunchConfigurationConstants.USE_TERMINAL_DEFAULT);
- monitor.worked(1);
-
- // check for cancellation
- if (monitor.isCanceled()) {
- return;
- }
- // call Valgrind
-
- command.execute(commandArray, getEnvironment(config), workDir, usePty, project);
- monitor.worked(3);
- process = createNewProcess(launch, command.getProcess(), commandArray[0]);
- // set the command line used
- process.setAttribute(IProcess.ATTR_CMDLINE, command.getCommandLine());
- while (!process.isTerminated()) {
- Thread.sleep(100);
- }
-
- // store these for use by other classes
- getPlugin().setCurrentLaunchConfiguration(config);
- getPlugin().setCurrentLaunch(launch);
-
- // parse Valgrind logs
- IValgrindMessage[] messages = parseLogs(outputPath);
-
- // create launch summary string to distinguish this launch
- launchStr = createLaunchStr();
-
- // create view
- ValgrindUIPlugin.getDefault().createView(launchStr, toolID);
- // set log messages
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- view.setMessages(messages);
- monitor.worked(1);
-
- // pass off control to extender
- dynamicDelegate.handleLaunch(config, launch, outputPath, monitor.newChild(2));
-
- // initialize tool-specific part of view
- dynamicDelegate.initializeView(view.getDynamicView(), launchStr, monitor.newChild(1));
-
- // refresh view
- ValgrindUIPlugin.getDefault().refreshView();
-
- // show view
- ValgrindUIPlugin.getDefault().showView();
-
- // set up resource listener for post-build events.
- ResourcesPlugin.getWorkspace().addResourceChangeListener(
- new ProjectBuildListener(project), IResourceChangeEvent.POST_BUILD);
-
- monitor.worked(1);
- } catch (IOException e) {
- abort(Messages.getString("ValgrindLaunchConfigurationDelegate.Error_starting_process"), e, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); //$NON-NLS-1$
- e.printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- m.done();
- }
- }
-
- protected IValgrindMessage[] parseLogs(IPath outputPath) throws IOException, CoreException {
- List<IValgrindMessage> messages = new ArrayList<>();
-
- for (File log : outputPath.toFile().listFiles(LOG_FILTER)) {
- ValgrindCoreParser parser = new ValgrindCoreParser(log, launch);
- IValgrindMessage[] results = parser.getMessages();
-
- if (results.length == 0){
- results = new IValgrindMessage[1];
- results[0] = new ValgrindInfo(null, Messages.getString("ValgrindOutputView.No_output"), launch); //$NON-NLS-1$
- }
- messages.addAll(Arrays.asList(results));
- createMarkers(results);
- }
-
- return messages.toArray(new IValgrindMessage[messages.size()]);
- }
-
- private void createMarkers(IValgrindMessage[] messages) throws CoreException {
- // find the topmost stack frame within the workspace to annotate with marker
- // traverse nested errors as well
- Stack<IValgrindMessage> messageStack = new Stack<>();
- messageStack.addAll(Arrays.asList(messages));
- while (!messageStack.isEmpty()) {
- IValgrindMessage message = messageStack.pop();
- IMarker marker = null;
- IValgrindMessage[] children = message.getChildren();
- for (int i = 0; i < children.length; i++) {
- // if we've found our marker we don't care about any further frames in this stack
- if (children[i] instanceof ValgrindStackFrame && marker == null) {
- ValgrindStackFrame frame = (ValgrindStackFrame) children[i];
- if (frame.getLine() > 0) {
- ISourceLocator locator = frame.getLaunch().getSourceLocator();
- ISourceLookupResult result = DebugUITools.lookupSource(frame.getFile(), locator);
- Object sourceElement = result.getSourceElement();
-
- if (sourceElement != null) {
- // Resolve IResource in case we get a LocalFileStorage object
- if (sourceElement instanceof LocalFileStorage) {
- IPath filePath = ((LocalFileStorage) sourceElement).getFullPath();
- URI fileURI = URIUtil.toURI(filePath);
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IFile[] files = root.findFilesForLocationURI(fileURI);
- if (files.length > 0) {
- // Take the first match
- sourceElement = files[0];
- }
- }
-
- if (sourceElement instanceof IResource) {
- IResource resource = (IResource) sourceElement;
- marker = resource.createMarker(ValgrindLaunchPlugin.MARKER_TYPE);
- marker.setAttribute(IMarker.MESSAGE, message.getText());
- marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
- marker.setAttribute(IMarker.LINE_NUMBER, frame.getLine());
- }
- }
- }
- }
- else if (children[i] instanceof ValgrindError) {
- // nested error
- messageStack.push(children[i]);
- }
- }
- }
- }
-
- protected IProcess createNewProcess(ILaunch launch, Process systemProcess, String programName) {
- return DebugPlugin.newProcess(launch, systemProcess, renderProcessLabel(programName));
- }
-
- protected ValgrindCommand getValgrindCommand() {
- return getPlugin().getValgrindCommand();
- }
-
- protected ValgrindLaunchPlugin getPlugin() {
- return ValgrindLaunchPlugin.getDefault();
- }
-
- protected IValgrindLaunchDelegate getDynamicDelegate(String toolID) throws CoreException {
- return getPlugin().getToolDelegate(toolID);
- }
-
- private IPath verifyOutputPath(ILaunchConfiguration config) throws CoreException {
- IPath result = null;
- String strPath = config.getAttribute(LaunchConfigurationConstants.ATTR_INTERNAL_OUTPUT_DIR, (String) null);
- if (strPath != null) {
- result = Path.fromPortableString(strPath);
- }
- if (result == null) {
- abort(Messages.getString("ValgrindLaunchConfigurationDelegate.Retrieving_location_failed"), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); //$NON-NLS-1$
- }
- return result;
- }
-
- protected void setOutputPath(ILaunchConfiguration config, IPath outputPath) throws CoreException {
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- wc.setAttribute(LaunchConfigurationConstants.ATTR_INTERNAL_OUTPUT_DIR, outputPath.toPortableString());
- wc.doSave();
- }
-
- protected void createDirectory(IPath path) throws IOException {
- File outputDir = path.toFile();
-
- if (outputDir.exists()) {
- // delete any preexisting files
- for (File outputFile : outputDir.listFiles()) {
- if (outputFile.isFile() && !outputFile.delete()) {
- throw new IOException(NLS.bind(Messages.getString("ValgrindOutputDirectory.Couldnt_delete"), outputFile.getAbsolutePath())); //$NON-NLS-1$
- }
- }
- } else if (!outputDir.mkdir()) {
- throw new IOException(NLS.bind(Messages.getString("ValgrindOutputDirectory.Couldnt_create"), outputDir.getAbsolutePath())); //$NON-NLS-1$
- }
- }
-
- private String createLaunchStr() {
- return config.getName() + " [" + getPlugin().getToolName(toolID) + "] " + process.getLabel(); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- protected String[] getValgrindArgumentsArray(ILaunchConfiguration config) throws CoreException {
- ArrayList<String> opts = new ArrayList<>();
- opts.add(CommandLineConstants.OPT_TOOL + EQUALS + getPlugin().getToolName(toolID));
- opts.add(CommandLineConstants.OPT_QUIET); // suppress uninteresting output
- opts.add(CommandLineConstants.OPT_LOGFILE + EQUALS + outputPath.append(LOG_FILE).toOSString());
-
- opts.add(CommandLineConstants.OPT_TRACECHILD + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, LaunchConfigurationConstants.DEFAULT_GENERAL_TRACECHILD) ? YES : NO));
- opts.add(CommandLineConstants.OPT_CHILDSILENT + EQUALS + YES); // necessary for parsing
- opts.add(CommandLineConstants.OPT_FREERES + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_FREERES, LaunchConfigurationConstants.DEFAULT_GENERAL_FREERES) ? YES : NO));
-
- opts.add(CommandLineConstants.OPT_DEMANGLE + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DEMANGLE, LaunchConfigurationConstants.DEFAULT_GENERAL_DEMANGLE) ? YES : NO));
- opts.add(CommandLineConstants.OPT_NUMCALLERS + EQUALS + config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_NUMCALLERS, LaunchConfigurationConstants.DEFAULT_GENERAL_NUMCALLERS));
- opts.add(CommandLineConstants.OPT_ERRLIMIT + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_ERRLIMIT, LaunchConfigurationConstants.DEFAULT_GENERAL_ERRLIMIT) ? YES : NO));
- opts.add(CommandLineConstants.OPT_BELOWMAIN + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_BELOWMAIN, LaunchConfigurationConstants.DEFAULT_GENERAL_BELOWMAIN) ? YES : NO));
- opts.add(CommandLineConstants.OPT_MAXFRAME + EQUALS + config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAXFRAME, LaunchConfigurationConstants.DEFAULT_GENERAL_MAXFRAME));
-
- // 3.4.0 specific
- if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
- boolean useMainStack = config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK_BOOL, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK_BOOL);
- if (useMainStack) {
- opts.add(CommandLineConstants.OPT_MAINSTACK + EQUALS + config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK));
- }
- }
-
- // 3.6.0 specific
- if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_6_0) >= 0) {
- if (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DSYMUTIL, LaunchConfigurationConstants.DEFAULT_GENERAL_DSYMUTIL) != LaunchConfigurationConstants.DEFAULT_GENERAL_DSYMUTIL)
- opts.add(CommandLineConstants.OPT_DSYMUTIL + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DSYMUTIL, LaunchConfigurationConstants.DEFAULT_GENERAL_DSYMUTIL) ? YES : NO));
- }
-
- List<?> suppFiles = config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_SUPPFILES, LaunchConfigurationConstants.DEFAULT_GENERAL_SUPPFILES);
- for (Object strpath : suppFiles) {
- IPath suppfile = getPlugin().parseWSPath((String) strpath);
- if (suppfile != null) {
- opts.add(CommandLineConstants.OPT_SUPPFILE + EQUALS + suppfile.toOSString());
- }
- }
- opts.addAll(Arrays.asList(dynamicDelegate.getCommandArray(config, valgrindVersion, outputPath)));
-
- String[] ret = new String[opts.size()];
- return opts.toArray(ret);
- }
-
- protected String getTool(ILaunchConfiguration config) throws CoreException {
- return config.getAttribute(LaunchConfigurationConstants.ATTR_TOOL, LaunchConfigurationConstants.DEFAULT_TOOL);
- }
-
- @Override
- protected String getPluginID() {
- return ValgrindLaunchPlugin.PLUGIN_ID;
- }
-
- @Override
- public boolean finalLaunchCheck(ILaunchConfiguration configuration,
- String mode, IProgressMonitor monitor) throws CoreException {
- //Delete our own problem markers
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- root.deleteMarkers(ValgrindLaunchPlugin.MARKER_TYPE, true, IResource.DEPTH_INFINITE);
- return super.finalLaunchCheck(configuration, mode, monitor);
- }
+ private static final String NO = "no"; //$NON-NLS-1$
+ private static final String YES = "yes"; //$NON-NLS-1$
+ private static final String EQUALS = "="; //$NON-NLS-1$
+
+ private static final String LOG_FILE = CommandLineConstants.LOG_PREFIX + "%p.txt"; //$NON-NLS-1$
+ private static final FileFilter LOG_FILTER = new FileFilter() {
+ @Override
+ public boolean accept(File pathname) {
+ return pathname.getName().startsWith(CommandLineConstants.LOG_PREFIX);
+ }
+ };
+
+ protected String toolID;
+ protected ValgrindCommand command;
+ protected IPath outputPath;
+ protected IValgrindLaunchDelegate dynamicDelegate;
+ protected ILaunchConfiguration config;
+ protected ILaunch launch;
+ protected IProcess process;
+ protected String launchStr;
+ protected Version valgrindVersion; // null if not used
+
+ @Override
+ public void launch(ILaunchConfiguration config, String mode,
+ ILaunch launch, IProgressMonitor m) throws CoreException {
+ if (m == null) {
+ m = new NullProgressMonitor();
+ }
+
+ SubMonitor monitor = SubMonitor.convert(m, Messages.getString("ValgrindLaunchConfigurationDelegate.Profiling_Local_CCPP_Application"), 10); //$NON-NLS-1$
+ // check for cancellation
+ if (monitor.isCanceled()) {
+ return;
+ }
+
+ this.config = config;
+ this.launch = launch;
+ try {
+ IProject project = CDebugUtils.verifyCProject(config).getProject();
+ command = getValgrindCommand();
+
+ // remove any output from previous run
+ ValgrindUIPlugin.getDefault().resetView();
+ // reset stored launch data
+ getPlugin().setCurrentLaunchConfiguration(null);
+ getPlugin().setCurrentLaunch(null);
+
+ String valgrindCommand= getValgrindCommand().getValgrindCommand();
+ // also ensure Valgrind version is usable
+ valgrindVersion = getPlugin().getValgrindVersion(project);
+
+ monitor.worked(1);
+ IPath exePath = CDebugUtils.verifyProgramPath(config);
+ String[] arguments = getProgramArgumentsArray(config);
+ File workDir = getWorkingDirectory(config);
+ if (workDir == null) {
+ workDir = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // set output directory in config
+ IValgrindOutputDirectoryProvider provider = getPlugin().getOutputDirectoryProvider();
+ setOutputPath(config, provider.getOutputPath());
+ outputPath = verifyOutputPath(config);
+ // create/empty output directory
+ createDirectory(outputPath);
+
+ // tool that was launched
+ toolID = getTool(config);
+ // ask tool extension for arguments
+ dynamicDelegate = getDynamicDelegate(toolID);
+ String[] opts = getValgrindArgumentsArray(config);
+
+ // set the default source locator if required
+ setDefaultSourceLocator(launch, config);
+
+ ArrayList<String> cmdLine = new ArrayList<>(1 + arguments.length);
+ cmdLine.add(valgrindCommand);
+ cmdLine.addAll(Arrays.asList(opts));
+ cmdLine.add(exePath.toOSString());
+ cmdLine.addAll(Arrays.asList(arguments));
+ String[] commandArray = cmdLine.toArray(new String[cmdLine.size()]);
+ boolean usePty = config.getAttribute(ICDTLaunchConfigurationConstants.ATTR_USE_TERMINAL, ICDTLaunchConfigurationConstants.USE_TERMINAL_DEFAULT);
+ monitor.worked(1);
+
+ // check for cancellation
+ if (monitor.isCanceled()) {
+ return;
+ }
+ // call Valgrind
+
+ command.execute(commandArray, getEnvironment(config), workDir, usePty, project);
+ monitor.worked(3);
+ process = createNewProcess(launch, command.getProcess(), commandArray[0]);
+ // set the command line used
+ process.setAttribute(IProcess.ATTR_CMDLINE, command.getCommandLine());
+ while (!process.isTerminated()) {
+ Thread.sleep(100);
+ }
+
+ // store these for use by other classes
+ getPlugin().setCurrentLaunchConfiguration(config);
+ getPlugin().setCurrentLaunch(launch);
+
+ // parse Valgrind logs
+ IValgrindMessage[] messages = parseLogs(outputPath);
+
+ // create launch summary string to distinguish this launch
+ launchStr = createLaunchStr();
+
+ // create view
+ ValgrindUIPlugin.getDefault().createView(launchStr, toolID);
+ // set log messages
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ view.setMessages(messages);
+ monitor.worked(1);
+
+ // pass off control to extender
+ dynamicDelegate.handleLaunch(config, launch, outputPath, monitor.newChild(2));
+
+ // initialize tool-specific part of view
+ dynamicDelegate.initializeView(view.getDynamicView(), launchStr, monitor.newChild(1));
+
+ // refresh view
+ ValgrindUIPlugin.getDefault().refreshView();
+
+ // show view
+ ValgrindUIPlugin.getDefault().showView();
+
+ // set up resource listener for post-build events.
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(
+ new ProjectBuildListener(project), IResourceChangeEvent.POST_BUILD);
+
+ monitor.worked(1);
+ } catch (IOException e) {
+ abort(Messages.getString("ValgrindLaunchConfigurationDelegate.Error_starting_process"), e, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); //$NON-NLS-1$
+ e.printStackTrace();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ } finally {
+ m.done();
+ }
+ }
+
+ protected IValgrindMessage[] parseLogs(IPath outputPath) throws IOException, CoreException {
+ List<IValgrindMessage> messages = new ArrayList<>();
+
+ for (File log : outputPath.toFile().listFiles(LOG_FILTER)) {
+ ValgrindCoreParser parser = new ValgrindCoreParser(log, launch);
+ IValgrindMessage[] results = parser.getMessages();
+
+ if (results.length == 0){
+ results = new IValgrindMessage[1];
+ results[0] = new ValgrindInfo(null, Messages.getString("ValgrindOutputView.No_output"), launch); //$NON-NLS-1$
+ }
+ messages.addAll(Arrays.asList(results));
+ createMarkers(results);
+ }
+
+ return messages.toArray(new IValgrindMessage[messages.size()]);
+ }
+
+ private void createMarkers(IValgrindMessage[] messages) throws CoreException {
+ // find the topmost stack frame within the workspace to annotate with marker
+ // traverse nested errors as well
+ Stack<IValgrindMessage> messageStack = new Stack<>();
+ messageStack.addAll(Arrays.asList(messages));
+ while (!messageStack.isEmpty()) {
+ IValgrindMessage message = messageStack.pop();
+ IMarker marker = null;
+ IValgrindMessage[] children = message.getChildren();
+ for (int i = 0; i < children.length; i++) {
+ // if we've found our marker we don't care about any further frames in this stack
+ if (children[i] instanceof ValgrindStackFrame && marker == null) {
+ ValgrindStackFrame frame = (ValgrindStackFrame) children[i];
+ if (frame.getLine() > 0) {
+ ISourceLocator locator = frame.getLaunch().getSourceLocator();
+ ISourceLookupResult result = DebugUITools.lookupSource(frame.getFile(), locator);
+ Object sourceElement = result.getSourceElement();
+
+ if (sourceElement != null) {
+ // Resolve IResource in case we get a LocalFileStorage object
+ if (sourceElement instanceof LocalFileStorage) {
+ IPath filePath = ((LocalFileStorage) sourceElement).getFullPath();
+ URI fileURI = URIUtil.toURI(filePath);
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ IFile[] files = root.findFilesForLocationURI(fileURI);
+ if (files.length > 0) {
+ // Take the first match
+ sourceElement = files[0];
+ }
+ }
+
+ if (sourceElement instanceof IResource) {
+ IResource resource = (IResource) sourceElement;
+ marker = resource.createMarker(ValgrindLaunchPlugin.MARKER_TYPE);
+ marker.setAttribute(IMarker.MESSAGE, message.getText());
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
+ marker.setAttribute(IMarker.LINE_NUMBER, frame.getLine());
+ }
+ }
+ }
+ }
+ else if (children[i] instanceof ValgrindError) {
+ // nested error
+ messageStack.push(children[i]);
+ }
+ }
+ }
+ }
+
+ protected IProcess createNewProcess(ILaunch launch, Process systemProcess, String programName) {
+ return DebugPlugin.newProcess(launch, systemProcess, renderProcessLabel(programName));
+ }
+
+ protected ValgrindCommand getValgrindCommand() {
+ return getPlugin().getValgrindCommand();
+ }
+
+ protected ValgrindLaunchPlugin getPlugin() {
+ return ValgrindLaunchPlugin.getDefault();
+ }
+
+ protected IValgrindLaunchDelegate getDynamicDelegate(String toolID) throws CoreException {
+ return getPlugin().getToolDelegate(toolID);
+ }
+
+ private IPath verifyOutputPath(ILaunchConfiguration config) throws CoreException {
+ IPath result = null;
+ String strPath = config.getAttribute(LaunchConfigurationConstants.ATTR_INTERNAL_OUTPUT_DIR, (String) null);
+ if (strPath != null) {
+ result = Path.fromPortableString(strPath);
+ }
+ if (result == null) {
+ abort(Messages.getString("ValgrindLaunchConfigurationDelegate.Retrieving_location_failed"), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); //$NON-NLS-1$
+ }
+ return result;
+ }
+
+ protected void setOutputPath(ILaunchConfiguration config, IPath outputPath) throws CoreException {
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ wc.setAttribute(LaunchConfigurationConstants.ATTR_INTERNAL_OUTPUT_DIR, outputPath.toPortableString());
+ wc.doSave();
+ }
+
+ protected void createDirectory(IPath path) throws IOException {
+ File outputDir = path.toFile();
+
+ if (outputDir.exists()) {
+ // delete any preexisting files
+ for (File outputFile : outputDir.listFiles()) {
+ if (outputFile.isFile() && !outputFile.delete()) {
+ throw new IOException(NLS.bind(Messages.getString("ValgrindOutputDirectory.Couldnt_delete"), outputFile.getAbsolutePath())); //$NON-NLS-1$
+ }
+ }
+ } else if (!outputDir.mkdir()) {
+ throw new IOException(NLS.bind(Messages.getString("ValgrindOutputDirectory.Couldnt_create"), outputDir.getAbsolutePath())); //$NON-NLS-1$
+ }
+ }
+
+ private String createLaunchStr() {
+ return config.getName() + " [" + getPlugin().getToolName(toolID) + "] " + process.getLabel(); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ protected String[] getValgrindArgumentsArray(ILaunchConfiguration config) throws CoreException {
+ ArrayList<String> opts = new ArrayList<>();
+ opts.add(CommandLineConstants.OPT_TOOL + EQUALS + getPlugin().getToolName(toolID));
+ opts.add(CommandLineConstants.OPT_QUIET); // suppress uninteresting output
+ opts.add(CommandLineConstants.OPT_LOGFILE + EQUALS + outputPath.append(LOG_FILE).toOSString());
+
+ opts.add(CommandLineConstants.OPT_TRACECHILD + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, LaunchConfigurationConstants.DEFAULT_GENERAL_TRACECHILD) ? YES : NO));
+ opts.add(CommandLineConstants.OPT_CHILDSILENT + EQUALS + YES); // necessary for parsing
+ opts.add(CommandLineConstants.OPT_FREERES + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_FREERES, LaunchConfigurationConstants.DEFAULT_GENERAL_FREERES) ? YES : NO));
+
+ opts.add(CommandLineConstants.OPT_DEMANGLE + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DEMANGLE, LaunchConfigurationConstants.DEFAULT_GENERAL_DEMANGLE) ? YES : NO));
+ opts.add(CommandLineConstants.OPT_NUMCALLERS + EQUALS + config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_NUMCALLERS, LaunchConfigurationConstants.DEFAULT_GENERAL_NUMCALLERS));
+ opts.add(CommandLineConstants.OPT_ERRLIMIT + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_ERRLIMIT, LaunchConfigurationConstants.DEFAULT_GENERAL_ERRLIMIT) ? YES : NO));
+ opts.add(CommandLineConstants.OPT_BELOWMAIN + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_BELOWMAIN, LaunchConfigurationConstants.DEFAULT_GENERAL_BELOWMAIN) ? YES : NO));
+ opts.add(CommandLineConstants.OPT_MAXFRAME + EQUALS + config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAXFRAME, LaunchConfigurationConstants.DEFAULT_GENERAL_MAXFRAME));
+
+ // 3.4.0 specific
+ if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
+ boolean useMainStack = config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK_BOOL, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK_BOOL);
+ if (useMainStack) {
+ opts.add(CommandLineConstants.OPT_MAINSTACK + EQUALS + config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK));
+ }
+ }
+
+ // 3.6.0 specific
+ if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_6_0) >= 0) {
+ if (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DSYMUTIL, LaunchConfigurationConstants.DEFAULT_GENERAL_DSYMUTIL) != LaunchConfigurationConstants.DEFAULT_GENERAL_DSYMUTIL)
+ opts.add(CommandLineConstants.OPT_DSYMUTIL + EQUALS + (config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DSYMUTIL, LaunchConfigurationConstants.DEFAULT_GENERAL_DSYMUTIL) ? YES : NO));
+ }
+
+ List<?> suppFiles = config.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_SUPPFILES, LaunchConfigurationConstants.DEFAULT_GENERAL_SUPPFILES);
+ for (Object strpath : suppFiles) {
+ IPath suppfile = getPlugin().parseWSPath((String) strpath);
+ if (suppfile != null) {
+ opts.add(CommandLineConstants.OPT_SUPPFILE + EQUALS + suppfile.toOSString());
+ }
+ }
+ opts.addAll(Arrays.asList(dynamicDelegate.getCommandArray(config, valgrindVersion, outputPath)));
+
+ String[] ret = new String[opts.size()];
+ return opts.toArray(ret);
+ }
+
+ protected String getTool(ILaunchConfiguration config) throws CoreException {
+ return config.getAttribute(LaunchConfigurationConstants.ATTR_TOOL, LaunchConfigurationConstants.DEFAULT_TOOL);
+ }
+
+ @Override
+ protected String getPluginID() {
+ return ValgrindLaunchPlugin.PLUGIN_ID;
+ }
+
+ @Override
+ public boolean finalLaunchCheck(ILaunchConfiguration configuration,
+ String mode, IProgressMonitor monitor) throws CoreException {
+ //Delete our own problem markers
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ root.deleteMarkers(ValgrindLaunchPlugin.MARKER_TYPE, true, IResource.DEPTH_INFINITE);
+ return super.finalLaunchCheck(configuration, mode, monitor);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchConfigurationTabGroup.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchConfigurationTabGroup.java
index b2d3fec069..5e9fc7e112 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchConfigurationTabGroup.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchConfigurationTabGroup.java
@@ -7,20 +7,20 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.launch;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTabGroup;
public class ValgrindLaunchConfigurationTabGroup extends
- ProfileLaunchConfigurationTabGroup {
+ ProfileLaunchConfigurationTabGroup {
+
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ return new AbstractLaunchConfigurationTab[] {
+ new ValgrindOptionsTab()
+ };
+ }
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- return new AbstractLaunchConfigurationTab[] {
- new ValgrindOptionsTab()
- };
- }
-
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchPlugin.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchPlugin.java
index 6c9c78e827..9b3836305b 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchPlugin.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchPlugin.java
@@ -40,236 +40,236 @@ import org.osgi.framework.Version;
public class ValgrindLaunchPlugin extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.launch"; //$NON-NLS-1$
- public static final String LAUNCH_ID = PLUGIN_ID + ".valgrindLaunch"; //$NON-NLS-1$
- public static final String MARKER_TYPE = PLUGIN_ID + ".marker"; //$NON-NLS-1$
- public static final String OUTPUT_DIR_EXT_ID = "outputDirectoryProviders"; //$NON-NLS-1$
-
- // Extension point constants
- public static final String TOOL_EXT_ID = "valgrindTools"; //$NON-NLS-1$
- public static final String TOOL_EXT_DEFAULT = PLUGIN_ID + ".memcheck"; //$NON-NLS-1$
- protected static final String EXT_ELEMENT_TOOL = "tool"; //$NON-NLS-1$
- protected static final String EXT_ATTR_NAME = "name"; //$NON-NLS-1$
- protected static final String EXT_ATTR_ID = "id"; //$NON-NLS-1$
- protected static final String EXT_ATTR_PAGE = "page"; //$NON-NLS-1$
- protected static final String EXT_ATTR_DELEGATE = "delegate"; //$NON-NLS-1$
-
- protected static final String EXT_ELEMENT_PROVIDER = "provider"; //$NON-NLS-1$
- protected static final String EXT_ATTR_CLASS = "class"; //$NON-NLS-1$
-
- public static final Version VER_3_3_0 = new Version(3, 3, 0);
- public static final Version VER_3_4_0 = new Version(3, 4, 0);
- public static final Version VER_3_6_0 = new Version(3, 6, 0);
-
- private static final Version MIN_VER = VER_3_3_0;
- private static final String VERSION_PREFIX = "valgrind-"; //$NON-NLS-1$
- private static final char VERSION_DELIMITER = '-';
-
- protected HashMap<String, IConfigurationElement> toolMap;
-
- private ValgrindCommand valgrindCommand;
- private ILaunchConfiguration config;
- private ILaunch launch;
-
- // The shared instance
- private static ValgrindLaunchPlugin plugin;
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static ValgrindLaunchPlugin getDefault() {
- return plugin;
- }
-
- /**
- * @since 0.10
- */
- public Version getValgrindVersion(IProject project) throws CoreException {
- Version valgrindVersion;
- try {
- String verString = getValgrindCommand().whichVersion(project);
- verString = verString.replace(VERSION_PREFIX, ""); //$NON-NLS-1$
- if (verString.indexOf(VERSION_DELIMITER) > 0) {
- verString = verString.substring(0, verString.indexOf(VERSION_DELIMITER));
- }
- if (!verString.isEmpty()) {
- valgrindVersion = Version.parseVersion(verString);
- } else {
- throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Couldn't_determine_version"))); //$NON-NLS-1$
- }
- } catch (IOException e) {
- IStatus status = new Status(IStatus.ERROR, PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Couldn't_determine_version"), e); //$NON-NLS-1$
- throw new CoreException(status);
- }
-
- // check for minimum supported version
- if (valgrindVersion.compareTo(MIN_VER) < 0) {
- throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, NLS.bind(Messages.getString("ValgrindLaunchPlugin.Error_min_version"), valgrindVersion.toString(), MIN_VER.toString()))); //$NON-NLS-1$
- }
- return valgrindVersion;
- }
-
- public void setValgrindCommand(ValgrindCommand command) {
- valgrindCommand = command;
- }
-
- /**
- * @since 0.10
- */
- protected ValgrindCommand getValgrindCommand() {
- if (valgrindCommand == null) {
- valgrindCommand = new ValgrindCommand();
- }
- return valgrindCommand;
- }
-
- public String[] getRegisteredToolIDs() {
- Set<String> ids = getToolMap().keySet();
- return ids.toArray(new String[ids.size()]);
- }
-
- public String getToolName(String id) {
- String name = null;
- IConfigurationElement config = getToolMap().get(id);
- if (config != null) {
- name = config.getAttribute(EXT_ATTR_NAME);
- }
- return name;
- }
-
- public IValgrindToolPage getToolPage(String id) throws CoreException {
- IValgrindToolPage tab = null;
- IConfigurationElement config = getToolMap().get(id);
- if (config != null) {
- Object obj = config.createExecutableExtension(EXT_ATTR_PAGE);
- if (obj instanceof IValgrindToolPage) {
- tab = (IValgrindToolPage) obj;
- }
- }
- if (tab == null) {
- throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Cannot_retrieve_page"))); //$NON-NLS-1$
- }
- return tab;
- }
-
- public IValgrindLaunchDelegate getToolDelegate(String id) throws CoreException {
- IValgrindLaunchDelegate delegate = null;
- IConfigurationElement config = getToolMap().get(id);
- if (config != null) {
- Object obj = config.createExecutableExtension(EXT_ATTR_DELEGATE);
- if (obj instanceof IValgrindLaunchDelegate) {
- delegate = (IValgrindLaunchDelegate) obj;
- }
- }
- if (delegate == null) {
- throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Cannot_retrieve_delegate"))); //$NON-NLS-1$
- }
- return delegate;
- }
-
- public IValgrindOutputDirectoryProvider getOutputDirectoryProvider() throws CoreException {
- IValgrindOutputDirectoryProvider provider = null;
- IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(PLUGIN_ID, OUTPUT_DIR_EXT_ID);
-
- // if we find more than one provider just take the first one
- IConfigurationElement[] configs = extPoint.getConfigurationElements();
- for (int i = 0; i < configs.length && provider == null; i++) {
- IConfigurationElement config = configs[i];
- if (config.getName().equals(EXT_ELEMENT_PROVIDER)) {
- Object obj = config.createExecutableExtension(EXT_ATTR_CLASS);
- if (obj instanceof IValgrindOutputDirectoryProvider) {
- provider = (IValgrindOutputDirectoryProvider) obj;
- }
- }
- }
-
- // if no extender, use default
- if (provider == null) {
- provider = new ValgrindOutputDirectoryProvider();
- }
-
- return provider;
- }
-
- public void setCurrentLaunchConfiguration(ILaunchConfiguration config) {
- this.config = config;
- }
-
- /**
- * @return ILaunchConfiguration associated with Valgrind execution
- * currently displayed in the Valgrind view.
- */
- public ILaunchConfiguration getCurrentLaunchConfiguration() {
- return config;
- }
-
- public void setCurrentLaunch(ILaunch launch) {
- this.launch = launch;
- }
-
- /**
- * @return ILaunch associated with Valgrind execution currently displayed
- * in the Valgrind view.
- */
- public ILaunch getCurrentLaunch() {
- return launch;
- }
-
- IPath parseWSPath(String strpath) throws CoreException {
- strpath = LaunchUtils.getStringVariableManager().performStringSubstitution(strpath, false);
- IPath path = new Path(strpath);
- if (!path.isAbsolute()) {
- IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
- if (res != null) {
- path = res.getLocation();
- }
- }
- return path;
- }
-
- private void initializeToolMap() {
- toolMap = new HashMap<>();
- IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(PLUGIN_ID, ValgrindLaunchPlugin.TOOL_EXT_ID);
- IConfigurationElement[] configs = extPoint.getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals(EXT_ELEMENT_TOOL)) {
- String id = config.getAttribute(EXT_ATTR_ID);
- if (id != null && config.getAttribute(EXT_ATTR_NAME) != null
- && config.getAttribute(EXT_ATTR_PAGE) != null
- && config.getAttribute(EXT_ATTR_DELEGATE) != null) {
- toolMap.put(id, config);
- }
- }
- }
- }
-
- private HashMap<String, IConfigurationElement> getToolMap() {
- if (toolMap == null) {
- initializeToolMap();
- }
- return toolMap;
- }
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.launch"; //$NON-NLS-1$
+ public static final String LAUNCH_ID = PLUGIN_ID + ".valgrindLaunch"; //$NON-NLS-1$
+ public static final String MARKER_TYPE = PLUGIN_ID + ".marker"; //$NON-NLS-1$
+ public static final String OUTPUT_DIR_EXT_ID = "outputDirectoryProviders"; //$NON-NLS-1$
+
+ // Extension point constants
+ public static final String TOOL_EXT_ID = "valgrindTools"; //$NON-NLS-1$
+ public static final String TOOL_EXT_DEFAULT = PLUGIN_ID + ".memcheck"; //$NON-NLS-1$
+ protected static final String EXT_ELEMENT_TOOL = "tool"; //$NON-NLS-1$
+ protected static final String EXT_ATTR_NAME = "name"; //$NON-NLS-1$
+ protected static final String EXT_ATTR_ID = "id"; //$NON-NLS-1$
+ protected static final String EXT_ATTR_PAGE = "page"; //$NON-NLS-1$
+ protected static final String EXT_ATTR_DELEGATE = "delegate"; //$NON-NLS-1$
+
+ protected static final String EXT_ELEMENT_PROVIDER = "provider"; //$NON-NLS-1$
+ protected static final String EXT_ATTR_CLASS = "class"; //$NON-NLS-1$
+
+ public static final Version VER_3_3_0 = new Version(3, 3, 0);
+ public static final Version VER_3_4_0 = new Version(3, 4, 0);
+ public static final Version VER_3_6_0 = new Version(3, 6, 0);
+
+ private static final Version MIN_VER = VER_3_3_0;
+ private static final String VERSION_PREFIX = "valgrind-"; //$NON-NLS-1$
+ private static final char VERSION_DELIMITER = '-';
+
+ protected HashMap<String, IConfigurationElement> toolMap;
+
+ private ValgrindCommand valgrindCommand;
+ private ILaunchConfiguration config;
+ private ILaunch launch;
+
+ // The shared instance
+ private static ValgrindLaunchPlugin plugin;
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static ValgrindLaunchPlugin getDefault() {
+ return plugin;
+ }
+
+ /**
+ * @since 0.10
+ */
+ public Version getValgrindVersion(IProject project) throws CoreException {
+ Version valgrindVersion;
+ try {
+ String verString = getValgrindCommand().whichVersion(project);
+ verString = verString.replace(VERSION_PREFIX, ""); //$NON-NLS-1$
+ if (verString.indexOf(VERSION_DELIMITER) > 0) {
+ verString = verString.substring(0, verString.indexOf(VERSION_DELIMITER));
+ }
+ if (!verString.isEmpty()) {
+ valgrindVersion = Version.parseVersion(verString);
+ } else {
+ throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Couldn't_determine_version"))); //$NON-NLS-1$
+ }
+ } catch (IOException e) {
+ IStatus status = new Status(IStatus.ERROR, PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Couldn't_determine_version"), e); //$NON-NLS-1$
+ throw new CoreException(status);
+ }
+
+ // check for minimum supported version
+ if (valgrindVersion.compareTo(MIN_VER) < 0) {
+ throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, NLS.bind(Messages.getString("ValgrindLaunchPlugin.Error_min_version"), valgrindVersion.toString(), MIN_VER.toString()))); //$NON-NLS-1$
+ }
+ return valgrindVersion;
+ }
+
+ public void setValgrindCommand(ValgrindCommand command) {
+ valgrindCommand = command;
+ }
+
+ /**
+ * @since 0.10
+ */
+ protected ValgrindCommand getValgrindCommand() {
+ if (valgrindCommand == null) {
+ valgrindCommand = new ValgrindCommand();
+ }
+ return valgrindCommand;
+ }
+
+ public String[] getRegisteredToolIDs() {
+ Set<String> ids = getToolMap().keySet();
+ return ids.toArray(new String[ids.size()]);
+ }
+
+ public String getToolName(String id) {
+ String name = null;
+ IConfigurationElement config = getToolMap().get(id);
+ if (config != null) {
+ name = config.getAttribute(EXT_ATTR_NAME);
+ }
+ return name;
+ }
+
+ public IValgrindToolPage getToolPage(String id) throws CoreException {
+ IValgrindToolPage tab = null;
+ IConfigurationElement config = getToolMap().get(id);
+ if (config != null) {
+ Object obj = config.createExecutableExtension(EXT_ATTR_PAGE);
+ if (obj instanceof IValgrindToolPage) {
+ tab = (IValgrindToolPage) obj;
+ }
+ }
+ if (tab == null) {
+ throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Cannot_retrieve_page"))); //$NON-NLS-1$
+ }
+ return tab;
+ }
+
+ public IValgrindLaunchDelegate getToolDelegate(String id) throws CoreException {
+ IValgrindLaunchDelegate delegate = null;
+ IConfigurationElement config = getToolMap().get(id);
+ if (config != null) {
+ Object obj = config.createExecutableExtension(EXT_ATTR_DELEGATE);
+ if (obj instanceof IValgrindLaunchDelegate) {
+ delegate = (IValgrindLaunchDelegate) obj;
+ }
+ }
+ if (delegate == null) {
+ throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Cannot_retrieve_delegate"))); //$NON-NLS-1$
+ }
+ return delegate;
+ }
+
+ public IValgrindOutputDirectoryProvider getOutputDirectoryProvider() throws CoreException {
+ IValgrindOutputDirectoryProvider provider = null;
+ IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(PLUGIN_ID, OUTPUT_DIR_EXT_ID);
+
+ // if we find more than one provider just take the first one
+ IConfigurationElement[] configs = extPoint.getConfigurationElements();
+ for (int i = 0; i < configs.length && provider == null; i++) {
+ IConfigurationElement config = configs[i];
+ if (config.getName().equals(EXT_ELEMENT_PROVIDER)) {
+ Object obj = config.createExecutableExtension(EXT_ATTR_CLASS);
+ if (obj instanceof IValgrindOutputDirectoryProvider) {
+ provider = (IValgrindOutputDirectoryProvider) obj;
+ }
+ }
+ }
+
+ // if no extender, use default
+ if (provider == null) {
+ provider = new ValgrindOutputDirectoryProvider();
+ }
+
+ return provider;
+ }
+
+ public void setCurrentLaunchConfiguration(ILaunchConfiguration config) {
+ this.config = config;
+ }
+
+ /**
+ * @return ILaunchConfiguration associated with Valgrind execution
+ * currently displayed in the Valgrind view.
+ */
+ public ILaunchConfiguration getCurrentLaunchConfiguration() {
+ return config;
+ }
+
+ public void setCurrentLaunch(ILaunch launch) {
+ this.launch = launch;
+ }
+
+ /**
+ * @return ILaunch associated with Valgrind execution currently displayed
+ * in the Valgrind view.
+ */
+ public ILaunch getCurrentLaunch() {
+ return launch;
+ }
+
+ IPath parseWSPath(String strpath) throws CoreException {
+ strpath = LaunchUtils.getStringVariableManager().performStringSubstitution(strpath, false);
+ IPath path = new Path(strpath);
+ if (!path.isAbsolute()) {
+ IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
+ if (res != null) {
+ path = res.getLocation();
+ }
+ }
+ return path;
+ }
+
+ private void initializeToolMap() {
+ toolMap = new HashMap<>();
+ IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(PLUGIN_ID, ValgrindLaunchPlugin.TOOL_EXT_ID);
+ IConfigurationElement[] configs = extPoint.getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals(EXT_ELEMENT_TOOL)) {
+ String id = config.getAttribute(EXT_ATTR_ID);
+ if (id != null && config.getAttribute(EXT_ATTR_NAME) != null
+ && config.getAttribute(EXT_ATTR_PAGE) != null
+ && config.getAttribute(EXT_ATTR_DELEGATE) != null) {
+ toolMap.put(id, config);
+ }
+ }
+ }
+ }
+
+ private HashMap<String, IConfigurationElement> getToolMap() {
+ if (toolMap == null) {
+ initializeToolMap();
+ }
+ return toolMap;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchShortcut.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchShortcut.java
index 1bd8689f8e..dd76daaae6 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchShortcut.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindLaunchShortcut.java
@@ -19,22 +19,22 @@ import org.eclipse.linuxtools.profiling.launch.ProfileLaunchShortcut;
public class ValgrindLaunchShortcut extends ProfileLaunchShortcut {
- @Override
- protected void setDefaultProfileAttributes(
- ILaunchConfigurationWorkingCopy wc) throws CoreException {
- ValgrindOptionsTab tab = new ValgrindOptionsTab();
- tab.setDefaults(wc);
- ILaunchConfigurationTab defaultTab = ValgrindLaunchPlugin.getDefault().getToolPage(ValgrindLaunchPlugin.TOOL_EXT_DEFAULT);
- defaultTab.setDefaults(wc);
- }
+ @Override
+ protected void setDefaultProfileAttributes(
+ ILaunchConfigurationWorkingCopy wc) throws CoreException {
+ ValgrindOptionsTab tab = new ValgrindOptionsTab();
+ tab.setDefaults(wc);
+ ILaunchConfigurationTab defaultTab = ValgrindLaunchPlugin.getDefault().getToolPage(ValgrindLaunchPlugin.TOOL_EXT_DEFAULT);
+ defaultTab.setDefaults(wc);
+ }
- /**
- * Method getValgrindLaunchConfigType.
- * @return ILaunchConfigurationType
- */
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(ValgrindLaunchPlugin.LAUNCH_ID);
- }
+ /**
+ * Method getValgrindLaunchConfigType.
+ * @return ILaunchConfigurationType
+ */
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(ValgrindLaunchPlugin.LAUNCH_ID);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindOptionsTab.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindOptionsTab.java
index af4ab22454..826b7f709e 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindOptionsTab.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindOptionsTab.java
@@ -58,667 +58,667 @@ import org.eclipse.ui.views.navigator.ResourceComparator;
import org.osgi.framework.Version;
public class ValgrindOptionsTab extends AbstractLaunchConfigurationTab {
- protected static final String EMPTY_STRING = ""; //$NON-NLS-1$
-
- // General controls
- protected Button traceChildrenButton;
- protected Button childSilentButton;
- protected Button runFreeresButton;
-
- protected Button demangleButton;
- protected Spinner numCallersSpinner;
- protected Button errorLimitButton;
- protected Button showBelowMainButton;
- protected Spinner maxStackFrameSpinner;
- protected Button mainStackSizeButton;
- protected Spinner mainStackSizeSpinner;
- protected Button dSymUtilButton;
- protected List suppFileList;
+ protected static final String EMPTY_STRING = ""; //$NON-NLS-1$
+
+ // General controls
+ protected Button traceChildrenButton;
+ protected Button childSilentButton;
+ protected Button runFreeresButton;
+
+ protected Button demangleButton;
+ protected Spinner numCallersSpinner;
+ protected Button errorLimitButton;
+ protected Button showBelowMainButton;
+ protected Spinner maxStackFrameSpinner;
+ protected Button mainStackSizeButton;
+ protected Spinner mainStackSizeSpinner;
+ protected Button dSymUtilButton;
+ protected List suppFileList;
- protected String tool;
- protected String[] tools;
+ protected String tool;
+ protected String[] tools;
- protected Composite top;
- protected Composite mainStackSizeTop;
- protected ScrolledComposite scrollTop;
- protected Combo toolsCombo;
- protected TabFolder optionsFolder;
- protected TabItem toolTab;
+ protected Composite top;
+ protected Composite mainStackSizeTop;
+ protected ScrolledComposite scrollTop;
+ protected Combo toolsCombo;
+ protected TabFolder optionsFolder;
+ protected TabItem toolTab;
- protected ILaunchConfigurationWorkingCopy launchConfigurationWorkingCopy;
- protected ILaunchConfiguration launchConfiguration;
+ protected ILaunchConfigurationWorkingCopy launchConfigurationWorkingCopy;
+ protected ILaunchConfiguration launchConfiguration;
- protected IValgrindToolPage dynamicTab;
- protected Composite dynamicTabHolder;
+ protected IValgrindToolPage dynamicTab;
+ protected Composite dynamicTabHolder;
- protected boolean isInitializing = false;
- protected boolean initDefaults = false;
+ protected boolean isInitializing = false;
+ protected boolean initDefaults = false;
- protected Exception ex;
+ protected Exception ex;
- /**
- * @since 1.2
- */
- protected boolean noToolCombo;
+ /**
+ * @since 1.2
+ */
+ protected boolean noToolCombo;
- private Version valgrindVersion;
- private boolean checkVersion;
+ private Version valgrindVersion;
+ private boolean checkVersion;
- public ValgrindOptionsTab() {
- this(true);
- }
+ public ValgrindOptionsTab() {
+ this(true);
+ }
- public ValgrindOptionsTab(boolean checkVersion) {
- this.checkVersion = checkVersion;
- }
+ public ValgrindOptionsTab(boolean checkVersion) {
+ this.checkVersion = checkVersion;
+ }
- private SelectionListener selectListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
- private ModifyListener modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
-
- @Override
- public void createControl(Composite parent) {
- // Check for exception
- if (ex != null) {
- setErrorMessage(ex.getLocalizedMessage());
- }
- scrollTop = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
- scrollTop.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- scrollTop.setExpandVertical(true);
- scrollTop.setExpandHorizontal(true);
-
- setControl(scrollTop);
-
- top = new Composite(scrollTop, SWT.NONE);
- top.setLayout(new GridLayout());
-
- createVerticalSpacer(top, 1);
-
- // provide the tool combo if it is not excluded
- if (!noToolCombo)
- createToolCombo(top);
-
- createVerticalSpacer(top, 1);
-
- optionsFolder = new TabFolder(top, SWT.BORDER);
- optionsFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- // "general" tab
- TabItem generalTab = new TabItem(optionsFolder, SWT.NONE);
- generalTab.setText(Messages.getString("ValgrindOptionsTab.General")); //$NON-NLS-1$
-
- Composite generalTop = new Composite(optionsFolder, SWT.NONE);
- generalTop.setLayout(new GridLayout());
- generalTop.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- createBasicOptions(generalTop);
-
- createVerticalSpacer(generalTop, 1);
-
- createErrorOptions(generalTop);
-
- generalTab.setControl(generalTop);
-
- TabItem suppTab = new TabItem(optionsFolder, SWT.NONE);
- suppTab.setText(Messages.getString("ValgrindOptionsTab.Suppressions")); //$NON-NLS-1$
-
- Composite suppTop = new Composite(optionsFolder, SWT.NONE);
- suppTop.setLayout(new GridLayout());
- suppTop.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- createSuppressionsOption(suppTop);
-
- suppTab.setControl(suppTop);
-
- toolTab = new TabItem(optionsFolder, SWT.NONE);
- toolTab.setText(Messages.getString("ValgrindOptionsTab.Tool")); //$NON-NLS-1$
-
- dynamicTabHolder = new Composite(optionsFolder, SWT.NONE);
- dynamicTabHolder.setLayout(new GridLayout());
- dynamicTabHolder.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- toolTab.setControl(dynamicTabHolder);
-
- scrollTop.setContent(top);
- recomputeSize();
-
- updateLaunchConfigurationDialog();
- }
-
- private void recomputeSize() {
- Point point = top.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- top.setSize(point);
- scrollTop.setMinSize(point);
- }
-
- private void createToolCombo(Composite top) {
- Composite comboTop = new Composite(top, SWT.NONE);
- comboTop.setLayout(new GridLayout(2, false));
- Label toolLabel = new Label(comboTop, SWT.NONE);
- toolLabel.setText(Messages.getString("ValgrindOptionsTab.Tool_to_run")); //$NON-NLS-1$
- toolsCombo = new Combo(comboTop, SWT.READ_ONLY);
- tools = getPlugin().getRegisteredToolIDs();
-
- String[] names = new String[tools.length];
- for (int i = 0; i < names.length; i++) {
- names[i] = capitalize(getPlugin().getToolName(tools[i]));
- }
- toolsCombo.setItems(names);
-
- toolsCombo.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- // user selected change, set defaults in new tool
- if (!isInitializing) {
- initDefaults = true;
- int ix = toolsCombo.getSelectionIndex();
- tool = tools[ix];
- handleToolChanged();
- updateLaunchConfigurationDialog();
- }
- }
- });
- }
-
- private String capitalize(String str) {
- if (str.length() > 0) {
- char[] buf = str.toCharArray();
- buf[0] = Character.toUpperCase(buf[0]);
-
- str = String.valueOf(buf);
- }
- return str;
- }
-
- private void createBasicOptions(Composite top) {
- Group basicGroup = new Group(top, SWT.NONE);
- basicGroup.setLayout(new GridLayout());
- basicGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- basicGroup.setText(Messages.getString("ValgrindOptionsTab.Basic_Options")); //$NON-NLS-1$
-
- Composite basicTop = new Composite(basicGroup, SWT.NONE);
- basicTop.setLayout(new GridLayout(2, true));
- basicTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- traceChildrenButton = new Button(basicTop, SWT.CHECK);
- traceChildrenButton.setText(Messages.getString("ValgrindOptionsTab.trace_children")); //$NON-NLS-1$
- traceChildrenButton.addSelectionListener(selectListener);
- traceChildrenButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- // Must be on to prevent mangled XML output
- childSilentButton = new Button(basicTop, SWT.CHECK);
- childSilentButton.setText(Messages.getString("ValgrindOptionsTab.child_silent")); //$NON-NLS-1$
- childSilentButton.setSelection(true);
- childSilentButton.setEnabled(false);
- childSilentButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- runFreeresButton = new Button(basicTop, SWT.CHECK);
- runFreeresButton.setText(Messages.getString("ValgrindOptionsTab.run_freeres")); //$NON-NLS-1$
- runFreeresButton.addSelectionListener(selectListener);
- runFreeresButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- }
-
- private void createErrorOptions(Composite top) {
- Group errorGroup = new Group(top, SWT.NONE);
- errorGroup.setLayout(new GridLayout());
- errorGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- errorGroup.setText(Messages.getString("ValgrindOptionsTab.Error_Options")); //$NON-NLS-1$
-
- Composite errorTop = new Composite(errorGroup, SWT.NONE);
- errorTop.setLayout(new GridLayout(2, true));
- errorTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- demangleButton = new Button(errorTop, SWT.CHECK);
- demangleButton.setText(Messages.getString("ValgrindOptionsTab.demangle")); //$NON-NLS-1$
- demangleButton.addSelectionListener(selectListener);
- demangleButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Composite numCallersTop = new Composite(errorTop, SWT.NONE);
- numCallersTop.setLayout(new GridLayout(2, false));
- Label numCallersLabel = new Label(numCallersTop, SWT.NONE);
- numCallersLabel.setText(Messages.getString("ValgrindOptionsTab.num_callers")); //$NON-NLS-1$
- numCallersSpinner = new Spinner(numCallersTop, SWT.BORDER);
- numCallersSpinner.setMaximum(50);
- numCallersSpinner.addModifyListener(modifyListener);
- numCallersSpinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- errorLimitButton = new Button(errorTop, SWT.CHECK);
- errorLimitButton.setText(Messages.getString("ValgrindOptionsTab.limit_errors")); //$NON-NLS-1$
- errorLimitButton.addSelectionListener(selectListener);
- errorLimitButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- showBelowMainButton = new Button(errorTop, SWT.CHECK);
- showBelowMainButton.setText(Messages.getString("ValgrindOptionsTab.show_errors_below_main")); //$NON-NLS-1$
- showBelowMainButton.addSelectionListener(selectListener);
- showBelowMainButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Composite maxStackFrameTop = new Composite(errorTop, SWT.NONE);
- maxStackFrameTop.setLayout(new GridLayout(2, false));
- Label maxStackFrameLabel = new Label(maxStackFrameTop, SWT.NONE);
- maxStackFrameLabel.setText(Messages.getString("ValgrindOptionsTab.max_size_of_stack_frame")); //$NON-NLS-1$
- maxStackFrameSpinner = new Spinner(maxStackFrameTop, SWT.BORDER);
- maxStackFrameSpinner.setMaximum(Integer.MAX_VALUE);
- maxStackFrameSpinner.addModifyListener(modifyListener);
- maxStackFrameSpinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- //Option only visible for valgrind > 3.4.0
- mainStackSizeTop = new Composite(errorTop, SWT.NONE);
- GridLayout mainStackSizeLayout = new GridLayout(2, false);
- mainStackSizeLayout.marginHeight = mainStackSizeLayout.marginWidth = 0;
- mainStackSizeTop.setLayout(mainStackSizeLayout);
- mainStackSizeButton = new Button(mainStackSizeTop, SWT.CHECK);
- mainStackSizeButton.setText(Messages.getString("ValgrindOptionsTab.Main_stack_size")); //$NON-NLS-1$
- mainStackSizeButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- checkMainStackEnablement();
- updateLaunchConfigurationDialog();
- }
- });
- mainStackSizeSpinner = new Spinner(mainStackSizeTop, SWT.BORDER);
- mainStackSizeSpinner.setMaximum(Integer.MAX_VALUE);
- mainStackSizeSpinner.addModifyListener(modifyListener);
- mainStackSizeSpinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mainStackSizeTop.setVisible(false);
-
- //Option only visible for valgrind > 3.6.0
- dSymUtilButton = new Button(errorTop, SWT.CHECK);
- dSymUtilButton.setText(Messages.getString("ValgrindOptionsTab.dsymutil")); //$NON-NLS-1$
- dSymUtilButton.addSelectionListener(selectListener);
- dSymUtilButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- dSymUtilButton.setVisible(false);
- }
-
- private void updateErrorOptions() {
- if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0)
- mainStackSizeTop.setVisible(true);
- else
- mainStackSizeTop.setVisible(false);
-
- if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_6_0) >= 0)
- dSymUtilButton.setVisible(true);
- else
- dSymUtilButton.setVisible(false);
- }
-
- private void createSuppressionsOption(Composite top) {
- Composite browseTop = new Composite(top, SWT.BORDER);
- browseTop.setLayout(new GridLayout(2, false));
- GridData browseData = new GridData(GridData.FILL_BOTH);
- browseTop.setLayoutData(browseData);
-
- Label suppFileLabel = new Label(browseTop, SWT.NONE);
- suppFileLabel.setText(Messages.getString("ValgrindOptionsTab.suppressions_file")); //$NON-NLS-1$
-
- createVerticalSpacer(browseTop, 1);
-
- suppFileList = new List(browseTop, SWT.BORDER);
- suppFileList.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- Composite buttonTop = new Composite(browseTop, SWT.NONE);
- GridLayout buttonLayout = new GridLayout();
- buttonLayout.marginWidth = buttonLayout.marginHeight = 0;
- buttonTop.setLayout(buttonLayout);
- buttonTop.setLayoutData(new GridData(SWT.CENTER, SWT.BEGINNING, false, false));
-
- Button workspaceBrowseButton = createPushButton(buttonTop, Messages.getString("ValgrindOptionsTab.Workspace"), null); //$NON-NLS-1$
- workspaceBrowseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
- dialog.setTitle(Messages.getString("ValgrindOptionsTab.Select_a_Resource")); //$NON-NLS-1$
- dialog.setMessage(Messages.getString("ValgrindOptionsTab.Select_a_Suppressions_File")); //$NON-NLS-1$
- dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
- dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
- if (dialog.open() == IDialogConstants.OK_ID) {
- IResource resource = (IResource) dialog.getFirstResult();
- String arg = resource.getFullPath().toString();
- String fileLoc = VariablesPlugin.getDefault().getStringVariableManager().generateVariableExpression("workspace_loc", arg); //$NON-NLS-1$
- suppFileList.add(fileLoc);
- updateLaunchConfigurationDialog();
- }
- }
- });
- Button fileBrowseButton = createPushButton(buttonTop, Messages.getString("ValgrindOptionsTab.File_System"), null); //$NON-NLS-1$
- fileBrowseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String filePath = null;
- FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
- filePath = dialog.open();
- if (filePath != null) {
- suppFileList.add(filePath);
- updateLaunchConfigurationDialog();
- }
- }
- });
- Button removeButton = createPushButton(buttonTop, Messages.getString("ValgrindOptionsTab.Supp_remove"), null); //$NON-NLS-1$
- removeButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int[] selected = suppFileList.getSelectionIndices();
- if (selected.length > 0) {
- suppFileList.remove(selected);
- updateLaunchConfigurationDialog();
- }
- }
- });
- }
-
- private void handleToolChanged() {
- try {
- // create dynamicTab
- loadDynamicArea();
-
- if (launchConfigurationWorkingCopy == null) {
- if (launchConfiguration.isWorkingCopy()) {
- launchConfigurationWorkingCopy = (ILaunchConfigurationWorkingCopy) launchConfiguration;
- } else {
- launchConfigurationWorkingCopy = launchConfiguration.getWorkingCopy();
- }
- }
-
- // setDefaults called on this tab so call on dynamicTab OR
- // user changed tool, not just restoring state
- if (initDefaults) {
- dynamicTab.setDefaults(launchConfigurationWorkingCopy);
- }
- initDefaults = false;
- dynamicTab.initializeFrom(launchConfigurationWorkingCopy);
-
- // change name of tool TabItem
- toolTab.setText(dynamicTab.getName());
- optionsFolder.layout(true);
-
- // adjust minimum size for ScrolledComposite
- recomputeSize();
- } catch (CoreException e) {
- ex = e;
- }
- }
-
- private void loadDynamicArea() throws CoreException {
- for (Control child : dynamicTabHolder.getChildren()) {
- child.dispose();
- }
-
- loadDynamicTab();
- if (dynamicTab == null) {
- throw new CoreException(new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, Messages.getString("ValgrindOptionsTab.No_options_tab_found") + tool)); //$NON-NLS-1$
- }
- dynamicTab.setLaunchConfigurationDialog(getLaunchConfigurationDialog());
- dynamicTab.setValgrindVersion(valgrindVersion);
- dynamicTab.createControl(dynamicTabHolder);
-
- dynamicTabHolder.layout(true);
- }
-
- private void loadDynamicTab() throws CoreException {
- dynamicTab = getPlugin().getToolPage(tool);
- }
-
- public IValgrindToolPage getDynamicTab() {
- return dynamicTab;
- }
-
- private ValgrindLaunchPlugin getPlugin() {
- return ValgrindLaunchPlugin.getDefault();
- }
-
- @Override
- public String getName() {
- return Messages.getString("ValgrindOptionsTab.Valgrind_Options"); //$NON-NLS-1$
- }
-
- @Override
- public Image getImage() {
- return AbstractUIPlugin.imageDescriptorFromPlugin(ValgrindLaunchPlugin.PLUGIN_ID, "icons/valgrind-icon.png").createImage(); //$NON-NLS-1$
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration configuration) {
- isInitializing = true;
- getControl().setRedraw(false);
- launchConfiguration = configuration;
- launchConfigurationWorkingCopy = null;
-
- if (checkVersion) {
- try {
- IProject project;
- try {
- project = ConfigUtils.getProject(ConfigUtils.getProjectName(configuration));
- } catch (Exception e1) {
- // no project is still a possibility the validator handles
- project = null;
- }
- valgrindVersion = getPlugin().getValgrindVersion(project);
- } catch (CoreException e) {
- ex = e;
- }
- }
-
- updateErrorOptions();
-
- try {
- if (!noToolCombo) {
- tool = configuration.getAttribute(LaunchConfigurationConstants.ATTR_TOOL, LaunchConfigurationConstants.DEFAULT_TOOL);
- int select = -1;
- for (int i = 0; i < tools.length && select < 0; i++) {
- if (tool.equals(tools[i])) {
- select = i;
- }
- }
-
- if (select != -1) {
- toolsCombo.select(select);
- }
- }
- handleToolChanged();
-
- traceChildrenButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, LaunchConfigurationConstants.DEFAULT_GENERAL_TRACECHILD));
- runFreeresButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_FREERES, LaunchConfigurationConstants.DEFAULT_GENERAL_FREERES));
- demangleButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DEMANGLE, LaunchConfigurationConstants.DEFAULT_GENERAL_DEMANGLE));
- numCallersSpinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_NUMCALLERS, LaunchConfigurationConstants.DEFAULT_GENERAL_NUMCALLERS));
- errorLimitButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_ERRLIMIT, LaunchConfigurationConstants.DEFAULT_GENERAL_ERRLIMIT));
- showBelowMainButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_BELOWMAIN, LaunchConfigurationConstants.DEFAULT_GENERAL_BELOWMAIN));
- maxStackFrameSpinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAXFRAME, LaunchConfigurationConstants.DEFAULT_GENERAL_MAXFRAME));
- java.util.List<String> suppFiles = configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_SUPPFILES, LaunchConfigurationConstants.DEFAULT_GENERAL_SUPPFILES);
- suppFileList.setItems(suppFiles.toArray(new String[suppFiles.size()]));
-
- // 3.4.0 specific
- if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
- mainStackSizeButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK_BOOL, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK_BOOL));
- mainStackSizeSpinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK));
- checkMainStackEnablement();
- }
-
- // 3.6.0 specific
- if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_6_0) >= 0) {
- dSymUtilButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DSYMUTIL, LaunchConfigurationConstants.DEFAULT_GENERAL_DSYMUTIL));
- }
- } catch (CoreException e) {
- ex = e;
- }
- getControl().setRedraw(true);
- isInitializing = false;
- }
-
- @Override
- public boolean isValid(ILaunchConfiguration launchConfig) {
- setErrorMessage(null);
-
- boolean result = false;
- if (ex != null) {
- setErrorMessage(ex.getLocalizedMessage());
- }
- else if (result = isGeneralValid() && dynamicTab != null) {
- result = dynamicTab.isValid(launchConfig);
- setErrorMessage(dynamicTab.getErrorMessage());
- }
- return result;
- }
-
- private boolean isGeneralValid() {
- String[] suppFiles = suppFileList.getItems();
- boolean result = true;
- for (int i = 0; i < suppFiles.length && result; i++) {
- try {
- IPath suppfile = getPlugin().parseWSPath(suppFiles[i]);
- if (!suppfile.toFile().exists()) {
- setErrorMessage(NLS.bind(Messages.getString("ValgrindOptionsTab.suppressions_file_doesnt_exist"), suppFiles[i])); //$NON-NLS-1$
- result = false;
- }
- } catch (CoreException e) {
- // should only occur if there's a cycle in variable substitution
- e.printStackTrace();
- }
- }
-
- return result;
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, tool);
-
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, traceChildrenButton.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_FREERES, runFreeresButton.getSelection());
-
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DEMANGLE, demangleButton.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_NUMCALLERS, numCallersSpinner.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_ERRLIMIT, errorLimitButton.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_BELOWMAIN, showBelowMainButton.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAXFRAME, maxStackFrameSpinner.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_SUPPFILES, Arrays.asList(suppFileList.getItems()));
-
- // 3.4.0 specific
- if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK_BOOL, mainStackSizeButton.getSelection());
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK, mainStackSizeSpinner.getSelection());
- }
-
- // 3.6.0 specific
- if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_6_0) >= 0) {
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DSYMUTIL, dSymUtilButton.getSelection());
- }
-
- if (dynamicTab != null) {
- dynamicTab.performApply(configuration);
- }
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
- launchConfigurationWorkingCopy = configuration;
-
- if (noToolCombo)
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, tool);
- else
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, LaunchConfigurationConstants.DEFAULT_TOOL);
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, LaunchConfigurationConstants.DEFAULT_GENERAL_TRACECHILD);
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_FREERES, LaunchConfigurationConstants.DEFAULT_GENERAL_FREERES);
-
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DEMANGLE, LaunchConfigurationConstants.DEFAULT_GENERAL_DEMANGLE);
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_NUMCALLERS, LaunchConfigurationConstants.DEFAULT_GENERAL_NUMCALLERS);
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_ERRLIMIT, LaunchConfigurationConstants.DEFAULT_GENERAL_ERRLIMIT);
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_BELOWMAIN, LaunchConfigurationConstants.DEFAULT_GENERAL_BELOWMAIN);
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAXFRAME, LaunchConfigurationConstants.DEFAULT_GENERAL_MAXFRAME);
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_SUPPFILES, LaunchConfigurationConstants.DEFAULT_GENERAL_SUPPFILES);
-
- // 3.4.0 specific
- if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK_BOOL, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK_BOOL);
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK);
- }
-
- // 3.6.0 specific
- if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_6_0) >= 0) {
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DSYMUTIL, LaunchConfigurationConstants.DEFAULT_GENERAL_DSYMUTIL);
- }
-
- if (dynamicTab != null) {
- dynamicTab.setDefaults(configuration);
- initDefaults = false;
- }
- }
-
- @Override
- public void dispose() {
- if (dynamicTab != null) {
- dynamicTab.dispose();
- }
- super.dispose();
- }
-
- @Override
- protected void updateLaunchConfigurationDialog() {
- if (!isInitializing) {
- super.updateLaunchConfigurationDialog();
- }
- }
-
- private void checkMainStackEnablement() {
- mainStackSizeSpinner.setEnabled(mainStackSizeButton.getSelection());
- }
-
- public Button getTraceChildrenButton() {
- return traceChildrenButton;
- }
-
- public Button getChildSilentButton() {
- return childSilentButton;
- }
-
- public Button getRunFreeresButton() {
- return runFreeresButton;
- }
-
- public Button getDemangleButton() {
- return demangleButton;
- }
-
- public Spinner getNumCallersSpinner() {
- return numCallersSpinner;
- }
-
- public Button getErrorLimitButton() {
- return errorLimitButton;
- }
-
- public Button getShowBelowMainButton() {
- return showBelowMainButton;
- }
-
- public Spinner getMaxStackFrameSpinner() {
- return maxStackFrameSpinner;
- }
-
- public Button getMainStackSizeButton() {
- return mainStackSizeButton;
- }
-
- public Spinner getMainStackSizeSpinner() {
- return mainStackSizeSpinner;
- }
-
- public List getSuppFileList() {
- return suppFileList;
- }
-
- public Combo getToolsCombo() {
- return toolsCombo;
- }
-
- public String[] getTools() {
- return tools;
- }
+ private SelectionListener selectListener = new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+ private ModifyListener modifyListener = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ @Override
+ public void createControl(Composite parent) {
+ // Check for exception
+ if (ex != null) {
+ setErrorMessage(ex.getLocalizedMessage());
+ }
+ scrollTop = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
+ scrollTop.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ scrollTop.setExpandVertical(true);
+ scrollTop.setExpandHorizontal(true);
+
+ setControl(scrollTop);
+
+ top = new Composite(scrollTop, SWT.NONE);
+ top.setLayout(new GridLayout());
+
+ createVerticalSpacer(top, 1);
+
+ // provide the tool combo if it is not excluded
+ if (!noToolCombo)
+ createToolCombo(top);
+
+ createVerticalSpacer(top, 1);
+
+ optionsFolder = new TabFolder(top, SWT.BORDER);
+ optionsFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ // "general" tab
+ TabItem generalTab = new TabItem(optionsFolder, SWT.NONE);
+ generalTab.setText(Messages.getString("ValgrindOptionsTab.General")); //$NON-NLS-1$
+
+ Composite generalTop = new Composite(optionsFolder, SWT.NONE);
+ generalTop.setLayout(new GridLayout());
+ generalTop.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ createBasicOptions(generalTop);
+
+ createVerticalSpacer(generalTop, 1);
+
+ createErrorOptions(generalTop);
+
+ generalTab.setControl(generalTop);
+
+ TabItem suppTab = new TabItem(optionsFolder, SWT.NONE);
+ suppTab.setText(Messages.getString("ValgrindOptionsTab.Suppressions")); //$NON-NLS-1$
+
+ Composite suppTop = new Composite(optionsFolder, SWT.NONE);
+ suppTop.setLayout(new GridLayout());
+ suppTop.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ createSuppressionsOption(suppTop);
+
+ suppTab.setControl(suppTop);
+
+ toolTab = new TabItem(optionsFolder, SWT.NONE);
+ toolTab.setText(Messages.getString("ValgrindOptionsTab.Tool")); //$NON-NLS-1$
+
+ dynamicTabHolder = new Composite(optionsFolder, SWT.NONE);
+ dynamicTabHolder.setLayout(new GridLayout());
+ dynamicTabHolder.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ toolTab.setControl(dynamicTabHolder);
+
+ scrollTop.setContent(top);
+ recomputeSize();
+
+ updateLaunchConfigurationDialog();
+ }
+
+ private void recomputeSize() {
+ Point point = top.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ top.setSize(point);
+ scrollTop.setMinSize(point);
+ }
+
+ private void createToolCombo(Composite top) {
+ Composite comboTop = new Composite(top, SWT.NONE);
+ comboTop.setLayout(new GridLayout(2, false));
+ Label toolLabel = new Label(comboTop, SWT.NONE);
+ toolLabel.setText(Messages.getString("ValgrindOptionsTab.Tool_to_run")); //$NON-NLS-1$
+ toolsCombo = new Combo(comboTop, SWT.READ_ONLY);
+ tools = getPlugin().getRegisteredToolIDs();
+
+ String[] names = new String[tools.length];
+ for (int i = 0; i < names.length; i++) {
+ names[i] = capitalize(getPlugin().getToolName(tools[i]));
+ }
+ toolsCombo.setItems(names);
+
+ toolsCombo.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ // user selected change, set defaults in new tool
+ if (!isInitializing) {
+ initDefaults = true;
+ int ix = toolsCombo.getSelectionIndex();
+ tool = tools[ix];
+ handleToolChanged();
+ updateLaunchConfigurationDialog();
+ }
+ }
+ });
+ }
+
+ private String capitalize(String str) {
+ if (str.length() > 0) {
+ char[] buf = str.toCharArray();
+ buf[0] = Character.toUpperCase(buf[0]);
+
+ str = String.valueOf(buf);
+ }
+ return str;
+ }
+
+ private void createBasicOptions(Composite top) {
+ Group basicGroup = new Group(top, SWT.NONE);
+ basicGroup.setLayout(new GridLayout());
+ basicGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ basicGroup.setText(Messages.getString("ValgrindOptionsTab.Basic_Options")); //$NON-NLS-1$
+
+ Composite basicTop = new Composite(basicGroup, SWT.NONE);
+ basicTop.setLayout(new GridLayout(2, true));
+ basicTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ traceChildrenButton = new Button(basicTop, SWT.CHECK);
+ traceChildrenButton.setText(Messages.getString("ValgrindOptionsTab.trace_children")); //$NON-NLS-1$
+ traceChildrenButton.addSelectionListener(selectListener);
+ traceChildrenButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ // Must be on to prevent mangled XML output
+ childSilentButton = new Button(basicTop, SWT.CHECK);
+ childSilentButton.setText(Messages.getString("ValgrindOptionsTab.child_silent")); //$NON-NLS-1$
+ childSilentButton.setSelection(true);
+ childSilentButton.setEnabled(false);
+ childSilentButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ runFreeresButton = new Button(basicTop, SWT.CHECK);
+ runFreeresButton.setText(Messages.getString("ValgrindOptionsTab.run_freeres")); //$NON-NLS-1$
+ runFreeresButton.addSelectionListener(selectListener);
+ runFreeresButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ }
+
+ private void createErrorOptions(Composite top) {
+ Group errorGroup = new Group(top, SWT.NONE);
+ errorGroup.setLayout(new GridLayout());
+ errorGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ errorGroup.setText(Messages.getString("ValgrindOptionsTab.Error_Options")); //$NON-NLS-1$
+
+ Composite errorTop = new Composite(errorGroup, SWT.NONE);
+ errorTop.setLayout(new GridLayout(2, true));
+ errorTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ demangleButton = new Button(errorTop, SWT.CHECK);
+ demangleButton.setText(Messages.getString("ValgrindOptionsTab.demangle")); //$NON-NLS-1$
+ demangleButton.addSelectionListener(selectListener);
+ demangleButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ Composite numCallersTop = new Composite(errorTop, SWT.NONE);
+ numCallersTop.setLayout(new GridLayout(2, false));
+ Label numCallersLabel = new Label(numCallersTop, SWT.NONE);
+ numCallersLabel.setText(Messages.getString("ValgrindOptionsTab.num_callers")); //$NON-NLS-1$
+ numCallersSpinner = new Spinner(numCallersTop, SWT.BORDER);
+ numCallersSpinner.setMaximum(50);
+ numCallersSpinner.addModifyListener(modifyListener);
+ numCallersSpinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ errorLimitButton = new Button(errorTop, SWT.CHECK);
+ errorLimitButton.setText(Messages.getString("ValgrindOptionsTab.limit_errors")); //$NON-NLS-1$
+ errorLimitButton.addSelectionListener(selectListener);
+ errorLimitButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ showBelowMainButton = new Button(errorTop, SWT.CHECK);
+ showBelowMainButton.setText(Messages.getString("ValgrindOptionsTab.show_errors_below_main")); //$NON-NLS-1$
+ showBelowMainButton.addSelectionListener(selectListener);
+ showBelowMainButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ Composite maxStackFrameTop = new Composite(errorTop, SWT.NONE);
+ maxStackFrameTop.setLayout(new GridLayout(2, false));
+ Label maxStackFrameLabel = new Label(maxStackFrameTop, SWT.NONE);
+ maxStackFrameLabel.setText(Messages.getString("ValgrindOptionsTab.max_size_of_stack_frame")); //$NON-NLS-1$
+ maxStackFrameSpinner = new Spinner(maxStackFrameTop, SWT.BORDER);
+ maxStackFrameSpinner.setMaximum(Integer.MAX_VALUE);
+ maxStackFrameSpinner.addModifyListener(modifyListener);
+ maxStackFrameSpinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ //Option only visible for valgrind > 3.4.0
+ mainStackSizeTop = new Composite(errorTop, SWT.NONE);
+ GridLayout mainStackSizeLayout = new GridLayout(2, false);
+ mainStackSizeLayout.marginHeight = mainStackSizeLayout.marginWidth = 0;
+ mainStackSizeTop.setLayout(mainStackSizeLayout);
+ mainStackSizeButton = new Button(mainStackSizeTop, SWT.CHECK);
+ mainStackSizeButton.setText(Messages.getString("ValgrindOptionsTab.Main_stack_size")); //$NON-NLS-1$
+ mainStackSizeButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ checkMainStackEnablement();
+ updateLaunchConfigurationDialog();
+ }
+ });
+ mainStackSizeSpinner = new Spinner(mainStackSizeTop, SWT.BORDER);
+ mainStackSizeSpinner.setMaximum(Integer.MAX_VALUE);
+ mainStackSizeSpinner.addModifyListener(modifyListener);
+ mainStackSizeSpinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ mainStackSizeTop.setVisible(false);
+
+ //Option only visible for valgrind > 3.6.0
+ dSymUtilButton = new Button(errorTop, SWT.CHECK);
+ dSymUtilButton.setText(Messages.getString("ValgrindOptionsTab.dsymutil")); //$NON-NLS-1$
+ dSymUtilButton.addSelectionListener(selectListener);
+ dSymUtilButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ dSymUtilButton.setVisible(false);
+ }
+
+ private void updateErrorOptions() {
+ if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0)
+ mainStackSizeTop.setVisible(true);
+ else
+ mainStackSizeTop.setVisible(false);
+
+ if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_6_0) >= 0)
+ dSymUtilButton.setVisible(true);
+ else
+ dSymUtilButton.setVisible(false);
+ }
+
+ private void createSuppressionsOption(Composite top) {
+ Composite browseTop = new Composite(top, SWT.BORDER);
+ browseTop.setLayout(new GridLayout(2, false));
+ GridData browseData = new GridData(GridData.FILL_BOTH);
+ browseTop.setLayoutData(browseData);
+
+ Label suppFileLabel = new Label(browseTop, SWT.NONE);
+ suppFileLabel.setText(Messages.getString("ValgrindOptionsTab.suppressions_file")); //$NON-NLS-1$
+
+ createVerticalSpacer(browseTop, 1);
+
+ suppFileList = new List(browseTop, SWT.BORDER);
+ suppFileList.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ Composite buttonTop = new Composite(browseTop, SWT.NONE);
+ GridLayout buttonLayout = new GridLayout();
+ buttonLayout.marginWidth = buttonLayout.marginHeight = 0;
+ buttonTop.setLayout(buttonLayout);
+ buttonTop.setLayoutData(new GridData(SWT.CENTER, SWT.BEGINNING, false, false));
+
+ Button workspaceBrowseButton = createPushButton(buttonTop, Messages.getString("ValgrindOptionsTab.Workspace"), null); //$NON-NLS-1$
+ workspaceBrowseButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
+ dialog.setTitle(Messages.getString("ValgrindOptionsTab.Select_a_Resource")); //$NON-NLS-1$
+ dialog.setMessage(Messages.getString("ValgrindOptionsTab.Select_a_Suppressions_File")); //$NON-NLS-1$
+ dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
+ dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
+ if (dialog.open() == IDialogConstants.OK_ID) {
+ IResource resource = (IResource) dialog.getFirstResult();
+ String arg = resource.getFullPath().toString();
+ String fileLoc = VariablesPlugin.getDefault().getStringVariableManager().generateVariableExpression("workspace_loc", arg); //$NON-NLS-1$
+ suppFileList.add(fileLoc);
+ updateLaunchConfigurationDialog();
+ }
+ }
+ });
+ Button fileBrowseButton = createPushButton(buttonTop, Messages.getString("ValgrindOptionsTab.File_System"), null); //$NON-NLS-1$
+ fileBrowseButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ String filePath = null;
+ FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
+ filePath = dialog.open();
+ if (filePath != null) {
+ suppFileList.add(filePath);
+ updateLaunchConfigurationDialog();
+ }
+ }
+ });
+ Button removeButton = createPushButton(buttonTop, Messages.getString("ValgrindOptionsTab.Supp_remove"), null); //$NON-NLS-1$
+ removeButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ int[] selected = suppFileList.getSelectionIndices();
+ if (selected.length > 0) {
+ suppFileList.remove(selected);
+ updateLaunchConfigurationDialog();
+ }
+ }
+ });
+ }
+
+ private void handleToolChanged() {
+ try {
+ // create dynamicTab
+ loadDynamicArea();
+
+ if (launchConfigurationWorkingCopy == null) {
+ if (launchConfiguration.isWorkingCopy()) {
+ launchConfigurationWorkingCopy = (ILaunchConfigurationWorkingCopy) launchConfiguration;
+ } else {
+ launchConfigurationWorkingCopy = launchConfiguration.getWorkingCopy();
+ }
+ }
+
+ // setDefaults called on this tab so call on dynamicTab OR
+ // user changed tool, not just restoring state
+ if (initDefaults) {
+ dynamicTab.setDefaults(launchConfigurationWorkingCopy);
+ }
+ initDefaults = false;
+ dynamicTab.initializeFrom(launchConfigurationWorkingCopy);
+
+ // change name of tool TabItem
+ toolTab.setText(dynamicTab.getName());
+ optionsFolder.layout(true);
+
+ // adjust minimum size for ScrolledComposite
+ recomputeSize();
+ } catch (CoreException e) {
+ ex = e;
+ }
+ }
+
+ private void loadDynamicArea() throws CoreException {
+ for (Control child : dynamicTabHolder.getChildren()) {
+ child.dispose();
+ }
+
+ loadDynamicTab();
+ if (dynamicTab == null) {
+ throw new CoreException(new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, Messages.getString("ValgrindOptionsTab.No_options_tab_found") + tool)); //$NON-NLS-1$
+ }
+ dynamicTab.setLaunchConfigurationDialog(getLaunchConfigurationDialog());
+ dynamicTab.setValgrindVersion(valgrindVersion);
+ dynamicTab.createControl(dynamicTabHolder);
+
+ dynamicTabHolder.layout(true);
+ }
+
+ private void loadDynamicTab() throws CoreException {
+ dynamicTab = getPlugin().getToolPage(tool);
+ }
+
+ public IValgrindToolPage getDynamicTab() {
+ return dynamicTab;
+ }
+
+ private ValgrindLaunchPlugin getPlugin() {
+ return ValgrindLaunchPlugin.getDefault();
+ }
+
+ @Override
+ public String getName() {
+ return Messages.getString("ValgrindOptionsTab.Valgrind_Options"); //$NON-NLS-1$
+ }
+
+ @Override
+ public Image getImage() {
+ return AbstractUIPlugin.imageDescriptorFromPlugin(ValgrindLaunchPlugin.PLUGIN_ID, "icons/valgrind-icon.png").createImage(); //$NON-NLS-1$
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration configuration) {
+ isInitializing = true;
+ getControl().setRedraw(false);
+ launchConfiguration = configuration;
+ launchConfigurationWorkingCopy = null;
+
+ if (checkVersion) {
+ try {
+ IProject project;
+ try {
+ project = ConfigUtils.getProject(ConfigUtils.getProjectName(configuration));
+ } catch (Exception e1) {
+ // no project is still a possibility the validator handles
+ project = null;
+ }
+ valgrindVersion = getPlugin().getValgrindVersion(project);
+ } catch (CoreException e) {
+ ex = e;
+ }
+ }
+
+ updateErrorOptions();
+
+ try {
+ if (!noToolCombo) {
+ tool = configuration.getAttribute(LaunchConfigurationConstants.ATTR_TOOL, LaunchConfigurationConstants.DEFAULT_TOOL);
+ int select = -1;
+ for (int i = 0; i < tools.length && select < 0; i++) {
+ if (tool.equals(tools[i])) {
+ select = i;
+ }
+ }
+
+ if (select != -1) {
+ toolsCombo.select(select);
+ }
+ }
+ handleToolChanged();
+
+ traceChildrenButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, LaunchConfigurationConstants.DEFAULT_GENERAL_TRACECHILD));
+ runFreeresButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_FREERES, LaunchConfigurationConstants.DEFAULT_GENERAL_FREERES));
+ demangleButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DEMANGLE, LaunchConfigurationConstants.DEFAULT_GENERAL_DEMANGLE));
+ numCallersSpinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_NUMCALLERS, LaunchConfigurationConstants.DEFAULT_GENERAL_NUMCALLERS));
+ errorLimitButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_ERRLIMIT, LaunchConfigurationConstants.DEFAULT_GENERAL_ERRLIMIT));
+ showBelowMainButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_BELOWMAIN, LaunchConfigurationConstants.DEFAULT_GENERAL_BELOWMAIN));
+ maxStackFrameSpinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAXFRAME, LaunchConfigurationConstants.DEFAULT_GENERAL_MAXFRAME));
+ java.util.List<String> suppFiles = configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_SUPPFILES, LaunchConfigurationConstants.DEFAULT_GENERAL_SUPPFILES);
+ suppFileList.setItems(suppFiles.toArray(new String[suppFiles.size()]));
+
+ // 3.4.0 specific
+ if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
+ mainStackSizeButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK_BOOL, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK_BOOL));
+ mainStackSizeSpinner.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK));
+ checkMainStackEnablement();
+ }
+
+ // 3.6.0 specific
+ if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_6_0) >= 0) {
+ dSymUtilButton.setSelection(configuration.getAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DSYMUTIL, LaunchConfigurationConstants.DEFAULT_GENERAL_DSYMUTIL));
+ }
+ } catch (CoreException e) {
+ ex = e;
+ }
+ getControl().setRedraw(true);
+ isInitializing = false;
+ }
+
+ @Override
+ public boolean isValid(ILaunchConfiguration launchConfig) {
+ setErrorMessage(null);
+
+ boolean result = false;
+ if (ex != null) {
+ setErrorMessage(ex.getLocalizedMessage());
+ }
+ else if (result = isGeneralValid() && dynamicTab != null) {
+ result = dynamicTab.isValid(launchConfig);
+ setErrorMessage(dynamicTab.getErrorMessage());
+ }
+ return result;
+ }
+
+ private boolean isGeneralValid() {
+ String[] suppFiles = suppFileList.getItems();
+ boolean result = true;
+ for (int i = 0; i < suppFiles.length && result; i++) {
+ try {
+ IPath suppfile = getPlugin().parseWSPath(suppFiles[i]);
+ if (!suppfile.toFile().exists()) {
+ setErrorMessage(NLS.bind(Messages.getString("ValgrindOptionsTab.suppressions_file_doesnt_exist"), suppFiles[i])); //$NON-NLS-1$
+ result = false;
+ }
+ } catch (CoreException e) {
+ // should only occur if there's a cycle in variable substitution
+ e.printStackTrace();
+ }
+ }
+
+ return result;
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, tool);
+
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, traceChildrenButton.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_FREERES, runFreeresButton.getSelection());
+
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DEMANGLE, demangleButton.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_NUMCALLERS, numCallersSpinner.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_ERRLIMIT, errorLimitButton.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_BELOWMAIN, showBelowMainButton.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAXFRAME, maxStackFrameSpinner.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_SUPPFILES, Arrays.asList(suppFileList.getItems()));
+
+ // 3.4.0 specific
+ if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK_BOOL, mainStackSizeButton.getSelection());
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK, mainStackSizeSpinner.getSelection());
+ }
+
+ // 3.6.0 specific
+ if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_6_0) >= 0) {
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DSYMUTIL, dSymUtilButton.getSelection());
+ }
+
+ if (dynamicTab != null) {
+ dynamicTab.performApply(configuration);
+ }
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
+ launchConfigurationWorkingCopy = configuration;
+
+ if (noToolCombo)
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, tool);
+ else
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, LaunchConfigurationConstants.DEFAULT_TOOL);
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, LaunchConfigurationConstants.DEFAULT_GENERAL_TRACECHILD);
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_FREERES, LaunchConfigurationConstants.DEFAULT_GENERAL_FREERES);
+
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DEMANGLE, LaunchConfigurationConstants.DEFAULT_GENERAL_DEMANGLE);
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_NUMCALLERS, LaunchConfigurationConstants.DEFAULT_GENERAL_NUMCALLERS);
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_ERRLIMIT, LaunchConfigurationConstants.DEFAULT_GENERAL_ERRLIMIT);
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_BELOWMAIN, LaunchConfigurationConstants.DEFAULT_GENERAL_BELOWMAIN);
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAXFRAME, LaunchConfigurationConstants.DEFAULT_GENERAL_MAXFRAME);
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_SUPPFILES, LaunchConfigurationConstants.DEFAULT_GENERAL_SUPPFILES);
+
+ // 3.4.0 specific
+ if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK_BOOL, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK_BOOL);
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_MAINSTACK, LaunchConfigurationConstants.DEFAULT_GENERAL_MAINSTACK);
+ }
+
+ // 3.6.0 specific
+ if (valgrindVersion == null || valgrindVersion.compareTo(ValgrindLaunchPlugin.VER_3_6_0) >= 0) {
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_DSYMUTIL, LaunchConfigurationConstants.DEFAULT_GENERAL_DSYMUTIL);
+ }
+
+ if (dynamicTab != null) {
+ dynamicTab.setDefaults(configuration);
+ initDefaults = false;
+ }
+ }
+
+ @Override
+ public void dispose() {
+ if (dynamicTab != null) {
+ dynamicTab.dispose();
+ }
+ super.dispose();
+ }
+
+ @Override
+ protected void updateLaunchConfigurationDialog() {
+ if (!isInitializing) {
+ super.updateLaunchConfigurationDialog();
+ }
+ }
+
+ private void checkMainStackEnablement() {
+ mainStackSizeSpinner.setEnabled(mainStackSizeButton.getSelection());
+ }
+
+ public Button getTraceChildrenButton() {
+ return traceChildrenButton;
+ }
+
+ public Button getChildSilentButton() {
+ return childSilentButton;
+ }
+
+ public Button getRunFreeresButton() {
+ return runFreeresButton;
+ }
+
+ public Button getDemangleButton() {
+ return demangleButton;
+ }
+
+ public Spinner getNumCallersSpinner() {
+ return numCallersSpinner;
+ }
+
+ public Button getErrorLimitButton() {
+ return errorLimitButton;
+ }
+
+ public Button getShowBelowMainButton() {
+ return showBelowMainButton;
+ }
+
+ public Spinner getMaxStackFrameSpinner() {
+ return maxStackFrameSpinner;
+ }
+
+ public Button getMainStackSizeButton() {
+ return mainStackSizeButton;
+ }
+
+ public Spinner getMainStackSizeSpinner() {
+ return mainStackSizeSpinner;
+ }
+
+ public List getSuppFileList() {
+ return suppFileList;
+ }
+
+ public Combo getToolsCombo() {
+ return toolsCombo;
+ }
+
+ public String[] getTools() {
+ return tools;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindOutputDirectoryProvider.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindOutputDirectoryProvider.java
index 4d54f7dee4..e87c60783b 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindOutputDirectoryProvider.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindOutputDirectoryProvider.java
@@ -14,18 +14,18 @@ import org.eclipse.core.runtime.IPath;
import org.eclipse.linuxtools.valgrind.launch.IValgrindOutputDirectoryProvider;
public class ValgrindOutputDirectoryProvider implements IValgrindOutputDirectoryProvider {
- private IPath outputPath;
+ private IPath outputPath;
- public ValgrindOutputDirectoryProvider() {
- outputPath = ValgrindLaunchPlugin.getDefault().getStateLocation();
- }
+ public ValgrindOutputDirectoryProvider() {
+ outputPath = ValgrindLaunchPlugin.getDefault().getStateLocation();
+ }
- /* (non-Javadoc)
- * @see org.eclipse.linuxtools.valgrind.launch.IValgrindOutputDirectoryProvider#getOutputPath()
- */
- @Override
- public IPath getOutputPath() {
- return outputPath;
- }
+ /* (non-Javadoc)
+ * @see org.eclipse.linuxtools.valgrind.launch.IValgrindOutputDirectoryProvider#getOutputPath()
+ */
+ @Override
+ public IPath getOutputPath() {
+ return outputPath;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindRemoteProxyLaunchConfigurationTabGroup.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindRemoteProxyLaunchConfigurationTabGroup.java
index 811172b9bb..da39676635 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindRemoteProxyLaunchConfigurationTabGroup.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindRemoteProxyLaunchConfigurationTabGroup.java
@@ -17,13 +17,13 @@ import org.eclipse.linuxtools.profiling.launch.RemoteProxyProfileLaunchConfigura
* @since 1.1
*/
public class ValgrindRemoteProxyLaunchConfigurationTabGroup extends
- RemoteProxyProfileLaunchConfigurationTabGroup {
+ RemoteProxyProfileLaunchConfigurationTabGroup {
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- return new AbstractLaunchConfigurationTab[] {
- new ValgrindOptionsTab()
- };
- }
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ return new AbstractLaunchConfigurationTab[] {
+ new ValgrindOptionsTab()
+ };
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindRemoteProxyLaunchDelegate.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindRemoteProxyLaunchDelegate.java
index f243d16fb2..a5fdd7c72b 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindRemoteProxyLaunchDelegate.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindRemoteProxyLaunchDelegate.java
@@ -53,273 +53,273 @@ import org.osgi.framework.Version;
*/
public class ValgrindRemoteProxyLaunchDelegate extends ValgrindLaunchConfigurationDelegate {
- private static final String VALGRIND_CMD = "valgrind"; //$NON-NLS-1$
-
- private ConfigUtils configUtils;
-
- public ValgrindRemoteProxyLaunchDelegate() {
- super();
- }
-
- private static final String VERSION_OPT = "--version"; //$NON-NLS-1$
-
- private String whichVersion(IProject project) {
- String cmdArray[] = new String[2];
- cmdArray[0] = VALGRIND_CMD;
- cmdArray[1] = VERSION_OPT;
-
- try {
-
- Process p = RuntimeProcessFactory.getFactory().exec(cmdArray,
- project);
-
- try (BufferedReader stdout = new BufferedReader(
- new InputStreamReader(p.getInputStream()))) {
- return stdout.readLine();
- }
- } catch (IOException e) {
- return null;
- }
- }
-
- private static final String VERSION_PREFIX = "valgrind-"; //$NON-NLS-1$
- private static final char VERSION_DELIMITER = '-';
- private static final Version MIN_VER = ValgrindLaunchPlugin.VER_3_3_0;
-
- private Version getValgrindVersion(IProject project) throws CoreException {
- Version valgrindVersion;
- String verString = whichVersion(project);
-
- if (verString == null || verString.isEmpty()){
- throw new CoreException(new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Couldn't_determine_version"))); //$NON-NLS-1$
- }
-
- verString = verString.replace(VERSION_PREFIX, ""); //$NON-NLS-1$
-
- if (verString.indexOf(VERSION_DELIMITER) > 0) {
- verString = verString.substring(0, verString.indexOf(VERSION_DELIMITER));
- }
- if (!verString.isEmpty()) {
- valgrindVersion = Version.parseVersion(verString);
- } else {
- throw new CoreException(new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Couldn't_determine_version"))); //$NON-NLS-1$
- }
-
- // check for minimum supported version
- if (valgrindVersion.compareTo(MIN_VER) < 0) {
- throw new CoreException(new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, NLS.bind(Messages.getString("ValgrindLaunchPlugin.Error_min_version"), valgrindVersion.toString(), MIN_VER.toString()))); //$NON-NLS-1$
- }
- return valgrindVersion;
- }
-
-
- @Override
- public void launch(final ILaunchConfiguration config, String mode,
- final ILaunch launch, IProgressMonitor m) throws CoreException {
- if (m == null) {
- m = new NullProgressMonitor();
- }
-
- // Clear process as we wait on it to be instantiated
- process = null;
-
- SubMonitor monitor = SubMonitor.convert(m,
- Messages.getString("ValgrindRemoteLaunchDelegate.task_name"), 10); //$NON-NLS-1$
- // check for cancellation
- if (monitor.isCanceled()) {
- return;
- }
-
- this.config = config;
- this.launch = launch;
- try {
- // remove any output from previous run
- ValgrindUIPlugin.getDefault().resetView();
- // reset stored launch data
- getPlugin().setCurrentLaunchConfiguration(null);
- getPlugin().setCurrentLaunch(null);
-
- this.configUtils = new ConfigUtils(config);
- IProject project = configUtils.getProject();
- URI exeURI = new URI(configUtils.getExecutablePath());
- RemoteConnection exeRC = new RemoteConnection(exeURI);
- monitor.worked(1);
- String valgrindPathString = RuntimeProcessFactory.getFactory().whichCommand(VALGRIND_CMD, project);
- IPath valgrindFullPath = Path.fromOSString(valgrindPathString);
- boolean copyExecutable = configUtils.getCopyExecutable();
- if (copyExecutable) {
- URI copyExeURI = new URI(configUtils.getCopyFromExecutablePath());
- RemoteConnection copyExeRC = new RemoteConnection(copyExeURI);
- IRemoteFileProxy copyExeRFP = copyExeRC.getRmtFileProxy();
- IFileStore copyExeFS = copyExeRFP.getResource(copyExeURI.getPath());
- IRemoteFileProxy exeRFP = exeRC.getRmtFileProxy();
- IFileStore exeFS = exeRFP.getResource(exeURI.getPath());
- IFileInfo exeFI = exeFS.fetchInfo();
- if (exeFI.isDirectory()) {
- // Assume the user wants to copy the file to the given directory, using
- // the same filename as the "copy from" executable.
- IPath copyExePath = Path.fromOSString(copyExeURI.getPath());
- IPath newExePath = Path.fromOSString(exeURI.getPath()).append(copyExePath.lastSegment());
- // update the exeURI with the new path.
- exeURI = new URI(exeURI.getScheme(), exeURI.getAuthority(), newExePath.toString(), exeURI.getQuery(), exeURI.getFragment());
- exeFS = exeRFP.getResource(exeURI.getPath());
- }
- copyExeFS.copy(exeFS, EFS.OVERWRITE | EFS.SHALLOW, new SubProgressMonitor(monitor, 1));
- // Note: assume that we don't need to create a new exeRC since the
- // scheme and authority remain the same between the original exeURI and the new one.
- }
- valgrindVersion = getValgrindVersion(project);
- IPath remoteBinFile = Path.fromOSString(exeURI.getPath());
- String configWorkingDir = configUtils.getWorkingDirectory();
- IFileStore workingDir;
- if(configWorkingDir == null){
- // If no working directory was provided, use the directory containing the
- // the executable as the working directory.
- IPath workingDirPath = remoteBinFile.removeLastSegments(1);
- IRemoteFileProxy workingDirRFP = exeRC.getRmtFileProxy();
- workingDir = workingDirRFP.getResource(workingDirPath.toOSString());
- } else {
- URI workingDirURI = new URI(configUtils.getWorkingDirectory());
- RemoteConnection workingDirRC = new RemoteConnection(workingDirURI);
- IRemoteFileProxy workingDirRFP = workingDirRC.getRmtFileProxy();
- workingDir = workingDirRFP.getResource(workingDirURI.getPath());
- }
-
- IPath remoteLogDir = Path.fromOSString("/tmp/"); //$NON-NLS-1$
- outputPath = remoteLogDir.append("eclipse-valgrind-" + System.currentTimeMillis()); //$NON-NLS-1$
-
- exeRC.createFolder(outputPath, new SubProgressMonitor(monitor, 1));
-
- // create/empty local output directory
- IValgrindOutputDirectoryProvider provider = getPlugin().getOutputDirectoryProvider();
- IPath localOutputDir = null;
- try {
- localOutputDir = provider.getOutputPath();
- createDirectory(localOutputDir);
- } catch (IOException e2) {
- throw new CoreException(new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, IStatus.OK,
- "", e2)); //$NON-NLS-1$
- }
-
- // tool that was launched
- toolID = getTool(config);
- // ask tool extension for arguments
- dynamicDelegate = getDynamicDelegate(toolID);
-
- String[] valgrindArgs = getValgrindArgumentsArray(config);
- String[] executableArgs = getProgramArgumentsArray(config);
- String[] allArgs = new String[executableArgs.length + valgrindArgs.length + 2];
-
- int idx = 0;
- allArgs[idx++] = VALGRIND_CMD;
- for (String valgrindArg : valgrindArgs) {
- allArgs[idx++] = valgrindArg;
- }
- allArgs[idx++] = remoteBinFile.toOSString();
- for (String executableArg : executableArgs) {
- allArgs[idx++] = executableArg;
- }
-
- Process p = RuntimeProcessFactory.getFactory().exec(allArgs, new String[0], workingDir, project);
-
- int state = p.waitFor();
-
- if (state != IRemoteCommandLauncher.OK) {
- abort("valgrind launcher exited with status " + state + ". See IRemoteCommandLauncher for details.\n",
- null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
- }
-
-
- if (p.exitValue() != 0) {
- String line = null;
-
- StringBuilder valgrindOutSB = new StringBuilder();
- BufferedReader valgrindOut = new BufferedReader(new InputStreamReader(p.getInputStream()));
- while((line = valgrindOut.readLine()) != null ){
- valgrindOutSB.append(line);
- }
-
- StringBuilder valgrindErrSB = new StringBuilder();
- BufferedReader valgrindErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
- while((line = valgrindErr.readLine()) != null ){
- valgrindErrSB.append(line);
- }
-
- abort("Standard ouput: " + valgrindOutSB.toString() +
- "\nStandard error: " + valgrindErrSB.toString(),
- null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
- }
-
- // move remote log files to local directory
- exeRC.download(outputPath, localOutputDir, new SubProgressMonitor(monitor, 1));
-
- // remove remote log dir and all files under it
- exeRC.delete(outputPath, new SubProgressMonitor(monitor, 1));
-
- // store these for use by other classes
- getPlugin().setCurrentLaunchConfiguration(config);
- getPlugin().setCurrentLaunch(launch);
-
- // parse Valgrind logs
- IValgrindMessage[] messages = parseLogs(localOutputDir);
-
- // create launch summary string to distinguish this launch
- launchStr = createLaunchStr(valgrindFullPath);
-
- // create view
- ValgrindUIPlugin.getDefault().createView(launchStr, toolID);
- // set log messages
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- view.setMessages(messages);
- monitor.worked(1);
-
- // pass off control to extender
- dynamicDelegate.handleLaunch(config, launch, localOutputDir, monitor.newChild(2));
-
- // initialize tool-specific part of view
- dynamicDelegate.initializeView(view.getDynamicView(), launchStr, monitor.newChild(1));
-
- // refresh view
- ValgrindUIPlugin.getDefault().refreshView();
-
- // show view
- ValgrindUIPlugin.getDefault().showView();
- monitor.worked(1);
-
- } catch (URISyntaxException|IOException|RemoteConnectionException|InterruptedException e) {
- abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
- } finally {
- monitor.done();
- m.done();
- }
- }
-
- private String createLaunchStr(IPath valgrindPath) throws CoreException {
- IProject project = configUtils.getProject();
- URI projectURI = project.getLocationURI();
-
- String host = projectURI.getHost();
-
- // Host might be null since it's not needed for a well-formed URI. Try authority instead
- if(host == null){
- host = projectURI.getAuthority();
- }
-
- // If authority is also null, use a generic name
- String location;
-
- if(host == null){
- location = "remote host"; //$NON-NLS-1$
- } else {
- location = projectURI.getScheme() + "://" + host; //$NON-NLS-1$
- }
-
- return config.getName()
- + " [" + getPlugin().getToolName(toolID) + "]" + " " + valgrindPath.toString() + " on " + location; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
+ private static final String VALGRIND_CMD = "valgrind"; //$NON-NLS-1$
+
+ private ConfigUtils configUtils;
+
+ public ValgrindRemoteProxyLaunchDelegate() {
+ super();
+ }
+
+ private static final String VERSION_OPT = "--version"; //$NON-NLS-1$
+
+ private String whichVersion(IProject project) {
+ String cmdArray[] = new String[2];
+ cmdArray[0] = VALGRIND_CMD;
+ cmdArray[1] = VERSION_OPT;
+
+ try {
+
+ Process p = RuntimeProcessFactory.getFactory().exec(cmdArray,
+ project);
+
+ try (BufferedReader stdout = new BufferedReader(
+ new InputStreamReader(p.getInputStream()))) {
+ return stdout.readLine();
+ }
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ private static final String VERSION_PREFIX = "valgrind-"; //$NON-NLS-1$
+ private static final char VERSION_DELIMITER = '-';
+ private static final Version MIN_VER = ValgrindLaunchPlugin.VER_3_3_0;
+
+ private Version getValgrindVersion(IProject project) throws CoreException {
+ Version valgrindVersion;
+ String verString = whichVersion(project);
+
+ if (verString == null || verString.isEmpty()){
+ throw new CoreException(new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Couldn't_determine_version"))); //$NON-NLS-1$
+ }
+
+ verString = verString.replace(VERSION_PREFIX, ""); //$NON-NLS-1$
+
+ if (verString.indexOf(VERSION_DELIMITER) > 0) {
+ verString = verString.substring(0, verString.indexOf(VERSION_DELIMITER));
+ }
+ if (!verString.isEmpty()) {
+ valgrindVersion = Version.parseVersion(verString);
+ } else {
+ throw new CoreException(new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, Messages.getString("ValgrindLaunchPlugin.Couldn't_determine_version"))); //$NON-NLS-1$
+ }
+
+ // check for minimum supported version
+ if (valgrindVersion.compareTo(MIN_VER) < 0) {
+ throw new CoreException(new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, NLS.bind(Messages.getString("ValgrindLaunchPlugin.Error_min_version"), valgrindVersion.toString(), MIN_VER.toString()))); //$NON-NLS-1$
+ }
+ return valgrindVersion;
+ }
+
+
+ @Override
+ public void launch(final ILaunchConfiguration config, String mode,
+ final ILaunch launch, IProgressMonitor m) throws CoreException {
+ if (m == null) {
+ m = new NullProgressMonitor();
+ }
+
+ // Clear process as we wait on it to be instantiated
+ process = null;
+
+ SubMonitor monitor = SubMonitor.convert(m,
+ Messages.getString("ValgrindRemoteLaunchDelegate.task_name"), 10); //$NON-NLS-1$
+ // check for cancellation
+ if (monitor.isCanceled()) {
+ return;
+ }
+
+ this.config = config;
+ this.launch = launch;
+ try {
+ // remove any output from previous run
+ ValgrindUIPlugin.getDefault().resetView();
+ // reset stored launch data
+ getPlugin().setCurrentLaunchConfiguration(null);
+ getPlugin().setCurrentLaunch(null);
+
+ this.configUtils = new ConfigUtils(config);
+ IProject project = configUtils.getProject();
+ URI exeURI = new URI(configUtils.getExecutablePath());
+ RemoteConnection exeRC = new RemoteConnection(exeURI);
+ monitor.worked(1);
+ String valgrindPathString = RuntimeProcessFactory.getFactory().whichCommand(VALGRIND_CMD, project);
+ IPath valgrindFullPath = Path.fromOSString(valgrindPathString);
+ boolean copyExecutable = configUtils.getCopyExecutable();
+ if (copyExecutable) {
+ URI copyExeURI = new URI(configUtils.getCopyFromExecutablePath());
+ RemoteConnection copyExeRC = new RemoteConnection(copyExeURI);
+ IRemoteFileProxy copyExeRFP = copyExeRC.getRmtFileProxy();
+ IFileStore copyExeFS = copyExeRFP.getResource(copyExeURI.getPath());
+ IRemoteFileProxy exeRFP = exeRC.getRmtFileProxy();
+ IFileStore exeFS = exeRFP.getResource(exeURI.getPath());
+ IFileInfo exeFI = exeFS.fetchInfo();
+ if (exeFI.isDirectory()) {
+ // Assume the user wants to copy the file to the given directory, using
+ // the same filename as the "copy from" executable.
+ IPath copyExePath = Path.fromOSString(copyExeURI.getPath());
+ IPath newExePath = Path.fromOSString(exeURI.getPath()).append(copyExePath.lastSegment());
+ // update the exeURI with the new path.
+ exeURI = new URI(exeURI.getScheme(), exeURI.getAuthority(), newExePath.toString(), exeURI.getQuery(), exeURI.getFragment());
+ exeFS = exeRFP.getResource(exeURI.getPath());
+ }
+ copyExeFS.copy(exeFS, EFS.OVERWRITE | EFS.SHALLOW, new SubProgressMonitor(monitor, 1));
+ // Note: assume that we don't need to create a new exeRC since the
+ // scheme and authority remain the same between the original exeURI and the new one.
+ }
+ valgrindVersion = getValgrindVersion(project);
+ IPath remoteBinFile = Path.fromOSString(exeURI.getPath());
+ String configWorkingDir = configUtils.getWorkingDirectory();
+ IFileStore workingDir;
+ if(configWorkingDir == null){
+ // If no working directory was provided, use the directory containing the
+ // the executable as the working directory.
+ IPath workingDirPath = remoteBinFile.removeLastSegments(1);
+ IRemoteFileProxy workingDirRFP = exeRC.getRmtFileProxy();
+ workingDir = workingDirRFP.getResource(workingDirPath.toOSString());
+ } else {
+ URI workingDirURI = new URI(configUtils.getWorkingDirectory());
+ RemoteConnection workingDirRC = new RemoteConnection(workingDirURI);
+ IRemoteFileProxy workingDirRFP = workingDirRC.getRmtFileProxy();
+ workingDir = workingDirRFP.getResource(workingDirURI.getPath());
+ }
+
+ IPath remoteLogDir = Path.fromOSString("/tmp/"); //$NON-NLS-1$
+ outputPath = remoteLogDir.append("eclipse-valgrind-" + System.currentTimeMillis()); //$NON-NLS-1$
+
+ exeRC.createFolder(outputPath, new SubProgressMonitor(monitor, 1));
+
+ // create/empty local output directory
+ IValgrindOutputDirectoryProvider provider = getPlugin().getOutputDirectoryProvider();
+ IPath localOutputDir = null;
+ try {
+ localOutputDir = provider.getOutputPath();
+ createDirectory(localOutputDir);
+ } catch (IOException e2) {
+ throw new CoreException(new Status(IStatus.ERROR, ValgrindLaunchPlugin.PLUGIN_ID, IStatus.OK,
+ "", e2)); //$NON-NLS-1$
+ }
+
+ // tool that was launched
+ toolID = getTool(config);
+ // ask tool extension for arguments
+ dynamicDelegate = getDynamicDelegate(toolID);
+
+ String[] valgrindArgs = getValgrindArgumentsArray(config);
+ String[] executableArgs = getProgramArgumentsArray(config);
+ String[] allArgs = new String[executableArgs.length + valgrindArgs.length + 2];
+
+ int idx = 0;
+ allArgs[idx++] = VALGRIND_CMD;
+ for (String valgrindArg : valgrindArgs) {
+ allArgs[idx++] = valgrindArg;
+ }
+ allArgs[idx++] = remoteBinFile.toOSString();
+ for (String executableArg : executableArgs) {
+ allArgs[idx++] = executableArg;
+ }
+
+ Process p = RuntimeProcessFactory.getFactory().exec(allArgs, new String[0], workingDir, project);
+
+ int state = p.waitFor();
+
+ if (state != IRemoteCommandLauncher.OK) {
+ abort("valgrind launcher exited with status " + state + ". See IRemoteCommandLauncher for details.\n",
+ null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
+ }
+
+
+ if (p.exitValue() != 0) {
+ String line = null;
+
+ StringBuilder valgrindOutSB = new StringBuilder();
+ BufferedReader valgrindOut = new BufferedReader(new InputStreamReader(p.getInputStream()));
+ while((line = valgrindOut.readLine()) != null ){
+ valgrindOutSB.append(line);
+ }
+
+ StringBuilder valgrindErrSB = new StringBuilder();
+ BufferedReader valgrindErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
+ while((line = valgrindErr.readLine()) != null ){
+ valgrindErrSB.append(line);
+ }
+
+ abort("Standard ouput: " + valgrindOutSB.toString() +
+ "\nStandard error: " + valgrindErrSB.toString(),
+ null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
+ }
+
+ // move remote log files to local directory
+ exeRC.download(outputPath, localOutputDir, new SubProgressMonitor(monitor, 1));
+
+ // remove remote log dir and all files under it
+ exeRC.delete(outputPath, new SubProgressMonitor(monitor, 1));
+
+ // store these for use by other classes
+ getPlugin().setCurrentLaunchConfiguration(config);
+ getPlugin().setCurrentLaunch(launch);
+
+ // parse Valgrind logs
+ IValgrindMessage[] messages = parseLogs(localOutputDir);
+
+ // create launch summary string to distinguish this launch
+ launchStr = createLaunchStr(valgrindFullPath);
+
+ // create view
+ ValgrindUIPlugin.getDefault().createView(launchStr, toolID);
+ // set log messages
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ view.setMessages(messages);
+ monitor.worked(1);
+
+ // pass off control to extender
+ dynamicDelegate.handleLaunch(config, launch, localOutputDir, monitor.newChild(2));
+
+ // initialize tool-specific part of view
+ dynamicDelegate.initializeView(view.getDynamicView(), launchStr, monitor.newChild(1));
+
+ // refresh view
+ ValgrindUIPlugin.getDefault().refreshView();
+
+ // show view
+ ValgrindUIPlugin.getDefault().showView();
+ monitor.worked(1);
+
+ } catch (URISyntaxException|IOException|RemoteConnectionException|InterruptedException e) {
+ abort(e.getLocalizedMessage(), null, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR);
+ } finally {
+ monitor.done();
+ m.done();
+ }
+ }
+
+ private String createLaunchStr(IPath valgrindPath) throws CoreException {
+ IProject project = configUtils.getProject();
+ URI projectURI = project.getLocationURI();
+
+ String host = projectURI.getHost();
+
+ // Host might be null since it's not needed for a well-formed URI. Try authority instead
+ if(host == null){
+ host = projectURI.getAuthority();
+ }
+
+ // If authority is also null, use a generic name
+ String location;
+
+ if(host == null){
+ location = "remote host"; //$NON-NLS-1$
+ } else {
+ location = projectURI.getScheme() + "://" + host; //$NON-NLS-1$
+ }
+
+ return config.getName()
+ + " [" + getPlugin().getToolName(toolID) + "]" + " " + valgrindPath.toString() + " on " + location; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
- @Override
- protected String getPluginID() {
- return ValgrindLaunchPlugin.PLUGIN_ID;
- }
+ @Override
+ protected String getPluginID() {
+ return ValgrindLaunchPlugin.PLUGIN_ID;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindSingleToolOptionsTab.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindSingleToolOptionsTab.java
index 55cc166e0e..24218a4f8d 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindSingleToolOptionsTab.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/internal/valgrind/launch/ValgrindSingleToolOptionsTab.java
@@ -12,19 +12,19 @@ package org.eclipse.linuxtools.internal.valgrind.launch;
/**
* @since 1.2
- *
+ *
* Special version of ValgrindOptionsTab to force the choice of Valgrind tool to
* just one. This is used by the Profiling Framework to offer more
* task-oriented choices to the end-user and not overwhelm them with all the
* tool choices.
*/
public class ValgrindSingleToolOptionsTab extends ValgrindOptionsTab {
-
- public ValgrindSingleToolOptionsTab(String toolId) {
- super();
- noToolCombo = true;
- tool = toolId;
- tools = new String[] {tool};
- }
-
+
+ public ValgrindSingleToolOptionsTab(String toolId) {
+ super();
+ noToolCombo = true;
+ tool = toolId;
+ tools = new String[] {tool};
+ }
+
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindLaunchDelegate.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindLaunchDelegate.java
index e0a30dd4f9..600fa943e4 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindLaunchDelegate.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindLaunchDelegate.java
@@ -24,40 +24,40 @@ import org.osgi.framework.Version;
*/
public interface IValgrindLaunchDelegate {
- /**
- * To be called after Valgrind has been called for a given launch.
- * This method is responsible for parsing Valgrind's output as needed
- * by this tool
- * @param config - the configuration to launch
- * @param launch - the launch object to contribute processes and debug
- * targets to
- * @param logDir - directory to store Valgrind log output files
- * @param monitor - to report progress
- * @throws CoreException - if this method fails
- */
- void handleLaunch(ILaunchConfiguration config, ILaunch launch, IPath logDir, IProgressMonitor monitor) throws CoreException;
+ /**
+ * To be called after Valgrind has been called for a given launch.
+ * This method is responsible for parsing Valgrind's output as needed
+ * by this tool
+ * @param config - the configuration to launch
+ * @param launch - the launch object to contribute processes and debug
+ * targets to
+ * @param logDir - directory to store Valgrind log output files
+ * @param monitor - to report progress
+ * @throws CoreException - if this method fails
+ */
+ void handleLaunch(ILaunchConfiguration config, ILaunch launch, IPath logDir, IProgressMonitor monitor) throws CoreException;
- /**
- * Called after handleLaunch returns control to the main Valgrind launch
- * delegate, and initializes the Valgrind view. This method is responsible
- * for initializing the tool-specific portion of the Valgrind view with tool-specific
- * output from the launch.
- * @param view - the tool-specific part of the Valgrind view contributed via extension point
- * @param contentDescription - String describing the launch that populated the view
- * @param monitor - to report progress
- * @throws CoreException - if this method fails
- */
- void initializeView(IValgrindToolView view, String contentDescription, IProgressMonitor monitor) throws CoreException;
+ /**
+ * Called after handleLaunch returns control to the main Valgrind launch
+ * delegate, and initializes the Valgrind view. This method is responsible
+ * for initializing the tool-specific portion of the Valgrind view with tool-specific
+ * output from the launch.
+ * @param view - the tool-specific part of the Valgrind view contributed via extension point
+ * @param contentDescription - String describing the launch that populated the view
+ * @param monitor - to report progress
+ * @throws CoreException - if this method fails
+ */
+ void initializeView(IValgrindToolView view, String contentDescription, IProgressMonitor monitor) throws CoreException;
- /**
- * Parses attributes of an <code>ILaunchConfiguration</code> into an array
- * of arguments to be passed to Valgrind
- * @param config - the <code>ILaunchConfiguration</code>
- * @param ver - the version of Valgrind, or null if version checking should not be performed
- * @param logDir - directory to store Valgrind log output files
- * @return an array of arguments that can appended to a <code>valgrind</code> command
- * @throws CoreException - retrieving attributes from config failed
- */
- String[] getCommandArray(ILaunchConfiguration config, Version ver, IPath logDir) throws CoreException;
+ /**
+ * Parses attributes of an <code>ILaunchConfiguration</code> into an array
+ * of arguments to be passed to Valgrind
+ * @param config - the <code>ILaunchConfiguration</code>
+ * @param ver - the version of Valgrind, or null if version checking should not be performed
+ * @param logDir - directory to store Valgrind log output files
+ * @return an array of arguments that can appended to a <code>valgrind</code> command
+ * @throws CoreException - retrieving attributes from config failed
+ */
+ String[] getCommandArray(ILaunchConfiguration config, Version ver, IPath logDir) throws CoreException;
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindOutputDirectoryProvider.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindOutputDirectoryProvider.java
index eee39955e7..e6569221cf 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindOutputDirectoryProvider.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindOutputDirectoryProvider.java
@@ -20,10 +20,10 @@ import org.eclipse.core.runtime.IPath;
*/
public interface IValgrindOutputDirectoryProvider {
- /**
- * Obtains a directory to store Valgrind output files.
- * @return the absolute path to this directory
- */
- IPath getOutputPath() throws IOException;
+ /**
+ * Obtains a directory to store Valgrind output files.
+ * @return the absolute path to this directory
+ */
+ IPath getOutputPath() throws IOException;
} \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindToolPage.java b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindToolPage.java
index 3613246c1a..47574c0855 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindToolPage.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.launch/src/org/eclipse/linuxtools/valgrind/launch/IValgrindToolPage.java
@@ -19,13 +19,13 @@ import org.osgi.framework.Version;
*/
public interface IValgrindToolPage extends ILaunchConfigurationTab {
- /**
- * To be called before createControl. This method is used to inform extenders
- * which version of Valgrind is available. The extender may then perform
- * tool-specific version checking. If a value of null is passed, then version
- * checking should not be performed.
- * @param ver - the version of Valgrind, or null
- */
- void setValgrindVersion(Version ver);
+ /**
+ * To be called before createControl. This method is used to inform extenders
+ * which version of Valgrind is available. The extender may then perform
+ * tool-specific version checking. If a value of null is passed, then version
+ * checking should not be performed.
+ * @param ver - the version of Valgrind, or null
+ */
+ void setValgrindVersion(Version ver);
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/AbstractMassifTest.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/AbstractMassifTest.java
index 7f61f3572b..c90915b869 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/AbstractMassifTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/AbstractMassifTest.java
@@ -40,10 +40,10 @@ import org.eclipse.ui.texteditor.ITextEditor;
public abstract class AbstractMassifTest extends AbstractValgrindTest {
- @Override
- protected String getToolID() {
- return MassifPlugin.TOOL_ID;
- }
+ @Override
+ protected String getToolID() {
+ return MassifPlugin.TOOL_ID;
+ }
protected void checkFile(IProject proj, MassifHeapTreeNode node) {
IEditorPart editor = PlatformUI.getWorkbench()
@@ -72,54 +72,54 @@ public abstract class AbstractMassifTest extends AbstractValgrindTest {
assertEquals(node.getLine(), line);
}
- /**
- * Check snapshots contain the expected used bytes.
- *
- * @param snapshots MassifSnapshots to check
- * @param usefulBytesDelta scale of useful bytes
- * @param extraBytesDelta scale of extra bytes
- */
- protected void checkSnapshots(MassifSnapshot[] snapshots, int usefulBytesDelta, int extraBytesDelta){
- long expectedHeapBytes = 0;
- long expectedHeapExtraBytes = 0;
- boolean pastPeakUsage = false;
+ /**
+ * Check snapshots contain the expected used bytes.
+ *
+ * @param snapshots MassifSnapshots to check
+ * @param usefulBytesDelta scale of useful bytes
+ * @param extraBytesDelta scale of extra bytes
+ */
+ protected void checkSnapshots(MassifSnapshot[] snapshots, int usefulBytesDelta, int extraBytesDelta){
+ long expectedHeapBytes = 0;
+ long expectedHeapExtraBytes = 0;
+ boolean pastPeakUsage = false;
- for (MassifSnapshot snapshot : snapshots) {
- if (snapshot.getTime() == 0) {
- // no need to update expected values
- } else if (snapshot.getType().compareTo(SnapshotType.PEAK) == 0) {
- pastPeakUsage = true;
- // no need to update expected values
- } else if (!pastPeakUsage) {
- expectedHeapBytes += usefulBytesDelta;
- expectedHeapExtraBytes += extraBytesDelta;
- } else {
- // past the peak , heap bytes used begin to decrease
- expectedHeapBytes -= usefulBytesDelta;
- expectedHeapExtraBytes -= extraBytesDelta;
- }
+ for (MassifSnapshot snapshot : snapshots) {
+ if (snapshot.getTime() == 0) {
+ // no need to update expected values
+ } else if (snapshot.getType().compareTo(SnapshotType.PEAK) == 0) {
+ pastPeakUsage = true;
+ // no need to update expected values
+ } else if (!pastPeakUsage) {
+ expectedHeapBytes += usefulBytesDelta;
+ expectedHeapExtraBytes += extraBytesDelta;
+ } else {
+ // past the peak , heap bytes used begin to decrease
+ expectedHeapBytes -= usefulBytesDelta;
+ expectedHeapExtraBytes -= extraBytesDelta;
+ }
- assertEquals(expectedHeapBytes, snapshot.getHeapBytes());
- assertEquals(expectedHeapExtraBytes, snapshot.getHeapExtra());
- assertEquals(expectedHeapBytes + expectedHeapExtraBytes, snapshot.getTotal());
- }
- }
+ assertEquals(expectedHeapBytes, snapshot.getHeapBytes());
+ assertEquals(expectedHeapExtraBytes, snapshot.getHeapExtra());
+ assertEquals(expectedHeapBytes + expectedHeapExtraBytes, snapshot.getTotal());
+ }
+ }
- protected IAction getToolbarAction(String actionId) {
- IAction result = null;
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- IToolBarManager manager = view.getViewSite().getActionBars()
- .getToolBarManager();
- for (IContributionItem item : manager.getItems()) {
- if (item instanceof ActionContributionItem) {
- ActionContributionItem actionItem = (ActionContributionItem) item;
- if (actionItem.getAction().getId()
- .equals(actionId)) {
- result = actionItem.getAction();
- }
- }
- }
- return result;
- }
+ protected IAction getToolbarAction(String actionId) {
+ IAction result = null;
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ IToolBarManager manager = view.getViewSite().getActionBars()
+ .getToolBarManager();
+ for (IContributionItem item : manager.getItems()) {
+ if (item instanceof ActionContributionItem) {
+ ActionContributionItem actionItem = (ActionContributionItem) item;
+ if (actionItem.getAction().getId()
+ .equals(actionId)) {
+ result = actionItem.getAction();
+ }
+ }
+ }
+ return result;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/AllTests.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/AllTests.java
index 12bf806934..5a024cdd52 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/AllTests.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/AllTests.java
@@ -15,8 +15,8 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ DoubleClickTest.class, ChartTests.class, TreeTest.class,
- BasicMassifTest.class, LaunchConfigTabTest.class,
- ExportWizardTest.class, MultiProcessTest.class,
- ExpandCollapseTest.class, SortTest.class, ChartExportTest.class, ShortcutTest.class })
+ BasicMassifTest.class, LaunchConfigTabTest.class,
+ ExportWizardTest.class, MultiProcessTest.class,
+ ExpandCollapseTest.class, SortTest.class, ChartExportTest.class, ShortcutTest.class })
public class AllTests {
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/BasicMassifTest.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/BasicMassifTest.java
index 61b8a70e6e..2a630000ba 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/BasicMassifTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/BasicMassifTest.java
@@ -23,27 +23,27 @@ import org.junit.Test;
public class BasicMassifTest extends AbstractMassifTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
-
- @Test
- public void testNumSnapshots() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testNumSnapshots"); //$NON-NLS-1$
-
- MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- MassifSnapshot[] snapshots = view.getSnapshots();
- assertEquals(14, snapshots.length);
- checkSnapshots(snapshots , 40, 16);
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ @Test
+ public void testNumSnapshots() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testNumSnapshots"); //$NON-NLS-1$
+
+ MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ MassifSnapshot[] snapshots = view.getSnapshots();
+ assertEquals(14, snapshots.length);
+ checkSnapshots(snapshots , 40, 16);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ChartExportTest.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ChartExportTest.java
index 5536926dc2..2caba60d39 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ChartExportTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ChartExportTest.java
@@ -31,65 +31,65 @@ import org.junit.Before;
import org.junit.Test;
public class ChartExportTest extends AbstractMassifTest {
- private String[] pathNames = new String[]{"chart.png", "chart.jpg", "chart.jpeg", "chart.bmp"};
- private ArrayList<IPath> paths = new ArrayList<>();
+ private String[] pathNames = new String[]{"chart.png", "chart.jpg", "chart.jpeg", "chart.bmp"};
+ private ArrayList<IPath> paths = new ArrayList<>();
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
- IPath basePath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
- assertNotNull(basePath);
- basePath = basePath.append("alloctest");
- for (String pathName : pathNames) {
- paths.add(basePath.append(pathName));
- }
- }
+ IPath basePath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
+ assertNotNull(basePath);
+ basePath = basePath.append("alloctest");
+ for (String pathName : pathNames) {
+ paths.add(basePath.append(pathName));
+ }
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- for (IPath path : paths) {
- File chartFile = path.toFile();
- if (chartFile.exists()) {
- chartFile.delete();
- }
- }
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ for (IPath path : paths) {
+ File chartFile = path.toFile();
+ if (chartFile.exists()) {
+ chartFile.delete();
+ }
+ }
- deleteProject(proj);
- super.tearDown();
- }
+ deleteProject(proj);
+ super.tearDown();
+ }
- @Test
- public void testChartExportPNG() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testDefaults"); //$NON-NLS-1$
+ @Test
+ public void testChartExportPNG() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testDefaults"); //$NON-NLS-1$
- IEditorInput input = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage().getActiveEditor()
- .getEditorInput();
- assertTrue("input must be ChartEditorInput",
- input instanceof ChartEditorInput);
+ IEditorInput input = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage().getActiveEditor()
+ .getEditorInput();
+ assertTrue("input must be ChartEditorInput",
+ input instanceof ChartEditorInput);
- Composite control = ((ChartEditorInput) input).getChart().getChartControl();
- if (control.getSize().x == 0 || control.getSize().y == 0) {
- // Manually resize the composite to non-zero width/height so it can be saved
- control.setSize(10, 10);
- }
+ Composite control = ((ChartEditorInput) input).getChart().getChartControl();
+ if (control.getSize().x == 0 || control.getSize().y == 0) {
+ // Manually resize the composite to non-zero width/height so it can be saved
+ control.setSize(10, 10);
+ }
- SaveChartAction saveChartAction = (SaveChartAction) getToolbarAction(MassifViewPart.SAVE_CHART_ACTION);
- assertNotNull(saveChartAction);
+ SaveChartAction saveChartAction = (SaveChartAction) getToolbarAction(MassifViewPart.SAVE_CHART_ACTION);
+ assertNotNull(saveChartAction);
- for (IPath path : paths) {
- saveAsPath(saveChartAction, path);
- }
- }
+ for (IPath path : paths) {
+ saveAsPath(saveChartAction, path);
+ }
+ }
- private void saveAsPath(SaveChartAction saveChartAction, IPath path) {
- saveChartAction.run(path.toString());
- File chartFile = path.toFile();
- assertTrue(chartFile.exists());
- assertTrue(chartFile.length() > 0);
- }
+ private void saveAsPath(SaveChartAction saveChartAction, IPath path) {
+ saveChartAction.run(path.toString());
+ File chartFile = path.toFile();
+ assertTrue(chartFile.exists());
+ assertTrue(chartFile.length() > 0);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ChartTests.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ChartTests.java
index caa3d1564e..86fcc605bc 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ChartTests.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ChartTests.java
@@ -42,134 +42,134 @@ import org.swtchart.Chart;
import org.swtchart.ILineSeries;
public class ChartTests extends AbstractMassifTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
-
- @Test
- public void testEditorName() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testEditorName"); //$NON-NLS-1$
-
- IAction chartAction = getChartAction();
- assertNotNull(chartAction);
- chartAction.run();
-
- IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
- .getActivePage().getActiveEditor();
- assertTrue(part.getTitle().startsWith("Heap Chart - alloctest")); //$NON-NLS-1$
- }
-
- @Test
- public void testByteScalingKiB() throws Exception {
- byteScalingHelper(1, 1, 1024 * 10, "testByteScalingKiB"); //$NON-NLS-1$
- }
-
- @Test
- public void testByteScalingMiB() throws Exception {
- byteScalingHelper(2, 1, 1024 * 1024 * 10, "testByteScalingMiB"); //$NON-NLS-1$
- }
-
- @Test
- public void testByteScalingGiB() throws Exception {
- byteScalingHelper(3, 1024, 1024 * 1024 * 10, "testByteScalingGiB"); //$NON-NLS-1$
- }
-
- @Test
- public void testByteScalingTiB() throws Exception {
- byteScalingHelper(4, 1024 * 1024, 1024 * 1024 * 10,
- "testByteScalingTiB"); //$NON-NLS-1$
- }
-
- @Test
- public void testChartCallback() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testChartCallback"); //$NON-NLS-1$
-
- IAction chartAction = getChartAction();
- assertNotNull(chartAction);
- chartAction.run();
-
- IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
- .getActivePage().getActiveEditor();
- assertTrue(part instanceof ChartEditor);
- Chart control = ((ChartEditor) part).getControl();
- ILineSeries lsTotal = (ILineSeries) control.getSeriesSet().getSeries(
- Messages.getString("HeapChart.Total_Heap")); //$NON-NLS-1$
- Point p1 = lsTotal.getPixelCoordinates(4);
-
- HeapChart heapChart = ((ChartEditorInput) ((ChartEditor) part)
- .getEditorInput()).getChart();
- int x = control.getAxisSet().getXAxis(0)
- .getPixelCoordinate(heapChart.time[4]);
- int y = control.getAxisSet().getYAxis(0)
- .getPixelCoordinate(heapChart.dataTotal[4]);
-
- assertEquals(x, p1.x);
- assertEquals(y, p1.y);
- }
-
- @Test
- public void testChartLocationsDialog() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testChartCallback"); //$NON-NLS-1$
-
- MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
- .getView().getDynamicView();
- MassifSnapshot snapshot = view.getSnapshots()[7]; // peak
- assertTrue(snapshot.isDetailed());
-
- Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
- .getShell();
- ChartLocationsDialog dialog = new ChartLocationsDialog(parent);
- dialog.setInput(snapshot);
- dialog.setBlockOnOpen(false);
- dialog.open();
-
- MassifHeapTreeNode element = snapshot.getRoot().getChildren()[1];
- dialog.getTableViewer().setSelection(new StructuredSelection(element));
- dialog.getOkButton().notifyListeners(SWT.Selection, null);
- dialog.openEditorForResult();
-
- checkFile(proj.getProject(), element);
- checkLine(element);
- }
-
- private void byteScalingHelper(int ix, long times, long bytes,
- String testName) throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- wc.setAttribute(
- ICDTLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
- String.valueOf(bytes) + " " + String.valueOf(times)); //$NON-NLS-1$
- wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_TIMEUNIT,
- MassifLaunchConstants.TIME_B);
- config = wc.doSave();
-
- doLaunch(config, testName);
-
- IAction chartAction = getChartAction();
- assertNotNull(chartAction);
- chartAction.run();
-
- IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
- .getActivePage().getActiveEditor();
- assertTrue(part.getEditorInput() instanceof ChartEditorInput);
- ChartEditorInput input = (ChartEditorInput) part.getEditorInput();
- HeapChart chart = input.getChart();
- assertEquals(HeapChart.getByteUnits()[ix], chart.getXUnits());
- }
-
- private IAction getChartAction() {
- return getToolbarAction(MassifViewPart.CHART_ACTION);
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ @Test
+ public void testEditorName() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testEditorName"); //$NON-NLS-1$
+
+ IAction chartAction = getChartAction();
+ assertNotNull(chartAction);
+ chartAction.run();
+
+ IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage().getActiveEditor();
+ assertTrue(part.getTitle().startsWith("Heap Chart - alloctest")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testByteScalingKiB() throws Exception {
+ byteScalingHelper(1, 1, 1024 * 10, "testByteScalingKiB"); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testByteScalingMiB() throws Exception {
+ byteScalingHelper(2, 1, 1024 * 1024 * 10, "testByteScalingMiB"); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testByteScalingGiB() throws Exception {
+ byteScalingHelper(3, 1024, 1024 * 1024 * 10, "testByteScalingGiB"); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testByteScalingTiB() throws Exception {
+ byteScalingHelper(4, 1024 * 1024, 1024 * 1024 * 10,
+ "testByteScalingTiB"); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testChartCallback() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testChartCallback"); //$NON-NLS-1$
+
+ IAction chartAction = getChartAction();
+ assertNotNull(chartAction);
+ chartAction.run();
+
+ IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage().getActiveEditor();
+ assertTrue(part instanceof ChartEditor);
+ Chart control = ((ChartEditor) part).getControl();
+ ILineSeries lsTotal = (ILineSeries) control.getSeriesSet().getSeries(
+ Messages.getString("HeapChart.Total_Heap")); //$NON-NLS-1$
+ Point p1 = lsTotal.getPixelCoordinates(4);
+
+ HeapChart heapChart = ((ChartEditorInput) ((ChartEditor) part)
+ .getEditorInput()).getChart();
+ int x = control.getAxisSet().getXAxis(0)
+ .getPixelCoordinate(heapChart.time[4]);
+ int y = control.getAxisSet().getYAxis(0)
+ .getPixelCoordinate(heapChart.dataTotal[4]);
+
+ assertEquals(x, p1.x);
+ assertEquals(y, p1.y);
+ }
+
+ @Test
+ public void testChartLocationsDialog() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testChartCallback"); //$NON-NLS-1$
+
+ MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
+ .getView().getDynamicView();
+ MassifSnapshot snapshot = view.getSnapshots()[7]; // peak
+ assertTrue(snapshot.isDetailed());
+
+ Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getShell();
+ ChartLocationsDialog dialog = new ChartLocationsDialog(parent);
+ dialog.setInput(snapshot);
+ dialog.setBlockOnOpen(false);
+ dialog.open();
+
+ MassifHeapTreeNode element = snapshot.getRoot().getChildren()[1];
+ dialog.getTableViewer().setSelection(new StructuredSelection(element));
+ dialog.getOkButton().notifyListeners(SWT.Selection, null);
+ dialog.openEditorForResult();
+
+ checkFile(proj.getProject(), element);
+ checkLine(element);
+ }
+
+ private void byteScalingHelper(int ix, long times, long bytes,
+ String testName) throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ wc.setAttribute(
+ ICDTLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
+ String.valueOf(bytes) + " " + String.valueOf(times)); //$NON-NLS-1$
+ wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_TIMEUNIT,
+ MassifLaunchConstants.TIME_B);
+ config = wc.doSave();
+
+ doLaunch(config, testName);
+
+ IAction chartAction = getChartAction();
+ assertNotNull(chartAction);
+ chartAction.run();
+
+ IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
+ .getActivePage().getActiveEditor();
+ assertTrue(part.getEditorInput() instanceof ChartEditorInput);
+ ChartEditorInput input = (ChartEditorInput) part.getEditorInput();
+ HeapChart chart = input.getChart();
+ assertEquals(HeapChart.getByteUnits()[ix], chart.getXUnits());
+ }
+
+ private IAction getChartAction() {
+ return getToolbarAction(MassifViewPart.CHART_ACTION);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/DoubleClickTest.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/DoubleClickTest.java
index 076c2e3364..ed05d5e3de 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/DoubleClickTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/DoubleClickTest.java
@@ -32,62 +32,62 @@ import org.junit.Before;
import org.junit.Test;
public class DoubleClickTest extends AbstractMassifTest {
- private MassifHeapTreeNode node;
+ private MassifHeapTreeNode node;
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
- private void doDoubleClick() {
- MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- MassifTreeViewer treeViewer = view.getTreeViewer();
+ private void doDoubleClick() {
+ MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ MassifTreeViewer treeViewer = view.getTreeViewer();
- MassifSnapshot[] snapshots = view.getSnapshots();
- node = snapshots[1].getRoot(); // first detailed
- TreePath path = new TreePath(new Object[] { node });
- while (node.getChildren().length > 0 && !node.hasSourceFile()) {
- node = node.getChildren()[0];
- path = path.createChildPath(node);
- }
- assertTrue(node.hasSourceFile());
- treeViewer.getViewer().expandToLevel(node,
- AbstractTreeViewer.ALL_LEVELS);
- TreeSelection selection = new TreeSelection(path);
+ MassifSnapshot[] snapshots = view.getSnapshots();
+ node = snapshots[1].getRoot(); // first detailed
+ TreePath path = new TreePath(new Object[] { node });
+ while (node.getChildren().length > 0 && !node.hasSourceFile()) {
+ node = node.getChildren()[0];
+ path = path.createChildPath(node);
+ }
+ assertTrue(node.hasSourceFile());
+ treeViewer.getViewer().expandToLevel(node,
+ AbstractTreeViewer.ALL_LEVELS);
+ TreeSelection selection = new TreeSelection(path);
- // do double click
- IDoubleClickListener listener = treeViewer.getDoubleClickListener();
- listener.doubleClick(new DoubleClickEvent(treeViewer.getViewer(), selection));
- }
- @Test
- public void testDoubleClickFile() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, 2);
- wc.doSave();
- doLaunch(config, "testDoubleClickFile"); //$NON-NLS-1$
+ // do double click
+ IDoubleClickListener listener = treeViewer.getDoubleClickListener();
+ listener.doubleClick(new DoubleClickEvent(treeViewer.getViewer(), selection));
+ }
+ @Test
+ public void testDoubleClickFile() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, 2);
+ wc.doSave();
+ doLaunch(config, "testDoubleClickFile"); //$NON-NLS-1$
- doDoubleClick();
+ doDoubleClick();
- checkFile(proj.getProject(), node);
- }
- @Test
- public void testDoubleClickLine() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, 2);
- wc.doSave();
- doLaunch(config, "testDoubleClickLine"); //$NON-NLS-1$
+ checkFile(proj.getProject(), node);
+ }
+ @Test
+ public void testDoubleClickLine() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, 2);
+ wc.doSave();
+ doLaunch(config, "testDoubleClickLine"); //$NON-NLS-1$
- doDoubleClick();
+ doDoubleClick();
- checkLine(node);
- }
+ checkLine(node);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ExpandCollapseTest.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ExpandCollapseTest.java
index 2c58804a74..974fc03877 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ExpandCollapseTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ExpandCollapseTest.java
@@ -29,67 +29,67 @@ import org.junit.Test;
public class ExpandCollapseTest extends AbstractMassifTest {
- protected TreeViewer viewer;
- protected Menu contextMenu;
+ protected TreeViewer viewer;
+ protected Menu contextMenu;
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
- @Test
- public void testExpand() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testDefaults"); //$NON-NLS-1$
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+ @Test
+ public void testExpand() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testDefaults"); //$NON-NLS-1$
- MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
- viewer = view.getTreeViewer().getViewer();
- contextMenu = viewer.getTree().getMenu();
+ MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault().getView().getDynamicView();
+ viewer = view.getTreeViewer().getViewer();
+ contextMenu = viewer.getTree().getMenu();
- // Select first snapshot and expand it
- MassifHeapTreeNode[] snapshots = (MassifHeapTreeNode[]) viewer.getInput();
- MassifHeapTreeNode snapshot = snapshots[0];
- TreeSelection selection = new TreeSelection(new TreePath(new Object[] { snapshot }));
- viewer.setSelection(selection);
- contextMenu.notifyListeners(SWT.Show, null);
- contextMenu.getItem(0).notifyListeners(SWT.Selection, null);
+ // Select first snapshot and expand it
+ MassifHeapTreeNode[] snapshots = (MassifHeapTreeNode[]) viewer.getInput();
+ MassifHeapTreeNode snapshot = snapshots[0];
+ TreeSelection selection = new TreeSelection(new TreePath(new Object[] { snapshot }));
+ viewer.setSelection(selection);
+ contextMenu.notifyListeners(SWT.Show, null);
+ contextMenu.getItem(0).notifyListeners(SWT.Selection, null);
- checkExpanded(snapshot, true);
- }
- @Test
- public void testCollapse() throws Exception {
- // Expand the element first
- testExpand();
+ checkExpanded(snapshot, true);
+ }
+ @Test
+ public void testCollapse() throws Exception {
+ // Expand the element first
+ testExpand();
- // Then collapse it
- MassifHeapTreeNode[] snapshots = (MassifHeapTreeNode[]) viewer.getInput();
- MassifHeapTreeNode snapshot = snapshots[0];
- TreeSelection selection = new TreeSelection(new TreePath(new Object[] { snapshot }));
- viewer.setSelection(selection);
- contextMenu.notifyListeners(SWT.Show, null);
- contextMenu.getItem(1).notifyListeners(SWT.Selection, null);
+ // Then collapse it
+ MassifHeapTreeNode[] snapshots = (MassifHeapTreeNode[]) viewer.getInput();
+ MassifHeapTreeNode snapshot = snapshots[0];
+ TreeSelection selection = new TreeSelection(new TreePath(new Object[] { snapshot }));
+ viewer.setSelection(selection);
+ contextMenu.notifyListeners(SWT.Show, null);
+ contextMenu.getItem(1).notifyListeners(SWT.Selection, null);
- checkExpanded(snapshot, false);
- }
+ checkExpanded(snapshot, false);
+ }
- private void checkExpanded(MassifHeapTreeNode element, boolean expanded) {
- if (element.getChildren().length > 0) {
- // only applicable to internal nodes
- if (expanded) {
- assertTrue(viewer.getExpandedState(element));
- }
- else {
- assertFalse(viewer.getExpandedState(element));
- }
- }
- for (MassifHeapTreeNode child : element.getChildren()) {
- checkExpanded(child, expanded);
- }
- }
+ private void checkExpanded(MassifHeapTreeNode element, boolean expanded) {
+ if (element.getChildren().length > 0) {
+ // only applicable to internal nodes
+ if (expanded) {
+ assertTrue(viewer.getExpandedState(element));
+ }
+ else {
+ assertFalse(viewer.getExpandedState(element));
+ }
+ }
+ for (MassifHeapTreeNode child : element.getChildren()) {
+ checkExpanded(child, expanded);
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ExportWizardTest.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ExportWizardTest.java
index e7e466e50e..e8b3b02811 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ExportWizardTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ExportWizardTest.java
@@ -35,180 +35,180 @@ import org.junit.Test;
public class ExportWizardTest extends AbstractMassifTest {
- private ValgrindExportWizard wizard;
- private WizardDialog dialog;
- private ValgrindExportWizardPage page;
-
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- // close dialog just in case
- if (dialog != null) {
- dialog.close();
- }
- super.tearDown();
- }
-
- @Test
- public void testExportBadPath() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunch launch = doLaunch(config, "testExport"); //$NON-NLS-1$
-
- IProcess p = launch.getProcesses()[0];
- assertEquals(0, p.getExitValue());
-
- createWizard();
-
- // set the output path, should trigger modify listener
- page.getDestText().setText("DOESNOTEXIST"); //$NON-NLS-1$
-
- assertNotNull(page.getErrorMessage());
- assertFalse(page.isPageComplete());
- assertFalse(wizard.canFinish());
- }
-
- @Test
- public void testExportNotDir() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunch launch = doLaunch(config, "testExport"); //$NON-NLS-1$
-
- IProcess p = launch.getProcesses()[0];
- assertEquals(0, p.getExitValue());
-
- createWizard();
-
- // set the output path, should trigger modify listener
- IPath pathToFiles = proj.getProject().getLocation();
- pathToFiles = pathToFiles.append("alloctest.c"); //$NON-NLS-1$
- assertTrue(pathToFiles.toFile().exists());
- page.getDestText().setText(pathToFiles.toOSString());
-
- assertNotNull(page.getErrorMessage());
- assertFalse(page.isPageComplete());
- assertFalse(wizard.canFinish());
- }
-
- @Test
- public void testExportBoth() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunch launch = doLaunch(config, "testExport"); //$NON-NLS-1$
-
- IProcess p = launch.getProcesses()[0];
- assertEquals(0, p.getExitValue());
-
- createWizard();
-
- // set the output path, should trigger modify listener
- File[] selectedFiles = page.getSelectedFiles();
- IPath pathToFiles = proj.getProject().getLocation();
- page.getDestText().setText(pathToFiles.toOSString());
-
- assertTrue(page.isPageComplete());
- assertTrue(wizard.canFinish());
-
- assertTrue(wizard.performFinish());
-
- // check files were copied
- for (File log : selectedFiles) {
- File copy = new File(pathToFiles.toFile(), log.getName());
- assertTrue(copy.exists());
- }
- }
-
- @Test
- public void testExportOne() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunch launch = doLaunch(config, "testExport"); //$NON-NLS-1$
-
- IProcess p = launch.getProcesses()[0];
- assertEquals(0, p.getExitValue());
-
- createWizard();
-
- // set the output path, should trigger modify listener
- File[] selectedFiles = page.getSelectedFiles();
- // uncheck first file
- File unselectedFile = selectedFiles[0];
- page.getViewer().setChecked(unselectedFile, false);
- selectedFiles = page.getSelectedFiles();
-
- IPath pathToFiles = proj.getProject().getLocation();
- page.getDestText().setText(pathToFiles.toOSString());
-
- assertTrue(page.isPageComplete());
- assertTrue(wizard.canFinish());
-
- assertTrue(wizard.performFinish());
-
- // check only selected file was copied
- for (File log : selectedFiles) {
- File copy = new File(pathToFiles.toFile(), log.getName());
- assertTrue(copy.exists());
- }
- File copy = new File(pathToFiles.toFile(), unselectedFile.getName());
- assertFalse(copy.exists());
- }
+ private ValgrindExportWizard wizard;
+ private WizardDialog dialog;
+ private ValgrindExportWizardPage page;
+
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ // close dialog just in case
+ if (dialog != null) {
+ dialog.close();
+ }
+ super.tearDown();
+ }
+
+ @Test
+ public void testExportBadPath() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunch launch = doLaunch(config, "testExport"); //$NON-NLS-1$
+
+ IProcess p = launch.getProcesses()[0];
+ assertEquals(0, p.getExitValue());
+
+ createWizard();
+
+ // set the output path, should trigger modify listener
+ page.getDestText().setText("DOESNOTEXIST"); //$NON-NLS-1$
+
+ assertNotNull(page.getErrorMessage());
+ assertFalse(page.isPageComplete());
+ assertFalse(wizard.canFinish());
+ }
+
+ @Test
+ public void testExportNotDir() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunch launch = doLaunch(config, "testExport"); //$NON-NLS-1$
+
+ IProcess p = launch.getProcesses()[0];
+ assertEquals(0, p.getExitValue());
+
+ createWizard();
+
+ // set the output path, should trigger modify listener
+ IPath pathToFiles = proj.getProject().getLocation();
+ pathToFiles = pathToFiles.append("alloctest.c"); //$NON-NLS-1$
+ assertTrue(pathToFiles.toFile().exists());
+ page.getDestText().setText(pathToFiles.toOSString());
+
+ assertNotNull(page.getErrorMessage());
+ assertFalse(page.isPageComplete());
+ assertFalse(wizard.canFinish());
+ }
+
+ @Test
+ public void testExportBoth() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunch launch = doLaunch(config, "testExport"); //$NON-NLS-1$
+
+ IProcess p = launch.getProcesses()[0];
+ assertEquals(0, p.getExitValue());
+
+ createWizard();
+
+ // set the output path, should trigger modify listener
+ File[] selectedFiles = page.getSelectedFiles();
+ IPath pathToFiles = proj.getProject().getLocation();
+ page.getDestText().setText(pathToFiles.toOSString());
+
+ assertTrue(page.isPageComplete());
+ assertTrue(wizard.canFinish());
+
+ assertTrue(wizard.performFinish());
+
+ // check files were copied
+ for (File log : selectedFiles) {
+ File copy = new File(pathToFiles.toFile(), log.getName());
+ assertTrue(copy.exists());
+ }
+ }
+
+ @Test
+ public void testExportOne() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunch launch = doLaunch(config, "testExport"); //$NON-NLS-1$
+
+ IProcess p = launch.getProcesses()[0];
+ assertEquals(0, p.getExitValue());
+
+ createWizard();
+
+ // set the output path, should trigger modify listener
+ File[] selectedFiles = page.getSelectedFiles();
+ // uncheck first file
+ File unselectedFile = selectedFiles[0];
+ page.getViewer().setChecked(unselectedFile, false);
+ selectedFiles = page.getSelectedFiles();
+
+ IPath pathToFiles = proj.getProject().getLocation();
+ page.getDestText().setText(pathToFiles.toOSString());
+
+ assertTrue(page.isPageComplete());
+ assertTrue(wizard.canFinish());
+
+ assertTrue(wizard.performFinish());
+
+ // check only selected file was copied
+ for (File log : selectedFiles) {
+ File copy = new File(pathToFiles.toFile(), log.getName());
+ assertTrue(copy.exists());
+ }
+ File copy = new File(pathToFiles.toFile(), unselectedFile.getName());
+ assertFalse(copy.exists());
+ }
- @Test
- public void testExportNone() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunch launch = doLaunch(config, "testExport"); //$NON-NLS-1$
+ @Test
+ public void testExportNone() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunch launch = doLaunch(config, "testExport"); //$NON-NLS-1$
- IProcess p = launch.getProcesses()[0];
- assertEquals(0, p.getExitValue());
-
- createWizard();
-
- // set the output path, should trigger modify listener
- File[] selectedFiles = page.getSelectedFiles();
- page.getViewer().setCheckedElements(new Object[0]);
- assertEquals(0, page.getSelectedFiles().length);
-
- IPath pathToFiles = proj.getProject().getLocation();
- page.getDestText().setText(pathToFiles.toOSString());
+ IProcess p = launch.getProcesses()[0];
+ assertEquals(0, p.getExitValue());
+
+ createWizard();
+
+ // set the output path, should trigger modify listener
+ File[] selectedFiles = page.getSelectedFiles();
+ page.getViewer().setCheckedElements(new Object[0]);
+ assertEquals(0, page.getSelectedFiles().length);
+
+ IPath pathToFiles = proj.getProject().getLocation();
+ page.getDestText().setText(pathToFiles.toOSString());
- assertTrue(page.isPageComplete());
- assertTrue(wizard.canFinish());
+ assertTrue(page.isPageComplete());
+ assertTrue(wizard.canFinish());
- assertTrue(wizard.performFinish());
+ assertTrue(wizard.performFinish());
- // check files were not copied
- for (File log : selectedFiles) {
- File copy = new File(pathToFiles.toFile(), log.getName());
- assertFalse(copy.exists());
- }
- }
+ // check files were not copied
+ for (File log : selectedFiles) {
+ File copy = new File(pathToFiles.toFile(), log.getName());
+ assertFalse(copy.exists());
+ }
+ }
- protected void createWizard() {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- wizard = new ValgrindExportWizard();
- wizard.init(PlatformUI.getWorkbench(), null);
+ protected void createWizard() {
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ wizard = new ValgrindExportWizard();
+ wizard.init(PlatformUI.getWorkbench(), null);
- dialog = new WizardDialog(PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getShell(), wizard);
- dialog.setBlockOnOpen(false);
- dialog.open();
+ dialog = new WizardDialog(PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getShell(), wizard);
+ dialog.setBlockOnOpen(false);
+ dialog.open();
- assertFalse(wizard.canFinish());
+ assertFalse(wizard.canFinish());
- page = (ValgrindExportWizardPage) wizard.getPages()[0];
- assertFalse(page.isPageComplete());
+ page = (ValgrindExportWizardPage) wizard.getPages()[0];
+ assertFalse(page.isPageComplete());
- }
+ }
- });
- }
+ });
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/LaunchConfigTabTest.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/LaunchConfigTabTest.java
index e9fe0e49f9..6a53b695b3 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/LaunchConfigTabTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/LaunchConfigTabTest.java
@@ -37,309 +37,309 @@ import org.junit.Test;
public class LaunchConfigTabTest extends AbstractMassifTest {
- private ValgrindOptionsTab tab;
- private MassifToolPage dynamicTab;
- private ILaunchConfiguration config;
- private Shell testShell;
-
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
-
- config = createConfiguration(proj.getProject());
-
- testShell = new Shell(Display.getDefault());
- testShell.setLayout(new GridLayout());
- tab = new ValgrindOptionsTab();
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- tab.dispose();
- testShell.dispose();
- deleteProject(proj);
- super.tearDown();
- }
-
- private ILaunchConfigurationWorkingCopy initConfig() throws CoreException {
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- tab.setDefaults(wc);
- tab.createControl(testShell);
- tab.initializeFrom(config);
- int ix = Arrays.asList(tab.getTools()).indexOf(MassifPlugin.TOOL_ID);
- tab.getToolsCombo().select(ix);
- ILaunchConfigurationTab dynamicTab = tab.getDynamicTab();
- this.dynamicTab = (MassifToolPage) dynamicTab;
- return wc;
- }
-
- private ILaunch saveAndLaunch(ILaunchConfigurationWorkingCopy wc,
- String testName) throws URISyntaxException, IOException,
- CoreException {
- tab.performApply(wc);
- config = wc.doSave();
-
- ILaunch launch = doLaunch(config, testName);
- return launch;
- }
-
- @Test
- public void testDefaults() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- ILaunch launch = saveAndLaunch(wc, "testDefaults"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--tool=massif")); //$NON-NLS-1$
- assertFalse(cmd.contains("--xml=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("-q")); //$NON-NLS-1$
- assertTrue(cmd.contains("--trace-children=no")); //$NON-NLS-1$
- assertTrue(cmd.contains("--child-silent-after-fork=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--demangle=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--num-callers=12")); //$NON-NLS-1$
- assertTrue(cmd.contains("--error-limit=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--show-below-main=no")); //$NON-NLS-1$
- assertFalse(cmd.contains("--suppressions")); //$NON-NLS-1$
- assertTrue(cmd.contains("--max-stackframe=2000000")); //$NON-NLS-1$
- assertTrue(cmd.contains("--run-libc-freeres=yes")); //$NON-NLS-1$
-
- assertTrue(cmd.contains("--heap=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--heap-admin=8")); //$NON-NLS-1$
- assertTrue(cmd.contains("--stacks=no")); //$NON-NLS-1$
- assertFalse(cmd.contains("--alloc-fn")); //$NON-NLS-1$
- assertTrue(cmd.contains("--threshold=1.0")); //$NON-NLS-1$
- assertTrue(cmd.contains("--peak-inaccuracy=1.0")); //$NON-NLS-1$
- assertTrue(cmd.contains("--time-unit=i")); //$NON-NLS-1$
- assertTrue(cmd.contains("--detailed-freq=10")); //$NON-NLS-1$
- assertTrue(cmd.contains("--max-snapshots=100")); //$NON-NLS-1$
- assertFalse(cmd.contains("--alignment=")); //$NON-NLS-1$
- }
-
- @Test
- public void testHeap() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getHeapButton().setSelection(false);
- ILaunch launch = saveAndLaunch(wc, "testHeap"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--heap=no")); //$NON-NLS-1$
- }
-
- @Test
- public void testHeapAdmin() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getHeapAdminSpinner().setSelection(30);
- ILaunch launch = saveAndLaunch(wc, "testHeapAdmin"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--heap-admin=30")); //$NON-NLS-1$
- }
-
- @Test
- public void testStacks() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getStacksButton().setSelection(true);
- ILaunch launch = saveAndLaunch(wc, "testStacks"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--stacks=yes")); //$NON-NLS-1$
- }
-
- @Test
- public void testDepth() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getDepthSpinner().setSelection(50);
- ILaunch launch = saveAndLaunch(wc, "testDepth"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--depth=50")); //$NON-NLS-1$
- }
-
- @Test
- public void testAllocFn() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getAllocFnList().add("foo"); //$NON-NLS-1$
- ILaunch launch = saveAndLaunch(wc, "testAllocFn"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--alloc-fn=foo")); //$NON-NLS-1$
- }
-
- @Test
- public void testAllocFnMultiple() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getAllocFnList().add("foo"); //$NON-NLS-1$
- dynamicTab.getAllocFnList().add("bar"); //$NON-NLS-1$
- ILaunch launch = saveAndLaunch(wc, "testAllocFnMultiple"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--alloc-fn=foo")); //$NON-NLS-1$
- assertTrue(cmd.contains("--alloc-fn=bar")); //$NON-NLS-1$
- }
-
- @Test
- public void testAllocFnSpace() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getAllocFnList().add("operator new(unsigned)"); //$NON-NLS-1$
- ILaunch launch = saveAndLaunch(wc, "testAllocFnSpace"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--alloc-fn=operator new(unsigned)")); //$NON-NLS-1$
- }
-
- @Test
- public void testThreshold() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getThresholdSpinner().setSelection(20);
- ILaunch launch = saveAndLaunch(wc, "testThreshold"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--threshold=2.0")); //$NON-NLS-1$
- }
-
- @Test
- public void testPeakInaccuracy() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getPeakInaccuracySpinner().setSelection(0);
- ILaunch launch = saveAndLaunch(wc, "testPeakInaccuracy"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--peak-inaccuracy=0.0")); //$NON-NLS-1$
- }
-
- @Test
- public void testTimeUnitBytes() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- String[] items = dynamicTab.getTimeUnitCombo().getItems();
- int ix = -1;
- for (int i = 0; i < items.length; i++) {
- if (items[i].equals(MassifToolPage.TIME_B_STRING)) {
- ix = i;
- }
- }
- dynamicTab.getTimeUnitCombo().select(ix);
- ILaunch launch = saveAndLaunch(wc, "testTimeUnitBytes"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--time-unit=B")); //$NON-NLS-1$
- }
-
- @Test
- public void testTimeUnitMilliseconds() throws CoreException,
- URISyntaxException, IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- String[] items = dynamicTab.getTimeUnitCombo().getItems();
- int ix = -1;
- for (int i = 0; i < items.length; i++) {
- if (items[i].equals(MassifToolPage.TIME_MS_STRING)) {
- ix = i;
- }
- }
- dynamicTab.getTimeUnitCombo().select(ix);
- ILaunch launch = saveAndLaunch(wc, "testTimeUnitMilliseconds"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--time-unit=ms")); //$NON-NLS-1$
- }
-
- @Test
- public void testDetailedFreq() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getDetailedFreqSpinner().setSelection(1);
- ILaunch launch = saveAndLaunch(wc, "testDetailedFreq"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--detailed-freq=1")); //$NON-NLS-1$
- }
-
- @Test
- public void testMaxSnapshots() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getMaxSnapshotsSpinner().setSelection(200);
- ILaunch launch = saveAndLaunch(wc, "testMaxSpapshots"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--max-snapshots=200")); //$NON-NLS-1$
- }
-
- @Test
- public void testAlignment() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
-
- assertFalse(dynamicTab.getAlignmentSpinner().getEnabled());
- dynamicTab.getAlignmentButton().setSelection(true);
- dynamicTab.getAlignmentButton().notifyListeners(SWT.Selection, null);
- assertTrue(dynamicTab.getAlignmentSpinner().getEnabled());
-
- dynamicTab.getAlignmentSpinner().setSelection(512);
- tab.performApply(wc);
- config = wc.doSave();
-
- assertTrue(tab.isValid(config));
-
- ILaunch launch = doLaunch(config, "testAlignment"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--alignment=512")); //$NON-NLS-1$
- }
-
- @Test
- public void testAlignmentBad() throws CoreException {
- ILaunchConfigurationWorkingCopy wc = initConfig();
-
- assertFalse(dynamicTab.getAlignmentSpinner().getEnabled());
- dynamicTab.getAlignmentButton().setSelection(true);
- dynamicTab.getAlignmentButton().notifyListeners(SWT.Selection, null);
- assertTrue(dynamicTab.getAlignmentSpinner().getEnabled());
-
- dynamicTab.getAlignmentSpinner().setSelection(63);
- tab.performApply(wc);
- config = wc.doSave();
-
- assertFalse(tab.isValid(config));
- }
+ private ValgrindOptionsTab tab;
+ private MassifToolPage dynamicTab;
+ private ILaunchConfiguration config;
+ private Shell testShell;
+
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
+
+ config = createConfiguration(proj.getProject());
+
+ testShell = new Shell(Display.getDefault());
+ testShell.setLayout(new GridLayout());
+ tab = new ValgrindOptionsTab();
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ tab.dispose();
+ testShell.dispose();
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ private ILaunchConfigurationWorkingCopy initConfig() throws CoreException {
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ tab.setDefaults(wc);
+ tab.createControl(testShell);
+ tab.initializeFrom(config);
+ int ix = Arrays.asList(tab.getTools()).indexOf(MassifPlugin.TOOL_ID);
+ tab.getToolsCombo().select(ix);
+ ILaunchConfigurationTab dynamicTab = tab.getDynamicTab();
+ this.dynamicTab = (MassifToolPage) dynamicTab;
+ return wc;
+ }
+
+ private ILaunch saveAndLaunch(ILaunchConfigurationWorkingCopy wc,
+ String testName) throws URISyntaxException, IOException,
+ CoreException {
+ tab.performApply(wc);
+ config = wc.doSave();
+
+ ILaunch launch = doLaunch(config, testName);
+ return launch;
+ }
+
+ @Test
+ public void testDefaults() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ ILaunch launch = saveAndLaunch(wc, "testDefaults"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--tool=massif")); //$NON-NLS-1$
+ assertFalse(cmd.contains("--xml=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("-q")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--trace-children=no")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--child-silent-after-fork=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--demangle=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--num-callers=12")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--error-limit=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--show-below-main=no")); //$NON-NLS-1$
+ assertFalse(cmd.contains("--suppressions")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--max-stackframe=2000000")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--run-libc-freeres=yes")); //$NON-NLS-1$
+
+ assertTrue(cmd.contains("--heap=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--heap-admin=8")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--stacks=no")); //$NON-NLS-1$
+ assertFalse(cmd.contains("--alloc-fn")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--threshold=1.0")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--peak-inaccuracy=1.0")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--time-unit=i")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--detailed-freq=10")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--max-snapshots=100")); //$NON-NLS-1$
+ assertFalse(cmd.contains("--alignment=")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testHeap() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getHeapButton().setSelection(false);
+ ILaunch launch = saveAndLaunch(wc, "testHeap"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--heap=no")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testHeapAdmin() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getHeapAdminSpinner().setSelection(30);
+ ILaunch launch = saveAndLaunch(wc, "testHeapAdmin"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--heap-admin=30")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testStacks() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getStacksButton().setSelection(true);
+ ILaunch launch = saveAndLaunch(wc, "testStacks"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--stacks=yes")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testDepth() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getDepthSpinner().setSelection(50);
+ ILaunch launch = saveAndLaunch(wc, "testDepth"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--depth=50")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testAllocFn() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getAllocFnList().add("foo"); //$NON-NLS-1$
+ ILaunch launch = saveAndLaunch(wc, "testAllocFn"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--alloc-fn=foo")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testAllocFnMultiple() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getAllocFnList().add("foo"); //$NON-NLS-1$
+ dynamicTab.getAllocFnList().add("bar"); //$NON-NLS-1$
+ ILaunch launch = saveAndLaunch(wc, "testAllocFnMultiple"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--alloc-fn=foo")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--alloc-fn=bar")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testAllocFnSpace() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getAllocFnList().add("operator new(unsigned)"); //$NON-NLS-1$
+ ILaunch launch = saveAndLaunch(wc, "testAllocFnSpace"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--alloc-fn=operator new(unsigned)")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testThreshold() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getThresholdSpinner().setSelection(20);
+ ILaunch launch = saveAndLaunch(wc, "testThreshold"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--threshold=2.0")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testPeakInaccuracy() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getPeakInaccuracySpinner().setSelection(0);
+ ILaunch launch = saveAndLaunch(wc, "testPeakInaccuracy"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--peak-inaccuracy=0.0")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testTimeUnitBytes() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ String[] items = dynamicTab.getTimeUnitCombo().getItems();
+ int ix = -1;
+ for (int i = 0; i < items.length; i++) {
+ if (items[i].equals(MassifToolPage.TIME_B_STRING)) {
+ ix = i;
+ }
+ }
+ dynamicTab.getTimeUnitCombo().select(ix);
+ ILaunch launch = saveAndLaunch(wc, "testTimeUnitBytes"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--time-unit=B")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testTimeUnitMilliseconds() throws CoreException,
+ URISyntaxException, IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ String[] items = dynamicTab.getTimeUnitCombo().getItems();
+ int ix = -1;
+ for (int i = 0; i < items.length; i++) {
+ if (items[i].equals(MassifToolPage.TIME_MS_STRING)) {
+ ix = i;
+ }
+ }
+ dynamicTab.getTimeUnitCombo().select(ix);
+ ILaunch launch = saveAndLaunch(wc, "testTimeUnitMilliseconds"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--time-unit=ms")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testDetailedFreq() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getDetailedFreqSpinner().setSelection(1);
+ ILaunch launch = saveAndLaunch(wc, "testDetailedFreq"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--detailed-freq=1")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testMaxSnapshots() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getMaxSnapshotsSpinner().setSelection(200);
+ ILaunch launch = saveAndLaunch(wc, "testMaxSpapshots"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--max-snapshots=200")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testAlignment() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+
+ assertFalse(dynamicTab.getAlignmentSpinner().getEnabled());
+ dynamicTab.getAlignmentButton().setSelection(true);
+ dynamicTab.getAlignmentButton().notifyListeners(SWT.Selection, null);
+ assertTrue(dynamicTab.getAlignmentSpinner().getEnabled());
+
+ dynamicTab.getAlignmentSpinner().setSelection(512);
+ tab.performApply(wc);
+ config = wc.doSave();
+
+ assertTrue(tab.isValid(config));
+
+ ILaunch launch = doLaunch(config, "testAlignment"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--alignment=512")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testAlignmentBad() throws CoreException {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+
+ assertFalse(dynamicTab.getAlignmentSpinner().getEnabled());
+ dynamicTab.getAlignmentButton().setSelection(true);
+ dynamicTab.getAlignmentButton().notifyListeners(SWT.Selection, null);
+ assertTrue(dynamicTab.getAlignmentSpinner().getEnabled());
+
+ dynamicTab.getAlignmentSpinner().setSelection(63);
+ tab.performApply(wc);
+ config = wc.doSave();
+
+ assertFalse(tab.isValid(config));
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/MultiProcessTest.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/MultiProcessTest.java
index a6038399c7..6b900f33b9 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/MultiProcessTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/MultiProcessTest.java
@@ -43,139 +43,139 @@ import org.junit.Before;
import org.junit.Test;
public class MultiProcessTest extends AbstractMassifTest {
- private ICProject refProj;
-
- @Before
- public void prep() throws Exception {
- refProj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
- proj = createProjectAndBuild("multiProcTest"); //$NON-NLS-1$
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- deleteProject(refProj);
- super.tearDown();
- }
-
- @Test
- public void testNoExec() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testNoExec"); //$NON-NLS-1$
-
- MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
- .getView().getDynamicView();
- MassifOutput output = view.getOutput();
- assertEquals(1, output.getPids().length);
- MassifSnapshot[] snapshots = view.getSnapshots();
- assertEquals(8, snapshots.length);
- checkSnapshots(snapshots, 400, 8);
- }
-
- @Test
- public void testExec() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy config = createConfiguration(
- proj.getProject()).getWorkingCopy();
- config.setAttribute(
- LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
- config.doSave();
- doLaunch(config, "testExec"); //$NON-NLS-1$
-
- MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
- .getView().getDynamicView();
- MassifOutput output = view.getOutput();
-
- Integer[] pids = output.getPids();
- assertEquals(2, pids.length);
-
- // child not necessarily higher PID than parent
- MassifSnapshot[] snapshots1 = output.getSnapshots(pids[0]);
- assertTrue(snapshots1.length == 8 || snapshots1.length == 14);
- MassifSnapshot[] snapshots2 = output.getSnapshots(pids[1]);
- assertTrue(snapshots2.length == 8 || snapshots2.length == 14);
- assertNotEquals(snapshots1.length, snapshots2.length);
-
- if (snapshots1.length == 8) {
- checkSnapshots(snapshots1, 400, 8);
- checkSnapshots(snapshots2, 40, 16);
- } else {
- checkSnapshots(snapshots1, 40, 16);
- checkSnapshots(snapshots2, 400, 8);
- }
- }
-
- @Test
- public void testExecPidMenu() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfigurationWorkingCopy config = createConfiguration(
- proj.getProject()).getWorkingCopy();
- config.setAttribute(
- LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
- config.doSave();
- doLaunch(config, "testExec"); //$NON-NLS-1$
-
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- MassifViewPart dynamicView = (MassifViewPart) view.getDynamicView();
- MassifOutput output = dynamicView.getOutput();
-
- MassifPidMenuAction menuAction = null;
- IToolBarManager manager = view.getViewSite().getActionBars()
- .getToolBarManager();
- for (IContributionItem item : manager.getItems()) {
- if (item instanceof ActionContributionItem
- && ((ActionContributionItem) item).getAction() instanceof MassifPidMenuAction) {
- menuAction = (MassifPidMenuAction) ((ActionContributionItem) item)
- .getAction();
- }
- }
-
- assertNotNull(menuAction);
-
- Integer[] pids = dynamicView.getOutput().getPids();
- Shell shell = new Shell(Display.getCurrent());
- Menu pidMenu = menuAction.getMenu(shell);
-
- assertEquals(2, pidMenu.getItemCount());
- ActionContributionItem firstPid = (ActionContributionItem) pidMenu
- .getItem(0).getData();
- ActionContributionItem secondPid = (ActionContributionItem) pidMenu
- .getItem(1).getData();
-
- // check initial state
- assertTrue(firstPid.getAction().isChecked());
- assertFalse(secondPid.getAction().isChecked());
- assertArrayEquals(output.getSnapshots(pids[0]),
- dynamicView.getSnapshots());
-
- // select second pid
- selectItem(pidMenu, 1);
-
- assertFalse(firstPid.getAction().isChecked());
- assertTrue(secondPid.getAction().isChecked());
- assertArrayEquals(output.getSnapshots(pids[1]),
- dynamicView.getSnapshots());
-
- // select second pid again
- selectItem(pidMenu, 1);
-
- assertFalse(firstPid.getAction().isChecked());
- assertTrue(secondPid.getAction().isChecked());
- assertArrayEquals(output.getSnapshots(pids[1]),
- dynamicView.getSnapshots());
-
- // select first pid
- selectItem(pidMenu, 0);
-
- assertTrue(firstPid.getAction().isChecked());
- assertFalse(secondPid.getAction().isChecked());
- assertArrayEquals(output.getSnapshots(pids[0]),
- dynamicView.getSnapshots());
- }
-
- private void selectItem(Menu pidMenu, int index) {
- pidMenu.getItem(index).notifyListeners(SWT.Selection, null);
- }
+ private ICProject refProj;
+
+ @Before
+ public void prep() throws Exception {
+ refProj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
+ proj = createProjectAndBuild("multiProcTest"); //$NON-NLS-1$
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ deleteProject(refProj);
+ super.tearDown();
+ }
+
+ @Test
+ public void testNoExec() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testNoExec"); //$NON-NLS-1$
+
+ MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
+ .getView().getDynamicView();
+ MassifOutput output = view.getOutput();
+ assertEquals(1, output.getPids().length);
+ MassifSnapshot[] snapshots = view.getSnapshots();
+ assertEquals(8, snapshots.length);
+ checkSnapshots(snapshots, 400, 8);
+ }
+
+ @Test
+ public void testExec() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy config = createConfiguration(
+ proj.getProject()).getWorkingCopy();
+ config.setAttribute(
+ LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
+ config.doSave();
+ doLaunch(config, "testExec"); //$NON-NLS-1$
+
+ MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
+ .getView().getDynamicView();
+ MassifOutput output = view.getOutput();
+
+ Integer[] pids = output.getPids();
+ assertEquals(2, pids.length);
+
+ // child not necessarily higher PID than parent
+ MassifSnapshot[] snapshots1 = output.getSnapshots(pids[0]);
+ assertTrue(snapshots1.length == 8 || snapshots1.length == 14);
+ MassifSnapshot[] snapshots2 = output.getSnapshots(pids[1]);
+ assertTrue(snapshots2.length == 8 || snapshots2.length == 14);
+ assertNotEquals(snapshots1.length, snapshots2.length);
+
+ if (snapshots1.length == 8) {
+ checkSnapshots(snapshots1, 400, 8);
+ checkSnapshots(snapshots2, 40, 16);
+ } else {
+ checkSnapshots(snapshots1, 40, 16);
+ checkSnapshots(snapshots2, 400, 8);
+ }
+ }
+
+ @Test
+ public void testExecPidMenu() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfigurationWorkingCopy config = createConfiguration(
+ proj.getProject()).getWorkingCopy();
+ config.setAttribute(
+ LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
+ config.doSave();
+ doLaunch(config, "testExec"); //$NON-NLS-1$
+
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ MassifViewPart dynamicView = (MassifViewPart) view.getDynamicView();
+ MassifOutput output = dynamicView.getOutput();
+
+ MassifPidMenuAction menuAction = null;
+ IToolBarManager manager = view.getViewSite().getActionBars()
+ .getToolBarManager();
+ for (IContributionItem item : manager.getItems()) {
+ if (item instanceof ActionContributionItem
+ && ((ActionContributionItem) item).getAction() instanceof MassifPidMenuAction) {
+ menuAction = (MassifPidMenuAction) ((ActionContributionItem) item)
+ .getAction();
+ }
+ }
+
+ assertNotNull(menuAction);
+
+ Integer[] pids = dynamicView.getOutput().getPids();
+ Shell shell = new Shell(Display.getCurrent());
+ Menu pidMenu = menuAction.getMenu(shell);
+
+ assertEquals(2, pidMenu.getItemCount());
+ ActionContributionItem firstPid = (ActionContributionItem) pidMenu
+ .getItem(0).getData();
+ ActionContributionItem secondPid = (ActionContributionItem) pidMenu
+ .getItem(1).getData();
+
+ // check initial state
+ assertTrue(firstPid.getAction().isChecked());
+ assertFalse(secondPid.getAction().isChecked());
+ assertArrayEquals(output.getSnapshots(pids[0]),
+ dynamicView.getSnapshots());
+
+ // select second pid
+ selectItem(pidMenu, 1);
+
+ assertFalse(firstPid.getAction().isChecked());
+ assertTrue(secondPid.getAction().isChecked());
+ assertArrayEquals(output.getSnapshots(pids[1]),
+ dynamicView.getSnapshots());
+
+ // select second pid again
+ selectItem(pidMenu, 1);
+
+ assertFalse(firstPid.getAction().isChecked());
+ assertTrue(secondPid.getAction().isChecked());
+ assertArrayEquals(output.getSnapshots(pids[1]),
+ dynamicView.getSnapshots());
+
+ // select first pid
+ selectItem(pidMenu, 0);
+
+ assertTrue(firstPid.getAction().isChecked());
+ assertFalse(secondPid.getAction().isChecked());
+ assertArrayEquals(output.getSnapshots(pids[0]),
+ dynamicView.getSnapshots());
+ }
+
+ private void selectItem(Menu pidMenu, int index) {
+ pidMenu.getItem(index).notifyListeners(SWT.Selection, null);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ShortcutTest.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ShortcutTest.java
index 9375a930eb..df7975b480 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ShortcutTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ShortcutTest.java
@@ -30,67 +30,67 @@ import org.junit.Test;
public class ShortcutTest extends AbstractMassifTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
-
- @Test
- public void testShortcutSelection() throws CoreException {
- ValgrindTestMassifLaunchShortcut shortcut = new ValgrindTestMassifLaunchShortcut();
-
- shortcut.launch(new StructuredSelection(proj.getProject()),
- ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration config = shortcut.getConfig();
-
- compareWithDefaults(config);
- }
-
- @Test
- public void testShortcutEditor() throws CoreException {
- ValgrindTestMassifLaunchShortcut shortcut = new ValgrindTestMassifLaunchShortcut();
-
- IWorkbenchPage page = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- IFile file = proj.getProject().getFile("test.c"); //$NON-NLS-1$
- IEditorPart editor = IDE.openEditor(page, file);
-
- assertNotNull(editor);
-
- shortcut.launch(editor, ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration config = shortcut.getConfig();
-
- compareWithDefaults(config);
- }
-
- @Test
- public void testShortcutExistingConfig() throws CoreException {
- ILaunchConfiguration prev = createConfiguration(proj.getProject());
-
- ValgrindTestMassifLaunchShortcut shortcut = new ValgrindTestMassifLaunchShortcut();
- shortcut.launch(new StructuredSelection(proj.getProject()),
- ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration current = shortcut.getConfig();
-
- assertEquals(prev, current);
- }
-
- private void compareWithDefaults(ILaunchConfiguration config)
- throws CoreException {
- // tests launch in foreground, this is not typical
- ILaunchConfiguration defaults = createConfiguration(proj.getProject());
- ILaunchConfigurationWorkingCopy wc = defaults.getWorkingCopy();
- wc.removeAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND);
- wc.doSave();
-
- // Compare launch config with defaults
- assertEquals(config.getAttributes(), defaults.getAttributes());
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ @Test
+ public void testShortcutSelection() throws CoreException {
+ ValgrindTestMassifLaunchShortcut shortcut = new ValgrindTestMassifLaunchShortcut();
+
+ shortcut.launch(new StructuredSelection(proj.getProject()),
+ ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration config = shortcut.getConfig();
+
+ compareWithDefaults(config);
+ }
+
+ @Test
+ public void testShortcutEditor() throws CoreException {
+ ValgrindTestMassifLaunchShortcut shortcut = new ValgrindTestMassifLaunchShortcut();
+
+ IWorkbenchPage page = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
+ IFile file = proj.getProject().getFile("test.c"); //$NON-NLS-1$
+ IEditorPart editor = IDE.openEditor(page, file);
+
+ assertNotNull(editor);
+
+ shortcut.launch(editor, ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration config = shortcut.getConfig();
+
+ compareWithDefaults(config);
+ }
+
+ @Test
+ public void testShortcutExistingConfig() throws CoreException {
+ ILaunchConfiguration prev = createConfiguration(proj.getProject());
+
+ ValgrindTestMassifLaunchShortcut shortcut = new ValgrindTestMassifLaunchShortcut();
+ shortcut.launch(new StructuredSelection(proj.getProject()),
+ ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration current = shortcut.getConfig();
+
+ assertEquals(prev, current);
+ }
+
+ private void compareWithDefaults(ILaunchConfiguration config)
+ throws CoreException {
+ // tests launch in foreground, this is not typical
+ ILaunchConfiguration defaults = createConfiguration(proj.getProject());
+ ILaunchConfigurationWorkingCopy wc = defaults.getWorkingCopy();
+ wc.removeAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND);
+ wc.doSave();
+
+ // Compare launch config with defaults
+ assertEquals(config.getAttributes(), defaults.getAttributes());
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/SortTest.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/SortTest.java
index 6e26de04d8..8618b215e0 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/SortTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/SortTest.java
@@ -38,92 +38,92 @@ import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class SortTest extends AbstractMassifTest {
- private int column;
+ private int column;
- public SortTest(int number) {
- this.column = number;
- }
+ public SortTest(int number) {
+ this.column = number;
+ }
- @Parameters
- public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][] {
- { 0 }, { 1 }, { 2 }, { 3 }, { 4 }, { 5 } });
- }
+ @Parameters
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][] {
+ { 0 }, { 1 }, { 2 }, { 3 }, { 4 }, { 5 } });
+ }
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_STACKS, true);
- wc.doSave();
- doLaunch(config, "testStacks"); //$NON-NLS-1$
- }
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_STACKS, true);
+ wc.doSave();
+ doLaunch(config, "testStacks"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
- @Test
- public void checkSortColumn() {
- MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
- .getView().getDynamicView();
- TableViewer viewer = view.getTableViewer();
- TableColumn control = viewer.getTable().getColumn(column);
+ @Test
+ public void checkSortColumn() {
+ MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
+ .getView().getDynamicView();
+ TableViewer viewer = view.getTableViewer();
+ TableColumn control = viewer.getTable().getColumn(column);
- // Test ascending
- control.notifyListeners(SWT.Selection, null);
- assertEquals(SWT.UP, viewer.getTable().getSortDirection());
- assertEquals(control, viewer.getTable().getSortColumn());
- checkOrder(viewer, column, true);
+ // Test ascending
+ control.notifyListeners(SWT.Selection, null);
+ assertEquals(SWT.UP, viewer.getTable().getSortDirection());
+ assertEquals(control, viewer.getTable().getSortColumn());
+ checkOrder(viewer, column, true);
- // Test descending
- control.notifyListeners(SWT.Selection, null);
- assertEquals(SWT.DOWN, viewer.getTable().getSortDirection());
- assertEquals(control, viewer.getTable().getSortColumn());
- checkOrder(viewer, column, false);
- }
+ // Test descending
+ control.notifyListeners(SWT.Selection, null);
+ assertEquals(SWT.DOWN, viewer.getTable().getSortDirection());
+ assertEquals(control, viewer.getTable().getSortColumn());
+ checkOrder(viewer, column, false);
+ }
- private void checkOrder(TableViewer viewer, int column, boolean ascending) {
- TableItem[] items = viewer.getTable().getItems();
- for (int i = 0; i < items.length - 1; i++) {
- MassifSnapshot first = (MassifSnapshot) items[i].getData();
- MassifSnapshot second = (MassifSnapshot) items[i + 1].getData();
+ private void checkOrder(TableViewer viewer, int column, boolean ascending) {
+ TableItem[] items = viewer.getTable().getItems();
+ for (int i = 0; i < items.length - 1; i++) {
+ MassifSnapshot first = (MassifSnapshot) items[i].getData();
+ MassifSnapshot second = (MassifSnapshot) items[i + 1].getData();
- switch (column) {
- case 0:
- assertTrue(ascending ? first.getNumber() <= second.getNumber()
- : first.getNumber() >= second.getNumber());
- break;
- case 1:
- assertTrue(ascending ? first.getTime() <= second.getTime()
- : first.getTime() >= second.getTime());
- break;
- case 2:
- assertTrue(ascending ? first.getTotal() <= second.getTotal()
- : first.getTotal() >= second.getTotal());
- break;
- case 3:
- assertTrue(ascending ? first.getHeapBytes() <= second
- .getHeapBytes() : first.getHeapBytes() >= second
- .getHeapBytes());
- break;
- case 4:
- assertTrue(ascending ? first.getHeapExtra() <= second
- .getHeapExtra() : first.getHeapExtra() >= second
- .getHeapExtra());
- break;
- case 5:
- assertTrue(ascending ? first.getStacks() <= second.getStacks()
- : first.getStacks() >= second.getStacks());
- break;
- default:
- fail();
- }
- }
- }
+ switch (column) {
+ case 0:
+ assertTrue(ascending ? first.getNumber() <= second.getNumber()
+ : first.getNumber() >= second.getNumber());
+ break;
+ case 1:
+ assertTrue(ascending ? first.getTime() <= second.getTime()
+ : first.getTime() >= second.getTime());
+ break;
+ case 2:
+ assertTrue(ascending ? first.getTotal() <= second.getTotal()
+ : first.getTotal() >= second.getTotal());
+ break;
+ case 3:
+ assertTrue(ascending ? first.getHeapBytes() <= second
+ .getHeapBytes() : first.getHeapBytes() >= second
+ .getHeapBytes());
+ break;
+ case 4:
+ assertTrue(ascending ? first.getHeapExtra() <= second
+ .getHeapExtra() : first.getHeapExtra() >= second
+ .getHeapExtra());
+ break;
+ case 5:
+ assertTrue(ascending ? first.getStacks() <= second.getStacks()
+ : first.getStacks() >= second.getStacks());
+ break;
+ default:
+ fail();
+ }
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/TreeTest.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/TreeTest.java
index 1093d5eead..2b948c1e18 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/TreeTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/TreeTest.java
@@ -30,60 +30,60 @@ import org.junit.Before;
import org.junit.Test;
public class TreeTest extends AbstractMassifTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("alloctest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
- @Test
- public void testTreeNodes() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, 2);
- wc.doSave();
- doLaunch(config, "testTreeNodes"); //$NON-NLS-1$
+ @Test
+ public void testTreeNodes() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, 2);
+ wc.doSave();
+ doLaunch(config, "testTreeNodes"); //$NON-NLS-1$
- MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
- .getView().getDynamicView();
- TreeViewer treeViewer = view.getTreeViewer().getViewer();
+ MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
+ .getView().getDynamicView();
+ TreeViewer treeViewer = view.getTreeViewer().getViewer();
- MassifSnapshot[] snapshots = view.getSnapshots();
- MassifHeapTreeNode[] nodes = (MassifHeapTreeNode[]) treeViewer
- .getInput();
- for (int i = 0; i < nodes.length; i++) {
- // every odd snapshot should be detailed with --detailed-freq=2
- // and thus in the tree
- assertEquals(snapshots[2 * i + 1].getRoot(), nodes[i]);
- }
- }
+ MassifSnapshot[] snapshots = view.getSnapshots();
+ MassifHeapTreeNode[] nodes = (MassifHeapTreeNode[]) treeViewer
+ .getInput();
+ for (int i = 0; i < nodes.length; i++) {
+ // every odd snapshot should be detailed with --detailed-freq=2
+ // and thus in the tree
+ assertEquals(snapshots[2 * i + 1].getRoot(), nodes[i]);
+ }
+ }
- @Test
- public void testNoDetailed() throws CoreException, URISyntaxException,
- IOException {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, 12); // >
- // #snapshots
- wc.doSave();
- doLaunch(config, "testNoDetailed"); //$NON-NLS-1$
+ @Test
+ public void testNoDetailed() throws CoreException, URISyntaxException,
+ IOException {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, 12); // >
+ // #snapshots
+ wc.doSave();
+ doLaunch(config, "testNoDetailed"); //$NON-NLS-1$
- MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
- .getView().getDynamicView();
- TreeViewer treeViewer = view.getTreeViewer().getViewer();
+ MassifViewPart view = (MassifViewPart) ValgrindUIPlugin.getDefault()
+ .getView().getDynamicView();
+ TreeViewer treeViewer = view.getTreeViewer().getViewer();
- MassifHeapTreeNode[] nodes = (MassifHeapTreeNode[]) treeViewer
- .getInput();
+ MassifHeapTreeNode[] nodes = (MassifHeapTreeNode[]) treeViewer
+ .getInput();
- assertNotNull(nodes);
- assertEquals(1, nodes.length); // should always contain peak
- }
+ assertNotNull(nodes);
+ assertEquals(1, nodes.length); // should always contain peak
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ValgrindTestMassifLaunchShortcut.java b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ValgrindTestMassifLaunchShortcut.java
index 6f6757324f..93d4e1c2b7 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ValgrindTestMassifLaunchShortcut.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif.tests/src/org/eclipse/linuxtools/internal/valgrind/massif/tests/ValgrindTestMassifLaunchShortcut.java
@@ -17,14 +17,14 @@ import org.eclipse.linuxtools.internal.valgrind.massif.MassifLaunchShortcut;
public class ValgrindTestMassifLaunchShortcut extends MassifLaunchShortcut {
- private ILaunchConfiguration config;
+ private ILaunchConfiguration config;
- @Override
- public void launch(IBinary bin, String mode) {
- config = findLaunchConfiguration(bin, mode);
- }
-
- public ILaunchConfiguration getConfig() {
- return config;
- }
+ @Override
+ public void launch(IBinary bin, String mode) {
+ config = findLaunchConfiguration(bin, mode);
+ }
+
+ public ILaunchConfiguration getConfig() {
+ return config;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/plugin.xml b/valgrind/org.eclipse.linuxtools.valgrind.massif/plugin.xml
index c754154996..629c94be18 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/plugin.xml
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/plugin.xml
@@ -40,5 +40,5 @@
tabgroup="org.eclipse.linuxtools.internal.valgrind.massif.MassifLaunchConfigurationTabGroup"
type="memory">
</provider>
- </extension>
+ </extension>
</plugin>
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifCommandConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifCommandConstants.java
index c9f2855a04..0fdf7fd645 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifCommandConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifCommandConstants.java
@@ -11,21 +11,21 @@
package org.eclipse.linuxtools.internal.valgrind.massif;
public final class MassifCommandConstants {
- // Valgrind program arguments
- public static final String OPT_MASSIF_OUTFILE = "--massif-out-file"; //$NON-NLS-1$
- public static final String OPT_HEAP = "--heap"; //$NON-NLS-1$
- public static final String OPT_HEAPADMIN = "--heap-admin"; //$NON-NLS-1$
- public static final String OPT_STACKS = "--stacks"; //$NON-NLS-1$
- public static final String OPT_DEPTH = "--depth"; //$NON-NLS-1$
- public static final String OPT_ALLOCFN = "--alloc-fn"; //$NON-NLS-1$
- public static final String OPT_IGNOREFN = "--ignore-fn"; //$NON-NLS-1$
- public static final String OPT_THRESHOLD = "--threshold"; //$NON-NLS-1$
- public static final String OPT_PEAKINACCURACY = "--peak-inaccuracy"; //$NON-NLS-1$
- public static final String OPT_TIMEUNIT = "--time-unit"; //$NON-NLS-1$
- public static final String OPT_DETAILEDFREQ = "--detailed-freq"; //$NON-NLS-1$
- public static final String OPT_MAXSNAPSHOTS = "--max-snapshots"; //$NON-NLS-1$
- public static final String OPT_ALIGNMENT = "--alignment"; //$NON-NLS-1$
-
- // VG >= 3.6.0
- public static final String OPT_PAGESASHEAP = "--pages-as-heap"; //$NON-NLS-1$
+ // Valgrind program arguments
+ public static final String OPT_MASSIF_OUTFILE = "--massif-out-file"; //$NON-NLS-1$
+ public static final String OPT_HEAP = "--heap"; //$NON-NLS-1$
+ public static final String OPT_HEAPADMIN = "--heap-admin"; //$NON-NLS-1$
+ public static final String OPT_STACKS = "--stacks"; //$NON-NLS-1$
+ public static final String OPT_DEPTH = "--depth"; //$NON-NLS-1$
+ public static final String OPT_ALLOCFN = "--alloc-fn"; //$NON-NLS-1$
+ public static final String OPT_IGNOREFN = "--ignore-fn"; //$NON-NLS-1$
+ public static final String OPT_THRESHOLD = "--threshold"; //$NON-NLS-1$
+ public static final String OPT_PEAKINACCURACY = "--peak-inaccuracy"; //$NON-NLS-1$
+ public static final String OPT_TIMEUNIT = "--time-unit"; //$NON-NLS-1$
+ public static final String OPT_DETAILEDFREQ = "--detailed-freq"; //$NON-NLS-1$
+ public static final String OPT_MAXSNAPSHOTS = "--max-snapshots"; //$NON-NLS-1$
+ public static final String OPT_ALIGNMENT = "--alignment"; //$NON-NLS-1$
+
+ // VG >= 3.6.0
+ public static final String OPT_PAGESASHEAP = "--pages-as-heap"; //$NON-NLS-1$
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifHeapTreeNode.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifHeapTreeNode.java
index 3f5ed63a6c..1181cabd92 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifHeapTreeNode.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifHeapTreeNode.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
import java.text.DecimalFormat;
@@ -15,127 +15,127 @@ import java.util.ArrayList;
import java.util.List;
public class MassifHeapTreeNode {
- protected MassifHeapTreeNode parent;
- protected String text;
- protected double percent;
- protected long bytes;
- protected String address;
- protected String function;
- protected String filename;
- protected int line;
- protected List<MassifHeapTreeNode> children;
-
- public MassifHeapTreeNode(MassifHeapTreeNode parent, double percent, long bytes, String address, String function, String filename, int line) {
- this.parent = parent;
-
- StringBuffer nodeText = new StringBuffer();
- formatBytes(percent, bytes, nodeText);
- nodeText.append(address).append(":"); //$NON-NLS-1$
- if (function.length() > 0) {
- nodeText.append(" "); //$NON-NLS-1$
- nodeText.append(function);
- }
- if (filename != null) {
- nodeText.append(" (").append(filename); //$NON-NLS-1$
- if (line > 0) {
- nodeText.append(":").append(line);//$NON-NLS-1$
- }
- nodeText.append(")"); //$NON-NLS-1$
- }
- this.percent = percent;
- this.bytes = bytes;
- this.address = address;
- this.function = function;
- this.filename = filename;
- this.line = line;
- this.text = nodeText.toString();
- children = new ArrayList<>();
- }
-
- public MassifHeapTreeNode(MassifHeapTreeNode parent, double percent, long bytes, String text) {
- this.parent = parent;
-
- StringBuffer nodeText = new StringBuffer();
- formatBytes(percent, bytes, nodeText);
- nodeText.append(text);
- this.percent = percent;
- this.bytes = bytes;
- this.address = null;
- this.function = null;
- this.filename = null;
- this.line = 0;
- this.text = nodeText.toString();
- children = new ArrayList<>();
- }
-
- private void formatBytes(double percent, long bytes, StringBuffer buffer) {
- buffer.append(new DecimalFormat("0.##").format(percent) + "%"); //$NON-NLS-1$ //$NON-NLS-2$
- buffer.append(" ("); //$NON-NLS-1$
- buffer.append(new DecimalFormat("#,##0").format(bytes) + "B"); //$NON-NLS-1$ //$NON-NLS-2$
- buffer.append(") "); //$NON-NLS-1$
- }
-
- public void addChild(MassifHeapTreeNode child) {
- children.add(child);
- }
-
- public MassifHeapTreeNode getParent() {
- return parent;
- }
-
- public MassifHeapTreeNode[] getChildren() {
- return children.toArray(new MassifHeapTreeNode[children.size()]);
- }
-
- public String getText() {
- return text;
- }
-
- public void setText(String text) {
- this.text = text;
- }
-
- public double getPercent() {
- return percent;
- }
-
- public long getBytes() {
- return bytes;
- }
-
- public String getAddress() {
- return address;
- }
-
- public String getFunction() {
- return function;
- }
-
- public String getFilename() {
- return filename;
- }
-
- public int getLine() {
- return line;
- }
-
- @Override
- public String toString() {
- return text;
- }
-
- public boolean hasSourceFile() {
- return filename != null && line > 0;
- }
-
- @Override
- public boolean equals(Object obj) {
- return obj instanceof MassifHeapTreeNode
- && text.equals(((MassifHeapTreeNode) obj).getText());
- }
-
- @Override
- public int hashCode() {
- return text.hashCode();
- }
+ protected MassifHeapTreeNode parent;
+ protected String text;
+ protected double percent;
+ protected long bytes;
+ protected String address;
+ protected String function;
+ protected String filename;
+ protected int line;
+ protected List<MassifHeapTreeNode> children;
+
+ public MassifHeapTreeNode(MassifHeapTreeNode parent, double percent, long bytes, String address, String function, String filename, int line) {
+ this.parent = parent;
+
+ StringBuffer nodeText = new StringBuffer();
+ formatBytes(percent, bytes, nodeText);
+ nodeText.append(address).append(":"); //$NON-NLS-1$
+ if (function.length() > 0) {
+ nodeText.append(" "); //$NON-NLS-1$
+ nodeText.append(function);
+ }
+ if (filename != null) {
+ nodeText.append(" (").append(filename); //$NON-NLS-1$
+ if (line > 0) {
+ nodeText.append(":").append(line);//$NON-NLS-1$
+ }
+ nodeText.append(")"); //$NON-NLS-1$
+ }
+ this.percent = percent;
+ this.bytes = bytes;
+ this.address = address;
+ this.function = function;
+ this.filename = filename;
+ this.line = line;
+ this.text = nodeText.toString();
+ children = new ArrayList<>();
+ }
+
+ public MassifHeapTreeNode(MassifHeapTreeNode parent, double percent, long bytes, String text) {
+ this.parent = parent;
+
+ StringBuffer nodeText = new StringBuffer();
+ formatBytes(percent, bytes, nodeText);
+ nodeText.append(text);
+ this.percent = percent;
+ this.bytes = bytes;
+ this.address = null;
+ this.function = null;
+ this.filename = null;
+ this.line = 0;
+ this.text = nodeText.toString();
+ children = new ArrayList<>();
+ }
+
+ private void formatBytes(double percent, long bytes, StringBuffer buffer) {
+ buffer.append(new DecimalFormat("0.##").format(percent) + "%"); //$NON-NLS-1$ //$NON-NLS-2$
+ buffer.append(" ("); //$NON-NLS-1$
+ buffer.append(new DecimalFormat("#,##0").format(bytes) + "B"); //$NON-NLS-1$ //$NON-NLS-2$
+ buffer.append(") "); //$NON-NLS-1$
+ }
+
+ public void addChild(MassifHeapTreeNode child) {
+ children.add(child);
+ }
+
+ public MassifHeapTreeNode getParent() {
+ return parent;
+ }
+
+ public MassifHeapTreeNode[] getChildren() {
+ return children.toArray(new MassifHeapTreeNode[children.size()]);
+ }
+
+ public String getText() {
+ return text;
+ }
+
+ public void setText(String text) {
+ this.text = text;
+ }
+
+ public double getPercent() {
+ return percent;
+ }
+
+ public long getBytes() {
+ return bytes;
+ }
+
+ public String getAddress() {
+ return address;
+ }
+
+ public String getFunction() {
+ return function;
+ }
+
+ public String getFilename() {
+ return filename;
+ }
+
+ public int getLine() {
+ return line;
+ }
+
+ @Override
+ public String toString() {
+ return text;
+ }
+
+ public boolean hasSourceFile() {
+ return filename != null && line > 0;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return obj instanceof MassifHeapTreeNode
+ && text.equals(((MassifHeapTreeNode) obj).getText());
+ }
+
+ @Override
+ public int hashCode() {
+ return text.hashCode();
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchConfigurationTabGroup.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchConfigurationTabGroup.java
index 5c81c2ed5f..a19bf6866c 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchConfigurationTabGroup.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchConfigurationTabGroup.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Red Hat Inc. - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
@@ -15,13 +15,13 @@ import org.eclipse.linuxtools.internal.valgrind.launch.ValgrindSingleToolOptions
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTabGroup;
public class MassifLaunchConfigurationTabGroup extends
- ProfileLaunchConfigurationTabGroup {
+ ProfileLaunchConfigurationTabGroup {
+
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ return new AbstractLaunchConfigurationTab[] {
+ new ValgrindSingleToolOptionsTab(MassifPlugin.TOOL_ID)
+ };
+ }
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- return new AbstractLaunchConfigurationTab[] {
- new ValgrindSingleToolOptionsTab(MassifPlugin.TOOL_ID)
- };
- }
-
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchConstants.java
index 3df0991812..866ab5386b 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchConstants.java
@@ -14,43 +14,43 @@ import java.util.Collections;
import java.util.List;
public final class MassifLaunchConstants {
- // LaunchConfiguration attributes
- public static final String ATTR_MASSIF_OUTFILE = MassifPlugin.PLUGIN_ID + ".MASSIF_OUTFILE"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_HEAP = MassifPlugin.PLUGIN_ID + ".MASSIF_HEAP"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_HEAPADMIN = MassifPlugin.PLUGIN_ID + ".MASSIF_HEAPADMIN"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_STACKS = MassifPlugin.PLUGIN_ID + ".MASSIF_STACKS"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_DEPTH = MassifPlugin.PLUGIN_ID + ".MASSIF_DEPTH"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_ALLOCFN = MassifPlugin.PLUGIN_ID + ".MASSIF_ALLOCFN"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_IGNOREFN = MassifPlugin.PLUGIN_ID + ".MASSIF_IGNOREFN"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_THRESHOLD = MassifPlugin.PLUGIN_ID + ".MASSIF_THRESHOLD"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_PEAKINACCURACY = MassifPlugin.PLUGIN_ID + ".MASSIF_PEAKINACCURACY"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_TIMEUNIT = MassifPlugin.PLUGIN_ID + ".MASSIF_TIMEUNIT"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_DETAILEDFREQ = MassifPlugin.PLUGIN_ID + ".MASSIF_DETAILEDFREQ"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_MAXSNAPSHOTS = MassifPlugin.PLUGIN_ID + ".MASSIF_MAXSNAPSHOTS"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_ALIGNMENT_BOOL = MassifPlugin.PLUGIN_ID + ".MASSIF_ALIGNMENT_BOOL"; //$NON-NLS-1$
- public static final String ATTR_MASSIF_ALIGNMENT_VAL = MassifPlugin.PLUGIN_ID + ".MASSIF_ALIGNMENT_VAL"; //$NON-NLS-1$
-
- // VG >= 3.6.0
- public static final String ATTR_MASSIF_PAGESASHEAP = MassifPlugin.PLUGIN_ID + ".MASSIF_PAGEASHEAP"; //$NON-NLS-1$
-
- public static final String TIME_I = "i"; //$NON-NLS-1$
- public static final String TIME_MS = "ms"; //$NON-NLS-1$
- public static final String TIME_B = "B"; //$NON-NLS-1$
-
- public static final boolean DEFAULT_MASSIF_HEAP = true;
- public static final int DEFAULT_MASSIF_HEAPADMIN = 8;
- public static final boolean DEFAULT_MASSIF_STACKS = false;
- public static final int DEFAULT_MASSIF_DEPTH = 30;
- public static final List<String> DEFAULT_MASSIF_ALLOCFN = Collections.emptyList();
- public static final List<String> DEFAULT_MASSIF_IGNOREFN = Collections.emptyList();
- public static final int DEFAULT_MASSIF_THRESHOLD = 10;
- public static final int DEFAULT_MASSIF_PEAKINACCURACY = 10;
- public static final String DEFAULT_MASSIF_TIMEUNIT = TIME_I;
- public static final int DEFAULT_MASSIF_DETAILEDFREQ = 10;
- public static final int DEFAULT_MASSIF_MAXSNAPSHOTS = 100;
- public static final boolean DEFAULT_MASSIF_ALIGNMENT_BOOL = false;
- public static final int DEFAULT_MASSIF_ALIGNMENT_VAL = 0;
-
- // VG >= 3.6.0
- public static final boolean DEFAULT_MASSIF_PAGESASHEAP = false;
+ // LaunchConfiguration attributes
+ public static final String ATTR_MASSIF_OUTFILE = MassifPlugin.PLUGIN_ID + ".MASSIF_OUTFILE"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_HEAP = MassifPlugin.PLUGIN_ID + ".MASSIF_HEAP"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_HEAPADMIN = MassifPlugin.PLUGIN_ID + ".MASSIF_HEAPADMIN"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_STACKS = MassifPlugin.PLUGIN_ID + ".MASSIF_STACKS"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_DEPTH = MassifPlugin.PLUGIN_ID + ".MASSIF_DEPTH"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_ALLOCFN = MassifPlugin.PLUGIN_ID + ".MASSIF_ALLOCFN"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_IGNOREFN = MassifPlugin.PLUGIN_ID + ".MASSIF_IGNOREFN"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_THRESHOLD = MassifPlugin.PLUGIN_ID + ".MASSIF_THRESHOLD"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_PEAKINACCURACY = MassifPlugin.PLUGIN_ID + ".MASSIF_PEAKINACCURACY"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_TIMEUNIT = MassifPlugin.PLUGIN_ID + ".MASSIF_TIMEUNIT"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_DETAILEDFREQ = MassifPlugin.PLUGIN_ID + ".MASSIF_DETAILEDFREQ"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_MAXSNAPSHOTS = MassifPlugin.PLUGIN_ID + ".MASSIF_MAXSNAPSHOTS"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_ALIGNMENT_BOOL = MassifPlugin.PLUGIN_ID + ".MASSIF_ALIGNMENT_BOOL"; //$NON-NLS-1$
+ public static final String ATTR_MASSIF_ALIGNMENT_VAL = MassifPlugin.PLUGIN_ID + ".MASSIF_ALIGNMENT_VAL"; //$NON-NLS-1$
+
+ // VG >= 3.6.0
+ public static final String ATTR_MASSIF_PAGESASHEAP = MassifPlugin.PLUGIN_ID + ".MASSIF_PAGEASHEAP"; //$NON-NLS-1$
+
+ public static final String TIME_I = "i"; //$NON-NLS-1$
+ public static final String TIME_MS = "ms"; //$NON-NLS-1$
+ public static final String TIME_B = "B"; //$NON-NLS-1$
+
+ public static final boolean DEFAULT_MASSIF_HEAP = true;
+ public static final int DEFAULT_MASSIF_HEAPADMIN = 8;
+ public static final boolean DEFAULT_MASSIF_STACKS = false;
+ public static final int DEFAULT_MASSIF_DEPTH = 30;
+ public static final List<String> DEFAULT_MASSIF_ALLOCFN = Collections.emptyList();
+ public static final List<String> DEFAULT_MASSIF_IGNOREFN = Collections.emptyList();
+ public static final int DEFAULT_MASSIF_THRESHOLD = 10;
+ public static final int DEFAULT_MASSIF_PEAKINACCURACY = 10;
+ public static final String DEFAULT_MASSIF_TIMEUNIT = TIME_I;
+ public static final int DEFAULT_MASSIF_DETAILEDFREQ = 10;
+ public static final int DEFAULT_MASSIF_MAXSNAPSHOTS = 100;
+ public static final boolean DEFAULT_MASSIF_ALIGNMENT_BOOL = false;
+ public static final int DEFAULT_MASSIF_ALIGNMENT_VAL = 0;
+
+ // VG >= 3.6.0
+ public static final boolean DEFAULT_MASSIF_PAGESASHEAP = false;
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchDelegate.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchDelegate.java
index e602f4bc34..9e6624ac16 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchDelegate.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchDelegate.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
import java.io.File;
@@ -30,120 +30,120 @@ import org.eclipse.linuxtools.valgrind.ui.IValgrindToolView;
import org.osgi.framework.Version;
public class MassifLaunchDelegate implements IValgrindLaunchDelegate {
- protected static final String OUT_PREFIX = "massif_"; //$NON-NLS-1$
- protected static final String OUT_FILE = OUT_PREFIX + "%p.txt"; //$NON-NLS-1$
- private static final FileFilter MASSIF_FILTER = new FileFilter() {
- @Override
- public boolean accept(File pathname) {
- return pathname.getName().startsWith(OUT_PREFIX);
- }
- };
-
- private static final String EQUALS = "="; //$NON-NLS-1$
- private static final String NO = "no"; //$NON-NLS-1$
- private static final String YES = "yes"; //$NON-NLS-1$
- private static final Version VER_3_6_0 = new Version(3, 6, 0);
-
-
- private MassifOutput output;
-
- @Override
- public void handleLaunch(ILaunchConfiguration config, ILaunch launch, IPath outDir, IProgressMonitor monitor)
- throws CoreException {
- MassifPlugin.getDefault().setSourceLocator(launch.getSourceLocator());
- try {
- monitor.beginTask(Messages.getString("MassifLaunchDelegate.Parsing_Massif_Output"), 3); //$NON-NLS-1$
-
- File[] massifOutputs = outDir.toFile().listFiles(MASSIF_FILTER);
-
- if (massifOutputs.length > 0) {
- parseOutput(massifOutputs, monitor);
- }
- } catch (IOException e) {
- e.printStackTrace();
- abort(Messages.getString("MassifLaunchDelegate.Error_parsing_output"), e, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); //$NON-NLS-1$
- } finally {
- monitor.done();
- }
- }
-
- private void parseOutput(File[] massifOutputs, IProgressMonitor monitor) throws IOException {
- output = new MassifOutput();
- for (File file : massifOutputs) {
- MassifParser parser = new MassifParser(file);
- output.putSnapshots(parser.getPid(), parser.getSnapshots());
- }
- monitor.worked(2);
- }
-
- @Override
- public String[] getCommandArray(ILaunchConfiguration config, Version ver, IPath logDir)
- throws CoreException {
- ArrayList<String> opts = new ArrayList<>();
-
- opts.add(MassifCommandConstants.OPT_MASSIF_OUTFILE + EQUALS + logDir.append(OUT_FILE).toOSString());
-
- opts.add(MassifCommandConstants.OPT_HEAP + EQUALS + (config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAP, MassifLaunchConstants.DEFAULT_MASSIF_HEAP) ? YES : NO));
- opts.add(MassifCommandConstants.OPT_HEAPADMIN + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAPADMIN, MassifLaunchConstants.DEFAULT_MASSIF_HEAPADMIN));
- opts.add(MassifCommandConstants.OPT_STACKS + EQUALS + (config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_STACKS, MassifLaunchConstants.DEFAULT_MASSIF_STACKS) ? YES : NO));
- opts.add(MassifCommandConstants.OPT_DEPTH + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_DEPTH, MassifLaunchConstants.DEFAULT_MASSIF_DEPTH));
- List<String> allocFns = config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALLOCFN, MassifLaunchConstants.DEFAULT_MASSIF_ALLOCFN);
- for (String func : allocFns) {
- opts.add(MassifCommandConstants.OPT_ALLOCFN + EQUALS + func);
- }
- List<String> ignoreFns = config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_IGNOREFN, MassifLaunchConstants.DEFAULT_MASSIF_IGNOREFN);
- for (String func : ignoreFns) {
- opts.add(MassifCommandConstants.OPT_IGNOREFN + EQUALS + func);
- }
- opts.add(MassifCommandConstants.OPT_THRESHOLD + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_THRESHOLD, MassifLaunchConstants.DEFAULT_MASSIF_THRESHOLD) / 10.0);
- opts.add(MassifCommandConstants.OPT_PEAKINACCURACY + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_PEAKINACCURACY, MassifLaunchConstants.DEFAULT_MASSIF_PEAKINACCURACY) / 10.0);
- opts.add(MassifCommandConstants.OPT_TIMEUNIT + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_TIMEUNIT, MassifLaunchConstants.DEFAULT_MASSIF_TIMEUNIT));
- opts.add(MassifCommandConstants.OPT_DETAILEDFREQ + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, MassifLaunchConstants.DEFAULT_MASSIF_DETAILEDFREQ));
- opts.add(MassifCommandConstants.OPT_MAXSNAPSHOTS + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_MAXSNAPSHOTS, MassifLaunchConstants.DEFAULT_MASSIF_MAXSNAPSHOTS));
- if (config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_BOOL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_BOOL)) {
- opts.add(MassifCommandConstants.OPT_ALIGNMENT + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_VAL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_VAL));
- }
-
- // VG >= 3.6.0
- if (ver == null || ver.compareTo(VER_3_6_0) >= 0) {
- opts.add(MassifCommandConstants.OPT_PAGESASHEAP + EQUALS + (config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_PAGESASHEAP, MassifLaunchConstants.DEFAULT_MASSIF_PAGESASHEAP) ? YES : NO));
- }
-
- return opts.toArray(new String[opts.size()]);
- }
-
- @Override
- public void initializeView(IValgrindToolView view, String contentDescription, IProgressMonitor monitor) {
- if (output != null && view instanceof MassifViewPart) {
- ((MassifViewPart) view).setChartName(contentDescription);
- ((MassifViewPart) view).setOutput(output);
- // initialize to first pid
- ((MassifViewPart) view).setPid(output.getPids()[0]);
- }
- monitor.worked(1);
- }
-
- /**
- * Throws a core exception with an error status object built from the given
- * message, lower level exception, and error code.
- *
- * @param message
- * the status message
- * @param exception
- * lower level exception associated with the error, or
- * <code>null</code> if none
- * @param code
- * error code
- */
- private void abort(String message, Throwable exception, int code) throws CoreException {
- IStatus status;
- if (exception != null) {
- MultiStatus multiStatus = new MultiStatus(MassifPlugin.PLUGIN_ID, code, message, exception);
- multiStatus.add(new Status(IStatus.ERROR, MassifPlugin.PLUGIN_ID, code, exception.getLocalizedMessage(), exception));
- status= multiStatus;
- } else {
- status= new Status(IStatus.ERROR, MassifPlugin.PLUGIN_ID, code, message, null);
- }
- throw new CoreException(status);
- }
+ protected static final String OUT_PREFIX = "massif_"; //$NON-NLS-1$
+ protected static final String OUT_FILE = OUT_PREFIX + "%p.txt"; //$NON-NLS-1$
+ private static final FileFilter MASSIF_FILTER = new FileFilter() {
+ @Override
+ public boolean accept(File pathname) {
+ return pathname.getName().startsWith(OUT_PREFIX);
+ }
+ };
+
+ private static final String EQUALS = "="; //$NON-NLS-1$
+ private static final String NO = "no"; //$NON-NLS-1$
+ private static final String YES = "yes"; //$NON-NLS-1$
+ private static final Version VER_3_6_0 = new Version(3, 6, 0);
+
+
+ private MassifOutput output;
+
+ @Override
+ public void handleLaunch(ILaunchConfiguration config, ILaunch launch, IPath outDir, IProgressMonitor monitor)
+ throws CoreException {
+ MassifPlugin.getDefault().setSourceLocator(launch.getSourceLocator());
+ try {
+ monitor.beginTask(Messages.getString("MassifLaunchDelegate.Parsing_Massif_Output"), 3); //$NON-NLS-1$
+
+ File[] massifOutputs = outDir.toFile().listFiles(MASSIF_FILTER);
+
+ if (massifOutputs.length > 0) {
+ parseOutput(massifOutputs, monitor);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ abort(Messages.getString("MassifLaunchDelegate.Error_parsing_output"), e, ICDTLaunchConfigurationConstants.ERR_INTERNAL_ERROR); //$NON-NLS-1$
+ } finally {
+ monitor.done();
+ }
+ }
+
+ private void parseOutput(File[] massifOutputs, IProgressMonitor monitor) throws IOException {
+ output = new MassifOutput();
+ for (File file : massifOutputs) {
+ MassifParser parser = new MassifParser(file);
+ output.putSnapshots(parser.getPid(), parser.getSnapshots());
+ }
+ monitor.worked(2);
+ }
+
+ @Override
+ public String[] getCommandArray(ILaunchConfiguration config, Version ver, IPath logDir)
+ throws CoreException {
+ ArrayList<String> opts = new ArrayList<>();
+
+ opts.add(MassifCommandConstants.OPT_MASSIF_OUTFILE + EQUALS + logDir.append(OUT_FILE).toOSString());
+
+ opts.add(MassifCommandConstants.OPT_HEAP + EQUALS + (config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAP, MassifLaunchConstants.DEFAULT_MASSIF_HEAP) ? YES : NO));
+ opts.add(MassifCommandConstants.OPT_HEAPADMIN + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAPADMIN, MassifLaunchConstants.DEFAULT_MASSIF_HEAPADMIN));
+ opts.add(MassifCommandConstants.OPT_STACKS + EQUALS + (config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_STACKS, MassifLaunchConstants.DEFAULT_MASSIF_STACKS) ? YES : NO));
+ opts.add(MassifCommandConstants.OPT_DEPTH + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_DEPTH, MassifLaunchConstants.DEFAULT_MASSIF_DEPTH));
+ List<String> allocFns = config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALLOCFN, MassifLaunchConstants.DEFAULT_MASSIF_ALLOCFN);
+ for (String func : allocFns) {
+ opts.add(MassifCommandConstants.OPT_ALLOCFN + EQUALS + func);
+ }
+ List<String> ignoreFns = config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_IGNOREFN, MassifLaunchConstants.DEFAULT_MASSIF_IGNOREFN);
+ for (String func : ignoreFns) {
+ opts.add(MassifCommandConstants.OPT_IGNOREFN + EQUALS + func);
+ }
+ opts.add(MassifCommandConstants.OPT_THRESHOLD + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_THRESHOLD, MassifLaunchConstants.DEFAULT_MASSIF_THRESHOLD) / 10.0);
+ opts.add(MassifCommandConstants.OPT_PEAKINACCURACY + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_PEAKINACCURACY, MassifLaunchConstants.DEFAULT_MASSIF_PEAKINACCURACY) / 10.0);
+ opts.add(MassifCommandConstants.OPT_TIMEUNIT + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_TIMEUNIT, MassifLaunchConstants.DEFAULT_MASSIF_TIMEUNIT));
+ opts.add(MassifCommandConstants.OPT_DETAILEDFREQ + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, MassifLaunchConstants.DEFAULT_MASSIF_DETAILEDFREQ));
+ opts.add(MassifCommandConstants.OPT_MAXSNAPSHOTS + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_MAXSNAPSHOTS, MassifLaunchConstants.DEFAULT_MASSIF_MAXSNAPSHOTS));
+ if (config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_BOOL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_BOOL)) {
+ opts.add(MassifCommandConstants.OPT_ALIGNMENT + EQUALS + config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_VAL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_VAL));
+ }
+
+ // VG >= 3.6.0
+ if (ver == null || ver.compareTo(VER_3_6_0) >= 0) {
+ opts.add(MassifCommandConstants.OPT_PAGESASHEAP + EQUALS + (config.getAttribute(MassifLaunchConstants.ATTR_MASSIF_PAGESASHEAP, MassifLaunchConstants.DEFAULT_MASSIF_PAGESASHEAP) ? YES : NO));
+ }
+
+ return opts.toArray(new String[opts.size()]);
+ }
+
+ @Override
+ public void initializeView(IValgrindToolView view, String contentDescription, IProgressMonitor monitor) {
+ if (output != null && view instanceof MassifViewPart) {
+ ((MassifViewPart) view).setChartName(contentDescription);
+ ((MassifViewPart) view).setOutput(output);
+ // initialize to first pid
+ ((MassifViewPart) view).setPid(output.getPids()[0]);
+ }
+ monitor.worked(1);
+ }
+
+ /**
+ * Throws a core exception with an error status object built from the given
+ * message, lower level exception, and error code.
+ *
+ * @param message
+ * the status message
+ * @param exception
+ * lower level exception associated with the error, or
+ * <code>null</code> if none
+ * @param code
+ * error code
+ */
+ private void abort(String message, Throwable exception, int code) throws CoreException {
+ IStatus status;
+ if (exception != null) {
+ MultiStatus multiStatus = new MultiStatus(MassifPlugin.PLUGIN_ID, code, message, exception);
+ multiStatus.add(new Status(IStatus.ERROR, MassifPlugin.PLUGIN_ID, code, exception.getLocalizedMessage(), exception));
+ status= multiStatus;
+ } else {
+ status= new Status(IStatus.ERROR, MassifPlugin.PLUGIN_ID, code, message, null);
+ }
+ throw new CoreException(status);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchShortcut.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchShortcut.java
index 21541c5a6b..df301fdb18 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchShortcut.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifLaunchShortcut.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Red Hat Inc - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
import org.eclipse.core.runtime.CoreException;
@@ -21,22 +21,22 @@ import org.eclipse.linuxtools.profiling.launch.ProfileLaunchShortcut;
public class MassifLaunchShortcut extends ProfileLaunchShortcut {
- @Override
- protected void setDefaultProfileAttributes(
- ILaunchConfigurationWorkingCopy wc) throws CoreException {
- ValgrindOptionsTab tab = new ValgrindOptionsTab();
- tab.setDefaults(wc);
- ILaunchConfigurationTab defaultTab = ValgrindLaunchPlugin.getDefault().getToolPage(MassifPlugin.TOOL_ID);
- defaultTab.setDefaults(wc);
- }
+ @Override
+ protected void setDefaultProfileAttributes(
+ ILaunchConfigurationWorkingCopy wc) throws CoreException {
+ ValgrindOptionsTab tab = new ValgrindOptionsTab();
+ tab.setDefaults(wc);
+ ILaunchConfigurationTab defaultTab = ValgrindLaunchPlugin.getDefault().getToolPage(MassifPlugin.TOOL_ID);
+ defaultTab.setDefaults(wc);
+ }
- /**
- * Method getValgrindLaunchConfigType.
- * @return ILaunchConfigurationType
- */
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(ValgrindLaunchPlugin.LAUNCH_ID);
- }
+ /**
+ * Method getValgrindLaunchConfigType.
+ * @return ILaunchConfigurationType
+ */
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(ValgrindLaunchPlugin.LAUNCH_ID);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifOutput.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifOutput.java
index 430044e5a8..4adf923e65 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifOutput.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifOutput.java
@@ -7,28 +7,28 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
import java.util.HashMap;
import java.util.Map;
public class MassifOutput {
- protected Map<Integer, MassifSnapshot[]> pidMap;
-
- public MassifOutput() {
- pidMap = new HashMap<>();
- }
-
- public void putSnapshots(Integer pid, MassifSnapshot[] snapshots) {
- pidMap.put(pid, snapshots);
- }
-
- public MassifSnapshot[] getSnapshots(Integer pid) {
- return pidMap.get(pid);
- }
-
- public Integer[] getPids() {
- return pidMap.keySet().toArray(new Integer[pidMap.size()]);
- }
+ protected Map<Integer, MassifSnapshot[]> pidMap;
+
+ public MassifOutput() {
+ pidMap = new HashMap<>();
+ }
+
+ public void putSnapshots(Integer pid, MassifSnapshot[] snapshots) {
+ pidMap.put(pid, snapshots);
+ }
+
+ public MassifSnapshot[] getSnapshots(Integer pid) {
+ return pidMap.get(pid);
+ }
+
+ public Integer[] getPids() {
+ return pidMap.keySet().toArray(new Integer[pidMap.size()]);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifParser.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifParser.java
index f1499b83fa..2a45fdbea5 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifParser.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifParser.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
import java.io.BufferedReader;
@@ -22,241 +22,241 @@ import org.eclipse.linuxtools.valgrind.core.ValgrindParserUtils;
import org.eclipse.osgi.util.NLS;
public class MassifParser {
- private static final String COLON = ":"; //$NON-NLS-1$
- private static final String SPACE = " "; //$NON-NLS-1$
- private static final String EQUALS = "="; //$NON-NLS-1$
-
- private static final String CMD = "cmd"; //$NON-NLS-1$
- private static final String TIME_UNIT = "time_unit"; //$NON-NLS-1$
- private static final String SNAPSHOT = "snapshot"; //$NON-NLS-1$
- private static final String TIME = "time"; //$NON-NLS-1$
- private static final String MEM_HEAP_B = "mem_heap_B"; //$NON-NLS-1$
- private static final String MEM_HEAP_EXTRA_B = "mem_heap_extra_B"; //$NON-NLS-1$
- private static final String MEM_STACKS_B = "mem_stacks_B"; //$NON-NLS-1$
- private static final String HEAP_TREE = "heap_tree"; //$NON-NLS-1$
-
- private static final String INSTRUCTIONS = "i"; //$NON-NLS-1$
- private static final String MILLISECONDS = "ms"; //$NON-NLS-1$
- private static final String BYTES = "B"; //$NON-NLS-1$
- private static final String PEAK = "peak"; //$NON-NLS-1$
- private static final String DETAILED = "detailed"; //$NON-NLS-1$
- private static final String EMPTY = "empty"; //$NON-NLS-1$
+ private static final String COLON = ":"; //$NON-NLS-1$
+ private static final String SPACE = " "; //$NON-NLS-1$
+ private static final String EQUALS = "="; //$NON-NLS-1$
- private Integer pid;
- private MassifSnapshot[] snapshots;
+ private static final String CMD = "cmd"; //$NON-NLS-1$
+ private static final String TIME_UNIT = "time_unit"; //$NON-NLS-1$
+ private static final String SNAPSHOT = "snapshot"; //$NON-NLS-1$
+ private static final String TIME = "time"; //$NON-NLS-1$
+ private static final String MEM_HEAP_B = "mem_heap_B"; //$NON-NLS-1$
+ private static final String MEM_HEAP_EXTRA_B = "mem_heap_extra_B"; //$NON-NLS-1$
+ private static final String MEM_STACKS_B = "mem_stacks_B"; //$NON-NLS-1$
+ private static final String HEAP_TREE = "heap_tree"; //$NON-NLS-1$
- public MassifParser(File inputFile) throws IOException {
- ArrayList<MassifSnapshot> list = new ArrayList<>();
- try (BufferedReader br = new BufferedReader(new FileReader(inputFile))){
- String line;
- MassifSnapshot snapshot = null;
- String cmd = null;
- TimeUnit unit = null;
- int n = 0;
+ private static final String INSTRUCTIONS = "i"; //$NON-NLS-1$
+ private static final String MILLISECONDS = "ms"; //$NON-NLS-1$
+ private static final String BYTES = "B"; //$NON-NLS-1$
+ private static final String PEAK = "peak"; //$NON-NLS-1$
+ private static final String DETAILED = "detailed"; //$NON-NLS-1$
+ private static final String EMPTY = "empty"; //$NON-NLS-1$
- // retrive PID from filename
- String filename = inputFile.getName();
- pid = ValgrindParserUtils.parsePID(filename, MassifLaunchDelegate.OUT_PREFIX);
+ private Integer pid;
+ private MassifSnapshot[] snapshots;
- // parse contents of file
- while ((line = br.readLine()) != null) {
- if (line.startsWith(CMD + COLON)){
- cmd = ValgrindParserUtils.parseStrValue(line, COLON + SPACE);
- } else if (line.startsWith(TIME_UNIT + COLON)) {
- unit = parseTimeUnit(line);
- } else if (line.startsWith(SNAPSHOT)) {
- if (snapshot != null) {
- // this snapshot finished parsing
- list.add(snapshot);
- n++;
- }
- snapshot = new MassifSnapshot(n);
- snapshot.setCmd(cmd);
- snapshot.setUnit(unit);
- } else if (line.startsWith(TIME + EQUALS)) {
- snapshot.setTime(ValgrindParserUtils.parseLongValue(line, EQUALS));
- } else if (line.startsWith(MEM_HEAP_B + EQUALS)) {
- snapshot.setHeapBytes(ValgrindParserUtils.parseLongValue(line, EQUALS));
- } else if (line.startsWith(MEM_HEAP_EXTRA_B + EQUALS)) {
- snapshot.setHeapExtra(ValgrindParserUtils.parseLongValue(line, EQUALS));
- } else if (line.startsWith(MEM_STACKS_B + EQUALS)) {
- snapshot.setStacks(ValgrindParserUtils.parseLongValue(line, EQUALS));
- } else if (line.startsWith(HEAP_TREE + EQUALS)) {
- SnapshotType type = parseSnapshotType(line);
- snapshot.setType(type);
- switch (type) {
- case DETAILED:
- case PEAK:
- MassifHeapTreeNode node = parseTree(snapshot, null, br);
- node.setText(NLS.bind(Messages.getString("MassifParser.Snapshot_n"), n, node.getText())); // prepend snapshot number //$NON-NLS-1$
- snapshot.setRoot(node);
- }
- }
- }
- if (snapshot != null) {
- // last snapshot that finished parsing
- list.add(snapshot);
- }
- snapshots = list.toArray(new MassifSnapshot[list.size()]);
- }
- }
+ public MassifParser(File inputFile) throws IOException {
+ ArrayList<MassifSnapshot> list = new ArrayList<>();
+ try (BufferedReader br = new BufferedReader(new FileReader(inputFile))){
+ String line;
+ MassifSnapshot snapshot = null;
+ String cmd = null;
+ TimeUnit unit = null;
+ int n = 0;
- private MassifHeapTreeNode parseTree(MassifSnapshot snapshot, MassifHeapTreeNode parent, BufferedReader br) throws IOException {
- String line = br.readLine();
- if (line == null) {
- throw new IOException(Messages.getString("MassifParser.Unexpected_EOF")); //$NON-NLS-1$
- }
- line = line.trim(); // remove leading whitespace
- String[] parts = line.split(" "); //$NON-NLS-1$
- // bounds checking so we can fail with a more informative error
- if (parts.length < 2) {
- ValgrindParserUtils.fail(line);
- }
-
- Integer numChildren = parseNumChildren(parts[0]);
- if (numChildren == null) {
- ValgrindParserUtils.fail(line);
- }
+ // retrive PID from filename
+ String filename = inputFile.getName();
+ pid = ValgrindParserUtils.parsePID(filename, MassifLaunchDelegate.OUT_PREFIX);
- Long numBytes = parseNumBytes(parts[1]);
- if (numBytes == null) {
- ValgrindParserUtils.fail(line);
- }
-
- double percentage;
- if (numBytes.intValue() == 0) {
- percentage = 0;
- } else {
- percentage = numBytes.doubleValue() / snapshot.getTotal() * 100;
- }
+ // parse contents of file
+ while ((line = br.readLine()) != null) {
+ if (line.startsWith(CMD + COLON)){
+ cmd = ValgrindParserUtils.parseStrValue(line, COLON + SPACE);
+ } else if (line.startsWith(TIME_UNIT + COLON)) {
+ unit = parseTimeUnit(line);
+ } else if (line.startsWith(SNAPSHOT)) {
+ if (snapshot != null) {
+ // this snapshot finished parsing
+ list.add(snapshot);
+ n++;
+ }
+ snapshot = new MassifSnapshot(n);
+ snapshot.setCmd(cmd);
+ snapshot.setUnit(unit);
+ } else if (line.startsWith(TIME + EQUALS)) {
+ snapshot.setTime(ValgrindParserUtils.parseLongValue(line, EQUALS));
+ } else if (line.startsWith(MEM_HEAP_B + EQUALS)) {
+ snapshot.setHeapBytes(ValgrindParserUtils.parseLongValue(line, EQUALS));
+ } else if (line.startsWith(MEM_HEAP_EXTRA_B + EQUALS)) {
+ snapshot.setHeapExtra(ValgrindParserUtils.parseLongValue(line, EQUALS));
+ } else if (line.startsWith(MEM_STACKS_B + EQUALS)) {
+ snapshot.setStacks(ValgrindParserUtils.parseLongValue(line, EQUALS));
+ } else if (line.startsWith(HEAP_TREE + EQUALS)) {
+ SnapshotType type = parseSnapshotType(line);
+ snapshot.setType(type);
+ switch (type) {
+ case DETAILED:
+ case PEAK:
+ MassifHeapTreeNode node = parseTree(snapshot, null, br);
+ node.setText(NLS.bind(Messages.getString("MassifParser.Snapshot_n"), n, node.getText())); // prepend snapshot number //$NON-NLS-1$
+ snapshot.setRoot(node);
+ }
+ }
+ }
+ if (snapshot != null) {
+ // last snapshot that finished parsing
+ list.add(snapshot);
+ }
+ snapshots = list.toArray(new MassifSnapshot[list.size()]);
+ }
+ }
- MassifHeapTreeNode node;
- String address = null;
- String function = null;
- String filename = null;
- int lineNo = 0;
- if (parts[2].startsWith("0x")) { //$NON-NLS-1$
- // we extend the above bounds checking
- if (parts.length < 3) {
- ValgrindParserUtils.fail(line);
- }
- // remove colon from address
- address = parts[2].substring(0, parts[2].length() - 1);
-
- function = parseFunction(parts[3], line);
-
- // Parse source file if specified
- Object[] subparts = ValgrindParserUtils.parseFilename(line);
- filename = (String) subparts[0];
- lineNo = (Integer) subparts[1];
-
- node = new MassifHeapTreeNode(parent, percentage, numBytes, address, function, filename, lineNo);
- } else {
- // concatenate the rest
- StringBuffer text = new StringBuffer();
- for (int i = 2; i < parts.length; i++) {
- text.append(parts[i]);
- text.append(" "); //$NON-NLS-1$
- }
-
- node = new MassifHeapTreeNode(parent, percentage, numBytes, text.toString().trim());
- }
-
-
- for (int i = 0; i < numChildren.intValue(); i++) {
- node.addChild(parseTree(snapshot, node, br));
- }
- return node;
- }
+ private MassifHeapTreeNode parseTree(MassifSnapshot snapshot, MassifHeapTreeNode parent, BufferedReader br) throws IOException {
+ String line = br.readLine();
+ if (line == null) {
+ throw new IOException(Messages.getString("MassifParser.Unexpected_EOF")); //$NON-NLS-1$
+ }
+ line = line.trim(); // remove leading whitespace
+ String[] parts = line.split(" "); //$NON-NLS-1$
+ // bounds checking so we can fail with a more informative error
+ if (parts.length < 2) {
+ ValgrindParserUtils.fail(line);
+ }
- private String parseFunction(String start, String line) throws IOException {
- String function = null;
- int ix = line.lastIndexOf('(');
- if (ix >= 0) {
- function = line.substring(line.indexOf(start), ix);
- }
- else {
- function = line.substring(line.indexOf(start));
- }
- if (function != null) {
- function = function.trim();
- }
- else {
- ValgrindParserUtils.fail(line);
- }
-
- return function;
- }
+ Integer numChildren = parseNumChildren(parts[0]);
+ if (numChildren == null) {
+ ValgrindParserUtils.fail(line);
+ }
- private Long parseNumBytes(String string) {
- Long result = null;
- if (ValgrindParserUtils.isNumber(string)) {
- result = Long.parseLong(string);
- }
- return result;
- }
+ Long numBytes = parseNumBytes(parts[1]);
+ if (numBytes == null) {
+ ValgrindParserUtils.fail(line);
+ }
- /*
- * format is "n[0-9]+:"
- */
- private Integer parseNumChildren(String string) {
- Integer result = null;
- if (string.length() >= 3) {
- String number = string.substring(1, string.length() - 1);
- if (ValgrindParserUtils.isNumber(number)) {
- result = Integer.parseInt(number);
- }
- }
- return result;
- }
+ double percentage;
+ if (numBytes.intValue() == 0) {
+ percentage = 0;
+ } else {
+ percentage = numBytes.doubleValue() / snapshot.getTotal() * 100;
+ }
- public Integer getPid() {
- return pid;
- }
-
- public MassifSnapshot[] getSnapshots() {
- return snapshots;
- }
+ MassifHeapTreeNode node;
+ String address = null;
+ String function = null;
+ String filename = null;
+ int lineNo = 0;
+ if (parts[2].startsWith("0x")) { //$NON-NLS-1$
+ // we extend the above bounds checking
+ if (parts.length < 3) {
+ ValgrindParserUtils.fail(line);
+ }
+ // remove colon from address
+ address = parts[2].substring(0, parts[2].length() - 1);
- private SnapshotType parseSnapshotType(String line) throws IOException {
- SnapshotType result = null;
- String[] parts = line.split(EQUALS);
- if (parts.length > 1) {
- String type = parts[1];
- if (type.equals(EMPTY)) {
- result = SnapshotType.EMPTY;
- }
- else if (type.equals(DETAILED)) {
- result = SnapshotType.DETAILED;
- }
- else if (type.equals(PEAK)) {
- result = SnapshotType.PEAK;
- }
- }
- if (result == null) {
- ValgrindParserUtils.fail(line);
- }
- return result;
- }
-
- private TimeUnit parseTimeUnit(String line) throws IOException {
- TimeUnit result = null;
- String[] parts = line.split(COLON + SPACE);
- if (parts.length > 1) {
- String type = parts[1];
- if (type.equals(INSTRUCTIONS)) {
- result = TimeUnit.INSTRUCTIONS;
- }
- else if (type.equals(MILLISECONDS)) {
- result = TimeUnit.MILLISECONDS;
- }
- else if (type.equals(BYTES)) {
- result = TimeUnit.BYTES;
- }
- }
- if (result == null) {
- ValgrindParserUtils.fail(line);
- }
- return result;
- }
+ function = parseFunction(parts[3], line);
+
+ // Parse source file if specified
+ Object[] subparts = ValgrindParserUtils.parseFilename(line);
+ filename = (String) subparts[0];
+ lineNo = (Integer) subparts[1];
+
+ node = new MassifHeapTreeNode(parent, percentage, numBytes, address, function, filename, lineNo);
+ } else {
+ // concatenate the rest
+ StringBuffer text = new StringBuffer();
+ for (int i = 2; i < parts.length; i++) {
+ text.append(parts[i]);
+ text.append(" "); //$NON-NLS-1$
+ }
+
+ node = new MassifHeapTreeNode(parent, percentage, numBytes, text.toString().trim());
+ }
+
+
+ for (int i = 0; i < numChildren.intValue(); i++) {
+ node.addChild(parseTree(snapshot, node, br));
+ }
+ return node;
+ }
+
+ private String parseFunction(String start, String line) throws IOException {
+ String function = null;
+ int ix = line.lastIndexOf('(');
+ if (ix >= 0) {
+ function = line.substring(line.indexOf(start), ix);
+ }
+ else {
+ function = line.substring(line.indexOf(start));
+ }
+ if (function != null) {
+ function = function.trim();
+ }
+ else {
+ ValgrindParserUtils.fail(line);
+ }
+
+ return function;
+ }
+
+ private Long parseNumBytes(String string) {
+ Long result = null;
+ if (ValgrindParserUtils.isNumber(string)) {
+ result = Long.parseLong(string);
+ }
+ return result;
+ }
+
+ /*
+ * format is "n[0-9]+:"
+ */
+ private Integer parseNumChildren(String string) {
+ Integer result = null;
+ if (string.length() >= 3) {
+ String number = string.substring(1, string.length() - 1);
+ if (ValgrindParserUtils.isNumber(number)) {
+ result = Integer.parseInt(number);
+ }
+ }
+ return result;
+ }
+
+ public Integer getPid() {
+ return pid;
+ }
+
+ public MassifSnapshot[] getSnapshots() {
+ return snapshots;
+ }
+
+ private SnapshotType parseSnapshotType(String line) throws IOException {
+ SnapshotType result = null;
+ String[] parts = line.split(EQUALS);
+ if (parts.length > 1) {
+ String type = parts[1];
+ if (type.equals(EMPTY)) {
+ result = SnapshotType.EMPTY;
+ }
+ else if (type.equals(DETAILED)) {
+ result = SnapshotType.DETAILED;
+ }
+ else if (type.equals(PEAK)) {
+ result = SnapshotType.PEAK;
+ }
+ }
+ if (result == null) {
+ ValgrindParserUtils.fail(line);
+ }
+ return result;
+ }
+
+ private TimeUnit parseTimeUnit(String line) throws IOException {
+ TimeUnit result = null;
+ String[] parts = line.split(COLON + SPACE);
+ if (parts.length > 1) {
+ String type = parts[1];
+ if (type.equals(INSTRUCTIONS)) {
+ result = TimeUnit.INSTRUCTIONS;
+ }
+ else if (type.equals(MILLISECONDS)) {
+ result = TimeUnit.MILLISECONDS;
+ }
+ else if (type.equals(BYTES)) {
+ result = TimeUnit.BYTES;
+ }
+ }
+ if (result == null) {
+ ValgrindParserUtils.fail(line);
+ }
+ return result;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifPidMenuAction.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifPidMenuAction.java
index 7012f6cdeb..5b800e05da 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifPidMenuAction.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifPidMenuAction.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
import org.eclipse.debug.ui.DebugUITools;
@@ -23,68 +23,68 @@ import org.eclipse.swt.widgets.MenuItem;
public class MassifPidMenuAction extends Action implements IMenuCreator {
- private Menu menu;
- private MassifViewPart view;
- private Integer[] pids;
+ private Menu menu;
+ private MassifViewPart view;
+ private Integer[] pids;
- public MassifPidMenuAction(MassifViewPart view) {
- super(Messages.getString("MassifPidMenuAction.Select_Process_ID"), IAction.AS_DROP_DOWN_MENU); //$NON-NLS-1$
- this.view = view;
+ public MassifPidMenuAction(MassifViewPart view) {
+ super(Messages.getString("MassifPidMenuAction.Select_Process_ID"), IAction.AS_DROP_DOWN_MENU); //$NON-NLS-1$
+ this.view = view;
- setToolTipText(Messages.getString("MassifPidMenuAction.Select_Process_ID")); //$NON-NLS-1$
- setImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_THREAD_RUNNING));
- setMenuCreator(this);
- }
+ setToolTipText(Messages.getString("MassifPidMenuAction.Select_Process_ID")); //$NON-NLS-1$
+ setImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_THREAD_RUNNING));
+ setMenuCreator(this);
+ }
- @Override
- public void dispose() {
- if (menu != null) {
- menu.dispose();
- }
- }
+ @Override
+ public void dispose() {
+ if (menu != null) {
+ menu.dispose();
+ }
+ }
- @Override
- public Menu getMenu(Control parent) {
- if (menu == null) {
- if (pids != null) {
- menu = new Menu(parent);
- for (int i = 0; i < pids.length; i++) {
- final Integer pid = pids[i];
- ActionContributionItem item = new ActionContributionItem(new Action("PID " + pids[i], IAction.AS_RADIO_BUTTON) { //$NON-NLS-1$
- @Override
- public void run() {
- MenuItem[] items = menu.getItems();
- for (int j = 0; j < items.length; j++) {
- IAction action = ((ActionContributionItem) items[j].getData()).getAction();
- action.setChecked(false);
- }
- setChecked(true);
- view.setPid(pid);
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- view.refreshView();
- }
- });
- }
- });
- item.fill(menu, -1);
- }
- }
- // Check first item
- ActionContributionItem item = (ActionContributionItem) menu.getItem(0).getData();
- item.getAction().setChecked(true);
- }
- return menu;
- }
+ @Override
+ public Menu getMenu(Control parent) {
+ if (menu == null) {
+ if (pids != null) {
+ menu = new Menu(parent);
+ for (int i = 0; i < pids.length; i++) {
+ final Integer pid = pids[i];
+ ActionContributionItem item = new ActionContributionItem(new Action("PID " + pids[i], IAction.AS_RADIO_BUTTON) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ MenuItem[] items = menu.getItems();
+ for (int j = 0; j < items.length; j++) {
+ IAction action = ((ActionContributionItem) items[j].getData()).getAction();
+ action.setChecked(false);
+ }
+ setChecked(true);
+ view.setPid(pid);
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ view.refreshView();
+ }
+ });
+ }
+ });
+ item.fill(menu, -1);
+ }
+ }
+ // Check first item
+ ActionContributionItem item = (ActionContributionItem) menu.getItem(0).getData();
+ item.getAction().setChecked(true);
+ }
+ return menu;
+ }
- @Override
- public Menu getMenu(Menu parent) {
- return null;
- }
+ @Override
+ public Menu getMenu(Menu parent) {
+ return null;
+ }
- public void setPids(Integer[] pids) {
- this.pids = pids;
- }
+ public void setPids(Integer[] pids) {
+ this.pids = pids;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifPlugin.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifPlugin.java
index 49b1b23643..d9e7ae792a 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifPlugin.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifPlugin.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
import org.eclipse.core.resources.IFile;
@@ -25,85 +25,85 @@ import org.osgi.framework.BundleContext;
public class MassifPlugin extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.massif"; //$NON-NLS-1$
- public static final String EDITOR_ID = PLUGIN_ID + ".chartEditor"; //$NON-NLS-1$
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.massif"; //$NON-NLS-1$
+ public static final String EDITOR_ID = PLUGIN_ID + ".chartEditor"; //$NON-NLS-1$
- // The shared instance
- private static MassifPlugin plugin;
-
- // Needed for source lookup on massif output, since massif only supplies filenames
- // and not full paths
- private ISourceLocator locator;
+ // The shared instance
+ private static MassifPlugin plugin;
- public static final String TOOL_ID = "org.eclipse.linuxtools.valgrind.launch.massif"; //$NON-NLS-1$
-
- /**
- * The constructor
- */
- public MassifPlugin() {
- }
+ // Needed for source lookup on massif output, since massif only supplies filenames
+ // and not full paths
+ private ISourceLocator locator;
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
+ public static final String TOOL_ID = "org.eclipse.linuxtools.valgrind.launch.massif"; //$NON-NLS-1$
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
+ /**
+ * The constructor
+ */
+ public MassifPlugin() {
+ }
- public static FontMetrics getFontMetrics(Control control) {
- GC gc = new GC(control);
- gc.setFont(control.getFont());
- FontMetrics fontMetrics = gc.getFontMetrics();
- gc.dispose();
- return fontMetrics;
- }
-
- public void openEditorForNode(MassifHeapTreeNode element) {
- // do source lookup
- if (locator instanceof ISourceLookupDirector) {
- Object obj = ((ISourceLookupDirector) locator).getSourceElement(element.getFilename());
- if (obj instanceof IStorage){
- try {
- // Most likely a remote project
- if (obj instanceof IFile) {
- ProfileUIUtils.openEditorAndSelect(((IFile)obj), element.getLine());
- // Local projects
- } else {
- String fullFilePath = ((IStorage) obj).getFullPath().toOSString();
- ProfileUIUtils.openEditorAndSelect(fullFilePath, element.getLine());
- }
- } catch (PartInitException|BadLocationException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- protected void setSourceLocator(ISourceLocator locator) {
- this.locator = locator;
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static MassifPlugin getDefault() {
- return plugin;
- }
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ public static FontMetrics getFontMetrics(Control control) {
+ GC gc = new GC(control);
+ gc.setFont(control.getFont());
+ FontMetrics fontMetrics = gc.getFontMetrics();
+ gc.dispose();
+ return fontMetrics;
+ }
+
+ public void openEditorForNode(MassifHeapTreeNode element) {
+ // do source lookup
+ if (locator instanceof ISourceLookupDirector) {
+ Object obj = ((ISourceLookupDirector) locator).getSourceElement(element.getFilename());
+ if (obj instanceof IStorage){
+ try {
+ // Most likely a remote project
+ if (obj instanceof IFile) {
+ ProfileUIUtils.openEditorAndSelect(((IFile)obj), element.getLine());
+ // Local projects
+ } else {
+ String fullFilePath = ((IStorage) obj).getFullPath().toOSString();
+ ProfileUIUtils.openEditorAndSelect(fullFilePath, element.getLine());
+ }
+ } catch (PartInitException|BadLocationException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+
+ protected void setSourceLocator(ISourceLocator locator) {
+ this.locator = locator;
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static MassifPlugin getDefault() {
+ return plugin;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifSnapshot.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifSnapshot.java
index cac6750041..fd1489f902 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifSnapshot.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifSnapshot.java
@@ -7,101 +7,101 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
public class MassifSnapshot {
- public static enum TimeUnit { INSTRUCTIONS, MILLISECONDS, BYTES }
- public static enum SnapshotType { EMPTY, DETAILED, PEAK }
-
- protected long number;
- protected long time;
- protected long heapBytes;
- protected long heapExtra;
- protected long stacks;
-
- protected String cmd;
- protected TimeUnit unit;
- protected SnapshotType type;
- protected MassifHeapTreeNode root;
-
- public MassifSnapshot(int number) {
- this.number = number;
- }
-
- public long getNumber() {
- return number;
- }
-
- public long getHeapBytes() {
- return heapBytes;
- }
-
- public long getHeapExtra() {
- return heapExtra;
- }
-
- public long getStacks() {
- return stacks;
- }
-
- public long getTime() {
- return time;
- }
-
- public long getTotal() {
- return heapBytes + heapExtra + stacks;
- }
-
- public SnapshotType getType() {
- return type;
- }
-
- public String getCmd() {
- return cmd;
- }
-
- public TimeUnit getUnit() {
- return unit;
- }
-
- public MassifHeapTreeNode getRoot() {
- return root;
- }
-
- public boolean isDetailed() {
- return !type.equals(SnapshotType.EMPTY);
- }
-
- protected void setTime(long time) {
- this.time = time;
- }
-
- protected void setHeapBytes(long heapBytes) {
- this.heapBytes = heapBytes;
- }
-
- protected void setHeapExtra(long heapExtra) {
- this.heapExtra = heapExtra;
- }
-
- protected void setStacks(long stacks) {
- this.stacks = stacks;
- }
-
- protected void setType(SnapshotType type) {
- this.type = type;
- }
-
- protected void setCmd(String cmd) {
- this.cmd = cmd;
- }
-
- protected void setUnit(TimeUnit unit) {
- this.unit = unit;
- }
-
- protected void setRoot(MassifHeapTreeNode root) {
- this.root = root;
- }
+ public static enum TimeUnit { INSTRUCTIONS, MILLISECONDS, BYTES }
+ public static enum SnapshotType { EMPTY, DETAILED, PEAK }
+
+ protected long number;
+ protected long time;
+ protected long heapBytes;
+ protected long heapExtra;
+ protected long stacks;
+
+ protected String cmd;
+ protected TimeUnit unit;
+ protected SnapshotType type;
+ protected MassifHeapTreeNode root;
+
+ public MassifSnapshot(int number) {
+ this.number = number;
+ }
+
+ public long getNumber() {
+ return number;
+ }
+
+ public long getHeapBytes() {
+ return heapBytes;
+ }
+
+ public long getHeapExtra() {
+ return heapExtra;
+ }
+
+ public long getStacks() {
+ return stacks;
+ }
+
+ public long getTime() {
+ return time;
+ }
+
+ public long getTotal() {
+ return heapBytes + heapExtra + stacks;
+ }
+
+ public SnapshotType getType() {
+ return type;
+ }
+
+ public String getCmd() {
+ return cmd;
+ }
+
+ public TimeUnit getUnit() {
+ return unit;
+ }
+
+ public MassifHeapTreeNode getRoot() {
+ return root;
+ }
+
+ public boolean isDetailed() {
+ return !type.equals(SnapshotType.EMPTY);
+ }
+
+ protected void setTime(long time) {
+ this.time = time;
+ }
+
+ protected void setHeapBytes(long heapBytes) {
+ this.heapBytes = heapBytes;
+ }
+
+ protected void setHeapExtra(long heapExtra) {
+ this.heapExtra = heapExtra;
+ }
+
+ protected void setStacks(long stacks) {
+ this.stacks = stacks;
+ }
+
+ protected void setType(SnapshotType type) {
+ this.type = type;
+ }
+
+ protected void setCmd(String cmd) {
+ this.cmd = cmd;
+ }
+
+ protected void setUnit(TimeUnit unit) {
+ this.unit = unit;
+ }
+
+ protected void setRoot(MassifHeapTreeNode root) {
+ this.root = root;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifToolPage.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifToolPage.java
index bfaaaa5baf..6676a6fb5c 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifToolPage.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifToolPage.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
import java.util.Arrays;
@@ -39,486 +39,486 @@ import org.eclipse.swt.widgets.Spinner;
import org.osgi.framework.Version;
public class MassifToolPage extends AbstractLaunchConfigurationTab
- implements IValgrindToolPage {
- public static final String TIME_B_STRING = Messages.getString("MassifToolPage.bytes"); //$NON-NLS-1$
- public static final String TIME_MS_STRING = Messages.getString("MassifToolPage.milliseconds"); //$NON-NLS-1$
- public static final String TIME_I_STRING = Messages.getString("MassifToolPage.instructions"); //$NON-NLS-1$
- public static final String MASSIF = "massif"; //$NON-NLS-1$
- public static final String PLUGIN_ID = MassifPlugin.PLUGIN_ID;
- private static final Version VER_3_6_0 = new Version(3, 6, 0);
-
- // Massif controls
- private Button heapButton;
- private Spinner heapAdminSpinner;
- private Button stacksButton;
- private Spinner depthSpinner;
- private List allocFnList;
- private List ignoreFnList;
- private Spinner thresholdSpinner;
- private Spinner peakInaccuracySpinner;
- private Combo timeUnitCombo;
- private Spinner detailedFreqSpinner;
- private Spinner maxSnapshotsSpinner;
- private Button alignmentButton;
- private Spinner alignmentSpinner;
-
- // VG >= 3.6.0
- private Button pagesasheapButton;
-
- private boolean isInitializing = false;
- private Version valgrindVersion;
-
- private SelectionListener selectListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
- private ModifyListener modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
-
- @Override
- public void createControl(Composite parent) {
- Composite top = new Composite(parent, SWT.NONE);
-
- GridLayout topLayout = new GridLayout(2, true);
- topLayout.horizontalSpacing = 10;
- top.setLayout(topLayout);
- top.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- Composite heapTop = new Composite(top, SWT.NONE);
- heapTop.setLayout(new GridLayout(2, false));
-
- heapButton = new Button(heapTop, SWT.CHECK);
- heapButton.setText(Messages.getString("MassifToolPage.profile_heap")); //$NON-NLS-1$
- heapButton.addSelectionListener(selectListener);
-
- Composite heapAdminTop = new Composite(top, SWT.NONE);
- heapAdminTop.setLayout(new GridLayout(2, false));
-
- Label heapAdminLabel = new Label(heapAdminTop, SWT.NONE);
- heapAdminLabel.setText(Messages.getString("MassifToolPage.administrative_bytes")); //$NON-NLS-1$
-
- heapAdminSpinner = new Spinner(heapAdminTop, SWT.BORDER);
- heapAdminSpinner.addModifyListener(modifyListener);
-
- Composite stacksTop = new Composite(top, SWT.NONE);
- stacksTop.setLayout(new GridLayout(2, false));
-
- stacksButton = new Button(stacksTop, SWT.CHECK);
- stacksButton.setText(Messages.getString("MassifToolPage.profile_stack")); //$NON-NLS-1$
- stacksButton.addSelectionListener(selectListener);
-
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
- Composite pagesasheapTop = new Composite(top, SWT.NONE);
- pagesasheapTop.setLayout(new GridLayout(2, false));
-
- pagesasheapButton = new Button(pagesasheapTop, SWT.CHECK);
- pagesasheapButton.setText(Messages.getString("MassifToolPage.profile_pagesasheap")); //$NON-NLS-1$
- pagesasheapButton.addSelectionListener(selectListener);
- }
-
- Composite depthTop = new Composite(top, SWT.NONE);
- depthTop.setLayout(new GridLayout(2, false));
-
- Label depthLabel = new Label(depthTop, SWT.NONE);
- depthLabel.setText(Messages.getString("MassifToolPage.allocation_tree_depth")); //$NON-NLS-1$
-
- depthSpinner = new Spinner(depthTop, SWT.BORDER);
- depthSpinner.addModifyListener(modifyListener);
-
- Composite thresholdTop = new Composite(top, SWT.NONE);
- thresholdTop.setLayout(new GridLayout(3, false));
-
- Label thresholdLabel = new Label(thresholdTop, SWT.NONE);
- thresholdLabel.setText(Messages.getString("MassifToolPage.heap_allocation_threshold")); //$NON-NLS-1$
-
- thresholdSpinner = new Spinner(thresholdTop, SWT.BORDER);
- thresholdSpinner.setDigits(1);
- thresholdSpinner.setMaximum(1000);
- thresholdSpinner.addModifyListener(modifyListener);
-
- Label thresholdPercentLabel = new Label(thresholdTop, SWT.NONE);
- thresholdPercentLabel.setText("%"); //$NON-NLS-1$
-
- Composite peakInaccuracyTop = new Composite(top, SWT.NONE);
- peakInaccuracyTop.setLayout(new GridLayout(3, false));
-
- Label peakInaccuracyLabel = new Label(peakInaccuracyTop, SWT.NONE);
- peakInaccuracyLabel.setText(Messages.getString("MassifToolPage.allocation_peak_inaccuracy")); //$NON-NLS-1$
-
- peakInaccuracySpinner = new Spinner(peakInaccuracyTop, SWT.BORDER);
- peakInaccuracySpinner.setDigits(1);
- peakInaccuracySpinner.setMaximum(1000);
- peakInaccuracySpinner.addModifyListener(modifyListener);
-
- Label peakInaccuracyPercentLabel = new Label(peakInaccuracyTop, SWT.NONE);
- peakInaccuracyPercentLabel.setText("%"); //$NON-NLS-1$
-
- Composite timeUnitTop = new Composite(top, SWT.NONE);
- timeUnitTop.setLayout(new GridLayout(2, false));
-
- Label timeUnitLabel = new Label(timeUnitTop, SWT.NONE);
- timeUnitLabel.setText(Messages.getString("MassifToolPage.time_unit")); //$NON-NLS-1$
-
- timeUnitCombo = new Combo(timeUnitTop, SWT.READ_ONLY);
- String[] items = new String[] { TIME_I_STRING, TIME_MS_STRING, TIME_B_STRING };
- timeUnitCombo.setItems(items);
- timeUnitCombo.addSelectionListener(selectListener);
-
- Composite detailedFreqTop = new Composite(top, SWT.NONE);
- detailedFreqTop.setLayout(new GridLayout(2, false));
-
- Label detailedFreqLabel = new Label(detailedFreqTop, SWT.NONE);
- detailedFreqLabel.setText(Messages.getString("MassifToolPage.detailed_snapshot_freq")); //$NON-NLS-1$
-
- detailedFreqSpinner = new Spinner(detailedFreqTop, SWT.BORDER);
- detailedFreqSpinner.setMinimum(1);
- detailedFreqSpinner.setMaximum(Integer.MAX_VALUE);
- detailedFreqSpinner.addModifyListener(modifyListener);
-
- Composite maxSnapshotsTop = new Composite(top, SWT.NONE);
- maxSnapshotsTop.setLayout(new GridLayout(2, false));
-
- Label maxSnapshotsLabel = new Label(maxSnapshotsTop, SWT.NONE);
- maxSnapshotsLabel.setText(Messages.getString("MassifToolPage.max_snapshots")); //$NON-NLS-1$
-
- maxSnapshotsSpinner = new Spinner(maxSnapshotsTop, SWT.BORDER);
- maxSnapshotsSpinner.setMaximum(Integer.MAX_VALUE);
- maxSnapshotsSpinner.addModifyListener(modifyListener);
-
- Composite alignmentTop = new Composite(top, SWT.NONE);
- GridLayout alignmentLayout = new GridLayout(2, false);
- alignmentLayout.marginWidth = alignmentLayout.marginHeight = 0;
- alignmentTop.setLayout(alignmentLayout);
- alignmentButton = new Button(alignmentTop, SWT.CHECK);
- alignmentButton.setText(Messages.getString("MassifToolPage.minimum_heap_block")); //$NON-NLS-1$
- alignmentButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- checkAlignmentEnablement();
- updateLaunchConfigurationDialog();
- }
- });
- alignmentSpinner = new Spinner(alignmentTop, SWT.BORDER);
- alignmentSpinner.setMinimum(0);
- alignmentSpinner.setMaximum(4096);
- alignmentSpinner.addModifyListener(modifyListener);
-
- Composite allocFnTop = new Composite(top, SWT.NONE);
- allocFnTop.setLayout(new GridLayout(3, false));
- allocFnTop.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, 2, 1));
-
- Label allocFnLabel = new Label(allocFnTop, SWT.NONE);
- allocFnLabel.setText(Messages.getString("MassifToolPage.allocation_functions")); //$NON-NLS-1$
- allocFnLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
-
- createAllocFnControls(allocFnTop);
-
- Composite ignoreFnTop = new Composite(top, SWT.NONE);
- ignoreFnTop.setLayout(new GridLayout(3, false));
- ignoreFnTop.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, 2, 1));
-
- Label ignoreFnLabel = new Label(ignoreFnTop, SWT.NONE);
- ignoreFnLabel.setText(Messages.getString("MassifToolPage.ignore_functions")); //$NON-NLS-1$
- ignoreFnLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
-
- createIgnoreFnControls(ignoreFnTop);
-
-
- }
-
- private void checkAlignmentEnablement() {
- alignmentSpinner.setEnabled(alignmentButton.getSelection());
- }
-
- private void createAllocFnControls(Composite top) {
-
- allocFnList = new List(top, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- FontMetrics fm = MassifPlugin.getFontMetrics(allocFnList);
- allocFnList.setLayoutData(new GridData(Dialog.convertWidthInCharsToPixels(fm, 50), Dialog.convertHeightInCharsToPixels(fm, 5)));
-
- Composite allocButtons = new Composite(top, SWT.NONE);
- GridLayout allocButtonsLayout = new GridLayout();
- allocButtonsLayout.marginWidth = allocButtonsLayout.marginHeight = 0;
- allocButtons.setLayout(allocButtonsLayout);
- allocButtons.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
-
- Button newButton = new Button(allocButtons, SWT.PUSH);
- newButton.setText(Messages.getString("MassifToolPage.New")); //$NON-NLS-1$
- newButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- newButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleAllocNewButtonPressed();
- updateLaunchConfigurationDialog();
- }
- });
-
- Button removeButton = new Button(allocButtons, SWT.PUSH);
- removeButton.setText(Messages.getString("MassifToolPage.Remove")); //$NON-NLS-1$
- removeButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- removeButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleAllocRemoveButtonPressed();
- updateLaunchConfigurationDialog();
- }
- });
- }
-
- private void createIgnoreFnControls(Composite top) {
-
- ignoreFnList = new List(top, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- FontMetrics fm = MassifPlugin.getFontMetrics(ignoreFnList);
- ignoreFnList.setLayoutData(new GridData(Dialog.convertWidthInCharsToPixels(fm, 50), Dialog.convertHeightInCharsToPixels(fm, 5)));
-
- Composite ignoreButtons = new Composite(top, SWT.NONE);
- GridLayout ignoreButtonsLayout = new GridLayout();
- ignoreButtonsLayout.marginWidth = ignoreButtonsLayout.marginHeight = 0;
- ignoreButtons.setLayout(ignoreButtonsLayout);
- ignoreButtons.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
-
- Button newButton = new Button(ignoreButtons, SWT.PUSH);
- newButton.setText(Messages.getString("MassifToolPage.New")); //$NON-NLS-1$
- newButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- newButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleIgnoreNewButtonPressed();
- updateLaunchConfigurationDialog();
- }
- });
-
- Button removeButton = new Button(ignoreButtons, SWT.PUSH);
- removeButton.setText(Messages.getString("MassifToolPage.Remove")); //$NON-NLS-1$
- removeButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- removeButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleIgnoreRemoveButtonPressed();
- updateLaunchConfigurationDialog();
- }
- });
- }
-
- private void handleAllocNewButtonPressed() {
- InputDialog dialog = new InputDialog(getShell(), Messages.getString("MassifToolPage.New_Allocation_Function"), Messages.getString("MassifToolPage.Function_name"), "", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (dialog.open() == Window.OK) {
- String function = dialog.getValue();
- if (!function.equals("")) { //$NON-NLS-1$
- allocFnList.add(function);
- }
- }
- }
-
- private void handleAllocRemoveButtonPressed() {
- int[] selections = allocFnList.getSelectionIndices();
- allocFnList.remove(selections);
- }
-
- private void handleIgnoreNewButtonPressed() {
- InputDialog dialog = new InputDialog(getShell(), Messages.getString("MassifToolPage.New_Ignore_Function"), Messages.getString("MassifToolPage.Function_name"), "", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (dialog.open() == Window.OK) {
- String function = dialog.getValue();
- if (!function.equals("")) { //$NON-NLS-1$
- ignoreFnList.add(function);
- }
- }
- }
-
- private void handleIgnoreRemoveButtonPressed() {
- int[] selections = ignoreFnList.getSelectionIndices();
- ignoreFnList.remove(selections);
- }
-
- @Override
- public String getName() {
- return Messages.getString("MassifToolPage.Massif_Options"); //$NON-NLS-1$
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration configuration) {
- isInitializing = true;
- try {
- heapButton.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAP, MassifLaunchConstants.DEFAULT_MASSIF_HEAP));
- heapAdminSpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAPADMIN, MassifLaunchConstants.DEFAULT_MASSIF_HEAPADMIN));
- stacksButton.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_STACKS, MassifLaunchConstants.DEFAULT_MASSIF_STACKS));
- depthSpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_DEPTH, MassifLaunchConstants.DEFAULT_MASSIF_DEPTH));
- java.util.List<String> allocFns = configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALLOCFN, MassifLaunchConstants.DEFAULT_MASSIF_ALLOCFN);
- allocFnList.setItems(allocFns.toArray(new String[allocFns.size()]));
- java.util.List<String> ignoreFns = configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_IGNOREFN, MassifLaunchConstants.DEFAULT_MASSIF_IGNOREFN);
- ignoreFnList.setItems(ignoreFns.toArray(new String[ignoreFns.size()]));
- thresholdSpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_THRESHOLD, MassifLaunchConstants.DEFAULT_MASSIF_THRESHOLD));
- peakInaccuracySpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_PEAKINACCURACY, MassifLaunchConstants.DEFAULT_MASSIF_PEAKINACCURACY));
-
- String timeUnit = configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_TIMEUNIT, MassifLaunchConstants.DEFAULT_MASSIF_TIMEUNIT);
- if (timeUnit.equals(MassifLaunchConstants.TIME_I)) {
- timeUnitCombo.select(0);
- } else if (timeUnit.equals(MassifLaunchConstants.TIME_MS)) {
- timeUnitCombo.select(1);
- } else {
- timeUnitCombo.select(2);
- }
-
- detailedFreqSpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, MassifLaunchConstants.DEFAULT_MASSIF_DETAILEDFREQ));
- maxSnapshotsSpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_MAXSNAPSHOTS, MassifLaunchConstants.DEFAULT_MASSIF_MAXSNAPSHOTS));
- alignmentButton.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_BOOL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_BOOL));
- checkAlignmentEnablement();
- int alignment = configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_VAL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_VAL);
- alignmentSpinner.setSelection(alignment);
-
- // VG >= 3.6.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
- pagesasheapButton.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_PAGESASHEAP, MassifLaunchConstants.DEFAULT_MASSIF_PAGESASHEAP));
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- isInitializing = false;
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAP, heapButton.getSelection());
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAPADMIN, heapAdminSpinner.getSelection());
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_STACKS, stacksButton.getSelection());
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DEPTH, depthSpinner.getSelection());
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALLOCFN, Arrays.asList(allocFnList.getItems()));
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_IGNOREFN, Arrays.asList(ignoreFnList.getItems()));
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_THRESHOLD, thresholdSpinner.getSelection());
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_PEAKINACCURACY, peakInaccuracySpinner.getSelection());
- int ix = timeUnitCombo.getSelectionIndex();
- String value;
- if (ix == 0) {
- value = MassifLaunchConstants.TIME_I;
- } else if (ix == 1) {
- value = MassifLaunchConstants.TIME_MS;
- } else {
- value = MassifLaunchConstants.TIME_B;
- }
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_TIMEUNIT, value);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, detailedFreqSpinner.getSelection());
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_MAXSNAPSHOTS, maxSnapshotsSpinner.getSelection());
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_BOOL, alignmentButton.getSelection());
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_VAL, alignmentSpinner.getSelection());
-
- // VG >= 3.6.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_PAGESASHEAP, pagesasheapButton.getSelection());
- }
- }
-
- @Override
- public boolean isValid(ILaunchConfiguration launchConfig) {
- setErrorMessage(null);
-
- boolean result = false;
- try {
- int alignment = launchConfig.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_VAL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_VAL);
- result = (alignment & (alignment - 1)) == 0; // is power of two?
- } catch (CoreException e) {
- e.printStackTrace();
- }
-
- if (!result) {
- setErrorMessage(Messages.getString("MassifToolPage.Alignment_must_be_power_2")); //$NON-NLS-1$
- }
- return result;
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, MassifPlugin.TOOL_ID);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAP, MassifLaunchConstants.DEFAULT_MASSIF_HEAP);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAPADMIN, MassifLaunchConstants.DEFAULT_MASSIF_HEAPADMIN);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_STACKS, MassifLaunchConstants.DEFAULT_MASSIF_STACKS);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DEPTH, MassifLaunchConstants.DEFAULT_MASSIF_DEPTH);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALLOCFN, MassifLaunchConstants.DEFAULT_MASSIF_ALLOCFN);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_THRESHOLD, MassifLaunchConstants.DEFAULT_MASSIF_THRESHOLD);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_PEAKINACCURACY, MassifLaunchConstants.DEFAULT_MASSIF_PEAKINACCURACY);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_TIMEUNIT, MassifLaunchConstants.DEFAULT_MASSIF_TIMEUNIT);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, MassifLaunchConstants.DEFAULT_MASSIF_DETAILEDFREQ);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_MAXSNAPSHOTS, MassifLaunchConstants.DEFAULT_MASSIF_MAXSNAPSHOTS);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_BOOL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_BOOL);
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_VAL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_VAL);
-
- // VG >= 3.6.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
- configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_PAGESASHEAP, MassifLaunchConstants.DEFAULT_MASSIF_PAGESASHEAP);
- }
- }
-
- @Override
- public void setValgrindVersion(Version ver) {
- valgrindVersion = ver;
- }
-
- @Override
- protected void updateLaunchConfigurationDialog() {
- if (!isInitializing) {
- super.updateLaunchConfigurationDialog();
- }
- }
-
- public Button getHeapButton() {
- return heapButton;
- }
-
- public Spinner getHeapAdminSpinner() {
- return heapAdminSpinner;
- }
-
- public Button getStacksButton() {
- return stacksButton;
- }
-
- public Button getPageasheapButton() {
- return pagesasheapButton;
- }
-
- public Spinner getDepthSpinner() {
- return depthSpinner;
- }
-
- public List getAllocFnList() {
- return allocFnList;
- }
-
- public List getIgnoreFnList() {
- return ignoreFnList;
- }
-
- public Spinner getThresholdSpinner() {
- return thresholdSpinner;
- }
-
- public Spinner getPeakInaccuracySpinner() {
- return peakInaccuracySpinner;
- }
-
- public Combo getTimeUnitCombo() {
- return timeUnitCombo;
- }
-
- public Spinner getDetailedFreqSpinner() {
- return detailedFreqSpinner;
- }
-
- public Spinner getMaxSnapshotsSpinner() {
- return maxSnapshotsSpinner;
- }
-
- public Button getAlignmentButton() {
- return alignmentButton;
- }
-
- public Spinner getAlignmentSpinner() {
- return alignmentSpinner;
- }
+ implements IValgrindToolPage {
+ public static final String TIME_B_STRING = Messages.getString("MassifToolPage.bytes"); //$NON-NLS-1$
+ public static final String TIME_MS_STRING = Messages.getString("MassifToolPage.milliseconds"); //$NON-NLS-1$
+ public static final String TIME_I_STRING = Messages.getString("MassifToolPage.instructions"); //$NON-NLS-1$
+ public static final String MASSIF = "massif"; //$NON-NLS-1$
+ public static final String PLUGIN_ID = MassifPlugin.PLUGIN_ID;
+ private static final Version VER_3_6_0 = new Version(3, 6, 0);
+
+ // Massif controls
+ private Button heapButton;
+ private Spinner heapAdminSpinner;
+ private Button stacksButton;
+ private Spinner depthSpinner;
+ private List allocFnList;
+ private List ignoreFnList;
+ private Spinner thresholdSpinner;
+ private Spinner peakInaccuracySpinner;
+ private Combo timeUnitCombo;
+ private Spinner detailedFreqSpinner;
+ private Spinner maxSnapshotsSpinner;
+ private Button alignmentButton;
+ private Spinner alignmentSpinner;
+
+ // VG >= 3.6.0
+ private Button pagesasheapButton;
+
+ private boolean isInitializing = false;
+ private Version valgrindVersion;
+
+ private SelectionListener selectListener = new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+ private ModifyListener modifyListener = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ @Override
+ public void createControl(Composite parent) {
+ Composite top = new Composite(parent, SWT.NONE);
+
+ GridLayout topLayout = new GridLayout(2, true);
+ topLayout.horizontalSpacing = 10;
+ top.setLayout(topLayout);
+ top.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ Composite heapTop = new Composite(top, SWT.NONE);
+ heapTop.setLayout(new GridLayout(2, false));
+
+ heapButton = new Button(heapTop, SWT.CHECK);
+ heapButton.setText(Messages.getString("MassifToolPage.profile_heap")); //$NON-NLS-1$
+ heapButton.addSelectionListener(selectListener);
+
+ Composite heapAdminTop = new Composite(top, SWT.NONE);
+ heapAdminTop.setLayout(new GridLayout(2, false));
+
+ Label heapAdminLabel = new Label(heapAdminTop, SWT.NONE);
+ heapAdminLabel.setText(Messages.getString("MassifToolPage.administrative_bytes")); //$NON-NLS-1$
+
+ heapAdminSpinner = new Spinner(heapAdminTop, SWT.BORDER);
+ heapAdminSpinner.addModifyListener(modifyListener);
+
+ Composite stacksTop = new Composite(top, SWT.NONE);
+ stacksTop.setLayout(new GridLayout(2, false));
+
+ stacksButton = new Button(stacksTop, SWT.CHECK);
+ stacksButton.setText(Messages.getString("MassifToolPage.profile_stack")); //$NON-NLS-1$
+ stacksButton.addSelectionListener(selectListener);
+
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
+ Composite pagesasheapTop = new Composite(top, SWT.NONE);
+ pagesasheapTop.setLayout(new GridLayout(2, false));
+
+ pagesasheapButton = new Button(pagesasheapTop, SWT.CHECK);
+ pagesasheapButton.setText(Messages.getString("MassifToolPage.profile_pagesasheap")); //$NON-NLS-1$
+ pagesasheapButton.addSelectionListener(selectListener);
+ }
+
+ Composite depthTop = new Composite(top, SWT.NONE);
+ depthTop.setLayout(new GridLayout(2, false));
+
+ Label depthLabel = new Label(depthTop, SWT.NONE);
+ depthLabel.setText(Messages.getString("MassifToolPage.allocation_tree_depth")); //$NON-NLS-1$
+
+ depthSpinner = new Spinner(depthTop, SWT.BORDER);
+ depthSpinner.addModifyListener(modifyListener);
+
+ Composite thresholdTop = new Composite(top, SWT.NONE);
+ thresholdTop.setLayout(new GridLayout(3, false));
+
+ Label thresholdLabel = new Label(thresholdTop, SWT.NONE);
+ thresholdLabel.setText(Messages.getString("MassifToolPage.heap_allocation_threshold")); //$NON-NLS-1$
+
+ thresholdSpinner = new Spinner(thresholdTop, SWT.BORDER);
+ thresholdSpinner.setDigits(1);
+ thresholdSpinner.setMaximum(1000);
+ thresholdSpinner.addModifyListener(modifyListener);
+
+ Label thresholdPercentLabel = new Label(thresholdTop, SWT.NONE);
+ thresholdPercentLabel.setText("%"); //$NON-NLS-1$
+
+ Composite peakInaccuracyTop = new Composite(top, SWT.NONE);
+ peakInaccuracyTop.setLayout(new GridLayout(3, false));
+
+ Label peakInaccuracyLabel = new Label(peakInaccuracyTop, SWT.NONE);
+ peakInaccuracyLabel.setText(Messages.getString("MassifToolPage.allocation_peak_inaccuracy")); //$NON-NLS-1$
+
+ peakInaccuracySpinner = new Spinner(peakInaccuracyTop, SWT.BORDER);
+ peakInaccuracySpinner.setDigits(1);
+ peakInaccuracySpinner.setMaximum(1000);
+ peakInaccuracySpinner.addModifyListener(modifyListener);
+
+ Label peakInaccuracyPercentLabel = new Label(peakInaccuracyTop, SWT.NONE);
+ peakInaccuracyPercentLabel.setText("%"); //$NON-NLS-1$
+
+ Composite timeUnitTop = new Composite(top, SWT.NONE);
+ timeUnitTop.setLayout(new GridLayout(2, false));
+
+ Label timeUnitLabel = new Label(timeUnitTop, SWT.NONE);
+ timeUnitLabel.setText(Messages.getString("MassifToolPage.time_unit")); //$NON-NLS-1$
+
+ timeUnitCombo = new Combo(timeUnitTop, SWT.READ_ONLY);
+ String[] items = new String[] { TIME_I_STRING, TIME_MS_STRING, TIME_B_STRING };
+ timeUnitCombo.setItems(items);
+ timeUnitCombo.addSelectionListener(selectListener);
+
+ Composite detailedFreqTop = new Composite(top, SWT.NONE);
+ detailedFreqTop.setLayout(new GridLayout(2, false));
+
+ Label detailedFreqLabel = new Label(detailedFreqTop, SWT.NONE);
+ detailedFreqLabel.setText(Messages.getString("MassifToolPage.detailed_snapshot_freq")); //$NON-NLS-1$
+
+ detailedFreqSpinner = new Spinner(detailedFreqTop, SWT.BORDER);
+ detailedFreqSpinner.setMinimum(1);
+ detailedFreqSpinner.setMaximum(Integer.MAX_VALUE);
+ detailedFreqSpinner.addModifyListener(modifyListener);
+
+ Composite maxSnapshotsTop = new Composite(top, SWT.NONE);
+ maxSnapshotsTop.setLayout(new GridLayout(2, false));
+
+ Label maxSnapshotsLabel = new Label(maxSnapshotsTop, SWT.NONE);
+ maxSnapshotsLabel.setText(Messages.getString("MassifToolPage.max_snapshots")); //$NON-NLS-1$
+
+ maxSnapshotsSpinner = new Spinner(maxSnapshotsTop, SWT.BORDER);
+ maxSnapshotsSpinner.setMaximum(Integer.MAX_VALUE);
+ maxSnapshotsSpinner.addModifyListener(modifyListener);
+
+ Composite alignmentTop = new Composite(top, SWT.NONE);
+ GridLayout alignmentLayout = new GridLayout(2, false);
+ alignmentLayout.marginWidth = alignmentLayout.marginHeight = 0;
+ alignmentTop.setLayout(alignmentLayout);
+ alignmentButton = new Button(alignmentTop, SWT.CHECK);
+ alignmentButton.setText(Messages.getString("MassifToolPage.minimum_heap_block")); //$NON-NLS-1$
+ alignmentButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ checkAlignmentEnablement();
+ updateLaunchConfigurationDialog();
+ }
+ });
+ alignmentSpinner = new Spinner(alignmentTop, SWT.BORDER);
+ alignmentSpinner.setMinimum(0);
+ alignmentSpinner.setMaximum(4096);
+ alignmentSpinner.addModifyListener(modifyListener);
+
+ Composite allocFnTop = new Composite(top, SWT.NONE);
+ allocFnTop.setLayout(new GridLayout(3, false));
+ allocFnTop.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, 2, 1));
+
+ Label allocFnLabel = new Label(allocFnTop, SWT.NONE);
+ allocFnLabel.setText(Messages.getString("MassifToolPage.allocation_functions")); //$NON-NLS-1$
+ allocFnLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
+
+ createAllocFnControls(allocFnTop);
+
+ Composite ignoreFnTop = new Composite(top, SWT.NONE);
+ ignoreFnTop.setLayout(new GridLayout(3, false));
+ ignoreFnTop.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, 2, 1));
+
+ Label ignoreFnLabel = new Label(ignoreFnTop, SWT.NONE);
+ ignoreFnLabel.setText(Messages.getString("MassifToolPage.ignore_functions")); //$NON-NLS-1$
+ ignoreFnLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
+
+ createIgnoreFnControls(ignoreFnTop);
+
+
+ }
+
+ private void checkAlignmentEnablement() {
+ alignmentSpinner.setEnabled(alignmentButton.getSelection());
+ }
+
+ private void createAllocFnControls(Composite top) {
+
+ allocFnList = new List(top, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
+ FontMetrics fm = MassifPlugin.getFontMetrics(allocFnList);
+ allocFnList.setLayoutData(new GridData(Dialog.convertWidthInCharsToPixels(fm, 50), Dialog.convertHeightInCharsToPixels(fm, 5)));
+
+ Composite allocButtons = new Composite(top, SWT.NONE);
+ GridLayout allocButtonsLayout = new GridLayout();
+ allocButtonsLayout.marginWidth = allocButtonsLayout.marginHeight = 0;
+ allocButtons.setLayout(allocButtonsLayout);
+ allocButtons.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
+
+ Button newButton = new Button(allocButtons, SWT.PUSH);
+ newButton.setText(Messages.getString("MassifToolPage.New")); //$NON-NLS-1$
+ newButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ newButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ handleAllocNewButtonPressed();
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ Button removeButton = new Button(allocButtons, SWT.PUSH);
+ removeButton.setText(Messages.getString("MassifToolPage.Remove")); //$NON-NLS-1$
+ removeButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ removeButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ handleAllocRemoveButtonPressed();
+ updateLaunchConfigurationDialog();
+ }
+ });
+ }
+
+ private void createIgnoreFnControls(Composite top) {
+
+ ignoreFnList = new List(top, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
+ FontMetrics fm = MassifPlugin.getFontMetrics(ignoreFnList);
+ ignoreFnList.setLayoutData(new GridData(Dialog.convertWidthInCharsToPixels(fm, 50), Dialog.convertHeightInCharsToPixels(fm, 5)));
+
+ Composite ignoreButtons = new Composite(top, SWT.NONE);
+ GridLayout ignoreButtonsLayout = new GridLayout();
+ ignoreButtonsLayout.marginWidth = ignoreButtonsLayout.marginHeight = 0;
+ ignoreButtons.setLayout(ignoreButtonsLayout);
+ ignoreButtons.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
+
+ Button newButton = new Button(ignoreButtons, SWT.PUSH);
+ newButton.setText(Messages.getString("MassifToolPage.New")); //$NON-NLS-1$
+ newButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ newButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ handleIgnoreNewButtonPressed();
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ Button removeButton = new Button(ignoreButtons, SWT.PUSH);
+ removeButton.setText(Messages.getString("MassifToolPage.Remove")); //$NON-NLS-1$
+ removeButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ removeButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ handleIgnoreRemoveButtonPressed();
+ updateLaunchConfigurationDialog();
+ }
+ });
+ }
+
+ private void handleAllocNewButtonPressed() {
+ InputDialog dialog = new InputDialog(getShell(), Messages.getString("MassifToolPage.New_Allocation_Function"), Messages.getString("MassifToolPage.Function_name"), "", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if (dialog.open() == Window.OK) {
+ String function = dialog.getValue();
+ if (!function.equals("")) { //$NON-NLS-1$
+ allocFnList.add(function);
+ }
+ }
+ }
+
+ private void handleAllocRemoveButtonPressed() {
+ int[] selections = allocFnList.getSelectionIndices();
+ allocFnList.remove(selections);
+ }
+
+ private void handleIgnoreNewButtonPressed() {
+ InputDialog dialog = new InputDialog(getShell(), Messages.getString("MassifToolPage.New_Ignore_Function"), Messages.getString("MassifToolPage.Function_name"), "", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if (dialog.open() == Window.OK) {
+ String function = dialog.getValue();
+ if (!function.equals("")) { //$NON-NLS-1$
+ ignoreFnList.add(function);
+ }
+ }
+ }
+
+ private void handleIgnoreRemoveButtonPressed() {
+ int[] selections = ignoreFnList.getSelectionIndices();
+ ignoreFnList.remove(selections);
+ }
+
+ @Override
+ public String getName() {
+ return Messages.getString("MassifToolPage.Massif_Options"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration configuration) {
+ isInitializing = true;
+ try {
+ heapButton.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAP, MassifLaunchConstants.DEFAULT_MASSIF_HEAP));
+ heapAdminSpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAPADMIN, MassifLaunchConstants.DEFAULT_MASSIF_HEAPADMIN));
+ stacksButton.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_STACKS, MassifLaunchConstants.DEFAULT_MASSIF_STACKS));
+ depthSpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_DEPTH, MassifLaunchConstants.DEFAULT_MASSIF_DEPTH));
+ java.util.List<String> allocFns = configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALLOCFN, MassifLaunchConstants.DEFAULT_MASSIF_ALLOCFN);
+ allocFnList.setItems(allocFns.toArray(new String[allocFns.size()]));
+ java.util.List<String> ignoreFns = configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_IGNOREFN, MassifLaunchConstants.DEFAULT_MASSIF_IGNOREFN);
+ ignoreFnList.setItems(ignoreFns.toArray(new String[ignoreFns.size()]));
+ thresholdSpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_THRESHOLD, MassifLaunchConstants.DEFAULT_MASSIF_THRESHOLD));
+ peakInaccuracySpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_PEAKINACCURACY, MassifLaunchConstants.DEFAULT_MASSIF_PEAKINACCURACY));
+
+ String timeUnit = configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_TIMEUNIT, MassifLaunchConstants.DEFAULT_MASSIF_TIMEUNIT);
+ if (timeUnit.equals(MassifLaunchConstants.TIME_I)) {
+ timeUnitCombo.select(0);
+ } else if (timeUnit.equals(MassifLaunchConstants.TIME_MS)) {
+ timeUnitCombo.select(1);
+ } else {
+ timeUnitCombo.select(2);
+ }
+
+ detailedFreqSpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, MassifLaunchConstants.DEFAULT_MASSIF_DETAILEDFREQ));
+ maxSnapshotsSpinner.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_MAXSNAPSHOTS, MassifLaunchConstants.DEFAULT_MASSIF_MAXSNAPSHOTS));
+ alignmentButton.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_BOOL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_BOOL));
+ checkAlignmentEnablement();
+ int alignment = configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_VAL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_VAL);
+ alignmentSpinner.setSelection(alignment);
+
+ // VG >= 3.6.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
+ pagesasheapButton.setSelection(configuration.getAttribute(MassifLaunchConstants.ATTR_MASSIF_PAGESASHEAP, MassifLaunchConstants.DEFAULT_MASSIF_PAGESASHEAP));
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ isInitializing = false;
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAP, heapButton.getSelection());
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAPADMIN, heapAdminSpinner.getSelection());
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_STACKS, stacksButton.getSelection());
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DEPTH, depthSpinner.getSelection());
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALLOCFN, Arrays.asList(allocFnList.getItems()));
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_IGNOREFN, Arrays.asList(ignoreFnList.getItems()));
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_THRESHOLD, thresholdSpinner.getSelection());
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_PEAKINACCURACY, peakInaccuracySpinner.getSelection());
+ int ix = timeUnitCombo.getSelectionIndex();
+ String value;
+ if (ix == 0) {
+ value = MassifLaunchConstants.TIME_I;
+ } else if (ix == 1) {
+ value = MassifLaunchConstants.TIME_MS;
+ } else {
+ value = MassifLaunchConstants.TIME_B;
+ }
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_TIMEUNIT, value);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, detailedFreqSpinner.getSelection());
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_MAXSNAPSHOTS, maxSnapshotsSpinner.getSelection());
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_BOOL, alignmentButton.getSelection());
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_VAL, alignmentSpinner.getSelection());
+
+ // VG >= 3.6.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_PAGESASHEAP, pagesasheapButton.getSelection());
+ }
+ }
+
+ @Override
+ public boolean isValid(ILaunchConfiguration launchConfig) {
+ setErrorMessage(null);
+
+ boolean result = false;
+ try {
+ int alignment = launchConfig.getAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_VAL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_VAL);
+ result = (alignment & (alignment - 1)) == 0; // is power of two?
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+
+ if (!result) {
+ setErrorMessage(Messages.getString("MassifToolPage.Alignment_must_be_power_2")); //$NON-NLS-1$
+ }
+ return result;
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, MassifPlugin.TOOL_ID);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAP, MassifLaunchConstants.DEFAULT_MASSIF_HEAP);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_HEAPADMIN, MassifLaunchConstants.DEFAULT_MASSIF_HEAPADMIN);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_STACKS, MassifLaunchConstants.DEFAULT_MASSIF_STACKS);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DEPTH, MassifLaunchConstants.DEFAULT_MASSIF_DEPTH);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALLOCFN, MassifLaunchConstants.DEFAULT_MASSIF_ALLOCFN);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_THRESHOLD, MassifLaunchConstants.DEFAULT_MASSIF_THRESHOLD);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_PEAKINACCURACY, MassifLaunchConstants.DEFAULT_MASSIF_PEAKINACCURACY);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_TIMEUNIT, MassifLaunchConstants.DEFAULT_MASSIF_TIMEUNIT);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_DETAILEDFREQ, MassifLaunchConstants.DEFAULT_MASSIF_DETAILEDFREQ);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_MAXSNAPSHOTS, MassifLaunchConstants.DEFAULT_MASSIF_MAXSNAPSHOTS);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_BOOL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_BOOL);
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_ALIGNMENT_VAL, MassifLaunchConstants.DEFAULT_MASSIF_ALIGNMENT_VAL);
+
+ // VG >= 3.6.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
+ configuration.setAttribute(MassifLaunchConstants.ATTR_MASSIF_PAGESASHEAP, MassifLaunchConstants.DEFAULT_MASSIF_PAGESASHEAP);
+ }
+ }
+
+ @Override
+ public void setValgrindVersion(Version ver) {
+ valgrindVersion = ver;
+ }
+
+ @Override
+ protected void updateLaunchConfigurationDialog() {
+ if (!isInitializing) {
+ super.updateLaunchConfigurationDialog();
+ }
+ }
+
+ public Button getHeapButton() {
+ return heapButton;
+ }
+
+ public Spinner getHeapAdminSpinner() {
+ return heapAdminSpinner;
+ }
+
+ public Button getStacksButton() {
+ return stacksButton;
+ }
+
+ public Button getPageasheapButton() {
+ return pagesasheapButton;
+ }
+
+ public Spinner getDepthSpinner() {
+ return depthSpinner;
+ }
+
+ public List getAllocFnList() {
+ return allocFnList;
+ }
+
+ public List getIgnoreFnList() {
+ return ignoreFnList;
+ }
+
+ public Spinner getThresholdSpinner() {
+ return thresholdSpinner;
+ }
+
+ public Spinner getPeakInaccuracySpinner() {
+ return peakInaccuracySpinner;
+ }
+
+ public Combo getTimeUnitCombo() {
+ return timeUnitCombo;
+ }
+
+ public Spinner getDetailedFreqSpinner() {
+ return detailedFreqSpinner;
+ }
+
+ public Spinner getMaxSnapshotsSpinner() {
+ return maxSnapshotsSpinner;
+ }
+
+ public Button getAlignmentButton() {
+ return alignmentButton;
+ }
+
+ public Spinner getAlignmentSpinner() {
+ return alignmentSpinner;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifTreeLabelProvider.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifTreeLabelProvider.java
index e05da51427..c105ee5f17 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifTreeLabelProvider.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifTreeLabelProvider.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
import org.eclipse.debug.ui.DebugUITools;
@@ -18,20 +18,20 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
public class MassifTreeLabelProvider extends LabelProvider {
- @Override
- public String getText(Object element) {
- return ((MassifHeapTreeNode) element).getText();
- }
+ @Override
+ public String getText(Object element) {
+ return ((MassifHeapTreeNode) element).getText();
+ }
+
+ @Override
+ public Image getImage(Object element) {
+ Image img = null;
+ if (((MassifHeapTreeNode) element).getParent() == null) { // only show for root elements
+ img = AbstractUIPlugin.imageDescriptorFromPlugin(MassifPlugin.PLUGIN_ID, "icons/memory_view.gif").createImage(); //$NON-NLS-1$
+ } else { // stack frame
+ img = DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_STACKFRAME);
+ }
+ return img;
+ }
- @Override
- public Image getImage(Object element) {
- Image img = null;
- if (((MassifHeapTreeNode) element).getParent() == null) { // only show for root elements
- img = AbstractUIPlugin.imageDescriptorFromPlugin(MassifPlugin.PLUGIN_ID, "icons/memory_view.gif").createImage(); //$NON-NLS-1$
- } else { // stack frame
- img = DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_STACKFRAME);
- }
- return img;
- }
-
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifTreeViewer.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifTreeViewer.java
index 4254c22bde..741ac960ab 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifTreeViewer.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifTreeViewer.java
@@ -29,90 +29,90 @@ import org.eclipse.swt.widgets.Menu;
public class MassifTreeViewer {
- private IDoubleClickListener doubleClickListener;
- private ITreeContentProvider contentProvider;
- private Action expandAction;
- private Action collapseAction;
-
- private TreeViewer viewer;
-
- public MassifTreeViewer(Composite parent) {
- viewer = new TreeViewer(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL);
-
- contentProvider = new ITreeContentProvider() {
- @Override
- public Object[] getChildren(Object parentElement) {
- return ((MassifHeapTreeNode) parentElement).getChildren();
- }
-
- @Override
- public Object getParent(Object element) {
- return ((MassifHeapTreeNode) element).getParent();
- }
-
- @Override
- public boolean hasChildren(Object element) {
- MassifHeapTreeNode[] children = ((MassifHeapTreeNode) element).getChildren();
- return children != null && children.length > 0;
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- return (Object[]) inputElement;
- }
-
- @Override
- public void dispose() {}
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput,
- Object newInput) {}
-
- };
- viewer.setContentProvider(contentProvider);
-
- viewer.setLabelProvider(new MassifTreeLabelProvider());
-
- doubleClickListener = new IDoubleClickListener() {
- @Override
- public void doubleClick(DoubleClickEvent event) {
- MassifHeapTreeNode element = (MassifHeapTreeNode) ((TreeSelection) event.getSelection()).getFirstElement();
- if (element.hasSourceFile()) {
- MassifPlugin.getDefault().openEditorForNode(element);
- }
- if (contentProvider.hasChildren(element)) {
- viewer.expandToLevel(element, 1);
- }
- }
- };
- viewer.addDoubleClickListener(doubleClickListener);
-
- expandAction = new ExpandAction(viewer);
- collapseAction = new CollapseAction(viewer);
-
- MenuManager manager = new MenuManager();
- manager.addMenuListener(new IMenuListener() {
- @Override
- public void menuAboutToShow(IMenuManager manager) {
- ITreeSelection selection = (ITreeSelection) viewer.getSelection();
- MassifHeapTreeNode element = (MassifHeapTreeNode) selection.getFirstElement();
- if (contentProvider.hasChildren(element)) {
- manager.add(expandAction);
- manager.add(collapseAction);
- }
- }
- });
-
- manager.setRemoveAllWhenShown(true);
- Menu contextMenu = manager.createContextMenu(viewer.getTree());
- viewer.getControl().setMenu(contextMenu);
- }
-
- public IDoubleClickListener getDoubleClickListener() {
- return doubleClickListener;
- }
-
- public TreeViewer getViewer() {
- return viewer;
- }
+ private IDoubleClickListener doubleClickListener;
+ private ITreeContentProvider contentProvider;
+ private Action expandAction;
+ private Action collapseAction;
+
+ private TreeViewer viewer;
+
+ public MassifTreeViewer(Composite parent) {
+ viewer = new TreeViewer(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL);
+
+ contentProvider = new ITreeContentProvider() {
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ return ((MassifHeapTreeNode) parentElement).getChildren();
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ return ((MassifHeapTreeNode) element).getParent();
+ }
+
+ @Override
+ public boolean hasChildren(Object element) {
+ MassifHeapTreeNode[] children = ((MassifHeapTreeNode) element).getChildren();
+ return children != null && children.length > 0;
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ return (Object[]) inputElement;
+ }
+
+ @Override
+ public void dispose() {}
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput,
+ Object newInput) {}
+
+ };
+ viewer.setContentProvider(contentProvider);
+
+ viewer.setLabelProvider(new MassifTreeLabelProvider());
+
+ doubleClickListener = new IDoubleClickListener() {
+ @Override
+ public void doubleClick(DoubleClickEvent event) {
+ MassifHeapTreeNode element = (MassifHeapTreeNode) ((TreeSelection) event.getSelection()).getFirstElement();
+ if (element.hasSourceFile()) {
+ MassifPlugin.getDefault().openEditorForNode(element);
+ }
+ if (contentProvider.hasChildren(element)) {
+ viewer.expandToLevel(element, 1);
+ }
+ }
+ };
+ viewer.addDoubleClickListener(doubleClickListener);
+
+ expandAction = new ExpandAction(viewer);
+ collapseAction = new CollapseAction(viewer);
+
+ MenuManager manager = new MenuManager();
+ manager.addMenuListener(new IMenuListener() {
+ @Override
+ public void menuAboutToShow(IMenuManager manager) {
+ ITreeSelection selection = (ITreeSelection) viewer.getSelection();
+ MassifHeapTreeNode element = (MassifHeapTreeNode) selection.getFirstElement();
+ if (contentProvider.hasChildren(element)) {
+ manager.add(expandAction);
+ manager.add(collapseAction);
+ }
+ }
+ });
+
+ manager.setRemoveAllWhenShown(true);
+ Menu contextMenu = manager.createContextMenu(viewer.getTree());
+ viewer.getControl().setMenu(contextMenu);
+ }
+
+ public IDoubleClickListener getDoubleClickListener() {
+ return doubleClickListener;
+ }
+
+ public TreeViewer getViewer() {
+ return viewer;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifViewPart.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifViewPart.java
index 79b92eb51a..d982298187 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifViewPart.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/MassifViewPart.java
@@ -58,425 +58,425 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
public class MassifViewPart extends ViewPart implements IValgrindToolView {
- private static final String TITLE_STACKS = Messages
- .getString("MassifViewPart.Stacks"); //$NON-NLS-1$
- private static final String TITLE_EXTRA = Messages
- .getString("MassifViewPart.Extra_Heap"); //$NON-NLS-1$
- private static final String TITLE_USEFUL = Messages
- .getString("MassifViewPart.Useful_Heap"); //$NON-NLS-1$
- private static final String TITLE_TOTAL = Messages
- .getString("MassifViewPart.Total"); //$NON-NLS-1$
- private static final String TITLE_TIME = Messages
- .getString("MassifViewPart.Time"); //$NON-NLS-1$
- private static final String TITLE_NUMBER = Messages
- .getString("MassifViewPart.Snapshot"); //$NON-NLS-1$
- private static final String TREE_ACTION = MassifPlugin.PLUGIN_ID
- + ".treeAction"; //$NON-NLS-1$
- public static final String CHART_ACTION = MassifPlugin.PLUGIN_ID
- + ".chartAction"; //$NON-NLS-1$
- public static final String PID_ACTION = MassifPlugin.PLUGIN_ID
- + ".pidAction"; //$NON-NLS-1$
- public static final String SAVE_CHART_ACTION = MassifPlugin.PLUGIN_ID
- + ".saveChartAction"; //$NON-NLS-1$
-
- private MassifOutput output;
- private Integer pid;
-
- private Composite top;
- private StackLayout stackLayout;
- private TableViewer viewer;
- private MassifTreeViewer treeViewer;
- private MassifHeapTreeNode[] nodes;
- private String chartName;
-
- private static final int COLUMN_SIZE = 125;
-
- private Action treeAction;
- private MassifPidMenuAction pidAction;
- private SaveChartAction saveChartAction;
-
- private List<ChartEditorInput> chartInputs;
-
- @Override
- public void createPartControl(Composite parent) {
- chartInputs = new ArrayList<>();
-
- top = new Composite(parent, SWT.NONE);
- stackLayout = new StackLayout();
- top.setLayout(stackLayout);
- top.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- viewer = new TableViewer(top, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL
- | SWT.FULL_SELECTION);
-
- Table table = viewer.getTable();
- table.setLayoutData(new GridData(GridData.FILL_BOTH));
-
-
- String[] columnTitles = { TITLE_NUMBER, TITLE_TIME, TITLE_TOTAL,
- TITLE_USEFUL, TITLE_EXTRA, TITLE_STACKS };
-
- for (int i = 0; i < columnTitles.length; i++) {
- TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
- column.getColumn().setText(columnTitles[i]);
- column.getColumn().setWidth(COLUMN_SIZE);
- column.getColumn().setResizable(true);
- column.getColumn().addSelectionListener(getHeaderListener());
- }
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
-
- viewer.setContentProvider(new ArrayContentProvider());
- viewer.setLabelProvider(new MassifLabelProvider());
-
- treeViewer = new MassifTreeViewer(top);
- treeViewer.getViewer().getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
-
- viewer.addDoubleClickListener(new IDoubleClickListener() {
- @Override
- public void doubleClick(DoubleClickEvent event) {
- MassifSnapshot snapshot = (MassifSnapshot) ((IStructuredSelection) event
- .getSelection()).getFirstElement();
- if (snapshot.getType() != SnapshotType.EMPTY) {
- treeAction.setChecked(true);
- setTopControl(treeViewer.getViewer().getControl());
- treeViewer.getViewer().setSelection(new StructuredSelection(snapshot
- .getRoot()), true);
- treeViewer.getViewer().expandToLevel(snapshot.getRoot(),
- AbstractTreeViewer.ALL_LEVELS);
- }
- }
- });
-
- stackLayout.topControl = viewer.getControl();
- top.layout();
- }
-
- private String getUnitString(MassifSnapshot[] snapshots) {
- String result;
- MassifSnapshot snapshot = snapshots[0];
- switch (snapshot.getUnit()) {
- case BYTES:
- result = "B"; //$NON-NLS-1$
- break;
- case INSTRUCTIONS:
- result = "i"; //$NON-NLS-1$
- break;
- default:
- result = "ms"; //$NON-NLS-1$
- break;
- }
- return result;
- }
-
- private SelectionListener getHeaderListener() {
- return new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- TableColumn column = (TableColumn) e.widget;
- Table table = viewer.getTable();
- if (column.equals(table.getSortColumn())) {
- int direction = table.getSortDirection() == SWT.UP ? SWT.DOWN
- : SWT.UP;
- table.setSortDirection(direction);
- } else {
- table.setSortDirection(SWT.UP);
- }
- table.setSortColumn(column);
- viewer.setComparator(new ViewerComparator() {
- @Override
- public int compare(Viewer viewer, Object o1, Object o2) {
- Table table = ((TableViewer) viewer).getTable();
- int direction = table.getSortDirection();
- MassifSnapshot s1 = (MassifSnapshot) o1;
- MassifSnapshot s2 = (MassifSnapshot) o2;
- long result;
- TableColumn column = table.getSortColumn();
- if (column.getText().equals(TITLE_NUMBER)) {
- result = s1.getNumber() - s2.getNumber();
- } else if (column.getText().startsWith(TITLE_TIME)) {
- result = s1.getTime() - s2.getTime();
- } else if (column.getText().equals(TITLE_TOTAL)) {
- result = s1.getTotal() - s2.getTotal();
- } else if (column.getText().equals(TITLE_USEFUL)) {
- result = s1.getHeapBytes() - s2.getHeapBytes();
- } else if (column.getText().equals(TITLE_EXTRA)) {
- result = s1.getHeapExtra() - s2.getHeapExtra();
- } else {
- result = s1.getStacks() - s2.getStacks();
- }
-
- // ascending / descending
- result = direction == SWT.UP ? result : -result;
-
- // overflow check
- if (result > Integer.MAX_VALUE) {
- result = Integer.MAX_VALUE;
- } else if (result < Integer.MIN_VALUE) {
- result = Integer.MIN_VALUE;
- }
- return (int) result;
- }
- });
- }
- };
- }
-
- @Override
- public IAction[] getToolbarActions() {
- pidAction = new MassifPidMenuAction(this);
- pidAction.setId(PID_ACTION);
-
- Action chartAction = new Action(
- Messages.getString("MassifViewPart.Display_Heap_Allocation"), IAction.AS_PUSH_BUTTON) { //$NON-NLS-1$
- @Override
- public void run() {
- ChartEditorInput input = getChartInput(pid);
- if (input != null) {
- displayChart(input);
- }
- }
- };
- chartAction.setId(CHART_ACTION);
- chartAction.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
- MassifPlugin.PLUGIN_ID, "icons/linecharticon.gif")); //$NON-NLS-1$
- chartAction.setToolTipText(Messages
- .getString("MassifViewPart.Display_Heap_Allocation")); //$NON-NLS-1$
-
- saveChartAction = new SaveChartAction();
- saveChartAction.setId(SAVE_CHART_ACTION);
-
- treeAction = new Action(
- Messages.getString("MassifViewPart.Show_Heap_Tree"), IAction.AS_CHECK_BOX) { //$NON-NLS-1$
- @Override
- public void run() {
- if (isChecked()) {
- stackLayout.topControl = treeViewer.getViewer().getControl();
- top.layout();
- } else {
- stackLayout.topControl = viewer.getControl();
- top.layout();
- }
- }
- };
- treeAction.setId(TREE_ACTION);
- treeAction.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
- MassifPlugin.PLUGIN_ID, "icons/call_hierarchy.gif")); //$NON-NLS-1$
- treeAction.setToolTipText(Messages
- .getString("MassifViewPart.Show_Heap_Tree")); //$NON-NLS-1$
-
- return new IAction[] { pidAction, chartAction, saveChartAction, treeAction };
- }
-
- private void createChart(MassifSnapshot[] snapshots) {
- String title = chartName + " [PID: " + pid + "]"; //$NON-NLS-1$//$NON-NLS-2$
- HeapChart chart = new HeapChart(snapshots, title);
-
- String name = getInputName(title);
- ChartEditorInput input = new ChartEditorInput(chart, this, name, pid);
- chartInputs.add(input);
-
- // open the editor
- displayChart(input);
- }
-
- private void displayChart(final ChartEditorInput chartInput) {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- try {
- IWorkbenchPage page = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage();
- page.openEditor(chartInput, MassifPlugin.EDITOR_ID);
- } catch (PartInitException e) {
- e.printStackTrace();
- }
- }
- });
- saveChartAction.setChart(chartInput.getChart().getChartControl(), chartInput.getName());
- }
-
- private String getInputName(String description) {
- String launchName;
- try {
- launchName = description.substring(0, description
- .indexOf("[massif")); //$NON-NLS-1$
- }
- catch(IndexOutOfBoundsException e) {
- launchName = "(No chart title)"; //$NON-NLS-1$
- }
- return launchName.trim();
- }
-
- @Override
- public void setFocus() {
- viewer.getTable().setFocus();
- }
-
- @Override
- public void refreshView() {
- if (output != null && pid != null) {
- saveChartAction.setChart(null);
- MassifSnapshot[] snapshots = output.getSnapshots(pid);
- pidAction.setPids(output.getPids());
- if (snapshots != null) {
- viewer.setInput(snapshots);
-
- String timeWithUnit = TITLE_TIME + " (" + getUnitString(snapshots) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
- for (TableColumn column : viewer.getTable().getColumns()) {
- if (column.getText().startsWith(TITLE_TIME)) {
- column.setText(timeWithUnit);
- }
- viewer.getTable().layout(true);
- }
- MassifSnapshot[] detailed = getDetailed(snapshots);
- nodes = new MassifHeapTreeNode[detailed.length];
- for (int i = 0; i < detailed.length; i++) {
- nodes[i] = detailed[i].getRoot();
- }
- treeViewer.getViewer().setInput(nodes);
-
- // create and display chart
- if (snapshots.length > 0) {
- ChartEditorInput input = getChartInput(pid);
- if (input == null) {
- createChart(snapshots);
- }
- else {
- displayChart(input);
- }
- }
- }
- }
- }
-
- @Override
- public void dispose() {
- // Close all chart editors to keep Valgrind output consistent throughout workbench
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- if (page != null) {
- for (IEditorInput input : chartInputs) {
- IEditorPart part = page.findEditor(input);
- if (part != null) {
- page.closeEditor(part, false);
- }
- }
- }
- super.dispose();
- }
-
- public void setTopControl(Control control) {
- stackLayout.topControl = control;
- top.layout(true);
- }
-
- public void setOutput(MassifOutput output) {
- this.output = output;
- }
-
- public MassifOutput getOutput() {
- return output;
- }
-
- public void setPid(Integer pid) {
- this.pid = pid;
- }
-
- public Integer getPid() {
- return pid;
- }
-
- public MassifSnapshot[] getSnapshots() {
- return output != null && pid != null ? output.getSnapshots(pid) : null;
- }
-
- public TableViewer getTableViewer() {
- return viewer;
- }
-
- public MassifTreeViewer getTreeViewer() {
- return treeViewer;
- }
-
- private static class MassifLabelProvider extends LabelProvider implements
- ITableLabelProvider, IFontProvider {
-
- @Override
- public Image getColumnImage(Object element, int columnIndex) {
- Image image = null;
- if (columnIndex == 0) {
- MassifSnapshot snapshot = (MassifSnapshot) element;
- switch (snapshot.getType()) {
- case EMPTY:
- break;
- case PEAK:
- case DETAILED:
- image = AbstractUIPlugin
- .imageDescriptorFromPlugin(MassifPlugin.PLUGIN_ID,
- "icons/call_hierarchy.gif").createImage(); //$NON-NLS-1$
- }
- }
- return image;
- }
-
- @Override
- public String getColumnText(Object element, int columnIndex) {
- MassifSnapshot snapshot = (MassifSnapshot) element;
- DecimalFormat df = new DecimalFormat("#,##0"); //$NON-NLS-1$
- switch (columnIndex) {
- case 0:
- return df.format(snapshot.getNumber());
- case 1:
- return df.format(snapshot.getTime());
- case 2:
- return df.format(snapshot.getTotal());
- case 3:
- return df.format(snapshot.getHeapBytes());
- case 4:
- return df.format(snapshot.getHeapExtra());
- default:
- return df.format(snapshot.getStacks());
- }
- }
-
- @Override
- public Font getFont(Object element) {
- Font font = null;
- MassifSnapshot snapshot = (MassifSnapshot) element;
- switch (snapshot.getType()) {
- case EMPTY:
- case DETAILED:
- break;
- case PEAK:
- font = JFaceResources.getFontRegistry().getBold(
- JFaceResources.DIALOG_FONT);
- }
- return font;
- }
- }
-
- public void setChartName(String chartName) {
- this.chartName = chartName;
- }
-
- private MassifSnapshot[] getDetailed(MassifSnapshot[] snapshots) {
- ArrayList<MassifSnapshot> list = new ArrayList<>();
- for (MassifSnapshot snapshot : snapshots) {
- if (snapshot.getType() != SnapshotType.EMPTY) {
- list.add(snapshot);
- }
- }
- return list.toArray(new MassifSnapshot[list.size()]);
- }
-
- private ChartEditorInput getChartInput(Integer pid) {
- ChartEditorInput result = null;
- for (int i = 0; i < chartInputs.size(); i++) {
- ChartEditorInput input = chartInputs.get(i);
- if (input.getPid().equals(pid)) {
- result = input;
- }
- }
- return result;
- }
+ private static final String TITLE_STACKS = Messages
+ .getString("MassifViewPart.Stacks"); //$NON-NLS-1$
+ private static final String TITLE_EXTRA = Messages
+ .getString("MassifViewPart.Extra_Heap"); //$NON-NLS-1$
+ private static final String TITLE_USEFUL = Messages
+ .getString("MassifViewPart.Useful_Heap"); //$NON-NLS-1$
+ private static final String TITLE_TOTAL = Messages
+ .getString("MassifViewPart.Total"); //$NON-NLS-1$
+ private static final String TITLE_TIME = Messages
+ .getString("MassifViewPart.Time"); //$NON-NLS-1$
+ private static final String TITLE_NUMBER = Messages
+ .getString("MassifViewPart.Snapshot"); //$NON-NLS-1$
+ private static final String TREE_ACTION = MassifPlugin.PLUGIN_ID
+ + ".treeAction"; //$NON-NLS-1$
+ public static final String CHART_ACTION = MassifPlugin.PLUGIN_ID
+ + ".chartAction"; //$NON-NLS-1$
+ public static final String PID_ACTION = MassifPlugin.PLUGIN_ID
+ + ".pidAction"; //$NON-NLS-1$
+ public static final String SAVE_CHART_ACTION = MassifPlugin.PLUGIN_ID
+ + ".saveChartAction"; //$NON-NLS-1$
+
+ private MassifOutput output;
+ private Integer pid;
+
+ private Composite top;
+ private StackLayout stackLayout;
+ private TableViewer viewer;
+ private MassifTreeViewer treeViewer;
+ private MassifHeapTreeNode[] nodes;
+ private String chartName;
+
+ private static final int COLUMN_SIZE = 125;
+
+ private Action treeAction;
+ private MassifPidMenuAction pidAction;
+ private SaveChartAction saveChartAction;
+
+ private List<ChartEditorInput> chartInputs;
+
+ @Override
+ public void createPartControl(Composite parent) {
+ chartInputs = new ArrayList<>();
+
+ top = new Composite(parent, SWT.NONE);
+ stackLayout = new StackLayout();
+ top.setLayout(stackLayout);
+ top.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ viewer = new TableViewer(top, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL
+ | SWT.FULL_SELECTION);
+
+ Table table = viewer.getTable();
+ table.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+
+ String[] columnTitles = { TITLE_NUMBER, TITLE_TIME, TITLE_TOTAL,
+ TITLE_USEFUL, TITLE_EXTRA, TITLE_STACKS };
+
+ for (int i = 0; i < columnTitles.length; i++) {
+ TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
+ column.getColumn().setText(columnTitles[i]);
+ column.getColumn().setWidth(COLUMN_SIZE);
+ column.getColumn().setResizable(true);
+ column.getColumn().addSelectionListener(getHeaderListener());
+ }
+ table.setHeaderVisible(true);
+ table.setLinesVisible(true);
+
+ viewer.setContentProvider(new ArrayContentProvider());
+ viewer.setLabelProvider(new MassifLabelProvider());
+
+ treeViewer = new MassifTreeViewer(top);
+ treeViewer.getViewer().getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ viewer.addDoubleClickListener(new IDoubleClickListener() {
+ @Override
+ public void doubleClick(DoubleClickEvent event) {
+ MassifSnapshot snapshot = (MassifSnapshot) ((IStructuredSelection) event
+ .getSelection()).getFirstElement();
+ if (snapshot.getType() != SnapshotType.EMPTY) {
+ treeAction.setChecked(true);
+ setTopControl(treeViewer.getViewer().getControl());
+ treeViewer.getViewer().setSelection(new StructuredSelection(snapshot
+ .getRoot()), true);
+ treeViewer.getViewer().expandToLevel(snapshot.getRoot(),
+ AbstractTreeViewer.ALL_LEVELS);
+ }
+ }
+ });
+
+ stackLayout.topControl = viewer.getControl();
+ top.layout();
+ }
+
+ private String getUnitString(MassifSnapshot[] snapshots) {
+ String result;
+ MassifSnapshot snapshot = snapshots[0];
+ switch (snapshot.getUnit()) {
+ case BYTES:
+ result = "B"; //$NON-NLS-1$
+ break;
+ case INSTRUCTIONS:
+ result = "i"; //$NON-NLS-1$
+ break;
+ default:
+ result = "ms"; //$NON-NLS-1$
+ break;
+ }
+ return result;
+ }
+
+ private SelectionListener getHeaderListener() {
+ return new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ TableColumn column = (TableColumn) e.widget;
+ Table table = viewer.getTable();
+ if (column.equals(table.getSortColumn())) {
+ int direction = table.getSortDirection() == SWT.UP ? SWT.DOWN
+ : SWT.UP;
+ table.setSortDirection(direction);
+ } else {
+ table.setSortDirection(SWT.UP);
+ }
+ table.setSortColumn(column);
+ viewer.setComparator(new ViewerComparator() {
+ @Override
+ public int compare(Viewer viewer, Object o1, Object o2) {
+ Table table = ((TableViewer) viewer).getTable();
+ int direction = table.getSortDirection();
+ MassifSnapshot s1 = (MassifSnapshot) o1;
+ MassifSnapshot s2 = (MassifSnapshot) o2;
+ long result;
+ TableColumn column = table.getSortColumn();
+ if (column.getText().equals(TITLE_NUMBER)) {
+ result = s1.getNumber() - s2.getNumber();
+ } else if (column.getText().startsWith(TITLE_TIME)) {
+ result = s1.getTime() - s2.getTime();
+ } else if (column.getText().equals(TITLE_TOTAL)) {
+ result = s1.getTotal() - s2.getTotal();
+ } else if (column.getText().equals(TITLE_USEFUL)) {
+ result = s1.getHeapBytes() - s2.getHeapBytes();
+ } else if (column.getText().equals(TITLE_EXTRA)) {
+ result = s1.getHeapExtra() - s2.getHeapExtra();
+ } else {
+ result = s1.getStacks() - s2.getStacks();
+ }
+
+ // ascending / descending
+ result = direction == SWT.UP ? result : -result;
+
+ // overflow check
+ if (result > Integer.MAX_VALUE) {
+ result = Integer.MAX_VALUE;
+ } else if (result < Integer.MIN_VALUE) {
+ result = Integer.MIN_VALUE;
+ }
+ return (int) result;
+ }
+ });
+ }
+ };
+ }
+
+ @Override
+ public IAction[] getToolbarActions() {
+ pidAction = new MassifPidMenuAction(this);
+ pidAction.setId(PID_ACTION);
+
+ Action chartAction = new Action(
+ Messages.getString("MassifViewPart.Display_Heap_Allocation"), IAction.AS_PUSH_BUTTON) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ ChartEditorInput input = getChartInput(pid);
+ if (input != null) {
+ displayChart(input);
+ }
+ }
+ };
+ chartAction.setId(CHART_ACTION);
+ chartAction.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
+ MassifPlugin.PLUGIN_ID, "icons/linecharticon.gif")); //$NON-NLS-1$
+ chartAction.setToolTipText(Messages
+ .getString("MassifViewPart.Display_Heap_Allocation")); //$NON-NLS-1$
+
+ saveChartAction = new SaveChartAction();
+ saveChartAction.setId(SAVE_CHART_ACTION);
+
+ treeAction = new Action(
+ Messages.getString("MassifViewPart.Show_Heap_Tree"), IAction.AS_CHECK_BOX) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ if (isChecked()) {
+ stackLayout.topControl = treeViewer.getViewer().getControl();
+ top.layout();
+ } else {
+ stackLayout.topControl = viewer.getControl();
+ top.layout();
+ }
+ }
+ };
+ treeAction.setId(TREE_ACTION);
+ treeAction.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
+ MassifPlugin.PLUGIN_ID, "icons/call_hierarchy.gif")); //$NON-NLS-1$
+ treeAction.setToolTipText(Messages
+ .getString("MassifViewPart.Show_Heap_Tree")); //$NON-NLS-1$
+
+ return new IAction[] { pidAction, chartAction, saveChartAction, treeAction };
+ }
+
+ private void createChart(MassifSnapshot[] snapshots) {
+ String title = chartName + " [PID: " + pid + "]"; //$NON-NLS-1$//$NON-NLS-2$
+ HeapChart chart = new HeapChart(snapshots, title);
+
+ String name = getInputName(title);
+ ChartEditorInput input = new ChartEditorInput(chart, this, name, pid);
+ chartInputs.add(input);
+
+ // open the editor
+ displayChart(input);
+ }
+
+ private void displayChart(final ChartEditorInput chartInput) {
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ IWorkbenchPage page = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage();
+ page.openEditor(chartInput, MassifPlugin.EDITOR_ID);
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+ saveChartAction.setChart(chartInput.getChart().getChartControl(), chartInput.getName());
+ }
+
+ private String getInputName(String description) {
+ String launchName;
+ try {
+ launchName = description.substring(0, description
+ .indexOf("[massif")); //$NON-NLS-1$
+ }
+ catch(IndexOutOfBoundsException e) {
+ launchName = "(No chart title)"; //$NON-NLS-1$
+ }
+ return launchName.trim();
+ }
+
+ @Override
+ public void setFocus() {
+ viewer.getTable().setFocus();
+ }
+
+ @Override
+ public void refreshView() {
+ if (output != null && pid != null) {
+ saveChartAction.setChart(null);
+ MassifSnapshot[] snapshots = output.getSnapshots(pid);
+ pidAction.setPids(output.getPids());
+ if (snapshots != null) {
+ viewer.setInput(snapshots);
+
+ String timeWithUnit = TITLE_TIME + " (" + getUnitString(snapshots) + ")"; //$NON-NLS-1$ //$NON-NLS-2$
+ for (TableColumn column : viewer.getTable().getColumns()) {
+ if (column.getText().startsWith(TITLE_TIME)) {
+ column.setText(timeWithUnit);
+ }
+ viewer.getTable().layout(true);
+ }
+ MassifSnapshot[] detailed = getDetailed(snapshots);
+ nodes = new MassifHeapTreeNode[detailed.length];
+ for (int i = 0; i < detailed.length; i++) {
+ nodes[i] = detailed[i].getRoot();
+ }
+ treeViewer.getViewer().setInput(nodes);
+
+ // create and display chart
+ if (snapshots.length > 0) {
+ ChartEditorInput input = getChartInput(pid);
+ if (input == null) {
+ createChart(snapshots);
+ }
+ else {
+ displayChart(input);
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public void dispose() {
+ // Close all chart editors to keep Valgrind output consistent throughout workbench
+ IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
+ if (page != null) {
+ for (IEditorInput input : chartInputs) {
+ IEditorPart part = page.findEditor(input);
+ if (part != null) {
+ page.closeEditor(part, false);
+ }
+ }
+ }
+ super.dispose();
+ }
+
+ public void setTopControl(Control control) {
+ stackLayout.topControl = control;
+ top.layout(true);
+ }
+
+ public void setOutput(MassifOutput output) {
+ this.output = output;
+ }
+
+ public MassifOutput getOutput() {
+ return output;
+ }
+
+ public void setPid(Integer pid) {
+ this.pid = pid;
+ }
+
+ public Integer getPid() {
+ return pid;
+ }
+
+ public MassifSnapshot[] getSnapshots() {
+ return output != null && pid != null ? output.getSnapshots(pid) : null;
+ }
+
+ public TableViewer getTableViewer() {
+ return viewer;
+ }
+
+ public MassifTreeViewer getTreeViewer() {
+ return treeViewer;
+ }
+
+ private static class MassifLabelProvider extends LabelProvider implements
+ ITableLabelProvider, IFontProvider {
+
+ @Override
+ public Image getColumnImage(Object element, int columnIndex) {
+ Image image = null;
+ if (columnIndex == 0) {
+ MassifSnapshot snapshot = (MassifSnapshot) element;
+ switch (snapshot.getType()) {
+ case EMPTY:
+ break;
+ case PEAK:
+ case DETAILED:
+ image = AbstractUIPlugin
+ .imageDescriptorFromPlugin(MassifPlugin.PLUGIN_ID,
+ "icons/call_hierarchy.gif").createImage(); //$NON-NLS-1$
+ }
+ }
+ return image;
+ }
+
+ @Override
+ public String getColumnText(Object element, int columnIndex) {
+ MassifSnapshot snapshot = (MassifSnapshot) element;
+ DecimalFormat df = new DecimalFormat("#,##0"); //$NON-NLS-1$
+ switch (columnIndex) {
+ case 0:
+ return df.format(snapshot.getNumber());
+ case 1:
+ return df.format(snapshot.getTime());
+ case 2:
+ return df.format(snapshot.getTotal());
+ case 3:
+ return df.format(snapshot.getHeapBytes());
+ case 4:
+ return df.format(snapshot.getHeapExtra());
+ default:
+ return df.format(snapshot.getStacks());
+ }
+ }
+
+ @Override
+ public Font getFont(Object element) {
+ Font font = null;
+ MassifSnapshot snapshot = (MassifSnapshot) element;
+ switch (snapshot.getType()) {
+ case EMPTY:
+ case DETAILED:
+ break;
+ case PEAK:
+ font = JFaceResources.getFontRegistry().getBold(
+ JFaceResources.DIALOG_FONT);
+ }
+ return font;
+ }
+ }
+
+ public void setChartName(String chartName) {
+ this.chartName = chartName;
+ }
+
+ private MassifSnapshot[] getDetailed(MassifSnapshot[] snapshots) {
+ ArrayList<MassifSnapshot> list = new ArrayList<>();
+ for (MassifSnapshot snapshot : snapshots) {
+ if (snapshot.getType() != SnapshotType.EMPTY) {
+ list.add(snapshot);
+ }
+ }
+ return list.toArray(new MassifSnapshot[list.size()]);
+ }
+
+ private ChartEditorInput getChartInput(Integer pid) {
+ ChartEditorInput result = null;
+ for (int i = 0; i < chartInputs.size(); i++) {
+ ChartEditorInput input = chartInputs.get(i);
+ if (input.getPid().equals(pid)) {
+ result = input;
+ }
+ }
+ return result;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/Messages.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/Messages.java
index 3564bd8457..096eb08050 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/Messages.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/Messages.java
@@ -7,26 +7,26 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.massif.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.massif.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartEditor.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartEditor.java
index ad9f2d8504..beb27a9be0 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartEditor.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartEditor.java
@@ -44,197 +44,197 @@ import org.swtchart.LineStyle;
import org.swtchart.Range;
public class ChartEditor extends EditorPart {
- private Chart control;
-
- @Override
- public void doSave(IProgressMonitor monitor) {
- }
-
- @Override
- public void doSaveAs() {
- }
-
- @Override
- public void init(IEditorSite site, IEditorInput input)
- throws PartInitException {
- if (input instanceof ChartEditorInput) {
- setInput(input);
- setSite(site);
- setPartName(NLS.bind(Messages.getString("ChartEditor.Heap_Chart"), input.getName())); //$NON-NLS-1$
- }
- else {
- throw new PartInitException(NLS.bind(Messages.getString("ChartEditor.Editor_input_must_be"), ChartEditorInput.class.getName())); //$NON-NLS-1$
- }
- }
-
- @Override
- public boolean isDirty() {
- return false;
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- @Override
- public void createPartControl(Composite parent) {
- final ChartEditorInput input = (ChartEditorInput) getEditorInput();
- final HeapChart heapChart = input.getChart();
- control = new Chart(parent, SWT.FILL);
- heapChart.setChartControl(control);
-
- final Color LIGHTYELLOW = new Color(Display.getDefault(), 255, 255, 225);
- final Color WHITE = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
- final Color BLACK = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
- final Color RED = Display.getDefault().getSystemColor(SWT.COLOR_RED);
- final Color ORANGE = new Color(Display.getDefault(), 255, 165, 0);
- final Color GREEN = Display.getDefault().getSystemColor(SWT.COLOR_GREEN);
- final Color DARK_BLUE = new Color(Display.getDefault(), 64, 128, 128);
- final int TICK_GAP = 40;
-
- control.setBackground(WHITE);
- control.setBackgroundInPlotArea(LIGHTYELLOW);
-
- FontData fd = JFaceResources.getDialogFont().getFontData()[0];
- fd.setStyle(SWT.BOLD);
-
- Font font = new Font(Display.getDefault(), fd);
- fd.setHeight(fd.getHeight() + 2);
- Font titleFont = new Font(Display.getDefault(), fd);
-
- ITitle title = control.getTitle();
- title.setFont(titleFont);
- title.setForeground(BLACK);
- title.setText(heapChart.title);
-
- IAxis xAxis = control.getAxisSet().getXAxis(0);
- xAxis.getGrid().setStyle(LineStyle.NONE);
- xAxis.getTick().setForeground(BLACK);
- ITitle xTitle = xAxis.getTitle();
- xTitle.setFont(font);
- xTitle.setForeground(BLACK);
- xTitle.setText(heapChart.xUnits);
-
- IAxis yAxis = control.getAxisSet().getYAxis(0);
- yAxis.getGrid().setStyle(LineStyle.SOLID);
- yAxis.getTick().setForeground(BLACK);
- yAxis.getTick().setTickMarkStepHint(TICK_GAP);
- ITitle yTitle = yAxis.getTitle();
- yTitle.setFont(font);
- yTitle.setText(heapChart.yUnits);
- yTitle.setForeground(BLACK);
-
- control.getLegend().setPosition(SWT.BOTTOM);
-
- // data
- final ILineSeries lsUseful = (ILineSeries) control.getSeriesSet().
- createSeries(SeriesType.LINE, Messages.getString("HeapChart.Useful_Heap")); //$NON-NLS-1$;
- lsUseful.setXSeries(heapChart.time);
- lsUseful.setYSeries(heapChart.dataUseful);
- lsUseful.setSymbolType(PlotSymbolType.DIAMOND);
- lsUseful.setSymbolColor(RED);
- lsUseful.setLineColor(RED);
-
- final ILineSeries lsExtra = (ILineSeries) control.getSeriesSet().
- createSeries(SeriesType.LINE, Messages.getString("HeapChart.Extra_Heap")); //$NON-NLS-1$;
- lsExtra.setXSeries(heapChart.time);
- lsExtra.setYSeries(heapChart.dataExtra);
- lsExtra.setSymbolType(PlotSymbolType.DIAMOND);
- lsExtra.setSymbolColor(ORANGE);
- lsExtra.setLineColor(ORANGE);
-
- if (heapChart.dataStacks != null){
- final ILineSeries lsStack = (ILineSeries) control.getSeriesSet().
- createSeries(SeriesType.LINE, Messages.getString("HeapChart.Stacks")); //$NON-NLS-1$;
- lsStack.setXSeries(heapChart.time);
- lsStack.setYSeries(heapChart.dataStacks);
- lsStack.setSymbolType(PlotSymbolType.DIAMOND);
- lsStack.setSymbolColor(DARK_BLUE);
- lsStack.setLineColor(DARK_BLUE);
- }
-
- final ILineSeries lsTotal = (ILineSeries) control.getSeriesSet().
- createSeries(SeriesType.LINE, Messages.getString("HeapChart.Total_Heap")); //$NON-NLS-1$;
- lsTotal.setXSeries(heapChart.time);
- lsTotal.setYSeries(heapChart.dataTotal);
- lsTotal.setSymbolType(PlotSymbolType.DIAMOND);
- lsTotal.setSymbolColor(GREEN);
- lsTotal.setLineColor(GREEN);
-
- // adjust axes
- control.getAxisSet().adjustRange();
-
- IAxisSet axisSet = control.getAxisSet();
- Range xRange = axisSet.getXAxis(0).getRange();
- Range yRange = axisSet.getYAxis(0).getRange();
-
- double xExtra = 0.05 * (xRange.upper - xRange.lower);
- double yExtra = 0.05 * (yRange.upper - yRange.lower);
-
- axisSet.getXAxis(0).setRange(new Range(xRange.lower, xRange.upper + xExtra));
- axisSet.getYAxis(0).setRange(new Range(yRange.lower, yRange.upper + yExtra));
-
- // listeners
- control.getPlotArea().addMouseListener(new MouseAdapter() {
-
- @Override
- public void mouseDown(MouseEvent e) {
- showView();
- TableViewer viewer = input.getView().getTableViewer();
- input.getView().setTopControl(viewer.getControl());
-
- Point p = new Point(e.x, e.y);
-
- int closest = 0;
- double d1, d2, d3, currMin;
- double globalMin = Double.MAX_VALUE;
- for (int i = 0; i < heapChart.time.length; i++){
- // get distance from click event to data points for the given index
- d1 = distance(lsUseful.getPixelCoordinates(i), p);
- d2 = distance(lsExtra.getPixelCoordinates(i), p);
- d3 = distance(lsTotal.getPixelCoordinates(i), p);
- // find the closest data point to the click event
- currMin = Math.min(Math.min(d1, d2), d3);
- if (currMin < globalMin){
- closest = i;
- globalMin = currMin;
- }
- }
-
- MassifSnapshot snapshot = (MassifSnapshot) viewer.getElementAt(closest);
- viewer.setSelection(new StructuredSelection(snapshot), true);
-
- if (e.count == 2 && snapshot.isDetailed()) {
- ChartLocationsDialog dialog = new ChartLocationsDialog(Display.getCurrent().getActiveShell());
- dialog.setInput(snapshot);
-
- if (dialog.open() == Window.OK) {
- dialog.openEditorForResult();
- }
- }
-
- }
- });
-
- }
-
- public Chart getControl() {
- return control;
- }
-
- @Override
- public void setFocus() {
- if (control != null) {
- control.setFocus();
- }
- }
-
- @Override
- public void dispose() {
- super.dispose();
- control.dispose();
- }
+ private Chart control;
+
+ @Override
+ public void doSave(IProgressMonitor monitor) {
+ }
+
+ @Override
+ public void doSaveAs() {
+ }
+
+ @Override
+ public void init(IEditorSite site, IEditorInput input)
+ throws PartInitException {
+ if (input instanceof ChartEditorInput) {
+ setInput(input);
+ setSite(site);
+ setPartName(NLS.bind(Messages.getString("ChartEditor.Heap_Chart"), input.getName())); //$NON-NLS-1$
+ }
+ else {
+ throw new PartInitException(NLS.bind(Messages.getString("ChartEditor.Editor_input_must_be"), ChartEditorInput.class.getName())); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public boolean isDirty() {
+ return false;
+ }
+
+ @Override
+ public boolean isSaveAsAllowed() {
+ return false;
+ }
+
+ @Override
+ public void createPartControl(Composite parent) {
+ final ChartEditorInput input = (ChartEditorInput) getEditorInput();
+ final HeapChart heapChart = input.getChart();
+ control = new Chart(parent, SWT.FILL);
+ heapChart.setChartControl(control);
+
+ final Color LIGHTYELLOW = new Color(Display.getDefault(), 255, 255, 225);
+ final Color WHITE = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+ final Color BLACK = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
+ final Color RED = Display.getDefault().getSystemColor(SWT.COLOR_RED);
+ final Color ORANGE = new Color(Display.getDefault(), 255, 165, 0);
+ final Color GREEN = Display.getDefault().getSystemColor(SWT.COLOR_GREEN);
+ final Color DARK_BLUE = new Color(Display.getDefault(), 64, 128, 128);
+ final int TICK_GAP = 40;
+
+ control.setBackground(WHITE);
+ control.setBackgroundInPlotArea(LIGHTYELLOW);
+
+ FontData fd = JFaceResources.getDialogFont().getFontData()[0];
+ fd.setStyle(SWT.BOLD);
+
+ Font font = new Font(Display.getDefault(), fd);
+ fd.setHeight(fd.getHeight() + 2);
+ Font titleFont = new Font(Display.getDefault(), fd);
+
+ ITitle title = control.getTitle();
+ title.setFont(titleFont);
+ title.setForeground(BLACK);
+ title.setText(heapChart.title);
+
+ IAxis xAxis = control.getAxisSet().getXAxis(0);
+ xAxis.getGrid().setStyle(LineStyle.NONE);
+ xAxis.getTick().setForeground(BLACK);
+ ITitle xTitle = xAxis.getTitle();
+ xTitle.setFont(font);
+ xTitle.setForeground(BLACK);
+ xTitle.setText(heapChart.xUnits);
+
+ IAxis yAxis = control.getAxisSet().getYAxis(0);
+ yAxis.getGrid().setStyle(LineStyle.SOLID);
+ yAxis.getTick().setForeground(BLACK);
+ yAxis.getTick().setTickMarkStepHint(TICK_GAP);
+ ITitle yTitle = yAxis.getTitle();
+ yTitle.setFont(font);
+ yTitle.setText(heapChart.yUnits);
+ yTitle.setForeground(BLACK);
+
+ control.getLegend().setPosition(SWT.BOTTOM);
+
+ // data
+ final ILineSeries lsUseful = (ILineSeries) control.getSeriesSet().
+ createSeries(SeriesType.LINE, Messages.getString("HeapChart.Useful_Heap")); //$NON-NLS-1$;
+ lsUseful.setXSeries(heapChart.time);
+ lsUseful.setYSeries(heapChart.dataUseful);
+ lsUseful.setSymbolType(PlotSymbolType.DIAMOND);
+ lsUseful.setSymbolColor(RED);
+ lsUseful.setLineColor(RED);
+
+ final ILineSeries lsExtra = (ILineSeries) control.getSeriesSet().
+ createSeries(SeriesType.LINE, Messages.getString("HeapChart.Extra_Heap")); //$NON-NLS-1$;
+ lsExtra.setXSeries(heapChart.time);
+ lsExtra.setYSeries(heapChart.dataExtra);
+ lsExtra.setSymbolType(PlotSymbolType.DIAMOND);
+ lsExtra.setSymbolColor(ORANGE);
+ lsExtra.setLineColor(ORANGE);
+
+ if (heapChart.dataStacks != null){
+ final ILineSeries lsStack = (ILineSeries) control.getSeriesSet().
+ createSeries(SeriesType.LINE, Messages.getString("HeapChart.Stacks")); //$NON-NLS-1$;
+ lsStack.setXSeries(heapChart.time);
+ lsStack.setYSeries(heapChart.dataStacks);
+ lsStack.setSymbolType(PlotSymbolType.DIAMOND);
+ lsStack.setSymbolColor(DARK_BLUE);
+ lsStack.setLineColor(DARK_BLUE);
+ }
+
+ final ILineSeries lsTotal = (ILineSeries) control.getSeriesSet().
+ createSeries(SeriesType.LINE, Messages.getString("HeapChart.Total_Heap")); //$NON-NLS-1$;
+ lsTotal.setXSeries(heapChart.time);
+ lsTotal.setYSeries(heapChart.dataTotal);
+ lsTotal.setSymbolType(PlotSymbolType.DIAMOND);
+ lsTotal.setSymbolColor(GREEN);
+ lsTotal.setLineColor(GREEN);
+
+ // adjust axes
+ control.getAxisSet().adjustRange();
+
+ IAxisSet axisSet = control.getAxisSet();
+ Range xRange = axisSet.getXAxis(0).getRange();
+ Range yRange = axisSet.getYAxis(0).getRange();
+
+ double xExtra = 0.05 * (xRange.upper - xRange.lower);
+ double yExtra = 0.05 * (yRange.upper - yRange.lower);
+
+ axisSet.getXAxis(0).setRange(new Range(xRange.lower, xRange.upper + xExtra));
+ axisSet.getYAxis(0).setRange(new Range(yRange.lower, yRange.upper + yExtra));
+
+ // listeners
+ control.getPlotArea().addMouseListener(new MouseAdapter() {
+
+ @Override
+ public void mouseDown(MouseEvent e) {
+ showView();
+ TableViewer viewer = input.getView().getTableViewer();
+ input.getView().setTopControl(viewer.getControl());
+
+ Point p = new Point(e.x, e.y);
+
+ int closest = 0;
+ double d1, d2, d3, currMin;
+ double globalMin = Double.MAX_VALUE;
+ for (int i = 0; i < heapChart.time.length; i++){
+ // get distance from click event to data points for the given index
+ d1 = distance(lsUseful.getPixelCoordinates(i), p);
+ d2 = distance(lsExtra.getPixelCoordinates(i), p);
+ d3 = distance(lsTotal.getPixelCoordinates(i), p);
+ // find the closest data point to the click event
+ currMin = Math.min(Math.min(d1, d2), d3);
+ if (currMin < globalMin){
+ closest = i;
+ globalMin = currMin;
+ }
+ }
+
+ MassifSnapshot snapshot = (MassifSnapshot) viewer.getElementAt(closest);
+ viewer.setSelection(new StructuredSelection(snapshot), true);
+
+ if (e.count == 2 && snapshot.isDetailed()) {
+ ChartLocationsDialog dialog = new ChartLocationsDialog(Display.getCurrent().getActiveShell());
+ dialog.setInput(snapshot);
+
+ if (dialog.open() == Window.OK) {
+ dialog.openEditorForResult();
+ }
+ }
+
+ }
+ });
+
+ }
+
+ public Chart getControl() {
+ return control;
+ }
+
+ @Override
+ public void setFocus() {
+ if (control != null) {
+ control.setFocus();
+ }
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ control.dispose();
+ }
/**
@@ -259,7 +259,7 @@ public class ChartEditor extends EditorPart {
* Calculate Euclidean distance between two points (R2).
*/
private double distance (Point p1, Point p2) {
- return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
+ return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
}
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartEditorInput.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartEditorInput.java
index 8b8700c941..bcedbaa9c9 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartEditorInput.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartEditorInput.java
@@ -20,59 +20,59 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
public class ChartEditorInput implements IEditorInput {
- private HeapChart chart;
- private MassifViewPart view;
- private String name;
- private Integer pid;
+ private HeapChart chart;
+ private MassifViewPart view;
+ private String name;
+ private Integer pid;
- public ChartEditorInput(HeapChart chart, MassifViewPart view, String name, Integer pid) {
- this.chart = chart;
- this.view = view;
- this.name = name;
- this.pid = pid;
- }
+ public ChartEditorInput(HeapChart chart, MassifViewPart view, String name, Integer pid) {
+ this.chart = chart;
+ this.view = view;
+ this.name = name;
+ this.pid = pid;
+ }
- @Override
- public boolean exists() {
- return false;
- }
+ @Override
+ public boolean exists() {
+ return false;
+ }
- @Override
- public ImageDescriptor getImageDescriptor() {
- return AbstractUIPlugin.imageDescriptorFromPlugin(MassifPlugin.PLUGIN_ID, "icons/linecharticon.gif"); //$NON-NLS-1$
- }
+ @Override
+ public ImageDescriptor getImageDescriptor() {
+ return AbstractUIPlugin.imageDescriptorFromPlugin(MassifPlugin.PLUGIN_ID, "icons/linecharticon.gif"); //$NON-NLS-1$
+ }
- @Override
- public String getName() {
- return name;
- }
+ @Override
+ public String getName() {
+ return name;
+ }
- public Integer getPid() {
- return pid;
- }
+ public Integer getPid() {
+ return pid;
+ }
- @Override
- public IPersistableElement getPersistable() {
- return null;
- }
+ @Override
+ public IPersistableElement getPersistable() {
+ return null;
+ }
- @Override
- public String getToolTipText() {
- return NLS.bind(Messages.getString("ChartEditorInput.Heap_allocation_chart_for"), name); //$NON-NLS-1$
- }
+ @Override
+ public String getToolTipText() {
+ return NLS.bind(Messages.getString("ChartEditorInput.Heap_allocation_chart_for"), name); //$NON-NLS-1$
+ }
- @Override
- @SuppressWarnings("rawtypes")
- public Object getAdapter(Class adapter) {
- return null;
- }
+ @Override
+ @SuppressWarnings("rawtypes")
+ public Object getAdapter(Class adapter) {
+ return null;
+ }
- public HeapChart getChart() {
- return chart;
- }
+ public HeapChart getChart() {
+ return chart;
+ }
- public MassifViewPart getView() {
- return view;
- }
+ public MassifViewPart getView() {
+ return view;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartLocationsDialog.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartLocationsDialog.java
index fa10a62e2f..175c31c2cb 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartLocationsDialog.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/ChartLocationsDialog.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif.charting;
import java.util.ArrayList;
@@ -23,58 +23,58 @@ import org.eclipse.ui.dialogs.ListDialog;
public class ChartLocationsDialog extends ListDialog {
- private List<MassifHeapTreeNode> allocs;
-
- public ChartLocationsDialog(Shell parent) {
- super(parent);
- setContentProvider(new ArrayContentProvider());
- setLabelProvider(new MassifTreeLabelProvider());
- setMessage(Messages.getString("ChartLocationsDialog.Message")); //$NON-NLS-1$
- setTitle(Messages.getString("ChartLocationsDialog.Title")); //$NON-NLS-1$
- }
-
- @Override
- public void setInput(Object input) {
- setInput((MassifSnapshot) input);
- }
-
- public void setInput(MassifSnapshot snapshot) {
- MassifHeapTreeNode node = snapshot.getRoot();
-
- allocs = new ArrayList<>(node.getChildren().length);
-
- for (MassifHeapTreeNode alloc : node.getChildren()) {
- if (alloc.hasSourceFile()) {
- allocs.add(alloc);
- }
- }
- super.setInput(allocs);
- }
-
- @Override
- public int open() {
- int result = OK;
-
- if (allocs.size() > 1) {
- result = super.open();
- }
-
- return result;
- }
-
- public void openEditorForResult() {
- MassifHeapTreeNode element = null;
-
- if (allocs.size() > 1) {
- element = (MassifHeapTreeNode) getResult()[0];
- }
- else if (allocs.size() == 1) {
- element = allocs.get(0);
- }
-
- if (element != null) {
- MassifPlugin.getDefault().openEditorForNode(element);
- }
- }
-
+ private List<MassifHeapTreeNode> allocs;
+
+ public ChartLocationsDialog(Shell parent) {
+ super(parent);
+ setContentProvider(new ArrayContentProvider());
+ setLabelProvider(new MassifTreeLabelProvider());
+ setMessage(Messages.getString("ChartLocationsDialog.Message")); //$NON-NLS-1$
+ setTitle(Messages.getString("ChartLocationsDialog.Title")); //$NON-NLS-1$
+ }
+
+ @Override
+ public void setInput(Object input) {
+ setInput((MassifSnapshot) input);
+ }
+
+ public void setInput(MassifSnapshot snapshot) {
+ MassifHeapTreeNode node = snapshot.getRoot();
+
+ allocs = new ArrayList<>(node.getChildren().length);
+
+ for (MassifHeapTreeNode alloc : node.getChildren()) {
+ if (alloc.hasSourceFile()) {
+ allocs.add(alloc);
+ }
+ }
+ super.setInput(allocs);
+ }
+
+ @Override
+ public int open() {
+ int result = OK;
+
+ if (allocs.size() > 1) {
+ result = super.open();
+ }
+
+ return result;
+ }
+
+ public void openEditorForResult() {
+ MassifHeapTreeNode element = null;
+
+ if (allocs.size() > 1) {
+ element = (MassifHeapTreeNode) getResult()[0];
+ }
+ else if (allocs.size() == 1) {
+ element = allocs.get(0);
+ }
+
+ if (element != null) {
+ MassifPlugin.getDefault().openEditorForNode(element);
+ }
+ }
+
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/HeapChart.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/HeapChart.java
index 19b2971fa8..0cf95382ae 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/HeapChart.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/HeapChart.java
@@ -17,162 +17,162 @@ import org.eclipse.swt.widgets.Composite;
public class HeapChart {
- private static String[] byteUnits = { Messages.getString("HeapChart.B"), //$NON-NLS-1$
- Messages.getString("HeapChart.KiB"), //$NON-NLS-1$
- Messages.getString("HeapChart.MiB"), //$NON-NLS-1$
- Messages.getString("HeapChart.GiB"), //$NON-NLS-1$
- Messages.getString("HeapChart.TiB") //$NON-NLS-1$
- };
- private static String[] instrUnits = { Messages.getString("HeapChart.i"), //$NON-NLS-1$
- Messages.getString("HeapChart.Ki"), //$NON-NLS-1$
- Messages.getString("HeapChart.Mi"), //$NON-NLS-1$
- Messages.getString("HeapChart.Gi"), //$NON-NLS-1$
- Messages.getString("HeapChart.Ti") //$NON-NLS-1$
- };
- private static String[] secondUnits = { Messages.getString("HeapChart.ms"), //$NON-NLS-1$
- Messages.getString("HeapChart.s") //$NON-NLS-1$
- };
-
- protected static final int BYTE_MULT = 1024;
- protected static final int BYTE_LIMIT = byteUnits.length - 1;
- protected static final int INSTR_MULT = 1000;
- protected static final int INSTR_LIMIT = instrUnits.length - 1;
- protected static final int MS_MULT = 1000;
- protected static final int MS_LIMIT = secondUnits.length - 1;
-
- protected static final int SCALING_THRESHOLD = 20;
-
- protected String title;
- protected String xUnits;
- protected String yUnits;
- public double [] time, dataUseful, dataExtra, dataStacks, dataTotal;
- private Composite chartControl;
-
- public HeapChart(MassifSnapshot[] snapshots, String title) {
- TimeUnit timeUnit = snapshots[0].getUnit();
- long xScaling = getXScaling(snapshots, timeUnit);
- long yScaling = getYScaling(snapshots);
-
- this.title = title;
- time = new double[snapshots.length];
- dataUseful = new double[snapshots.length];
- dataExtra = new double[snapshots.length];
- dataStacks = null;
-
- boolean isStack = isStackProfiled(snapshots);
- if (isStack) {
- dataStacks = new double[snapshots.length];
- }
- dataTotal = new double[snapshots.length];
- for (int i = 0; i < snapshots.length; i++) {
- time[i] = snapshots[i].getTime() / (double) xScaling;
- dataUseful[i] = snapshots[i].getHeapBytes() / (double) yScaling;
- dataExtra[i] = snapshots[i].getHeapExtra() / (double) yScaling;
- dataTotal[i] = dataUseful[i] + dataExtra[i];
- if (isStack) {
- dataStacks[i] = snapshots[i].getStacks() / (double) yScaling;
- }
- }
-
- }
-
- private boolean isStackProfiled(MassifSnapshot[] snapshots) {
- return getMaxStack(snapshots) > 0;
- }
-
- private long getYScaling(MassifSnapshot[] snapshots) {
- long max = getMaxValue(snapshots);
-
- int count = 0;
- while (max > BYTE_MULT * SCALING_THRESHOLD && count < BYTE_LIMIT) {
- max /= BYTE_MULT;
- count++;
- }
-
- yUnits = byteUnits[count];
-
- return (long) Math.pow(BYTE_MULT, count);
- }
-
- private long getXScaling(MassifSnapshot[] snapshots, TimeUnit unit) {
- long max = snapshots[snapshots.length - 1].getTime();
- int mult, limit;
- String[] units;
- switch (unit) {
- case BYTES:
- mult = BYTE_MULT;
- limit = BYTE_LIMIT;
- units = byteUnits;
- break;
- case INSTRUCTIONS:
- mult = INSTR_MULT;
- limit = INSTR_LIMIT;
- units = instrUnits;
- break;
- default:
- mult = MS_MULT;
- limit = MS_LIMIT;
- units = secondUnits;
- break;
- }
-
- int count = 0;
- while (max > mult * SCALING_THRESHOLD && count < limit) {
- max /= mult;
- count++;
- }
-
- xUnits = units[count];
-
- return (long) Math.pow(mult, count);
- }
-
- private static long getMaxValue(MassifSnapshot[] snapshots) {
- long max = 0;
- for (MassifSnapshot snapshot : snapshots) {
- if (snapshot.getTotal() > max) {
- max = snapshot.getTotal();
- }
- }
- return max;
- }
-
- private static long getMaxStack(MassifSnapshot[] snapshots) {
- long max = 0;
- for (MassifSnapshot snapshot : snapshots) {
- if (snapshot.getTotal() > max) {
- max = snapshot.getStacks();
- }
- }
- return max;
- }
-
- public String getXUnits() {
- return xUnits;
- }
-
- public String getYUnits() {
- return yUnits;
- }
-
- public static String[] getByteUnits() {
- return byteUnits;
- }
-
- public static String[] getInstrUnits() {
- return instrUnits;
- }
-
- public static String[] getSecondUnits() {
- return secondUnits;
- }
-
- public void setChartControl(Composite control) {
- chartControl = control;
- }
-
- public Composite getChartControl (){
- return chartControl;
- }
+ private static String[] byteUnits = { Messages.getString("HeapChart.B"), //$NON-NLS-1$
+ Messages.getString("HeapChart.KiB"), //$NON-NLS-1$
+ Messages.getString("HeapChart.MiB"), //$NON-NLS-1$
+ Messages.getString("HeapChart.GiB"), //$NON-NLS-1$
+ Messages.getString("HeapChart.TiB") //$NON-NLS-1$
+ };
+ private static String[] instrUnits = { Messages.getString("HeapChart.i"), //$NON-NLS-1$
+ Messages.getString("HeapChart.Ki"), //$NON-NLS-1$
+ Messages.getString("HeapChart.Mi"), //$NON-NLS-1$
+ Messages.getString("HeapChart.Gi"), //$NON-NLS-1$
+ Messages.getString("HeapChart.Ti") //$NON-NLS-1$
+ };
+ private static String[] secondUnits = { Messages.getString("HeapChart.ms"), //$NON-NLS-1$
+ Messages.getString("HeapChart.s") //$NON-NLS-1$
+ };
+
+ protected static final int BYTE_MULT = 1024;
+ protected static final int BYTE_LIMIT = byteUnits.length - 1;
+ protected static final int INSTR_MULT = 1000;
+ protected static final int INSTR_LIMIT = instrUnits.length - 1;
+ protected static final int MS_MULT = 1000;
+ protected static final int MS_LIMIT = secondUnits.length - 1;
+
+ protected static final int SCALING_THRESHOLD = 20;
+
+ protected String title;
+ protected String xUnits;
+ protected String yUnits;
+ public double [] time, dataUseful, dataExtra, dataStacks, dataTotal;
+ private Composite chartControl;
+
+ public HeapChart(MassifSnapshot[] snapshots, String title) {
+ TimeUnit timeUnit = snapshots[0].getUnit();
+ long xScaling = getXScaling(snapshots, timeUnit);
+ long yScaling = getYScaling(snapshots);
+
+ this.title = title;
+ time = new double[snapshots.length];
+ dataUseful = new double[snapshots.length];
+ dataExtra = new double[snapshots.length];
+ dataStacks = null;
+
+ boolean isStack = isStackProfiled(snapshots);
+ if (isStack) {
+ dataStacks = new double[snapshots.length];
+ }
+ dataTotal = new double[snapshots.length];
+ for (int i = 0; i < snapshots.length; i++) {
+ time[i] = snapshots[i].getTime() / (double) xScaling;
+ dataUseful[i] = snapshots[i].getHeapBytes() / (double) yScaling;
+ dataExtra[i] = snapshots[i].getHeapExtra() / (double) yScaling;
+ dataTotal[i] = dataUseful[i] + dataExtra[i];
+ if (isStack) {
+ dataStacks[i] = snapshots[i].getStacks() / (double) yScaling;
+ }
+ }
+
+ }
+
+ private boolean isStackProfiled(MassifSnapshot[] snapshots) {
+ return getMaxStack(snapshots) > 0;
+ }
+
+ private long getYScaling(MassifSnapshot[] snapshots) {
+ long max = getMaxValue(snapshots);
+
+ int count = 0;
+ while (max > BYTE_MULT * SCALING_THRESHOLD && count < BYTE_LIMIT) {
+ max /= BYTE_MULT;
+ count++;
+ }
+
+ yUnits = byteUnits[count];
+
+ return (long) Math.pow(BYTE_MULT, count);
+ }
+
+ private long getXScaling(MassifSnapshot[] snapshots, TimeUnit unit) {
+ long max = snapshots[snapshots.length - 1].getTime();
+ int mult, limit;
+ String[] units;
+ switch (unit) {
+ case BYTES:
+ mult = BYTE_MULT;
+ limit = BYTE_LIMIT;
+ units = byteUnits;
+ break;
+ case INSTRUCTIONS:
+ mult = INSTR_MULT;
+ limit = INSTR_LIMIT;
+ units = instrUnits;
+ break;
+ default:
+ mult = MS_MULT;
+ limit = MS_LIMIT;
+ units = secondUnits;
+ break;
+ }
+
+ int count = 0;
+ while (max > mult * SCALING_THRESHOLD && count < limit) {
+ max /= mult;
+ count++;
+ }
+
+ xUnits = units[count];
+
+ return (long) Math.pow(mult, count);
+ }
+
+ private static long getMaxValue(MassifSnapshot[] snapshots) {
+ long max = 0;
+ for (MassifSnapshot snapshot : snapshots) {
+ if (snapshot.getTotal() > max) {
+ max = snapshot.getTotal();
+ }
+ }
+ return max;
+ }
+
+ private static long getMaxStack(MassifSnapshot[] snapshots) {
+ long max = 0;
+ for (MassifSnapshot snapshot : snapshots) {
+ if (snapshot.getTotal() > max) {
+ max = snapshot.getStacks();
+ }
+ }
+ return max;
+ }
+
+ public String getXUnits() {
+ return xUnits;
+ }
+
+ public String getYUnits() {
+ return yUnits;
+ }
+
+ public static String[] getByteUnits() {
+ return byteUnits;
+ }
+
+ public static String[] getInstrUnits() {
+ return instrUnits;
+ }
+
+ public static String[] getSecondUnits() {
+ return secondUnits;
+ }
+
+ public void setChartControl(Composite control) {
+ chartControl = control;
+ }
+
+ public Composite getChartControl (){
+ return chartControl;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/Messages.java b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/Messages.java
index 5973ad926b..9a2bd11dee 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/Messages.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.massif/src/org/eclipse/linuxtools/internal/valgrind/massif/charting/Messages.java
@@ -7,26 +7,26 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.massif.charting;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.massif.charting.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.massif.charting.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/pom.xml b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/pom.xml
index 8e8c688eff..e98f78b5d4 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/pom.xml
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/pom.xml
@@ -36,7 +36,7 @@
</excludes>
<testSuite>org.eclipse.linuxtools.valgrind.memcheck.tests</testSuite>
<testClass>org.eclipse.linuxtools.internal.valgrind.memcheck.tests.AllTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.platform.ide</product>
<surefire.timeout>1800</surefire.timeout>
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AbstractLinkedResourceMemcheckTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AbstractLinkedResourceMemcheckTest.java
index 1193c8326a..8bd2606134 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AbstractLinkedResourceMemcheckTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AbstractLinkedResourceMemcheckTest.java
@@ -26,45 +26,45 @@ import org.junit.After;
import org.junit.Before;
public abstract class AbstractLinkedResourceMemcheckTest extends
- AbstractMemcheckTest {
+ AbstractMemcheckTest {
- @Before
- public void linkedResourceSetUp() throws Exception {
- proj = createProject(getBundle(), "linkedTest"); //$NON-NLS-1$
+ @Before
+ public void linkedResourceSetUp() throws Exception {
+ proj = createProject(getBundle(), "linkedTest"); //$NON-NLS-1$
- // delete source folder and replace it with a link to its bundle
- // location
- final Exception[] ex = new Exception[1];
- ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
+ // delete source folder and replace it with a link to its bundle
+ // location
+ final Exception[] ex = new Exception[1];
+ ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
- @Override
- public void run(IProgressMonitor monitor) {
- try {
- URL location = FileLocator.find(getBundle(), new Path(
- "resources/linkedTest/src"), null); //$NON-NLS-1$
- IFolder srcFolder = proj.getProject().getFolder("src"); //$NON-NLS-1$
- srcFolder.delete(true, null);
- srcFolder.createLink(FileLocator.toFileURL(location)
- .toURI(), IResource.REPLACE, null);
- } catch (Exception e) {
- ex[0] = e;
- }
- }
+ @Override
+ public void run(IProgressMonitor monitor) {
+ try {
+ URL location = FileLocator.find(getBundle(), new Path(
+ "resources/linkedTest/src"), null); //$NON-NLS-1$
+ IFolder srcFolder = proj.getProject().getFolder("src"); //$NON-NLS-1$
+ srcFolder.delete(true, null);
+ srcFolder.createLink(FileLocator.toFileURL(location)
+ .toURI(), IResource.REPLACE, null);
+ } catch (Exception e) {
+ ex[0] = e;
+ }
+ }
- }, null);
+ }, null);
- if (ex[0] != null) {
- throw ex[0];
- }
+ if (ex[0] != null) {
+ throw ex[0];
+ }
- assertEquals(0, proj.getBinaryContainer().getBinaries().length);
+ assertEquals(0, proj.getBinaryContainer().getBinaries().length);
- buildProject(proj);
- }
+ buildProject(proj);
+ }
- @After
- public void cleanupLinkedResource() throws CoreException {
- deleteProject(proj);
- }
+ @After
+ public void cleanupLinkedResource() throws CoreException {
+ deleteProject(proj);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AbstractMemcheckTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AbstractMemcheckTest.java
index 99417b39a6..5f4e110213 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AbstractMemcheckTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AbstractMemcheckTest.java
@@ -20,55 +20,55 @@ import org.eclipse.linuxtools.valgrind.core.IValgrindMessage;
public abstract class AbstractMemcheckTest extends AbstractValgrindTest {
- @Override
- public String getToolID() {
- return MemcheckPlugin.TOOL_ID;
- }
+ @Override
+ public String getToolID() {
+ return MemcheckPlugin.TOOL_ID;
+ }
- /**
- * Check messages appear as expected for the specified test.
- *
- * @param messages IValgrindMessage messages
- * @param testName test name
- */
- public void checkTestMessages(IValgrindMessage[] messages, String testName) {
- assertTrue(messages.length > 0);
- String lostBytesMsg = "10 bytes in 1 blocks are definitely lost in loss record 1 of 1"; //$NON-NLS-1$
- String invalidReadMsg = "Invalid read of size 1"; //$NON-NLS-1$
- String invalidWriteMsg = "Invalid write of size 1"; //$NON-NLS-1$
+ /**
+ * Check messages appear as expected for the specified test.
+ *
+ * @param messages IValgrindMessage messages
+ * @param testName test name
+ */
+ public void checkTestMessages(IValgrindMessage[] messages, String testName) {
+ assertTrue(messages.length > 0);
+ String lostBytesMsg = "10 bytes in 1 blocks are definitely lost in loss record 1 of 1"; //$NON-NLS-1$
+ String invalidReadMsg = "Invalid read of size 1"; //$NON-NLS-1$
+ String invalidWriteMsg = "Invalid write of size 1"; //$NON-NLS-1$
- for (IValgrindMessage message : messages) {
- for (IValgrindMessage child : message.getChildren()) {
- if (child instanceof ValgrindStackFrame) {
- ValgrindStackFrame stackFrameMsg = (ValgrindStackFrame) child;
+ for (IValgrindMessage message : messages) {
+ for (IValgrindMessage child : message.getChildren()) {
+ if (child instanceof ValgrindStackFrame) {
+ ValgrindStackFrame stackFrameMsg = (ValgrindStackFrame) child;
- // check expected error messages exist for basicTest (child process in multiProcTest)
- if (("testNumErrors".equals(testName) || "testExec".equals(testName)) //$NON-NLS-1$ //$NON-NLS-2$
- && "test.c".equals(stackFrameMsg.getFile())) { //$NON-NLS-1$
- assertTrue(stackFrameMsg.getLine() >= 15);
- switch (stackFrameMsg.getLine()) {
- case 15:
- assertTrue(message.getText().contains(lostBytesMsg));
- break;
- case 16:
- assertTrue(message.getText().contains(invalidReadMsg));
- break;
- case 17:
- assertTrue(message.getText().contains(invalidWriteMsg));
- break;
- default:
- break;
- }
- }
+ // check expected error messages exist for basicTest (child process in multiProcTest)
+ if (("testNumErrors".equals(testName) || "testExec".equals(testName)) //$NON-NLS-1$ //$NON-NLS-2$
+ && "test.c".equals(stackFrameMsg.getFile())) { //$NON-NLS-1$
+ assertTrue(stackFrameMsg.getLine() >= 15);
+ switch (stackFrameMsg.getLine()) {
+ case 15:
+ assertTrue(message.getText().contains(lostBytesMsg));
+ break;
+ case 16:
+ assertTrue(message.getText().contains(invalidReadMsg));
+ break;
+ case 17:
+ assertTrue(message.getText().contains(invalidWriteMsg));
+ break;
+ default:
+ break;
+ }
+ }
- // check expected error messages exist for parent process in multiProcTest
- if (("testNoExec".equals(testName) || "testExec".equals(testName)) //$NON-NLS-1$ //$NON-NLS-2$
- && "parent.c".equals(stackFrameMsg.getFile())) { //$NON-NLS-1$
- assertEquals(8, stackFrameMsg.getLine());
- assertTrue(child.getParent().getText().contains(lostBytesMsg));
- }
- }
- }
- }
- }
+ // check expected error messages exist for parent process in multiProcTest
+ if (("testNoExec".equals(testName) || "testExec".equals(testName)) //$NON-NLS-1$ //$NON-NLS-2$
+ && "parent.c".equals(stackFrameMsg.getFile())) { //$NON-NLS-1$
+ assertEquals(8, stackFrameMsg.getLine());
+ assertTrue(child.getParent().getText().contains(lostBytesMsg));
+ }
+ }
+ }
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AllTests.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AllTests.java
index 1e09e3897c..22c5ec7959 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AllTests.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/AllTests.java
@@ -16,9 +16,9 @@ import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ BasicMemcheckTest.class, DoubleClickTest.class,
- LaunchConfigTabTest.class, MarkerTest.class,
- LinkedResourceDoubleClickTest.class, LinkedResourceMarkerTest.class,
- MultiProcessTest.class, ExpandCollapseTest.class, ShortcutTest.class,
- SignalTest.class, MinVersionTest.class })
+ LaunchConfigTabTest.class, MarkerTest.class,
+ LinkedResourceDoubleClickTest.class, LinkedResourceMarkerTest.class,
+ MultiProcessTest.class, ExpandCollapseTest.class, ShortcutTest.class,
+ SignalTest.class, MinVersionTest.class })
public class AllTests {
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/BasicMemcheckTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/BasicMemcheckTest.java
index 9a4569e220..ee2453d557 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/BasicMemcheckTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/BasicMemcheckTest.java
@@ -22,26 +22,26 @@ import org.junit.Test;
public class BasicMemcheckTest extends AbstractMemcheckTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
- @Test
- public void testNumErrors() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testNumErrors"); //$NON-NLS-1$
+ @Test
+ public void testNumErrors() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testNumErrors"); //$NON-NLS-1$
- IValgrindMessage[] messages = ValgrindUIPlugin.getDefault().getView()
- .getMessages();
- assertEquals(3, messages.length);
- checkTestMessages(messages, "testNumErrors"); //$NON-NLS-1$
- }
+ IValgrindMessage[] messages = ValgrindUIPlugin.getDefault().getView()
+ .getMessages();
+ assertEquals(3, messages.length);
+ checkTestMessages(messages, "testNumErrors"); //$NON-NLS-1$
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/DoubleClickTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/DoubleClickTest.java
index 761447ef94..5aca4a6c15 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/DoubleClickTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/DoubleClickTest.java
@@ -42,115 +42,115 @@ import org.junit.Before;
import org.junit.Test;
public class DoubleClickTest extends AbstractMemcheckTest {
- private ValgrindStackFrame frame;
-
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
- }
-
- private void doDoubleClick() {
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- CoreMessagesViewer viewer = view.getMessagesViewer();
-
- // get first leaf
- IValgrindMessage[] elements = (IValgrindMessage[]) viewer
- .getTreeViewer().getInput();
- IValgrindMessage element = elements[0];
- TreePath path = new TreePath(new Object[] { element });
- frame = null;
- while (element.getChildren().length > 0) {
- element = element.getChildren()[0];
- path = path.createChildPath(element);
- if (element instanceof ValgrindStackFrame) {
- frame = (ValgrindStackFrame) element;
- }
- }
- assertNotNull(frame);
-
- viewer.getTreeViewer().expandToLevel(frame,
- AbstractTreeViewer.ALL_LEVELS);
- TreeSelection selection = new TreeSelection(path);
-
- // do double click
- IDoubleClickListener listener = viewer.getDoubleClickListener();
- listener.doubleClick(new DoubleClickEvent(viewer.getTreeViewer(),
- selection));
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
-
- @Test
- public void testDoubleClickFile() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testDoubleClickFile"); //$NON-NLS-1$
-
- doDoubleClick();
-
- IEditorPart editor = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- IEditorInput input = editor.getEditorInput();
-
- assertTrue("Input should be IFileEditorInput",
- input instanceof IFileEditorInput);
- IFileEditorInput fileInput = (IFileEditorInput) input;
- File expectedFile = new File(proj.getProject().getLocation()
- .toOSString(), frame.getFile());
- File actualFile = fileInput.getFile().getLocation().toFile();
-
- assertEquals(expectedFile.getCanonicalPath(),
- actualFile.getCanonicalPath());
- }
-
- @Test
- public void testDoubleClickLine() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testDoubleClickLine"); //$NON-NLS-1$
-
- doDoubleClick();
-
- IEditorPart editor = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- assertTrue("editor should be ITextEditor",
- editor instanceof ITextEditor);
- ITextEditor textEditor = (ITextEditor) editor;
-
- ISelection selection = textEditor.getSelectionProvider().getSelection();
- assertTrue("selection must be TextSelection",
- selection instanceof TextSelection);
- TextSelection textSelection = (TextSelection) selection;
- int line = textSelection.getStartLine() + 1; // zero-indexed
-
- assertEquals(frame.getLine(), line);
- }
-
- @Test
- public void testDoubleClickLaunchRemoved() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- ILaunch launch = doLaunch(config, "testDoubleClickLine"); //$NON-NLS-1$
-
- // Remove launch - tests #284919
- DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
-
- doDoubleClick();
-
- IEditorPart editor = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- assertTrue("editor should be ITextEditor",
- editor instanceof ITextEditor);
- ITextEditor textEditor = (ITextEditor) editor;
-
- ISelection selection = textEditor.getSelectionProvider().getSelection();
- assertTrue("selection must be TextSelection",
- selection instanceof TextSelection);
- TextSelection textSelection = (TextSelection) selection;
- int line = textSelection.getStartLine() + 1; // zero-indexed
-
- assertEquals(frame.getLine(), line);
- }
+ private ValgrindStackFrame frame;
+
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+ }
+
+ private void doDoubleClick() {
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ CoreMessagesViewer viewer = view.getMessagesViewer();
+
+ // get first leaf
+ IValgrindMessage[] elements = (IValgrindMessage[]) viewer
+ .getTreeViewer().getInput();
+ IValgrindMessage element = elements[0];
+ TreePath path = new TreePath(new Object[] { element });
+ frame = null;
+ while (element.getChildren().length > 0) {
+ element = element.getChildren()[0];
+ path = path.createChildPath(element);
+ if (element instanceof ValgrindStackFrame) {
+ frame = (ValgrindStackFrame) element;
+ }
+ }
+ assertNotNull(frame);
+
+ viewer.getTreeViewer().expandToLevel(frame,
+ AbstractTreeViewer.ALL_LEVELS);
+ TreeSelection selection = new TreeSelection(path);
+
+ // do double click
+ IDoubleClickListener listener = viewer.getDoubleClickListener();
+ listener.doubleClick(new DoubleClickEvent(viewer.getTreeViewer(),
+ selection));
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ @Test
+ public void testDoubleClickFile() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testDoubleClickFile"); //$NON-NLS-1$
+
+ doDoubleClick();
+
+ IEditorPart editor = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage().getActiveEditor();
+ IEditorInput input = editor.getEditorInput();
+
+ assertTrue("Input should be IFileEditorInput",
+ input instanceof IFileEditorInput);
+ IFileEditorInput fileInput = (IFileEditorInput) input;
+ File expectedFile = new File(proj.getProject().getLocation()
+ .toOSString(), frame.getFile());
+ File actualFile = fileInput.getFile().getLocation().toFile();
+
+ assertEquals(expectedFile.getCanonicalPath(),
+ actualFile.getCanonicalPath());
+ }
+
+ @Test
+ public void testDoubleClickLine() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testDoubleClickLine"); //$NON-NLS-1$
+
+ doDoubleClick();
+
+ IEditorPart editor = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage().getActiveEditor();
+ assertTrue("editor should be ITextEditor",
+ editor instanceof ITextEditor);
+ ITextEditor textEditor = (ITextEditor) editor;
+
+ ISelection selection = textEditor.getSelectionProvider().getSelection();
+ assertTrue("selection must be TextSelection",
+ selection instanceof TextSelection);
+ TextSelection textSelection = (TextSelection) selection;
+ int line = textSelection.getStartLine() + 1; // zero-indexed
+
+ assertEquals(frame.getLine(), line);
+ }
+
+ @Test
+ public void testDoubleClickLaunchRemoved() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ ILaunch launch = doLaunch(config, "testDoubleClickLine"); //$NON-NLS-1$
+
+ // Remove launch - tests #284919
+ DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
+
+ doDoubleClick();
+
+ IEditorPart editor = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage().getActiveEditor();
+ assertTrue("editor should be ITextEditor",
+ editor instanceof ITextEditor);
+ ITextEditor textEditor = (ITextEditor) editor;
+
+ ISelection selection = textEditor.getSelectionProvider().getSelection();
+ assertTrue("selection must be TextSelection",
+ selection instanceof TextSelection);
+ TextSelection textSelection = (TextSelection) selection;
+ int line = textSelection.getStartLine() + 1; // zero-indexed
+
+ assertEquals(frame.getLine(), line);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/ExpandCollapseTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/ExpandCollapseTest.java
index 2da2da4443..baf679205f 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/ExpandCollapseTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/ExpandCollapseTest.java
@@ -29,72 +29,72 @@ import org.junit.Test;
public class ExpandCollapseTest extends AbstractMemcheckTest {
- private CoreMessagesViewer viewer;
- private Menu contextMenu;
+ private CoreMessagesViewer viewer;
+ private Menu contextMenu;
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
- @Test
- public void testExpand() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testDefaults"); //$NON-NLS-1$
+ @Test
+ public void testExpand() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testDefaults"); //$NON-NLS-1$
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- viewer = view.getMessagesViewer();
- contextMenu = viewer.getTreeViewer().getTree().getMenu();
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ viewer = view.getMessagesViewer();
+ contextMenu = viewer.getTreeViewer().getTree().getMenu();
- // Select first error and expand it
- IValgrindMessage[] messages = (IValgrindMessage[]) viewer
- .getTreeViewer().getInput();
- IValgrindMessage element = messages[0];
- TreeSelection selection = new TreeSelection(new TreePath(
- new Object[] { element }));
- viewer.getTreeViewer().setSelection(selection);
- contextMenu.notifyListeners(SWT.Show, null);
- contextMenu.getItem(0).notifyListeners(SWT.Selection, null);
+ // Select first error and expand it
+ IValgrindMessage[] messages = (IValgrindMessage[]) viewer
+ .getTreeViewer().getInput();
+ IValgrindMessage element = messages[0];
+ TreeSelection selection = new TreeSelection(new TreePath(
+ new Object[] { element }));
+ viewer.getTreeViewer().setSelection(selection);
+ contextMenu.notifyListeners(SWT.Show, null);
+ contextMenu.getItem(0).notifyListeners(SWT.Selection, null);
- checkExpanded(element, true);
- }
+ checkExpanded(element, true);
+ }
- @Test
- public void testCollapse() throws Exception {
- // Expand the element first
- testExpand();
+ @Test
+ public void testCollapse() throws Exception {
+ // Expand the element first
+ testExpand();
- // Then collapse it
- IValgrindMessage[] messages = (IValgrindMessage[]) viewer
- .getTreeViewer().getInput();
- IValgrindMessage element = messages[0];
- TreeSelection selection = new TreeSelection(new TreePath(
- new Object[] { element }));
- viewer.getTreeViewer().setSelection(selection);
- contextMenu.notifyListeners(SWT.Show, null);
- contextMenu.getItem(1).notifyListeners(SWT.Selection, null);
+ // Then collapse it
+ IValgrindMessage[] messages = (IValgrindMessage[]) viewer
+ .getTreeViewer().getInput();
+ IValgrindMessage element = messages[0];
+ TreeSelection selection = new TreeSelection(new TreePath(
+ new Object[] { element }));
+ viewer.getTreeViewer().setSelection(selection);
+ contextMenu.notifyListeners(SWT.Show, null);
+ contextMenu.getItem(1).notifyListeners(SWT.Selection, null);
- checkExpanded(element, false);
- }
+ checkExpanded(element, false);
+ }
- private void checkExpanded(IValgrindMessage element, boolean expanded) {
- if (element.getChildren().length > 0) {
- // only applicable to internal nodes
- if (expanded) {
- assertTrue(viewer.getTreeViewer().getExpandedState(element));
- } else {
- assertFalse(viewer.getTreeViewer().getExpandedState(element));
- }
- }
- for (IValgrindMessage child : element.getChildren()) {
- checkExpanded(child, expanded);
- }
- }
+ private void checkExpanded(IValgrindMessage element, boolean expanded) {
+ if (element.getChildren().length > 0) {
+ // only applicable to internal nodes
+ if (expanded) {
+ assertTrue(viewer.getTreeViewer().getExpandedState(element));
+ } else {
+ assertFalse(viewer.getTreeViewer().getExpandedState(element));
+ }
+ }
+ for (IValgrindMessage child : element.getChildren()) {
+ checkExpanded(child, expanded);
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LaunchConfigTabTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LaunchConfigTabTest.java
index b4b12820cb..4e402f017f 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LaunchConfigTabTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LaunchConfigTabTest.java
@@ -47,461 +47,461 @@ import org.osgi.framework.Version;
public class LaunchConfigTabTest extends AbstractMemcheckTest {
- private ValgrindOptionsTab tab;
- private MemcheckToolPage dynamicTab;
- private ILaunchConfiguration config;
- private Shell testShell;
-
- @Before
- public void setUpProject() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
-
- config = createConfiguration(proj.getProject());
-
- testShell = new Shell(Display.getDefault());
- testShell.setLayout(new GridLayout());
- tab = new ValgrindOptionsTab();
- }
-
- @After
- public void cleanup() throws Exception {
- tab.dispose();
- testShell.dispose();
- deleteProject(proj);
- super.tearDown();
- }
-
- private ILaunchConfigurationWorkingCopy initConfig() throws CoreException {
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- tab.setDefaults(wc);
- tab.createControl(testShell);
- tab.initializeFrom(config);
- int ix = Arrays.asList(tab.getTools()).indexOf(MemcheckPlugin.TOOL_ID);
- tab.getToolsCombo().select(ix);
- ILaunchConfigurationTab dynamicTab = tab.getDynamicTab();
- this.dynamicTab = (MemcheckToolPage) dynamicTab;
- return wc;
- }
-
- private ILaunch saveAndLaunch(ILaunchConfigurationWorkingCopy wc,
- String testName) throws Exception {
- tab.performApply(wc);
- config = wc.doSave();
-
- return doLaunch(config, testName);
- }
-
- @Test
- public void testDefaults() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- ILaunch launch = saveAndLaunch(wc, "testDefaults"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--tool=memcheck")); //$NON-NLS-1$
- assertTrue(cmd.contains("-q")); //$NON-NLS-1$
- assertTrue(cmd.contains("--trace-children=no")); //$NON-NLS-1$
- assertTrue(cmd.contains("--child-silent-after-fork=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--demangle=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--num-callers=12")); //$NON-NLS-1$
- assertTrue(cmd.contains("--error-limit=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--show-below-main=no")); //$NON-NLS-1$
- assertFalse(cmd.contains("--suppressions=")); //$NON-NLS-1$
- assertTrue(cmd.contains("--max-stackframe=2000000")); //$NON-NLS-1$
- assertFalse(cmd.contains("--alignment=")); //$NON-NLS-1$
- assertTrue(cmd.contains("--run-libc-freeres=yes")); //$NON-NLS-1$
-
- assertTrue(cmd.contains("--leak-check=yes")); //$NON-NLS-1$
- assertTrue(cmd.contains("--show-reachable=no")); //$NON-NLS-1$
- assertTrue(cmd.contains("--leak-resolution=high")); //$NON-NLS-1$
- assertTrue(cmd.contains("--freelist-vol=10000000")); //$NON-NLS-1$
- assertTrue(cmd.contains("--workaround-gcc296-bugs=no")); //$NON-NLS-1$
- assertTrue(cmd.contains("--partial-loads-ok=no")); //$NON-NLS-1$
- assertTrue(cmd.contains("--undef-value-errors=yes")); //$NON-NLS-1$
-
- // 3.4.0 specific
- IProject project = CDebugUtils.verifyCProject(wc).getProject();
- Version ver = ValgrindLaunchPlugin.getDefault().getValgrindVersion(
- project);
- if (ver.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
- assertFalse(cmd.contains("--track-origins")); //$NON-NLS-1$
- }
- assertFalse(cmd.contains("--main-stacksize")); //$NON-NLS-1$
- }
-
- @Test
- public void testWSSuppresions() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- String text = "${workspace_loc:/basicTest/testsuppfile.supp}"; //$NON-NLS-1$
- tab.getSuppFileList().add(text);
- ILaunch launch = saveAndLaunch(wc, "testWSSuppresions"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- IPath suppPath = ResourcesPlugin
- .getWorkspace()
- .getRoot()
- .findMember(new Path("basicTest/testsuppfile.supp")).getLocation(); //$NON-NLS-1$
- assertTrue(cmd.contains("--suppressions=" + suppPath.toOSString())); //$NON-NLS-1$
- }
-
- @Test
- public void testSuppressions() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- IPath suppPath = ResourcesPlugin
- .getWorkspace()
- .getRoot()
- .findMember(new Path("basicTest/testsuppfile.supp")).getLocation(); //$NON-NLS-1$
- tab.getSuppFileList().add(suppPath.toOSString());
- ILaunch launch = saveAndLaunch(wc, "testSuppressions"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--suppressions=" + suppPath.toOSString())); //$NON-NLS-1$
- }
-
- @Test
- public void testSuppressionsMultiple() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- IPath suppPath = ResourcesPlugin
- .getWorkspace()
- .getRoot()
- .findMember(new Path("basicTest/testsuppfile.supp")).getLocation(); //$NON-NLS-1$
- IPath suppPath2 = ResourcesPlugin
- .getWorkspace()
- .getRoot()
- .findMember(new Path("basicTest/testsuppfile2.supp")).getLocation(); //$NON-NLS-1$
- tab.getSuppFileList().add(suppPath.toOSString());
- tab.getSuppFileList().add(suppPath2.toOSString());
- ILaunch launch = saveAndLaunch(wc, "testSuppressionsMultiple"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--suppressions=" + suppPath.toOSString())); //$NON-NLS-1$
- assertTrue(cmd.contains("--suppressions=" + suppPath2.toOSString())); //$NON-NLS-1$
- }
-
- @Test
- public void testSuppressionsSpaces() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- IPath suppPath = ResourcesPlugin
- .getWorkspace()
- .getRoot()
- .findMember(new Path("basicTest/test suppfile.supp")).getLocation(); //$NON-NLS-1$
- tab.getSuppFileList().add(suppPath.toOSString());
- ILaunch launch = saveAndLaunch(wc, "testSuppressionsSpaces"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--suppressions=" + suppPath.toOSString())); //$NON-NLS-1$
- }
-
- @Test
- public void testTraceChildren() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- tab.getTraceChildrenButton().setSelection(true);
- ILaunch launch = saveAndLaunch(wc, "testTraceChildren"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--trace-children=yes")); //$NON-NLS-1$
- }
-
- @Test
- public void testDemangle() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- tab.getDemangleButton().setSelection(false);
- ILaunch launch = saveAndLaunch(wc, "testDemangle"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--demangle=no")); //$NON-NLS-1$
- }
-
- @Test
- public void testNumCallers() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- tab.getNumCallersSpinner().setSelection(24);
- ILaunch launch = saveAndLaunch(wc, "testNumCallers"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--num-callers=24")); //$NON-NLS-1$
- }
-
- @Test
- public void testErrorLimit() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- tab.getErrorLimitButton().setSelection(false);
- ILaunch launch = saveAndLaunch(wc, "testErrorLimit"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--error-limit=no")); //$NON-NLS-1$
- }
-
- @Test
- public void testShowBelowMain() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- tab.getShowBelowMainButton().setSelection(true);
- ILaunch launch = saveAndLaunch(wc, "testShowBelowMain"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--show-below-main=yes")); //$NON-NLS-1$
- }
-
- @Test
- public void testMaxStackframe() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- tab.getMaxStackFrameSpinner().setSelection(50000000);
- ILaunch launch = saveAndLaunch(wc, "testMaxStackframe"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--max-stackframe=50000000")); //$NON-NLS-1$
- }
-
- @Test
- public void testRunFreeRes() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- tab.getRunFreeresButton().setSelection(false);
- ILaunch launch = saveAndLaunch(wc, "testRunFreeRes"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue(p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--run-libc-freeres=no")); //$NON-NLS-1$
- }
-
- @Test
- public void testAlignment() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
-
- assertFalse(dynamicTab.getAlignmentSpinner().getEnabled());
- dynamicTab.getAlignmentButton().setSelection(true);
- dynamicTab.getAlignmentButton().notifyListeners(SWT.Selection, null);
- assertTrue(dynamicTab.getAlignmentSpinner().getEnabled());
-
- dynamicTab.getAlignmentSpinner().setSelection(512);
- tab.performApply(wc);
- config = wc.doSave();
-
- assertTrue(tab.isValid(config));
-
- ILaunch launch = doLaunch(config, "testAlignment"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--alignment=512")); //$NON-NLS-1$
- }
-
- @Test
- public void testAlignmentBad() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
-
- assertFalse(dynamicTab.getAlignmentSpinner().getEnabled());
- dynamicTab.getAlignmentButton().setSelection(true);
- dynamicTab.getAlignmentButton().notifyListeners(SWT.Selection, null);
- assertTrue(dynamicTab.getAlignmentSpinner().getEnabled());
-
- dynamicTab.getAlignmentSpinner().setSelection(63);
- tab.performApply(wc);
- config = wc.doSave();
-
- assertFalse(tab.isValid(config));
- }
-
- @Test
- public void testNoLeakCheck() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getLeakCheckButton().setSelection(false);
- ILaunch launch = saveAndLaunch(wc, "testNoLeakCheck"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--leak-check=no")); //$NON-NLS-1$
- }
-
- @Test
- public void testShowReachable() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getShowReachableButton().setSelection(true);
- ILaunch launch = saveAndLaunch(wc, "testShowReachable"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--show-reachable=yes")); //$NON-NLS-1$
- }
-
- @Test
- public void testLeakResolutionMed() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- String[] opts = dynamicTab.getLeakResCombo().getItems();
- int ix = Arrays.asList(opts).indexOf(
- MemcheckLaunchConstants.LEAK_RES_MED);
- dynamicTab.getLeakResCombo().select(ix);
- ILaunch launch = saveAndLaunch(wc, "testLeakResolutionMed"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--leak-resolution=med")); //$NON-NLS-1$
- }
-
- @Test
- public void testLeakResolutionHigh() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- String[] opts = dynamicTab.getLeakResCombo().getItems();
- int ix = Arrays.asList(opts).indexOf(
- MemcheckLaunchConstants.LEAK_RES_HIGH);
- dynamicTab.getLeakResCombo().select(ix);
- ILaunch launch = saveAndLaunch(wc, "testLeakResolutionHigh"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--leak-resolution=high")); //$NON-NLS-1$
- }
-
- @Test
- public void testFreeListVol() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getFreelistSpinner().setSelection(2000000);
- ILaunch launch = saveAndLaunch(wc, "testFreeListVol"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--freelist-vol=2000000")); //$NON-NLS-1$
- }
-
- @Test
- public void testWorkaroundGCCBugs() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getGccWorkaroundButton().setSelection(true);
- ILaunch launch = saveAndLaunch(wc, "testWorkaroundGCCBugs"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--workaround-gcc296-bugs=yes")); //$NON-NLS-1$
- }
-
- @Test
- public void testPartialLoads() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getPartialLoadsButton().setSelection(true);
- ILaunch launch = saveAndLaunch(wc, "testPartialLoads"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--partial-loads-ok=yes")); //$NON-NLS-1$
- }
-
- @Test
- public void testUndefValueErrors() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- dynamicTab.getUndefValueButton().setSelection(false);
- ILaunch launch = saveAndLaunch(wc, "testUndefValueErrors"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--undef-value-errors=no")); //$NON-NLS-1$
- }
-
- @Test
- public void testMainStackSize() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- IProject project = CDebugUtils.verifyCProject(wc).getProject();
- Version ver = ValgrindLaunchPlugin.getDefault().getValgrindVersion(
- project);
- if (ver.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
- assertFalse(tab.getMainStackSizeSpinner().isEnabled());
- tab.getMainStackSizeButton().setSelection(true);
- tab.getMainStackSizeButton().notifyListeners(SWT.Selection, null);
- assertTrue(tab.getMainStackSizeSpinner().isEnabled());
- tab.getMainStackSizeSpinner().setSelection(2048);
- ILaunch launch = saveAndLaunch(wc, "testMainStackFrame"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--main-stacksize=2048")); //$NON-NLS-1$
- } else {
- assertNull(tab.getMainStackSizeButton());
- assertNull(tab.getMainStackSizeSpinner());
- }
- }
-
- @Test
- public void testTrackOrigins() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- IProject project = CDebugUtils.verifyCProject(config).getProject();
- Version ver = ValgrindLaunchPlugin.getDefault().getValgrindVersion(
- project);
- if (ver.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
- dynamicTab.getTrackOriginsButton().setSelection(true);
- ILaunch launch = saveAndLaunch(wc, "testTrackOrigins"); //$NON-NLS-1$
- IProcess[] p = launch.getProcesses();
- assertTrue("process array should not be empty", p.length > 0);
- String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
- assertEquals(0, p[0].getExitValue());
- assertTrue(cmd.contains("--track-origins=yes")); //$NON-NLS-1$
- } else {
- assertNull(dynamicTab.getTrackOriginsButton());
- }
- }
-
- @Test
- public void testTrackOriginsValidity() throws Exception {
- ILaunchConfigurationWorkingCopy wc = initConfig();
- IProject project = CDebugUtils.verifyCProject(config).getProject();
- Version ver = ValgrindLaunchPlugin.getDefault().getValgrindVersion(
- project);
- if (ver.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
- dynamicTab.getTrackOriginsButton().setSelection(true);
- tab.performApply(wc);
- assertTrue(tab.isValid(wc));
- dynamicTab.getUndefValueButton().setSelection(false);
- tab.performApply(wc);
- assertFalse(tab.isValid(wc));
- }
- }
-
- @Test
- public void testValgrindError() throws Exception {
- String notExistentFile = "DOES NOT EXIST"; //$NON-NLS-1$
- ILaunchConfigurationWorkingCopy wc = initConfig();
- tab.getSuppFileList().add(notExistentFile);
- tab.performApply(wc);
- config = wc.doSave();
-
- assertFalse(tab.isValid(config));
-
- doLaunch(config, "testValgrindError"); //$NON-NLS-1$
-
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- IValgrindMessage[] messages = view.getMessages();
- assertTrue(messages.length > 0);
-
- String text = messages[0].getText();
- assertTrue(text.contains(notExistentFile));
- }
+ private ValgrindOptionsTab tab;
+ private MemcheckToolPage dynamicTab;
+ private ILaunchConfiguration config;
+ private Shell testShell;
+
+ @Before
+ public void setUpProject() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+
+ config = createConfiguration(proj.getProject());
+
+ testShell = new Shell(Display.getDefault());
+ testShell.setLayout(new GridLayout());
+ tab = new ValgrindOptionsTab();
+ }
+
+ @After
+ public void cleanup() throws Exception {
+ tab.dispose();
+ testShell.dispose();
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ private ILaunchConfigurationWorkingCopy initConfig() throws CoreException {
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ tab.setDefaults(wc);
+ tab.createControl(testShell);
+ tab.initializeFrom(config);
+ int ix = Arrays.asList(tab.getTools()).indexOf(MemcheckPlugin.TOOL_ID);
+ tab.getToolsCombo().select(ix);
+ ILaunchConfigurationTab dynamicTab = tab.getDynamicTab();
+ this.dynamicTab = (MemcheckToolPage) dynamicTab;
+ return wc;
+ }
+
+ private ILaunch saveAndLaunch(ILaunchConfigurationWorkingCopy wc,
+ String testName) throws Exception {
+ tab.performApply(wc);
+ config = wc.doSave();
+
+ return doLaunch(config, testName);
+ }
+
+ @Test
+ public void testDefaults() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ ILaunch launch = saveAndLaunch(wc, "testDefaults"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--tool=memcheck")); //$NON-NLS-1$
+ assertTrue(cmd.contains("-q")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--trace-children=no")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--child-silent-after-fork=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--demangle=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--num-callers=12")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--error-limit=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--show-below-main=no")); //$NON-NLS-1$
+ assertFalse(cmd.contains("--suppressions=")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--max-stackframe=2000000")); //$NON-NLS-1$
+ assertFalse(cmd.contains("--alignment=")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--run-libc-freeres=yes")); //$NON-NLS-1$
+
+ assertTrue(cmd.contains("--leak-check=yes")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--show-reachable=no")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--leak-resolution=high")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--freelist-vol=10000000")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--workaround-gcc296-bugs=no")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--partial-loads-ok=no")); //$NON-NLS-1$
+ assertTrue(cmd.contains("--undef-value-errors=yes")); //$NON-NLS-1$
+
+ // 3.4.0 specific
+ IProject project = CDebugUtils.verifyCProject(wc).getProject();
+ Version ver = ValgrindLaunchPlugin.getDefault().getValgrindVersion(
+ project);
+ if (ver.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
+ assertFalse(cmd.contains("--track-origins")); //$NON-NLS-1$
+ }
+ assertFalse(cmd.contains("--main-stacksize")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testWSSuppresions() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ String text = "${workspace_loc:/basicTest/testsuppfile.supp}"; //$NON-NLS-1$
+ tab.getSuppFileList().add(text);
+ ILaunch launch = saveAndLaunch(wc, "testWSSuppresions"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ IPath suppPath = ResourcesPlugin
+ .getWorkspace()
+ .getRoot()
+ .findMember(new Path("basicTest/testsuppfile.supp")).getLocation(); //$NON-NLS-1$
+ assertTrue(cmd.contains("--suppressions=" + suppPath.toOSString())); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testSuppressions() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ IPath suppPath = ResourcesPlugin
+ .getWorkspace()
+ .getRoot()
+ .findMember(new Path("basicTest/testsuppfile.supp")).getLocation(); //$NON-NLS-1$
+ tab.getSuppFileList().add(suppPath.toOSString());
+ ILaunch launch = saveAndLaunch(wc, "testSuppressions"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--suppressions=" + suppPath.toOSString())); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testSuppressionsMultiple() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ IPath suppPath = ResourcesPlugin
+ .getWorkspace()
+ .getRoot()
+ .findMember(new Path("basicTest/testsuppfile.supp")).getLocation(); //$NON-NLS-1$
+ IPath suppPath2 = ResourcesPlugin
+ .getWorkspace()
+ .getRoot()
+ .findMember(new Path("basicTest/testsuppfile2.supp")).getLocation(); //$NON-NLS-1$
+ tab.getSuppFileList().add(suppPath.toOSString());
+ tab.getSuppFileList().add(suppPath2.toOSString());
+ ILaunch launch = saveAndLaunch(wc, "testSuppressionsMultiple"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--suppressions=" + suppPath.toOSString())); //$NON-NLS-1$
+ assertTrue(cmd.contains("--suppressions=" + suppPath2.toOSString())); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testSuppressionsSpaces() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ IPath suppPath = ResourcesPlugin
+ .getWorkspace()
+ .getRoot()
+ .findMember(new Path("basicTest/test suppfile.supp")).getLocation(); //$NON-NLS-1$
+ tab.getSuppFileList().add(suppPath.toOSString());
+ ILaunch launch = saveAndLaunch(wc, "testSuppressionsSpaces"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--suppressions=" + suppPath.toOSString())); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testTraceChildren() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ tab.getTraceChildrenButton().setSelection(true);
+ ILaunch launch = saveAndLaunch(wc, "testTraceChildren"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--trace-children=yes")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testDemangle() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ tab.getDemangleButton().setSelection(false);
+ ILaunch launch = saveAndLaunch(wc, "testDemangle"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--demangle=no")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testNumCallers() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ tab.getNumCallersSpinner().setSelection(24);
+ ILaunch launch = saveAndLaunch(wc, "testNumCallers"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--num-callers=24")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testErrorLimit() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ tab.getErrorLimitButton().setSelection(false);
+ ILaunch launch = saveAndLaunch(wc, "testErrorLimit"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--error-limit=no")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testShowBelowMain() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ tab.getShowBelowMainButton().setSelection(true);
+ ILaunch launch = saveAndLaunch(wc, "testShowBelowMain"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--show-below-main=yes")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testMaxStackframe() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ tab.getMaxStackFrameSpinner().setSelection(50000000);
+ ILaunch launch = saveAndLaunch(wc, "testMaxStackframe"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--max-stackframe=50000000")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testRunFreeRes() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ tab.getRunFreeresButton().setSelection(false);
+ ILaunch launch = saveAndLaunch(wc, "testRunFreeRes"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue(p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--run-libc-freeres=no")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testAlignment() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+
+ assertFalse(dynamicTab.getAlignmentSpinner().getEnabled());
+ dynamicTab.getAlignmentButton().setSelection(true);
+ dynamicTab.getAlignmentButton().notifyListeners(SWT.Selection, null);
+ assertTrue(dynamicTab.getAlignmentSpinner().getEnabled());
+
+ dynamicTab.getAlignmentSpinner().setSelection(512);
+ tab.performApply(wc);
+ config = wc.doSave();
+
+ assertTrue(tab.isValid(config));
+
+ ILaunch launch = doLaunch(config, "testAlignment"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--alignment=512")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testAlignmentBad() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+
+ assertFalse(dynamicTab.getAlignmentSpinner().getEnabled());
+ dynamicTab.getAlignmentButton().setSelection(true);
+ dynamicTab.getAlignmentButton().notifyListeners(SWT.Selection, null);
+ assertTrue(dynamicTab.getAlignmentSpinner().getEnabled());
+
+ dynamicTab.getAlignmentSpinner().setSelection(63);
+ tab.performApply(wc);
+ config = wc.doSave();
+
+ assertFalse(tab.isValid(config));
+ }
+
+ @Test
+ public void testNoLeakCheck() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getLeakCheckButton().setSelection(false);
+ ILaunch launch = saveAndLaunch(wc, "testNoLeakCheck"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--leak-check=no")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testShowReachable() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getShowReachableButton().setSelection(true);
+ ILaunch launch = saveAndLaunch(wc, "testShowReachable"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--show-reachable=yes")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testLeakResolutionMed() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ String[] opts = dynamicTab.getLeakResCombo().getItems();
+ int ix = Arrays.asList(opts).indexOf(
+ MemcheckLaunchConstants.LEAK_RES_MED);
+ dynamicTab.getLeakResCombo().select(ix);
+ ILaunch launch = saveAndLaunch(wc, "testLeakResolutionMed"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--leak-resolution=med")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testLeakResolutionHigh() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ String[] opts = dynamicTab.getLeakResCombo().getItems();
+ int ix = Arrays.asList(opts).indexOf(
+ MemcheckLaunchConstants.LEAK_RES_HIGH);
+ dynamicTab.getLeakResCombo().select(ix);
+ ILaunch launch = saveAndLaunch(wc, "testLeakResolutionHigh"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--leak-resolution=high")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testFreeListVol() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getFreelistSpinner().setSelection(2000000);
+ ILaunch launch = saveAndLaunch(wc, "testFreeListVol"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--freelist-vol=2000000")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testWorkaroundGCCBugs() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getGccWorkaroundButton().setSelection(true);
+ ILaunch launch = saveAndLaunch(wc, "testWorkaroundGCCBugs"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--workaround-gcc296-bugs=yes")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testPartialLoads() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getPartialLoadsButton().setSelection(true);
+ ILaunch launch = saveAndLaunch(wc, "testPartialLoads"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--partial-loads-ok=yes")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testUndefValueErrors() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ dynamicTab.getUndefValueButton().setSelection(false);
+ ILaunch launch = saveAndLaunch(wc, "testUndefValueErrors"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--undef-value-errors=no")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testMainStackSize() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ IProject project = CDebugUtils.verifyCProject(wc).getProject();
+ Version ver = ValgrindLaunchPlugin.getDefault().getValgrindVersion(
+ project);
+ if (ver.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
+ assertFalse(tab.getMainStackSizeSpinner().isEnabled());
+ tab.getMainStackSizeButton().setSelection(true);
+ tab.getMainStackSizeButton().notifyListeners(SWT.Selection, null);
+ assertTrue(tab.getMainStackSizeSpinner().isEnabled());
+ tab.getMainStackSizeSpinner().setSelection(2048);
+ ILaunch launch = saveAndLaunch(wc, "testMainStackFrame"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--main-stacksize=2048")); //$NON-NLS-1$
+ } else {
+ assertNull(tab.getMainStackSizeButton());
+ assertNull(tab.getMainStackSizeSpinner());
+ }
+ }
+
+ @Test
+ public void testTrackOrigins() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ IProject project = CDebugUtils.verifyCProject(config).getProject();
+ Version ver = ValgrindLaunchPlugin.getDefault().getValgrindVersion(
+ project);
+ if (ver.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
+ dynamicTab.getTrackOriginsButton().setSelection(true);
+ ILaunch launch = saveAndLaunch(wc, "testTrackOrigins"); //$NON-NLS-1$
+ IProcess[] p = launch.getProcesses();
+ assertTrue("process array should not be empty", p.length > 0);
+ String cmd = p[0].getAttribute(IProcess.ATTR_CMDLINE);
+ assertEquals(0, p[0].getExitValue());
+ assertTrue(cmd.contains("--track-origins=yes")); //$NON-NLS-1$
+ } else {
+ assertNull(dynamicTab.getTrackOriginsButton());
+ }
+ }
+
+ @Test
+ public void testTrackOriginsValidity() throws Exception {
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ IProject project = CDebugUtils.verifyCProject(config).getProject();
+ Version ver = ValgrindLaunchPlugin.getDefault().getValgrindVersion(
+ project);
+ if (ver.compareTo(ValgrindLaunchPlugin.VER_3_4_0) >= 0) {
+ dynamicTab.getTrackOriginsButton().setSelection(true);
+ tab.performApply(wc);
+ assertTrue(tab.isValid(wc));
+ dynamicTab.getUndefValueButton().setSelection(false);
+ tab.performApply(wc);
+ assertFalse(tab.isValid(wc));
+ }
+ }
+
+ @Test
+ public void testValgrindError() throws Exception {
+ String notExistentFile = "DOES NOT EXIST"; //$NON-NLS-1$
+ ILaunchConfigurationWorkingCopy wc = initConfig();
+ tab.getSuppFileList().add(notExistentFile);
+ tab.performApply(wc);
+ config = wc.doSave();
+
+ assertFalse(tab.isValid(config));
+
+ doLaunch(config, "testValgrindError"); //$NON-NLS-1$
+
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ IValgrindMessage[] messages = view.getMessages();
+ assertTrue(messages.length > 0);
+
+ String text = messages[0].getText();
+ assertTrue(text.contains(notExistentFile));
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LinkedResourceDoubleClickTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LinkedResourceDoubleClickTest.java
index 0c7caf03cb..e1bf578712 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LinkedResourceDoubleClickTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LinkedResourceDoubleClickTest.java
@@ -37,73 +37,73 @@ import org.eclipse.ui.texteditor.ITextEditor;
import org.junit.Test;
public class LinkedResourceDoubleClickTest extends AbstractLinkedResourceMemcheckTest {
- private ValgrindStackFrame frame;
- @Test
- public void testLinkedDoubleClickFile() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testLinkedDoubleClickFile"); //$NON-NLS-1$
+ private ValgrindStackFrame frame;
+ @Test
+ public void testLinkedDoubleClickFile() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testLinkedDoubleClickFile"); //$NON-NLS-1$
- doDoubleClick();
+ doDoubleClick();
- IEditorPart editor = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- IEditorInput input = editor.getEditorInput();
- assertTrue("editor input must be file input",
- input instanceof IFileEditorInput);
- IFileEditorInput fileInput = (IFileEditorInput) input;
- IFolder srcFolder = proj.getProject().getFolder("src"); //$NON-NLS-1$
- File expectedFile = new File(srcFolder.getLocation().toOSString(),
- frame.getFile());
- File actualFile = fileInput.getFile().getLocation().toFile();
+ IEditorPart editor = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage().getActiveEditor();
+ IEditorInput input = editor.getEditorInput();
+ assertTrue("editor input must be file input",
+ input instanceof IFileEditorInput);
+ IFileEditorInput fileInput = (IFileEditorInput) input;
+ IFolder srcFolder = proj.getProject().getFolder("src"); //$NON-NLS-1$
+ File expectedFile = new File(srcFolder.getLocation().toOSString(),
+ frame.getFile());
+ File actualFile = fileInput.getFile().getLocation().toFile();
- assertTrue(fileInput.getFile().isLinked(IResource.CHECK_ANCESTORS));
- assertEquals(expectedFile.getCanonicalPath(),
- actualFile.getCanonicalPath());
- }
- @Test
- public void testLinkedDoubleClickLine() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testLinkedDoubleClickLine"); //$NON-NLS-1$
+ assertTrue(fileInput.getFile().isLinked(IResource.CHECK_ANCESTORS));
+ assertEquals(expectedFile.getCanonicalPath(),
+ actualFile.getCanonicalPath());
+ }
+ @Test
+ public void testLinkedDoubleClickLine() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testLinkedDoubleClickLine"); //$NON-NLS-1$
- doDoubleClick();
+ doDoubleClick();
- IEditorPart editor = PlatformUI.getWorkbench()
- .getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- assertTrue("editor must be text editor", editor instanceof ITextEditor);
- ITextEditor textEditor = (ITextEditor) editor;
+ IEditorPart editor = PlatformUI.getWorkbench()
+ .getActiveWorkbenchWindow().getActivePage().getActiveEditor();
+ assertTrue("editor must be text editor", editor instanceof ITextEditor);
+ ITextEditor textEditor = (ITextEditor) editor;
- ISelection selection = textEditor.getSelectionProvider().getSelection();
- assertTrue("selection must be text one",
- selection instanceof TextSelection);
- TextSelection textSelection = (TextSelection) selection;
- int line = textSelection.getStartLine() + 1; // zero-indexed
+ ISelection selection = textEditor.getSelectionProvider().getSelection();
+ assertTrue("selection must be text one",
+ selection instanceof TextSelection);
+ TextSelection textSelection = (TextSelection) selection;
+ int line = textSelection.getStartLine() + 1; // zero-indexed
- assertEquals(frame.getLine(), line);
- }
+ assertEquals(frame.getLine(), line);
+ }
- private void doDoubleClick() {
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- CoreMessagesViewer viewer = view.getMessagesViewer();
+ private void doDoubleClick() {
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ CoreMessagesViewer viewer = view.getMessagesViewer();
- // get first leaf
- IValgrindMessage[] elements = (IValgrindMessage[]) viewer.getTreeViewer().getInput();
- IValgrindMessage element = elements[0];
- TreePath path = new TreePath(new Object[] { element });
- frame = null;
- while (element.getChildren().length > 0) {
- element = element.getChildren()[0];
- path = path.createChildPath(element);
- if (element instanceof ValgrindStackFrame) {
- frame = (ValgrindStackFrame) element;
- }
- }
- assertNotNull(frame);
+ // get first leaf
+ IValgrindMessage[] elements = (IValgrindMessage[]) viewer.getTreeViewer().getInput();
+ IValgrindMessage element = elements[0];
+ TreePath path = new TreePath(new Object[] { element });
+ frame = null;
+ while (element.getChildren().length > 0) {
+ element = element.getChildren()[0];
+ path = path.createChildPath(element);
+ if (element instanceof ValgrindStackFrame) {
+ frame = (ValgrindStackFrame) element;
+ }
+ }
+ assertNotNull(frame);
- viewer.getTreeViewer().expandToLevel(frame, AbstractTreeViewer.ALL_LEVELS);
- TreeSelection selection = new TreeSelection(path);
+ viewer.getTreeViewer().expandToLevel(frame, AbstractTreeViewer.ALL_LEVELS);
+ TreeSelection selection = new TreeSelection(path);
- // do double click
- IDoubleClickListener listener = viewer.getDoubleClickListener();
- listener.doubleClick(new DoubleClickEvent(viewer.getTreeViewer(), selection));
- }
+ // do double click
+ IDoubleClickListener listener = viewer.getDoubleClickListener();
+ listener.doubleClick(new DoubleClickEvent(viewer.getTreeViewer(), selection));
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LinkedResourceMarkerTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LinkedResourceMarkerTest.java
index 432fc7fdbe..3ca6e154db 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LinkedResourceMarkerTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/LinkedResourceMarkerTest.java
@@ -31,55 +31,55 @@ import org.eclipse.linuxtools.valgrind.core.IValgrindMessage;
import org.junit.Test;
public class LinkedResourceMarkerTest extends AbstractLinkedResourceMemcheckTest {
- @Test
- public void testLinkedMarkers() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testLinkedMarkers"); //$NON-NLS-1$
+ @Test
+ public void testLinkedMarkers() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testLinkedMarkers"); //$NON-NLS-1$
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- IValgrindMessage[] errors = view.getMessages();
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ IValgrindMessage[] errors = view.getMessages();
- ArrayList<IMarker> markers = new ArrayList<>(Arrays.asList(proj
- .getProject().findMarkers(ValgrindLaunchPlugin.MARKER_TYPE,
- true, IResource.DEPTH_INFINITE)));
- assertEquals(5, markers.size());
- for (IValgrindMessage error : errors) {
- findMarker(markers, error);
- }
- assertEquals(0, markers.size());
- }
+ ArrayList<IMarker> markers = new ArrayList<>(Arrays.asList(proj
+ .getProject().findMarkers(ValgrindLaunchPlugin.MARKER_TYPE,
+ true, IResource.DEPTH_INFINITE)));
+ assertEquals(5, markers.size());
+ for (IValgrindMessage error : errors) {
+ findMarker(markers, error);
+ }
+ assertEquals(0, markers.size());
+ }
- private void findMarker(ArrayList<IMarker> markers, IValgrindMessage error)
- throws Exception, CoreException {
- ValgrindStackFrame frame = null;
- IValgrindMessage[] children = error.getChildren();
- for (int i = 0; i < children.length; i++) {
- if (frame == null && children[i] instanceof ValgrindStackFrame
- && isWorkspaceFrame((ValgrindStackFrame) children[i])) {
- frame = (ValgrindStackFrame) children[i];
- } else if (children[i] instanceof ValgrindError) {
- findMarker(markers, children[i]);
- }
- }
+ private void findMarker(ArrayList<IMarker> markers, IValgrindMessage error)
+ throws Exception, CoreException {
+ ValgrindStackFrame frame = null;
+ IValgrindMessage[] children = error.getChildren();
+ for (int i = 0; i < children.length; i++) {
+ if (frame == null && children[i] instanceof ValgrindStackFrame
+ && isWorkspaceFrame((ValgrindStackFrame) children[i])) {
+ frame = (ValgrindStackFrame) children[i];
+ } else if (children[i] instanceof ValgrindError) {
+ findMarker(markers, children[i]);
+ }
+ }
- int ix = -1;
- for (int i = 0; i < markers.size(); i++) {
- IMarker marker = markers.get(i);
- if (marker.getAttribute(IMarker.MESSAGE).equals(error.getText())
- && marker.getResource().getName().equals(frame.getFile())
- && marker.getAttribute(IMarker.LINE_NUMBER).equals(
- frame.getLine())) {
- ix = i;
- }
- }
- assertFalse(ix < 0);
- markers.remove(ix);
- }
+ int ix = -1;
+ for (int i = 0; i < markers.size(); i++) {
+ IMarker marker = markers.get(i);
+ if (marker.getAttribute(IMarker.MESSAGE).equals(error.getText())
+ && marker.getResource().getName().equals(frame.getFile())
+ && marker.getAttribute(IMarker.LINE_NUMBER).equals(
+ frame.getLine())) {
+ ix = i;
+ }
+ }
+ assertFalse(ix < 0);
+ markers.remove(ix);
+ }
- private boolean isWorkspaceFrame(ValgrindStackFrame frame) {
- ISourceLocator locator = frame.getLaunch().getSourceLocator();
- Object result = DebugUITools.lookupSource(frame.getFile(), locator)
- .getSourceElement();
- return result != null && result instanceof IResource;
- }
+ private boolean isWorkspaceFrame(ValgrindStackFrame frame) {
+ ISourceLocator locator = frame.getLaunch().getSourceLocator();
+ Object result = DebugUITools.lookupSource(frame.getFile(), locator)
+ .getSourceElement();
+ return result != null && result instanceof IResource;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MarkerTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MarkerTest.java
index 5a912be15d..61454e88de 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MarkerTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MarkerTest.java
@@ -33,67 +33,67 @@ import org.junit.Before;
import org.junit.Test;
public class MarkerTest extends AbstractMemcheckTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
- @Test
- public void testMarkers() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testDefaults"); //$NON-NLS-1$
+ @Test
+ public void testMarkers() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testDefaults"); //$NON-NLS-1$
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- IValgrindMessage[] errors = view.getMessages();
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ IValgrindMessage[] errors = view.getMessages();
- ArrayList<IMarker> markers = new ArrayList<>(Arrays.asList(proj
- .getProject().findMarkers(ValgrindLaunchPlugin.MARKER_TYPE,
- true, IResource.DEPTH_INFINITE)));
- assertEquals(5, markers.size());
- for (IValgrindMessage error : errors) {
- findMarker(markers, error);
- }
- assertEquals(0, markers.size());
- }
+ ArrayList<IMarker> markers = new ArrayList<>(Arrays.asList(proj
+ .getProject().findMarkers(ValgrindLaunchPlugin.MARKER_TYPE,
+ true, IResource.DEPTH_INFINITE)));
+ assertEquals(5, markers.size());
+ for (IValgrindMessage error : errors) {
+ findMarker(markers, error);
+ }
+ assertEquals(0, markers.size());
+ }
- private void findMarker(ArrayList<IMarker> markers, IValgrindMessage error)
- throws Exception, CoreException {
- ValgrindStackFrame frame = null;
- IValgrindMessage[] children = error.getChildren();
- for (int i = 0; i < children.length; i++) {
- if (frame == null && children[i] instanceof ValgrindStackFrame
- && isWorkspaceFrame((ValgrindStackFrame) children[i])) {
- frame = (ValgrindStackFrame) children[i];
- } else if (children[i] instanceof ValgrindError) {
- findMarker(markers, children[i]);
- }
- }
+ private void findMarker(ArrayList<IMarker> markers, IValgrindMessage error)
+ throws Exception, CoreException {
+ ValgrindStackFrame frame = null;
+ IValgrindMessage[] children = error.getChildren();
+ for (int i = 0; i < children.length; i++) {
+ if (frame == null && children[i] instanceof ValgrindStackFrame
+ && isWorkspaceFrame((ValgrindStackFrame) children[i])) {
+ frame = (ValgrindStackFrame) children[i];
+ } else if (children[i] instanceof ValgrindError) {
+ findMarker(markers, children[i]);
+ }
+ }
- int ix = -1;
- for (int i = 0; i < markers.size(); i++) {
- IMarker marker = markers.get(i);
- if (marker.getAttribute(IMarker.MESSAGE).equals(error.getText())
- && marker.getResource().getName().equals(frame.getFile())
- && marker.getAttribute(IMarker.LINE_NUMBER).equals(
- frame.getLine())) {
- ix = i;
- }
- }
- assertFalse(ix < 0);
- markers.remove(ix);
- }
+ int ix = -1;
+ for (int i = 0; i < markers.size(); i++) {
+ IMarker marker = markers.get(i);
+ if (marker.getAttribute(IMarker.MESSAGE).equals(error.getText())
+ && marker.getResource().getName().equals(frame.getFile())
+ && marker.getAttribute(IMarker.LINE_NUMBER).equals(
+ frame.getLine())) {
+ ix = i;
+ }
+ }
+ assertFalse(ix < 0);
+ markers.remove(ix);
+ }
- private boolean isWorkspaceFrame(ValgrindStackFrame frame) {
- ISourceLocator locator = frame.getLaunch().getSourceLocator();
- Object result = DebugUITools.lookupSource(frame.getFile(), locator)
- .getSourceElement();
- return result != null && result instanceof IResource;
- }
+ private boolean isWorkspaceFrame(ValgrindStackFrame frame) {
+ ISourceLocator locator = frame.getLaunch().getSourceLocator();
+ Object result = DebugUITools.lookupSource(frame.getFile(), locator)
+ .getSourceElement();
+ return result != null && result instanceof IResource;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MinVersionTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MinVersionTest.java
index 12f03cedf0..fff9504730 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MinVersionTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MinVersionTest.java
@@ -30,75 +30,75 @@ import org.junit.Test;
public class MinVersionTest extends AbstractMemcheckTest {
- static class ValgrindIncorrectVersion extends ValgrindStubCommand {
- @Override
- public String whichVersion(IProject project) {
- return "valgrind-3.2.1"; //$NON-NLS-1$
- }
- }
-
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
-
- saveVersion();
- }
-
- private void saveVersion() {
- ValgrindLaunchPlugin.getDefault().setValgrindCommand(
- new ValgrindIncorrectVersion());
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- restoreVersion();
-
- deleteProject(proj);
- super.tearDown();
- }
-
- private void restoreVersion() {
- ValgrindLaunchPlugin.getDefault().setValgrindCommand(
- new ValgrindCommand());
- }
-
- @Test
- public void testLaunchBadVersion() throws Exception {
- // Put this back so we can make a valid config
- restoreVersion();
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- // For some reason we downgraded
- saveVersion();
-
- try {
- doLaunch(config, "testDefaults"); //$NON-NLS-1$
- } catch (CoreException e) {
- assertNotNull(e);
- }
-
- }
-
- @Test
- public void testTabsBadVersion() throws Exception {
- Shell testShell = new Shell(Display.getDefault());
- testShell.setLayout(new GridLayout());
- ValgrindOptionsTab tab = new ValgrindOptionsTab();
-
- ILaunchConfiguration config = getLaunchConfigType().newInstance(
- null,
- getLaunchManager().generateLaunchConfigurationName(
- proj.getProject().getName()));
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- tab.setDefaults(wc);
- tab.createControl(testShell);
- tab.initializeFrom(config);
- tab.performApply(wc);
-
- assertFalse(tab.isValid(config));
- assertNotNull(tab.getErrorMessage());
-
- testShell.dispose();
- }
+ static class ValgrindIncorrectVersion extends ValgrindStubCommand {
+ @Override
+ public String whichVersion(IProject project) {
+ return "valgrind-3.2.1"; //$NON-NLS-1$
+ }
+ }
+
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+
+ saveVersion();
+ }
+
+ private void saveVersion() {
+ ValgrindLaunchPlugin.getDefault().setValgrindCommand(
+ new ValgrindIncorrectVersion());
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ restoreVersion();
+
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ private void restoreVersion() {
+ ValgrindLaunchPlugin.getDefault().setValgrindCommand(
+ new ValgrindCommand());
+ }
+
+ @Test
+ public void testLaunchBadVersion() throws Exception {
+ // Put this back so we can make a valid config
+ restoreVersion();
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ // For some reason we downgraded
+ saveVersion();
+
+ try {
+ doLaunch(config, "testDefaults"); //$NON-NLS-1$
+ } catch (CoreException e) {
+ assertNotNull(e);
+ }
+
+ }
+
+ @Test
+ public void testTabsBadVersion() throws Exception {
+ Shell testShell = new Shell(Display.getDefault());
+ testShell.setLayout(new GridLayout());
+ ValgrindOptionsTab tab = new ValgrindOptionsTab();
+
+ ILaunchConfiguration config = getLaunchConfigType().newInstance(
+ null,
+ getLaunchManager().generateLaunchConfigurationName(
+ proj.getProject().getName()));
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ tab.setDefaults(wc);
+ tab.createControl(testShell);
+ tab.initializeFrom(config);
+ tab.performApply(wc);
+
+ assertFalse(tab.isValid(config));
+ assertNotNull(tab.getErrorMessage());
+
+ testShell.dispose();
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MultiProcessTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MultiProcessTest.java
index fefbfacdaf..be1a9dece5 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MultiProcessTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/MultiProcessTest.java
@@ -24,39 +24,39 @@ import org.junit.Before;
import org.junit.Test;
public class MultiProcessTest extends AbstractMemcheckTest {
- private ICProject refProj;
+ private ICProject refProj;
- @Before
- public void prep() throws Exception {
- refProj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
- proj = createProjectAndBuild("multiProcTest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ refProj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+ proj = createProjectAndBuild("multiProcTest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- deleteProject(refProj);
- super.tearDown();
- }
- @Test
- public void testNoExec() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testNoExec"); //$NON-NLS-1$
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ deleteProject(refProj);
+ super.tearDown();
+ }
+ @Test
+ public void testNoExec() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testNoExec"); //$NON-NLS-1$
- IValgrindMessage[] messages = ValgrindUIPlugin.getDefault().getView().getMessages();
- assertEquals(1, messages.length);
- checkTestMessages(messages, "testNoExec"); //$NON-NLS-1$
- }
- @Test
- public void testExec() throws Exception {
- ILaunchConfigurationWorkingCopy config = createConfiguration(proj.getProject()).getWorkingCopy();
- config.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
- config.doSave();
- doLaunch(config, "testExec"); //$NON-NLS-1$
+ IValgrindMessage[] messages = ValgrindUIPlugin.getDefault().getView().getMessages();
+ assertEquals(1, messages.length);
+ checkTestMessages(messages, "testNoExec"); //$NON-NLS-1$
+ }
+ @Test
+ public void testExec() throws Exception {
+ ILaunchConfigurationWorkingCopy config = createConfiguration(proj.getProject()).getWorkingCopy();
+ config.setAttribute(LaunchConfigurationConstants.ATTR_GENERAL_TRACECHILD, true);
+ config.doSave();
+ doLaunch(config, "testExec"); //$NON-NLS-1$
- IValgrindMessage[] messages = ValgrindUIPlugin.getDefault().getView().getMessages();
- assertEquals(4, messages.length);
- checkTestMessages(messages, "testExec"); //$NON-NLS-1$
- }
+ IValgrindMessage[] messages = ValgrindUIPlugin.getDefault().getView().getMessages();
+ assertEquals(4, messages.length);
+ checkTestMessages(messages, "testExec"); //$NON-NLS-1$
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/ShortcutTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/ShortcutTest.java
index 97baacab0a..d8ba491e54 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/ShortcutTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/ShortcutTest.java
@@ -31,61 +31,61 @@ import org.junit.Test;
public class ShortcutTest extends AbstractMemcheckTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("basicTest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
- @Test
- public void testShortcutSelection() throws Exception {
- ValgrindTestLaunchShortcut shortcut = new ValgrindTestLaunchShortcut();
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+ @Test
+ public void testShortcutSelection() throws Exception {
+ ValgrindTestLaunchShortcut shortcut = new ValgrindTestLaunchShortcut();
- shortcut.launch(new StructuredSelection(proj.getProject()), ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration config = shortcut.getConfig();
+ shortcut.launch(new StructuredSelection(proj.getProject()), ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration config = shortcut.getConfig();
- compareWithDefaults(config);
- }
- @Test
- public void testShortcutEditor() throws Exception {
- ValgrindTestLaunchShortcut shortcut = new ValgrindTestLaunchShortcut();
+ compareWithDefaults(config);
+ }
+ @Test
+ public void testShortcutEditor() throws Exception {
+ ValgrindTestLaunchShortcut shortcut = new ValgrindTestLaunchShortcut();
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- IFile file = proj.getProject().getFile("test.c"); //$NON-NLS-1$
- IEditorPart editor = IDE.openEditor(page, file);
+ IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
+ IFile file = proj.getProject().getFile("test.c"); //$NON-NLS-1$
+ IEditorPart editor = IDE.openEditor(page, file);
- assertNotNull(editor);
+ assertNotNull(editor);
- shortcut.launch(editor, ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration config = shortcut.getConfig();
+ shortcut.launch(editor, ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration config = shortcut.getConfig();
- compareWithDefaults(config);
- }
- @Test
- public void testShortcutExistingConfig() throws Exception {
- ILaunchConfiguration prev = createConfiguration(proj.getProject());
+ compareWithDefaults(config);
+ }
+ @Test
+ public void testShortcutExistingConfig() throws Exception {
+ ILaunchConfiguration prev = createConfiguration(proj.getProject());
- ValgrindTestLaunchShortcut shortcut = new ValgrindTestLaunchShortcut();
- shortcut.launch(new StructuredSelection(proj.getProject()), ILaunchManager.PROFILE_MODE);
- ILaunchConfiguration current = shortcut.getConfig();
+ ValgrindTestLaunchShortcut shortcut = new ValgrindTestLaunchShortcut();
+ shortcut.launch(new StructuredSelection(proj.getProject()), ILaunchManager.PROFILE_MODE);
+ ILaunchConfiguration current = shortcut.getConfig();
- assertEquals(prev, current);
- }
+ assertEquals(prev, current);
+ }
- private void compareWithDefaults(ILaunchConfiguration config)
- throws CoreException {
- // tests launch in foreground, this is not typical
- ILaunchConfiguration defaults = createConfiguration(proj.getProject());
- ILaunchConfigurationWorkingCopy wc = defaults.getWorkingCopy();
- wc.removeAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND);
- wc.doSave();
+ private void compareWithDefaults(ILaunchConfiguration config)
+ throws CoreException {
+ // tests launch in foreground, this is not typical
+ ILaunchConfiguration defaults = createConfiguration(proj.getProject());
+ ILaunchConfigurationWorkingCopy wc = defaults.getWorkingCopy();
+ wc.removeAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND);
+ wc.doSave();
- // Compare launch config with defaults
- assertEquals(config.getAttributes(), defaults.getAttributes());
- }
+ // Compare launch config with defaults
+ assertEquals(config.getAttributes(), defaults.getAttributes());
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/SignalTest.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/SignalTest.java
index 69a9ec5b41..e8731a5210 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/SignalTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck.tests/src/org/eclipse/linuxtools/internal/valgrind/memcheck/tests/SignalTest.java
@@ -23,26 +23,26 @@ import org.junit.Test;
public class SignalTest extends AbstractMemcheckTest {
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("segvtest"); //$NON-NLS-1$
- }
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("segvtest"); //$NON-NLS-1$
+ }
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
- @Test
- public void testSegfaultHandle() throws Exception {
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "testSegfault"); //$NON-NLS-1$
+ @Test
+ public void testSegfaultHandle() throws Exception {
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "testSegfault"); //$NON-NLS-1$
- ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
- IValgrindMessage[] messages = view.getMessages();
- assertTrue(messages.length > 0);
- assertTrue(messages[0].getText().contains("SIGSEGV")); //$NON-NLS-1$
- }
+ ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
+ IValgrindMessage[] messages = view.getMessages();
+ assertTrue(messages.length > 0);
+ assertTrue(messages[0].getText().contains("SIGSEGV")); //$NON-NLS-1$
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/plugin.xml b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/plugin.xml
index 4a4fdf5f62..b31f0629ce 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/plugin.xml
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/plugin.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
- <extension
+ <extension
point="org.eclipse.linuxtools.valgrind.launch.valgrindTools">
<tool
delegate="org.eclipse.linuxtools.internal.valgrind.memcheck.MemcheckLaunchDelegate"
@@ -30,5 +30,5 @@
tabgroup="org.eclipse.linuxtools.internal.valgrind.memcheck.MemcheckLaunchConfigurationTabGroup"
type="memory">
</provider>
- </extension>
+ </extension>
</plugin>
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckCommandConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckCommandConstants.java
index 102a281ce5..b5f54a5af9 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckCommandConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckCommandConstants.java
@@ -11,22 +11,22 @@
package org.eclipse.linuxtools.internal.valgrind.memcheck;
public final class MemcheckCommandConstants {
- // Valgrind program arguments
- public static final String OPT_LEAKCHECK = "--leak-check"; //$NON-NLS-1$
- public static final String OPT_SHOWREACH = "--show-reachable"; //$NON-NLS-1$
- public static final String OPT_LEAKRES = "--leak-resolution"; //$NON-NLS-1$
- public static final String OPT_FREELIST = "--freelist-vol"; //$NON-NLS-1$
- public static final String OPT_GCCWORK = "--workaround-gcc296-bugs"; //$NON-NLS-1$
- public static final String OPT_PARTIAL = "--partial-loads-ok"; //$NON-NLS-1$
- public static final String OPT_UNDEF = "--undef-value-errors"; //$NON-NLS-1$
- public static final String OPT_ALIGNMENT = "--alignment"; //$NON-NLS-1$
- public static final String OPT_IGNORERANGES = "--ignore-ranges"; //$NON-NLS-1$
- public static final String OPT_MALLOCFILL = "--malloc-fill"; //$NON-NLS-1$
- public static final String OPT_FREEFILL = "--free-fill"; //$NON-NLS-1$
-
- // VG >= 3.4.0
- public static final String OPT_TRACKORIGINS = "--track-origins"; //$NON-NLS-1$
-
- // VG >= 3.6.0
- public static final String OPT_SHOW_POSSIBLY_LOST = "--show-possibly-lost"; //$NON-NLS-1$
+ // Valgrind program arguments
+ public static final String OPT_LEAKCHECK = "--leak-check"; //$NON-NLS-1$
+ public static final String OPT_SHOWREACH = "--show-reachable"; //$NON-NLS-1$
+ public static final String OPT_LEAKRES = "--leak-resolution"; //$NON-NLS-1$
+ public static final String OPT_FREELIST = "--freelist-vol"; //$NON-NLS-1$
+ public static final String OPT_GCCWORK = "--workaround-gcc296-bugs"; //$NON-NLS-1$
+ public static final String OPT_PARTIAL = "--partial-loads-ok"; //$NON-NLS-1$
+ public static final String OPT_UNDEF = "--undef-value-errors"; //$NON-NLS-1$
+ public static final String OPT_ALIGNMENT = "--alignment"; //$NON-NLS-1$
+ public static final String OPT_IGNORERANGES = "--ignore-ranges"; //$NON-NLS-1$
+ public static final String OPT_MALLOCFILL = "--malloc-fill"; //$NON-NLS-1$
+ public static final String OPT_FREEFILL = "--free-fill"; //$NON-NLS-1$
+
+ // VG >= 3.4.0
+ public static final String OPT_TRACKORIGINS = "--track-origins"; //$NON-NLS-1$
+
+ // VG >= 3.6.0
+ public static final String OPT_SHOW_POSSIBLY_LOST = "--show-possibly-lost"; //$NON-NLS-1$
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchConfigurationTabGroup.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchConfigurationTabGroup.java
index 281f325026..640fb66f63 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchConfigurationTabGroup.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchConfigurationTabGroup.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Red Hat Inc. - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.memcheck;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
@@ -15,13 +15,13 @@ import org.eclipse.linuxtools.internal.valgrind.launch.ValgrindSingleToolOptions
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationTabGroup;
public class MemcheckLaunchConfigurationTabGroup extends
- ProfileLaunchConfigurationTabGroup {
+ ProfileLaunchConfigurationTabGroup {
+
+ @Override
+ public AbstractLaunchConfigurationTab[] getProfileTabs() {
+ return new AbstractLaunchConfigurationTab[] {
+ new ValgrindSingleToolOptionsTab(MemcheckPlugin.TOOL_ID)
+ };
+ }
- @Override
- public AbstractLaunchConfigurationTab[] getProfileTabs() {
- return new AbstractLaunchConfigurationTab[] {
- new ValgrindSingleToolOptionsTab(MemcheckPlugin.TOOL_ID)
- };
- }
-
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchConstants.java
index eb9cf94c10..bd5e02dc95 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchConstants.java
@@ -14,50 +14,50 @@ import java.util.Collections;
import java.util.List;
public final class MemcheckLaunchConstants {
- // LaunchConfiguration attributes
- public static final String ATTR_MEMCHECK_LEAKCHECK = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_LEAKCHECK"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_LEAKRES = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_LEAKRES"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_SHOWREACH = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_SHOWREACH"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_PARTIAL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_PARTIAL"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_UNDEF = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_UNDEF"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_FREELIST = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_FREELIST"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_GCCWORK = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_GCCWORK"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_ALIGNMENT_BOOL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_ALIGNMENT_BOOL"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_ALIGNMENT_VAL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_ALIGNMENT_VAL"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_MALLOCFILL_BOOL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_MALLOCFILL_BOOL"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_MALLOCFILL_VAL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_MALLOCFILL_VAL"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_FREEFILL_BOOL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_FREEFILL_BOOL"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_FREEFILL_VAL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_FREEFILL_VAL"; //$NON-NLS-1$
- public static final String ATTR_MEMCHECK_IGNORE_RANGES = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_IGNORE_RANGES"; //$NON-NLS-1$
-
- // VG >= 3.4.0
- public static final String ATTR_MEMCHECK_TRACKORIGINS = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_TRACKORIGINS"; //$NON-NLS-1$
-
- // VG >= 3.6.0
- public static final String ATTR_MEMCHECK_POSSIBLY_LOST_BOOL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_POSSIBLY_LOST"; //$NON-NLS-1$
-
- public static final String LEAK_RES_LOW = "low"; //$NON-NLS-1$
- public static final String LEAK_RES_MED = "med"; //$NON-NLS-1$
- public static final String LEAK_RES_HIGH = "high"; //$NON-NLS-1$
-
- public static final boolean DEFAULT_MEMCHECK_LEAKCHECK = true;
- public static final String DEFAULT_MEMCHECK_LEAKRES = LEAK_RES_HIGH;
- public static final boolean DEFAULT_MEMCHECK_SHOWREACH = false;
- public static final boolean DEFAULT_MEMCHECK_PARTIAL = false;
- public static final boolean DEFAULT_MEMCHECK_UNDEF = true;
- public static final int DEFAULT_MEMCHECK_FREELIST = 10000000;
- public static final boolean DEFAULT_MEMCHECK_GCCWORK = false;
- public static final boolean DEFAULT_MEMCHECK_ALIGNMENT_BOOL = false;
- public static final int DEFAULT_MEMCHECK_ALIGNMENT_VAL = 0;
- public static final boolean DEFAULT_MEMCHECK_MALLOCFILL_BOOL = false;
- public static final String DEFAULT_MEMCHECK_MALLOCFILL_VAL = ""; //$NON-NLS-1$
- public static final boolean DEFAULT_MEMCHECK_FREEFILL_BOOL = false;
- public static final String DEFAULT_MEMCHECK_FREEFILL_VAL = ""; //$NON-NLS-1$
- public static final List<String> DEFAULT_MEMCHECK_IGNORE_RANGES = Collections.emptyList();
-
- // VG >= 3.4.0
- public static final boolean DEFAULT_MEMCHECK_TRACKORIGINS = false;
-
- // VG >= 3.6.0
- public static final boolean DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL = false;
+ // LaunchConfiguration attributes
+ public static final String ATTR_MEMCHECK_LEAKCHECK = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_LEAKCHECK"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_LEAKRES = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_LEAKRES"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_SHOWREACH = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_SHOWREACH"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_PARTIAL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_PARTIAL"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_UNDEF = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_UNDEF"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_FREELIST = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_FREELIST"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_GCCWORK = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_GCCWORK"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_ALIGNMENT_BOOL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_ALIGNMENT_BOOL"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_ALIGNMENT_VAL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_ALIGNMENT_VAL"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_MALLOCFILL_BOOL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_MALLOCFILL_BOOL"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_MALLOCFILL_VAL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_MALLOCFILL_VAL"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_FREEFILL_BOOL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_FREEFILL_BOOL"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_FREEFILL_VAL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_FREEFILL_VAL"; //$NON-NLS-1$
+ public static final String ATTR_MEMCHECK_IGNORE_RANGES = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_IGNORE_RANGES"; //$NON-NLS-1$
+
+ // VG >= 3.4.0
+ public static final String ATTR_MEMCHECK_TRACKORIGINS = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_TRACKORIGINS"; //$NON-NLS-1$
+
+ // VG >= 3.6.0
+ public static final String ATTR_MEMCHECK_POSSIBLY_LOST_BOOL = MemcheckPlugin.PLUGIN_ID + ".MEMCHECK_POSSIBLY_LOST"; //$NON-NLS-1$
+
+ public static final String LEAK_RES_LOW = "low"; //$NON-NLS-1$
+ public static final String LEAK_RES_MED = "med"; //$NON-NLS-1$
+ public static final String LEAK_RES_HIGH = "high"; //$NON-NLS-1$
+
+ public static final boolean DEFAULT_MEMCHECK_LEAKCHECK = true;
+ public static final String DEFAULT_MEMCHECK_LEAKRES = LEAK_RES_HIGH;
+ public static final boolean DEFAULT_MEMCHECK_SHOWREACH = false;
+ public static final boolean DEFAULT_MEMCHECK_PARTIAL = false;
+ public static final boolean DEFAULT_MEMCHECK_UNDEF = true;
+ public static final int DEFAULT_MEMCHECK_FREELIST = 10000000;
+ public static final boolean DEFAULT_MEMCHECK_GCCWORK = false;
+ public static final boolean DEFAULT_MEMCHECK_ALIGNMENT_BOOL = false;
+ public static final int DEFAULT_MEMCHECK_ALIGNMENT_VAL = 0;
+ public static final boolean DEFAULT_MEMCHECK_MALLOCFILL_BOOL = false;
+ public static final String DEFAULT_MEMCHECK_MALLOCFILL_VAL = ""; //$NON-NLS-1$
+ public static final boolean DEFAULT_MEMCHECK_FREEFILL_BOOL = false;
+ public static final String DEFAULT_MEMCHECK_FREEFILL_VAL = ""; //$NON-NLS-1$
+ public static final List<String> DEFAULT_MEMCHECK_IGNORE_RANGES = Collections.emptyList();
+
+ // VG >= 3.4.0
+ public static final boolean DEFAULT_MEMCHECK_TRACKORIGINS = false;
+
+ // VG >= 3.6.0
+ public static final boolean DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL = false;
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchDelegate.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchDelegate.java
index 598adca443..50e669300b 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchDelegate.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckLaunchDelegate.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.memcheck;
import java.util.ArrayList;
@@ -23,59 +23,59 @@ import org.eclipse.linuxtools.valgrind.ui.IValgrindToolView;
import org.osgi.framework.Version;
public class MemcheckLaunchDelegate implements IValgrindLaunchDelegate {
- private static final Version VER_3_4_0 = new Version(3, 4, 0);
- private static final Version VER_3_6_0 = new Version(3, 6, 0);
- private static final String EQUALS = "="; //$NON-NLS-1$
- private static final String NO = "no"; //$NON-NLS-1$
- private static final String YES = "yes"; //$NON-NLS-1$
- private static final String HEX = "0x"; //$NON-NLS-1$
+ private static final Version VER_3_4_0 = new Version(3, 4, 0);
+ private static final Version VER_3_6_0 = new Version(3, 6, 0);
+ private static final String EQUALS = "="; //$NON-NLS-1$
+ private static final String NO = "no"; //$NON-NLS-1$
+ private static final String YES = "yes"; //$NON-NLS-1$
+ private static final String HEX = "0x"; //$NON-NLS-1$
- @Override
- public void handleLaunch(ILaunchConfiguration config, ILaunch launch, IPath outDir, IProgressMonitor monitor) {
- }
-
- @Override
- public String[] getCommandArray(ILaunchConfiguration config, Version ver, IPath logDir) throws CoreException {
- ArrayList<String> opts = new ArrayList<>();
-
- opts.add(MemcheckCommandConstants.OPT_LEAKCHECK + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKCHECK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKCHECK) ? YES : NO));
- opts.add(MemcheckCommandConstants.OPT_SHOWREACH + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_SHOWREACH, MemcheckLaunchConstants.DEFAULT_MEMCHECK_SHOWREACH) ? YES : NO));
- opts.add(MemcheckCommandConstants.OPT_LEAKRES + EQUALS + config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKRES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKRES));
- opts.add(MemcheckCommandConstants.OPT_FREELIST + EQUALS + config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREELIST, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREELIST));
- opts.add(MemcheckCommandConstants.OPT_GCCWORK + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_GCCWORK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_GCCWORK) ? YES : NO));
- opts.add(MemcheckCommandConstants.OPT_PARTIAL + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_PARTIAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_PARTIAL) ? YES : NO));
- opts.add(MemcheckCommandConstants.OPT_UNDEF + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_UNDEF, MemcheckLaunchConstants.DEFAULT_MEMCHECK_UNDEF) ? YES : NO));
- if (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_BOOL)) {
- opts.add(MemcheckCommandConstants.OPT_ALIGNMENT + EQUALS + config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_VAL));
- }
-
- // VG >= 3.4.0
- if (ver == null || ver.compareTo(VER_3_4_0) >= 0) {
- if (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS) != MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS)
- opts.add(MemcheckCommandConstants.OPT_TRACKORIGINS + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS) ? YES : NO));
- }
-
- // VG >= 3.6.0
- if (ver == null || ver.compareTo(VER_3_6_0) >= 0) {
- if (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_POSSIBLY_LOST_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL) != MemcheckLaunchConstants.DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL)
- opts.add(MemcheckCommandConstants.OPT_SHOW_POSSIBLY_LOST + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_POSSIBLY_LOST_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL) ? YES : NO));
- }
-
- if (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_MALLOCFILL_BOOL)) {
- opts.add(MemcheckCommandConstants.OPT_MALLOCFILL + EQUALS + HEX + config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_MALLOCFILL_VAL));
- }
+ @Override
+ public void handleLaunch(ILaunchConfiguration config, ILaunch launch, IPath outDir, IProgressMonitor monitor) {
+ }
- if (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREEFILL_BOOL)) {
- opts.add(MemcheckCommandConstants.OPT_FREEFILL + EQUALS + HEX + config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREEFILL_VAL));
- }
- List<String> ignoreRangesFns = config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_IGNORE_RANGES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_IGNORE_RANGES);
- for (String func : ignoreRangesFns) {
- opts.add(MemcheckCommandConstants.OPT_IGNORERANGES + EQUALS + func);
- }
- return opts.toArray(new String[opts.size()]);
- }
+ @Override
+ public String[] getCommandArray(ILaunchConfiguration config, Version ver, IPath logDir) throws CoreException {
+ ArrayList<String> opts = new ArrayList<>();
- @Override
- public void initializeView(IValgrindToolView view, String contentDescription, IProgressMonitor monitor) {
- }
+ opts.add(MemcheckCommandConstants.OPT_LEAKCHECK + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKCHECK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKCHECK) ? YES : NO));
+ opts.add(MemcheckCommandConstants.OPT_SHOWREACH + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_SHOWREACH, MemcheckLaunchConstants.DEFAULT_MEMCHECK_SHOWREACH) ? YES : NO));
+ opts.add(MemcheckCommandConstants.OPT_LEAKRES + EQUALS + config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKRES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKRES));
+ opts.add(MemcheckCommandConstants.OPT_FREELIST + EQUALS + config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREELIST, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREELIST));
+ opts.add(MemcheckCommandConstants.OPT_GCCWORK + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_GCCWORK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_GCCWORK) ? YES : NO));
+ opts.add(MemcheckCommandConstants.OPT_PARTIAL + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_PARTIAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_PARTIAL) ? YES : NO));
+ opts.add(MemcheckCommandConstants.OPT_UNDEF + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_UNDEF, MemcheckLaunchConstants.DEFAULT_MEMCHECK_UNDEF) ? YES : NO));
+ if (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_BOOL)) {
+ opts.add(MemcheckCommandConstants.OPT_ALIGNMENT + EQUALS + config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_VAL));
+ }
+
+ // VG >= 3.4.0
+ if (ver == null || ver.compareTo(VER_3_4_0) >= 0) {
+ if (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS) != MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS)
+ opts.add(MemcheckCommandConstants.OPT_TRACKORIGINS + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS) ? YES : NO));
+ }
+
+ // VG >= 3.6.0
+ if (ver == null || ver.compareTo(VER_3_6_0) >= 0) {
+ if (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_POSSIBLY_LOST_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL) != MemcheckLaunchConstants.DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL)
+ opts.add(MemcheckCommandConstants.OPT_SHOW_POSSIBLY_LOST + EQUALS + (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_POSSIBLY_LOST_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL) ? YES : NO));
+ }
+
+ if (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_MALLOCFILL_BOOL)) {
+ opts.add(MemcheckCommandConstants.OPT_MALLOCFILL + EQUALS + HEX + config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_MALLOCFILL_VAL));
+ }
+
+ if (config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREEFILL_BOOL)) {
+ opts.add(MemcheckCommandConstants.OPT_FREEFILL + EQUALS + HEX + config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREEFILL_VAL));
+ }
+ List<String> ignoreRangesFns = config.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_IGNORE_RANGES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_IGNORE_RANGES);
+ for (String func : ignoreRangesFns) {
+ opts.add(MemcheckCommandConstants.OPT_IGNORERANGES + EQUALS + func);
+ }
+ return opts.toArray(new String[opts.size()]);
+ }
+
+ @Override
+ public void initializeView(IValgrindToolView view, String contentDescription, IProgressMonitor monitor) {
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckPlugin.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckPlugin.java
index 433f0b41e3..6d86be22f9 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckPlugin.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckPlugin.java
@@ -16,17 +16,17 @@ import org.eclipse.swt.widgets.Control;
public class MemcheckPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.memcheck"; //$NON-NLS-1$
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.memcheck"; //$NON-NLS-1$
- public static final String TOOL_ID = "org.eclipse.linuxtools.valgrind.launch.memcheck"; //$NON-NLS-1$
+ public static final String TOOL_ID = "org.eclipse.linuxtools.valgrind.launch.memcheck"; //$NON-NLS-1$
- public static FontMetrics getFontMetrics(Control control) {
- GC gc = new GC(control);
- gc.setFont(control.getFont());
- FontMetrics fontMetrics = gc.getFontMetrics();
- gc.dispose();
- return fontMetrics;
- }
+ public static FontMetrics getFontMetrics(Control control) {
+ GC gc = new GC(control);
+ gc.setFont(control.getFont());
+ FontMetrics fontMetrics = gc.getFontMetrics();
+ gc.dispose();
+ return fontMetrics;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckToolPage.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckToolPage.java
index afef8888e9..285b729862 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckToolPage.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckToolPage.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.memcheck;
import java.util.Arrays;
@@ -41,436 +41,436 @@ import org.eclipse.swt.widgets.Text;
import org.osgi.framework.Version;
public class MemcheckToolPage extends AbstractLaunchConfigurationTab implements IValgrindToolPage {
- private static final Version VER_3_4_0 = new Version(3, 4, 0);
- private static final Version VER_3_6_0 = new Version(3, 6, 0);
-
- // MEMCHECK controls
- private Button leakCheckButton;
- private Combo leakResCombo;
- private Button showReachableButton;
- private Spinner freelistSpinner;
- private Button partialLoadsButton;
- private Button undefValueButton;
- private Button gccWorkaroundButton;
- private Button alignmentButton;
- private Spinner alignmentSpinner;
- private Button mallocFillButton;
- private Text mallocFillText;
- private Button freeFillButton;
- private Text freeFillText;
- private List ignoreRangesList;
-
- // VG >= 3.4.0
- private Button trackOriginsButton;
-
- // VG >= 3.6.0
- private Button showPossiblyLostButton;
-
- private boolean isInitializing = false;
- private Version valgrindVersion;
- private CoreException ex = null;
-
- private SelectionListener selectListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
- private ModifyListener modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
-
- @Override
- public void createControl(Composite parent) {
- Composite top = new Composite(parent, SWT.NONE);
- GridLayout memcheckLayout = new GridLayout(2, true);
- top.setLayout(memcheckLayout);
- top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- leakCheckButton = new Button(top, SWT.CHECK);
- leakCheckButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- leakCheckButton.setText(Messages.getString("MemcheckToolPage.leak_check")); //$NON-NLS-1$
- leakCheckButton.addSelectionListener(selectListener);
-
- Composite leakResTop = new Composite(top, SWT.NONE);
- leakResTop.setLayout(new GridLayout(2, false));
- leakResTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Label leakResLabel = new Label(leakResTop, SWT.NONE);
- leakResLabel.setText(Messages.getString("MemcheckToolPage.leak_resolution")); //$NON-NLS-1$
- leakResCombo = new Combo(leakResTop, SWT.READ_ONLY);
- String[] leakResOpts = { MemcheckLaunchConstants.LEAK_RES_LOW, MemcheckLaunchConstants.LEAK_RES_MED, MemcheckLaunchConstants.LEAK_RES_HIGH };
- leakResCombo.setItems(leakResOpts);
- leakResCombo.addSelectionListener(selectListener);
-
- Composite freelistTop = new Composite(top, SWT.NONE);
- freelistTop.setLayout(new GridLayout(2, false));
- freelistTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Label freelistLabel = new Label(freelistTop, SWT.NONE);
- freelistLabel.setText(Messages.getString("MemcheckToolPage.freelist_size")); //$NON-NLS-1$
- freelistSpinner = new Spinner(freelistTop, SWT.BORDER);
- freelistSpinner.setMaximum(Integer.MAX_VALUE);
- freelistSpinner.addModifyListener(modifyListener);
-
- showReachableButton = new Button(top, SWT.CHECK);
- showReachableButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- showReachableButton.setText(Messages.getString("MemcheckToolPage.show_reachable")); //$NON-NLS-1$
- showReachableButton.addSelectionListener(selectListener);
-
- partialLoadsButton = new Button(top, SWT.CHECK);
- partialLoadsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- partialLoadsButton.setText(Messages.getString("MemcheckToolPage.allow_partial")); //$NON-NLS-1$
- partialLoadsButton.addSelectionListener(selectListener);
-
- undefValueButton = new Button(top, SWT.CHECK);
- undefValueButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- undefValueButton.setText(Messages.getString("MemcheckToolPage.undef_value_errors")); //$NON-NLS-1$
- undefValueButton.addSelectionListener(selectListener);
-
- // VG >= 3.4.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_4_0) >= 0) {
- trackOriginsButton = new Button(top, SWT.CHECK);
- trackOriginsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- trackOriginsButton.setText(Messages.getString("MemcheckToolPage.Track_origins")); //$NON-NLS-1$
- trackOriginsButton.addSelectionListener(selectListener);
- }
-
- gccWorkaroundButton = new Button(top, SWT.CHECK);
- gccWorkaroundButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- gccWorkaroundButton.setText(Messages.getString("MemcheckToolPage.gcc_296_workarounds")); //$NON-NLS-1$
- gccWorkaroundButton.addSelectionListener(selectListener);
-
- Composite alignmentTop = new Composite(top, SWT.NONE);
- GridLayout alignmentLayout = new GridLayout(2, false);
- alignmentLayout.marginWidth = alignmentLayout.marginHeight = 0;
- alignmentTop.setLayout(alignmentLayout);
- alignmentTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- alignmentButton = new Button(alignmentTop, SWT.CHECK);
- alignmentButton.setText(Messages.getString("MemcheckToolPage.minimum_heap_block")); //$NON-NLS-1$
- alignmentButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- checkAlignmentEnablement();
- updateLaunchConfigurationDialog();
- }
- });
- alignmentSpinner = new Spinner(alignmentTop, SWT.BORDER);
- alignmentSpinner.setMinimum(0);
- alignmentSpinner.setMaximum(4096);
- alignmentSpinner.addModifyListener(modifyListener);
-
- // VG >= 3.6.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
- showPossiblyLostButton = new Button(top, SWT.CHECK);
- showPossiblyLostButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- showPossiblyLostButton.setText(Messages.getString("MemcheckToolPage.Show_Possibly_Lost")); //$NON-NLS-1$
- showPossiblyLostButton.addSelectionListener(selectListener);
- }
-
- Composite mallocFillTop = new Composite(top, SWT.NONE);
- GridLayout mallocFillLayout = new GridLayout(2, false);
- mallocFillLayout.marginWidth = mallocFillLayout.marginHeight = 0;
- mallocFillTop.setLayout(mallocFillLayout);
- mallocFillTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- mallocFillButton = new Button(mallocFillTop, SWT.CHECK);
- mallocFillButton.setText(Messages.getString("MemcheckToolPage.Malloc_Fill")); //$NON-NLS-1$
- mallocFillButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- checkMallocFillEnablement();
- updateLaunchConfigurationDialog();
- }
- });
- mallocFillText = new Text(mallocFillTop, SWT.BORDER);
- mallocFillText.setTextLimit(8);
- mallocFillText.addModifyListener(modifyListener);
-
-
- Composite freeFillTop = new Composite(top, SWT.NONE);
- GridLayout freeFillLayout = new GridLayout(2, false);
- freeFillLayout.marginWidth = freeFillLayout.marginHeight = 0;
- freeFillTop.setLayout(freeFillLayout);
- freeFillTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- freeFillButton = new Button(freeFillTop, SWT.CHECK);
- freeFillButton.setText(Messages.getString("MemcheckToolPage.Free_Fill")); //$NON-NLS-1$
- freeFillButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- checkFreeFillEnablement();
- updateLaunchConfigurationDialog();
- }
- });
- freeFillText = new Text(freeFillTop, SWT.BORDER);
- mallocFillText.setTextLimit(8);
- freeFillText.addModifyListener(modifyListener);
-
- Composite ignoreRangesTop = new Composite(top, SWT.NONE);
- ignoreRangesTop.setLayout(new GridLayout(3, false));
- ignoreRangesTop.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, 2, 1));
-
- Label ignoreRangesLabel = new Label(ignoreRangesTop, SWT.NONE);
- ignoreRangesLabel.setText(Messages.getString("MemcheckToolPage.Ignore_Ranges")); //$NON-NLS-1$
- ignoreRangesLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
-
- createIgnoreRangesControls(ignoreRangesTop);
+ private static final Version VER_3_4_0 = new Version(3, 4, 0);
+ private static final Version VER_3_6_0 = new Version(3, 6, 0);
+
+ // MEMCHECK controls
+ private Button leakCheckButton;
+ private Combo leakResCombo;
+ private Button showReachableButton;
+ private Spinner freelistSpinner;
+ private Button partialLoadsButton;
+ private Button undefValueButton;
+ private Button gccWorkaroundButton;
+ private Button alignmentButton;
+ private Spinner alignmentSpinner;
+ private Button mallocFillButton;
+ private Text mallocFillText;
+ private Button freeFillButton;
+ private Text freeFillText;
+ private List ignoreRangesList;
+
+ // VG >= 3.4.0
+ private Button trackOriginsButton;
+
+ // VG >= 3.6.0
+ private Button showPossiblyLostButton;
+
+ private boolean isInitializing = false;
+ private Version valgrindVersion;
+ private CoreException ex = null;
+
+ private SelectionListener selectListener = new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+ private ModifyListener modifyListener = new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ updateLaunchConfigurationDialog();
+ }
+ };
+
+ @Override
+ public void createControl(Composite parent) {
+ Composite top = new Composite(parent, SWT.NONE);
+ GridLayout memcheckLayout = new GridLayout(2, true);
+ top.setLayout(memcheckLayout);
+ top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ leakCheckButton = new Button(top, SWT.CHECK);
+ leakCheckButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ leakCheckButton.setText(Messages.getString("MemcheckToolPage.leak_check")); //$NON-NLS-1$
+ leakCheckButton.addSelectionListener(selectListener);
+
+ Composite leakResTop = new Composite(top, SWT.NONE);
+ leakResTop.setLayout(new GridLayout(2, false));
+ leakResTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ Label leakResLabel = new Label(leakResTop, SWT.NONE);
+ leakResLabel.setText(Messages.getString("MemcheckToolPage.leak_resolution")); //$NON-NLS-1$
+ leakResCombo = new Combo(leakResTop, SWT.READ_ONLY);
+ String[] leakResOpts = { MemcheckLaunchConstants.LEAK_RES_LOW, MemcheckLaunchConstants.LEAK_RES_MED, MemcheckLaunchConstants.LEAK_RES_HIGH };
+ leakResCombo.setItems(leakResOpts);
+ leakResCombo.addSelectionListener(selectListener);
+
+ Composite freelistTop = new Composite(top, SWT.NONE);
+ freelistTop.setLayout(new GridLayout(2, false));
+ freelistTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ Label freelistLabel = new Label(freelistTop, SWT.NONE);
+ freelistLabel.setText(Messages.getString("MemcheckToolPage.freelist_size")); //$NON-NLS-1$
+ freelistSpinner = new Spinner(freelistTop, SWT.BORDER);
+ freelistSpinner.setMaximum(Integer.MAX_VALUE);
+ freelistSpinner.addModifyListener(modifyListener);
+
+ showReachableButton = new Button(top, SWT.CHECK);
+ showReachableButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ showReachableButton.setText(Messages.getString("MemcheckToolPage.show_reachable")); //$NON-NLS-1$
+ showReachableButton.addSelectionListener(selectListener);
+
+ partialLoadsButton = new Button(top, SWT.CHECK);
+ partialLoadsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ partialLoadsButton.setText(Messages.getString("MemcheckToolPage.allow_partial")); //$NON-NLS-1$
+ partialLoadsButton.addSelectionListener(selectListener);
+
+ undefValueButton = new Button(top, SWT.CHECK);
+ undefValueButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ undefValueButton.setText(Messages.getString("MemcheckToolPage.undef_value_errors")); //$NON-NLS-1$
+ undefValueButton.addSelectionListener(selectListener);
+
+ // VG >= 3.4.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_4_0) >= 0) {
+ trackOriginsButton = new Button(top, SWT.CHECK);
+ trackOriginsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ trackOriginsButton.setText(Messages.getString("MemcheckToolPage.Track_origins")); //$NON-NLS-1$
+ trackOriginsButton.addSelectionListener(selectListener);
+ }
+
+ gccWorkaroundButton = new Button(top, SWT.CHECK);
+ gccWorkaroundButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ gccWorkaroundButton.setText(Messages.getString("MemcheckToolPage.gcc_296_workarounds")); //$NON-NLS-1$
+ gccWorkaroundButton.addSelectionListener(selectListener);
+
+ Composite alignmentTop = new Composite(top, SWT.NONE);
+ GridLayout alignmentLayout = new GridLayout(2, false);
+ alignmentLayout.marginWidth = alignmentLayout.marginHeight = 0;
+ alignmentTop.setLayout(alignmentLayout);
+ alignmentTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ alignmentButton = new Button(alignmentTop, SWT.CHECK);
+ alignmentButton.setText(Messages.getString("MemcheckToolPage.minimum_heap_block")); //$NON-NLS-1$
+ alignmentButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ checkAlignmentEnablement();
+ updateLaunchConfigurationDialog();
+ }
+ });
+ alignmentSpinner = new Spinner(alignmentTop, SWT.BORDER);
+ alignmentSpinner.setMinimum(0);
+ alignmentSpinner.setMaximum(4096);
+ alignmentSpinner.addModifyListener(modifyListener);
+
+ // VG >= 3.6.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
+ showPossiblyLostButton = new Button(top, SWT.CHECK);
+ showPossiblyLostButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ showPossiblyLostButton.setText(Messages.getString("MemcheckToolPage.Show_Possibly_Lost")); //$NON-NLS-1$
+ showPossiblyLostButton.addSelectionListener(selectListener);
+ }
+
+ Composite mallocFillTop = new Composite(top, SWT.NONE);
+ GridLayout mallocFillLayout = new GridLayout(2, false);
+ mallocFillLayout.marginWidth = mallocFillLayout.marginHeight = 0;
+ mallocFillTop.setLayout(mallocFillLayout);
+ mallocFillTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ mallocFillButton = new Button(mallocFillTop, SWT.CHECK);
+ mallocFillButton.setText(Messages.getString("MemcheckToolPage.Malloc_Fill")); //$NON-NLS-1$
+ mallocFillButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ checkMallocFillEnablement();
+ updateLaunchConfigurationDialog();
+ }
+ });
+ mallocFillText = new Text(mallocFillTop, SWT.BORDER);
+ mallocFillText.setTextLimit(8);
+ mallocFillText.addModifyListener(modifyListener);
+
+
+ Composite freeFillTop = new Composite(top, SWT.NONE);
+ GridLayout freeFillLayout = new GridLayout(2, false);
+ freeFillLayout.marginWidth = freeFillLayout.marginHeight = 0;
+ freeFillTop.setLayout(freeFillLayout);
+ freeFillTop.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ freeFillButton = new Button(freeFillTop, SWT.CHECK);
+ freeFillButton.setText(Messages.getString("MemcheckToolPage.Free_Fill")); //$NON-NLS-1$
+ freeFillButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ checkFreeFillEnablement();
+ updateLaunchConfigurationDialog();
+ }
+ });
+ freeFillText = new Text(freeFillTop, SWT.BORDER);
+ mallocFillText.setTextLimit(8);
+ freeFillText.addModifyListener(modifyListener);
+
+ Composite ignoreRangesTop = new Composite(top, SWT.NONE);
+ ignoreRangesTop.setLayout(new GridLayout(3, false));
+ ignoreRangesTop.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, 2, 1));
+
+ Label ignoreRangesLabel = new Label(ignoreRangesTop, SWT.NONE);
+ ignoreRangesLabel.setText(Messages.getString("MemcheckToolPage.Ignore_Ranges")); //$NON-NLS-1$
+ ignoreRangesLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
+
+ createIgnoreRangesControls(ignoreRangesTop);
}
-
- private void createIgnoreRangesControls(Composite top) {
-
- ignoreRangesList = new List(top, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
- FontMetrics fm = MemcheckPlugin.getFontMetrics(ignoreRangesList);
- ignoreRangesList.setLayoutData(new GridData(Dialog.convertWidthInCharsToPixels(fm, 50), Dialog.convertHeightInCharsToPixels(fm, 5)));
-
- Composite ignoreButtons = new Composite(top, SWT.NONE);
- GridLayout ignoreButtonsLayout = new GridLayout();
- ignoreButtonsLayout.marginWidth = ignoreButtonsLayout.marginHeight = 0;
- ignoreButtons.setLayout(ignoreButtonsLayout);
- ignoreButtons.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
-
- Button newButton = new Button(ignoreButtons, SWT.PUSH);
- newButton.setText(Messages.getString("MemcheckToolPage.New")); //$NON-NLS-1$
- newButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- newButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleIgnoreNewButtonPressed();
- updateLaunchConfigurationDialog();
- }
- });
-
- Button removeButton = new Button(ignoreButtons, SWT.PUSH);
- removeButton.setText(Messages.getString("MemcheckToolPage.Remove")); //$NON-NLS-1$
- removeButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- removeButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleIgnoreRemoveButtonPressed();
- updateLaunchConfigurationDialog();
- }
- });
-
- }
-
- private void handleIgnoreNewButtonPressed() {
- InputDialog dialog = new InputDialog(getShell(), Messages.getString("MemcheckToolPage.Ignore_Ranges"), Messages.getString("MemcheckToolPage.Range"), "", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (dialog.open() == Window.OK) {
- String function = dialog.getValue();
- if (!function.equals("")) { //$NON-NLS-1$
- ignoreRangesList.add(function);
- }
- }
- }
-
- private void handleIgnoreRemoveButtonPressed() {
- int[] selections = ignoreRangesList.getSelectionIndices();
- ignoreRangesList.remove(selections);
- }
-
- private void checkAlignmentEnablement() {
- alignmentSpinner.setEnabled(alignmentButton.getSelection());
- }
-
- private void checkMallocFillEnablement() {
- mallocFillText.setEnabled(mallocFillButton.getSelection());
- }
-
- private void checkFreeFillEnablement() {
- freeFillText.setEnabled(freeFillButton.getSelection());
- }
-
- @Override
- public String getName() {
- return Messages.getString("MemcheckToolPage.Memcheck_Options"); //$NON-NLS-1$
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration configuration) {
- isInitializing = true;
- try {
- leakCheckButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKCHECK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKCHECK));
- leakResCombo.setText(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKRES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKRES));
- showReachableButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_SHOWREACH, MemcheckLaunchConstants.DEFAULT_MEMCHECK_SHOWREACH));
- freelistSpinner.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREELIST, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREELIST));
- partialLoadsButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_PARTIAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_PARTIAL));
- undefValueButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_UNDEF, MemcheckLaunchConstants.DEFAULT_MEMCHECK_UNDEF));
- gccWorkaroundButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_GCCWORK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_GCCWORK));
- alignmentButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_BOOL));
- checkAlignmentEnablement();
- alignmentSpinner.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_VAL));
-
- // VG >= 3.4.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_4_0) >= 0) {
- trackOriginsButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS));
- }
-
- // VG >= 3.6.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
- showPossiblyLostButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_POSSIBLY_LOST_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL));
- }
-
- mallocFillButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_MALLOCFILL_BOOL));
- checkMallocFillEnablement();
- mallocFillText.setText(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_MALLOCFILL_VAL));
- freeFillButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREEFILL_BOOL));
- checkFreeFillEnablement();
- freeFillText.setText(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREEFILL_VAL));
- java.util.List<String> ignoreFns = configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_IGNORE_RANGES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_IGNORE_RANGES);
- ignoreRangesList.setItems(ignoreFns.toArray(new String[ignoreFns.size()]));
-
-
- } catch (CoreException e) {
- ex = e;
- }
- isInitializing = false;
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKCHECK, leakCheckButton.getSelection());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKRES, leakResCombo.getText());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_SHOWREACH, showReachableButton.getSelection());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREELIST, freelistSpinner.getSelection());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_PARTIAL, partialLoadsButton.getSelection());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_UNDEF, undefValueButton.getSelection());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_GCCWORK, gccWorkaroundButton.getSelection());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_BOOL, alignmentButton.getSelection());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_VAL, alignmentSpinner.getSelection());
-
- // VG >= 3.4.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_4_0) >= 0) {
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, trackOriginsButton.getSelection());
- }
-
- // VG >= 3.6.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_POSSIBLY_LOST_BOOL, showPossiblyLostButton.getSelection());
- }
-
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_BOOL, mallocFillButton.getSelection());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_VAL, mallocFillText.getText());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_BOOL, freeFillButton.getSelection());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_VAL, freeFillText.getText());
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_IGNORE_RANGES, Arrays.asList(ignoreRangesList.getItems()));
- }
-
- @Override
- public boolean isValid(ILaunchConfiguration launchConfig) {
- setErrorMessage(null);
-
- boolean result = false;
- try {
- // check alignment
- int alignment = launchConfig.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_VAL);
- result = (alignment & (alignment - 1)) == 0; // is power of two?
- if (!result) {
- setErrorMessage(Messages.getString("MemcheckToolPage.Alignment_must_be_power_2")); //$NON-NLS-1$
- }
- else {
- // VG >= 3.4.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_4_0) >= 0) {
- // check track-origins
- boolean trackOrigins = launchConfig.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS);
- if (trackOrigins) {
- // undef-value-errors must be selected
- result = launchConfig.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_UNDEF, MemcheckLaunchConstants.DEFAULT_MEMCHECK_UNDEF);
- if (!result) {
- setErrorMessage(NLS.bind(Messages.getString("MemcheckToolPage.Track_origins_needs_undef"), Messages.getString("MemcheckToolPage.Track_origins"), Messages.getString("MemcheckToolPage.undef_value_errors"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- }
- }
- }
- } catch (CoreException e) {
- ex = e;
- }
-
- if (ex != null) {
- setErrorMessage(ex.getLocalizedMessage());
- }
- return result;
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, MemcheckPlugin.TOOL_ID);
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKCHECK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKCHECK);
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKRES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKRES);
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_SHOWREACH, MemcheckLaunchConstants.DEFAULT_MEMCHECK_SHOWREACH);
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREELIST, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREELIST);
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_PARTIAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_PARTIAL);
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_UNDEF, MemcheckLaunchConstants.DEFAULT_MEMCHECK_UNDEF);
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_GCCWORK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_GCCWORK);
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_BOOL);
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_VAL);
-
- // VG >= 3.4.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_4_0) >= 0) {
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS);
- }
-
- // VG >= 3.6.0
- if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_POSSIBLY_LOST_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL);
- }
-
- configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_IGNORE_RANGES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_IGNORE_RANGES);
- }
-
- @Override
- public void setValgrindVersion(Version ver) {
- valgrindVersion = ver;
- }
-
- @Override
- public void updateLaunchConfigurationDialog() {
- if (!isInitializing) {
- super.updateLaunchConfigurationDialog();
- }
- }
-
- public Button getLeakCheckButton() {
- return leakCheckButton;
- }
-
- public Combo getLeakResCombo() {
- return leakResCombo;
- }
-
- public Button getShowReachableButton() {
- return showReachableButton;
- }
-
- public Spinner getFreelistSpinner() {
- return freelistSpinner;
- }
-
- public Button getPartialLoadsButton() {
- return partialLoadsButton;
- }
-
- public Button getUndefValueButton() {
- return undefValueButton;
- }
-
- public Button getGccWorkaroundButton() {
- return gccWorkaroundButton;
- }
-
- public Button getAlignmentButton() {
- return alignmentButton;
- }
-
- public Spinner getAlignmentSpinner() {
- return alignmentSpinner;
- }
-
- public Button getTrackOriginsButton() {
- return trackOriginsButton;
- }
+
+ private void createIgnoreRangesControls(Composite top) {
+
+ ignoreRangesList = new List(top, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
+ FontMetrics fm = MemcheckPlugin.getFontMetrics(ignoreRangesList);
+ ignoreRangesList.setLayoutData(new GridData(Dialog.convertWidthInCharsToPixels(fm, 50), Dialog.convertHeightInCharsToPixels(fm, 5)));
+
+ Composite ignoreButtons = new Composite(top, SWT.NONE);
+ GridLayout ignoreButtonsLayout = new GridLayout();
+ ignoreButtonsLayout.marginWidth = ignoreButtonsLayout.marginHeight = 0;
+ ignoreButtons.setLayout(ignoreButtonsLayout);
+ ignoreButtons.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false));
+
+ Button newButton = new Button(ignoreButtons, SWT.PUSH);
+ newButton.setText(Messages.getString("MemcheckToolPage.New")); //$NON-NLS-1$
+ newButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ newButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ handleIgnoreNewButtonPressed();
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ Button removeButton = new Button(ignoreButtons, SWT.PUSH);
+ removeButton.setText(Messages.getString("MemcheckToolPage.Remove")); //$NON-NLS-1$
+ removeButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ removeButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ handleIgnoreRemoveButtonPressed();
+ updateLaunchConfigurationDialog();
+ }
+ });
+
+ }
+
+ private void handleIgnoreNewButtonPressed() {
+ InputDialog dialog = new InputDialog(getShell(), Messages.getString("MemcheckToolPage.Ignore_Ranges"), Messages.getString("MemcheckToolPage.Range"), "", null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if (dialog.open() == Window.OK) {
+ String function = dialog.getValue();
+ if (!function.equals("")) { //$NON-NLS-1$
+ ignoreRangesList.add(function);
+ }
+ }
+ }
+
+ private void handleIgnoreRemoveButtonPressed() {
+ int[] selections = ignoreRangesList.getSelectionIndices();
+ ignoreRangesList.remove(selections);
+ }
+
+ private void checkAlignmentEnablement() {
+ alignmentSpinner.setEnabled(alignmentButton.getSelection());
+ }
+
+ private void checkMallocFillEnablement() {
+ mallocFillText.setEnabled(mallocFillButton.getSelection());
+ }
+
+ private void checkFreeFillEnablement() {
+ freeFillText.setEnabled(freeFillButton.getSelection());
+ }
+
+ @Override
+ public String getName() {
+ return Messages.getString("MemcheckToolPage.Memcheck_Options"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void initializeFrom(ILaunchConfiguration configuration) {
+ isInitializing = true;
+ try {
+ leakCheckButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKCHECK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKCHECK));
+ leakResCombo.setText(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKRES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKRES));
+ showReachableButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_SHOWREACH, MemcheckLaunchConstants.DEFAULT_MEMCHECK_SHOWREACH));
+ freelistSpinner.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREELIST, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREELIST));
+ partialLoadsButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_PARTIAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_PARTIAL));
+ undefValueButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_UNDEF, MemcheckLaunchConstants.DEFAULT_MEMCHECK_UNDEF));
+ gccWorkaroundButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_GCCWORK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_GCCWORK));
+ alignmentButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_BOOL));
+ checkAlignmentEnablement();
+ alignmentSpinner.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_VAL));
+
+ // VG >= 3.4.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_4_0) >= 0) {
+ trackOriginsButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS));
+ }
+
+ // VG >= 3.6.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
+ showPossiblyLostButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_POSSIBLY_LOST_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL));
+ }
+
+ mallocFillButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_MALLOCFILL_BOOL));
+ checkMallocFillEnablement();
+ mallocFillText.setText(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_MALLOCFILL_VAL));
+ freeFillButton.setSelection(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREEFILL_BOOL));
+ checkFreeFillEnablement();
+ freeFillText.setText(configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREEFILL_VAL));
+ java.util.List<String> ignoreFns = configuration.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_IGNORE_RANGES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_IGNORE_RANGES);
+ ignoreRangesList.setItems(ignoreFns.toArray(new String[ignoreFns.size()]));
+
+
+ } catch (CoreException e) {
+ ex = e;
+ }
+ isInitializing = false;
+ }
+
+ @Override
+ public void performApply(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKCHECK, leakCheckButton.getSelection());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKRES, leakResCombo.getText());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_SHOWREACH, showReachableButton.getSelection());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREELIST, freelistSpinner.getSelection());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_PARTIAL, partialLoadsButton.getSelection());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_UNDEF, undefValueButton.getSelection());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_GCCWORK, gccWorkaroundButton.getSelection());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_BOOL, alignmentButton.getSelection());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_VAL, alignmentSpinner.getSelection());
+
+ // VG >= 3.4.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_4_0) >= 0) {
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, trackOriginsButton.getSelection());
+ }
+
+ // VG >= 3.6.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_POSSIBLY_LOST_BOOL, showPossiblyLostButton.getSelection());
+ }
+
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_BOOL, mallocFillButton.getSelection());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_MALLOCFILL_VAL, mallocFillText.getText());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_BOOL, freeFillButton.getSelection());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREEFILL_VAL, freeFillText.getText());
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_IGNORE_RANGES, Arrays.asList(ignoreRangesList.getItems()));
+ }
+
+ @Override
+ public boolean isValid(ILaunchConfiguration launchConfig) {
+ setErrorMessage(null);
+
+ boolean result = false;
+ try {
+ // check alignment
+ int alignment = launchConfig.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_VAL);
+ result = (alignment & (alignment - 1)) == 0; // is power of two?
+ if (!result) {
+ setErrorMessage(Messages.getString("MemcheckToolPage.Alignment_must_be_power_2")); //$NON-NLS-1$
+ }
+ else {
+ // VG >= 3.4.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_4_0) >= 0) {
+ // check track-origins
+ boolean trackOrigins = launchConfig.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS);
+ if (trackOrigins) {
+ // undef-value-errors must be selected
+ result = launchConfig.getAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_UNDEF, MemcheckLaunchConstants.DEFAULT_MEMCHECK_UNDEF);
+ if (!result) {
+ setErrorMessage(NLS.bind(Messages.getString("MemcheckToolPage.Track_origins_needs_undef"), Messages.getString("MemcheckToolPage.Track_origins"), Messages.getString("MemcheckToolPage.undef_value_errors"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ }
+ }
+ }
+ } catch (CoreException e) {
+ ex = e;
+ }
+
+ if (ex != null) {
+ setErrorMessage(ex.getLocalizedMessage());
+ }
+ return result;
+ }
+
+ @Override
+ public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
+ configuration.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, MemcheckPlugin.TOOL_ID);
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKCHECK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKCHECK);
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_LEAKRES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_LEAKRES);
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_SHOWREACH, MemcheckLaunchConstants.DEFAULT_MEMCHECK_SHOWREACH);
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_FREELIST, MemcheckLaunchConstants.DEFAULT_MEMCHECK_FREELIST);
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_PARTIAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_PARTIAL);
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_UNDEF, MemcheckLaunchConstants.DEFAULT_MEMCHECK_UNDEF);
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_GCCWORK, MemcheckLaunchConstants.DEFAULT_MEMCHECK_GCCWORK);
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_BOOL);
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_ALIGNMENT_VAL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_ALIGNMENT_VAL);
+
+ // VG >= 3.4.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_4_0) >= 0) {
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_TRACKORIGINS, MemcheckLaunchConstants.DEFAULT_MEMCHECK_TRACKORIGINS);
+ }
+
+ // VG >= 3.6.0
+ if (valgrindVersion == null || valgrindVersion.compareTo(VER_3_6_0) >= 0) {
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_POSSIBLY_LOST_BOOL, MemcheckLaunchConstants.DEFAULT_MEMCHECK_POSSIBLY_LOST_BOOL);
+ }
+
+ configuration.setAttribute(MemcheckLaunchConstants.ATTR_MEMCHECK_IGNORE_RANGES, MemcheckLaunchConstants.DEFAULT_MEMCHECK_IGNORE_RANGES);
+ }
+
+ @Override
+ public void setValgrindVersion(Version ver) {
+ valgrindVersion = ver;
+ }
+
+ @Override
+ public void updateLaunchConfigurationDialog() {
+ if (!isInitializing) {
+ super.updateLaunchConfigurationDialog();
+ }
+ }
+
+ public Button getLeakCheckButton() {
+ return leakCheckButton;
+ }
+
+ public Combo getLeakResCombo() {
+ return leakResCombo;
+ }
+
+ public Button getShowReachableButton() {
+ return showReachableButton;
+ }
+
+ public Spinner getFreelistSpinner() {
+ return freelistSpinner;
+ }
+
+ public Button getPartialLoadsButton() {
+ return partialLoadsButton;
+ }
+
+ public Button getUndefValueButton() {
+ return undefValueButton;
+ }
+
+ public Button getGccWorkaroundButton() {
+ return gccWorkaroundButton;
+ }
+
+ public Button getAlignmentButton() {
+ return alignmentButton;
+ }
+
+ public Spinner getAlignmentSpinner() {
+ return alignmentSpinner;
+ }
+
+ public Button getTrackOriginsButton() {
+ return trackOriginsButton;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckViewPart.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckViewPart.java
index 2bdbd7700c..e93beb558a 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckViewPart.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/MemcheckViewPart.java
@@ -7,7 +7,7 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.memcheck;
import org.eclipse.jface.action.IAction;
@@ -17,21 +17,21 @@ import org.eclipse.ui.part.ViewPart;
public class MemcheckViewPart extends ViewPart implements IValgrindToolView {
- @Override
- public void createPartControl(Composite parent) {
- }
+ @Override
+ public void createPartControl(Composite parent) {
+ }
- @Override
- public void setFocus() {
- }
+ @Override
+ public void setFocus() {
+ }
- @Override
- public void refreshView() {
- }
+ @Override
+ public void refreshView() {
+ }
+
+ @Override
+ public IAction[] getToolbarActions() {
+ return null;
+ }
- @Override
- public IAction[] getToolbarActions() {
- return null;
- }
-
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/Messages.java b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/Messages.java
index 246f630d8d..5b0401187b 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/Messages.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.memcheck/src/org/eclipse/linuxtools/internal/valgrind/memcheck/Messages.java
@@ -7,26 +7,26 @@
*
* Contributors:
* Elliott Baron <ebaron@redhat.com> - initial API and implementation
- *******************************************************************************/
+ *******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.memcheck;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.memcheck.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.memcheck.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/AbstractValgrindTest.java b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/AbstractValgrindTest.java
index 6c9b63c5bf..545f571fcd 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/AbstractValgrindTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/AbstractValgrindTest.java
@@ -48,168 +48,168 @@ import org.osgi.framework.FrameworkUtil;
public abstract class AbstractValgrindTest extends AbstractTest {
- private static final String TEMPLATE_PREFIX = "template_"; //$NON-NLS-1$
- private static final FileFilter TEMPLATE_FILTER = new FileFilter() {
- @Override
- public boolean accept(File pathname) {
- return pathname.getName().startsWith(TEMPLATE_PREFIX)
- && !pathname.isHidden();
- }
- };
- private static final FileFilter NOT_TEMPLATE_FILTER = new FileFilter() {
- @Override
- public boolean accept(File pathname) {
- return !pathname.getName().startsWith(TEMPLATE_PREFIX)
- && !pathname.isHidden();
- }
- };
-
- private static final String SEARCH_STRING_WS = "XXXXXXXXXXXX"; //$NON-NLS-1$
- private static final String SEARCH_STRING_BL = "YYYYYYYYYYYY"; //$NON-NLS-1$
-
- private List<ILaunch> launches;
-
- @Before
- public void setUp() {
- launches = new ArrayList<>();
-
- // Substitute Valgrind command line interaction
- ValgrindLaunchPlugin.getDefault().setValgrindCommand(
- getValgrindCommand());
- }
-
- @After
- public void tearDown() throws CoreException {
- ILaunchManager lm = DebugPlugin.getDefault().getLaunchManager();
- if (launches.size() > 0) {
- lm.removeLaunches(launches.toArray(new ILaunch[launches.size()]));
- launches.clear();
- }
- // Delete the Launch Configurations
- ILaunchConfiguration[] configs = lm.getLaunchConfigurations();
- for (ILaunchConfiguration config : configs) {
- config.delete();
- }
- }
-
- @Override
- protected ILaunchConfigurationType getLaunchConfigType() {
- return getLaunchManager().getLaunchConfigurationType(
- ValgrindLaunchPlugin.LAUNCH_ID);
- }
-
- protected ILaunch doLaunch(ILaunchConfiguration config, String testName)
- throws URISyntaxException, IOException, CoreException {
- ILaunch launch;
- IPath pathToFiles = getPathToFiles(testName);
-
- if (!ValgrindTestsPlugin.RUN_VALGRIND) {
- bindLocation(pathToFiles);
- }
-
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- wc.setAttribute(LaunchConfigurationConstants.ATTR_INTERNAL_OUTPUT_DIR,
- pathToFiles.toOSString());
- wc.doSave();
-
- ValgrindTestLaunchDelegate delegate = new ValgrindTestLaunchDelegate();
- launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
-
- DebugPlugin.getDefault().getLaunchManager().addLaunch(launch);
- launches.add(launch);
- delegate.launch(config, ILaunchManager.PROFILE_MODE, launch, null);
-
- if (ValgrindTestsPlugin.GENERATE_FILES
- && ValgrindTestsPlugin.versionSupported()) {
- unbindLocation(pathToFiles);
- }
- return launch;
- }
-
- protected IPath getPathToFiles(String testName) throws URISyntaxException,
- IOException {
- URL location = FileLocator.find(getBundle(),
- new Path("valgrindFiles"), null); //$NON-NLS-1$
- File file = new File(FileLocator.toFileURL(location).toURI());
- IPath pathToFiles = new Path(file.getCanonicalPath()).append(testName);
- return pathToFiles;
- }
-
- private void unbindLocation(IPath pathToFiles) throws IOException {
- String bundleLoc = FileLocator.getBundleFile(getBundle())
- .getCanonicalPath();
- String workspaceLoc = ResourcesPlugin.getWorkspace().getRoot()
- .getLocation().toOSString();
- File testDir = pathToFiles.toFile();
- for (File log : testDir.listFiles(NOT_TEMPLATE_FILTER)) {
- File template = new File(testDir, TEMPLATE_PREFIX + log.getName());
- replaceLocation(log, template, new String[] { bundleLoc,
- workspaceLoc }, new String[] { SEARCH_STRING_BL,
- SEARCH_STRING_WS });
- }
- }
-
- private void bindLocation(IPath pathToFiles) throws IOException {
- String bundleLoc = FileLocator.getBundleFile(getBundle())
- .getCanonicalPath();
- String workspaceLoc = ResourcesPlugin.getWorkspace().getRoot()
- .getLocation().toOSString();
- File testDir = pathToFiles.toFile();
- for (File template : testDir.listFiles(TEMPLATE_FILTER)) {
- String name = template.getName().replace(TEMPLATE_PREFIX, ""); //$NON-NLS-1$
- File log = new File(testDir, name.substring(name
- .indexOf(TEMPLATE_PREFIX) + 1));
- replaceLocation(template, log, new String[] { SEARCH_STRING_BL,
- SEARCH_STRING_WS },
- new String[] { bundleLoc, workspaceLoc });
- }
- }
-
- private void replaceLocation(File oldFile, File newFile, String[] from,
- String[] to) {
- if (oldFile.isFile()) {
- try (BufferedReader br = new BufferedReader(new FileReader(oldFile));
- PrintWriter pw = new PrintWriter(new FileWriter(newFile))) {
- String line;
- while ((line = br.readLine()) != null) {
- for (int i = 0; i < from.length; i++) {
- line = line.replaceAll(from[i], to[i]);
- }
- pw.println(line);
- }
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- @Override
- protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc)
- throws CoreException {
- ILaunchConfigurationTab tab = new ValgrindOptionsTab();
- tab.setDefaults(wc);
- tab = ValgrindLaunchPlugin.getDefault().getToolPage(getToolID());
- tab.setDefaults(wc);
- wc.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, getToolID());
- }
-
- protected ICProject createProjectAndBuild(String projname) throws Exception {
- return createProjectAndBuild(getBundle(), projname);
- }
-
- protected Bundle getBundle() {
- return FrameworkUtil.getBundle(this.getClass());
- }
-
- protected abstract String getToolID();
-
- private ValgrindCommand getValgrindCommand() {
- if (!ValgrindTestsPlugin.RUN_VALGRIND) {
- return new ValgrindStubCommand();
- } else {
- return new ValgrindCommand();
- }
- }
+ private static final String TEMPLATE_PREFIX = "template_"; //$NON-NLS-1$
+ private static final FileFilter TEMPLATE_FILTER = new FileFilter() {
+ @Override
+ public boolean accept(File pathname) {
+ return pathname.getName().startsWith(TEMPLATE_PREFIX)
+ && !pathname.isHidden();
+ }
+ };
+ private static final FileFilter NOT_TEMPLATE_FILTER = new FileFilter() {
+ @Override
+ public boolean accept(File pathname) {
+ return !pathname.getName().startsWith(TEMPLATE_PREFIX)
+ && !pathname.isHidden();
+ }
+ };
+
+ private static final String SEARCH_STRING_WS = "XXXXXXXXXXXX"; //$NON-NLS-1$
+ private static final String SEARCH_STRING_BL = "YYYYYYYYYYYY"; //$NON-NLS-1$
+
+ private List<ILaunch> launches;
+
+ @Before
+ public void setUp() {
+ launches = new ArrayList<>();
+
+ // Substitute Valgrind command line interaction
+ ValgrindLaunchPlugin.getDefault().setValgrindCommand(
+ getValgrindCommand());
+ }
+
+ @After
+ public void tearDown() throws CoreException {
+ ILaunchManager lm = DebugPlugin.getDefault().getLaunchManager();
+ if (launches.size() > 0) {
+ lm.removeLaunches(launches.toArray(new ILaunch[launches.size()]));
+ launches.clear();
+ }
+ // Delete the Launch Configurations
+ ILaunchConfiguration[] configs = lm.getLaunchConfigurations();
+ for (ILaunchConfiguration config : configs) {
+ config.delete();
+ }
+ }
+
+ @Override
+ protected ILaunchConfigurationType getLaunchConfigType() {
+ return getLaunchManager().getLaunchConfigurationType(
+ ValgrindLaunchPlugin.LAUNCH_ID);
+ }
+
+ protected ILaunch doLaunch(ILaunchConfiguration config, String testName)
+ throws URISyntaxException, IOException, CoreException {
+ ILaunch launch;
+ IPath pathToFiles = getPathToFiles(testName);
+
+ if (!ValgrindTestsPlugin.RUN_VALGRIND) {
+ bindLocation(pathToFiles);
+ }
+
+ ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
+ wc.setAttribute(LaunchConfigurationConstants.ATTR_INTERNAL_OUTPUT_DIR,
+ pathToFiles.toOSString());
+ wc.doSave();
+
+ ValgrindTestLaunchDelegate delegate = new ValgrindTestLaunchDelegate();
+ launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);
+
+ DebugPlugin.getDefault().getLaunchManager().addLaunch(launch);
+ launches.add(launch);
+ delegate.launch(config, ILaunchManager.PROFILE_MODE, launch, null);
+
+ if (ValgrindTestsPlugin.GENERATE_FILES
+ && ValgrindTestsPlugin.versionSupported()) {
+ unbindLocation(pathToFiles);
+ }
+ return launch;
+ }
+
+ protected IPath getPathToFiles(String testName) throws URISyntaxException,
+ IOException {
+ URL location = FileLocator.find(getBundle(),
+ new Path("valgrindFiles"), null); //$NON-NLS-1$
+ File file = new File(FileLocator.toFileURL(location).toURI());
+ IPath pathToFiles = new Path(file.getCanonicalPath()).append(testName);
+ return pathToFiles;
+ }
+
+ private void unbindLocation(IPath pathToFiles) throws IOException {
+ String bundleLoc = FileLocator.getBundleFile(getBundle())
+ .getCanonicalPath();
+ String workspaceLoc = ResourcesPlugin.getWorkspace().getRoot()
+ .getLocation().toOSString();
+ File testDir = pathToFiles.toFile();
+ for (File log : testDir.listFiles(NOT_TEMPLATE_FILTER)) {
+ File template = new File(testDir, TEMPLATE_PREFIX + log.getName());
+ replaceLocation(log, template, new String[] { bundleLoc,
+ workspaceLoc }, new String[] { SEARCH_STRING_BL,
+ SEARCH_STRING_WS });
+ }
+ }
+
+ private void bindLocation(IPath pathToFiles) throws IOException {
+ String bundleLoc = FileLocator.getBundleFile(getBundle())
+ .getCanonicalPath();
+ String workspaceLoc = ResourcesPlugin.getWorkspace().getRoot()
+ .getLocation().toOSString();
+ File testDir = pathToFiles.toFile();
+ for (File template : testDir.listFiles(TEMPLATE_FILTER)) {
+ String name = template.getName().replace(TEMPLATE_PREFIX, ""); //$NON-NLS-1$
+ File log = new File(testDir, name.substring(name
+ .indexOf(TEMPLATE_PREFIX) + 1));
+ replaceLocation(template, log, new String[] { SEARCH_STRING_BL,
+ SEARCH_STRING_WS },
+ new String[] { bundleLoc, workspaceLoc });
+ }
+ }
+
+ private void replaceLocation(File oldFile, File newFile, String[] from,
+ String[] to) {
+ if (oldFile.isFile()) {
+ try (BufferedReader br = new BufferedReader(new FileReader(oldFile));
+ PrintWriter pw = new PrintWriter(new FileWriter(newFile))) {
+ String line;
+ while ((line = br.readLine()) != null) {
+ for (int i = 0; i < from.length; i++) {
+ line = line.replaceAll(from[i], to[i]);
+ }
+ pw.println(line);
+ }
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ protected void setProfileAttributes(ILaunchConfigurationWorkingCopy wc)
+ throws CoreException {
+ ILaunchConfigurationTab tab = new ValgrindOptionsTab();
+ tab.setDefaults(wc);
+ tab = ValgrindLaunchPlugin.getDefault().getToolPage(getToolID());
+ tab.setDefaults(wc);
+ wc.setAttribute(LaunchConfigurationConstants.ATTR_TOOL, getToolID());
+ }
+
+ protected ICProject createProjectAndBuild(String projname) throws Exception {
+ return createProjectAndBuild(getBundle(), projname);
+ }
+
+ protected Bundle getBundle() {
+ return FrameworkUtil.getBundle(this.getClass());
+ }
+
+ protected abstract String getToolID();
+
+ private ValgrindCommand getValgrindCommand() {
+ if (!ValgrindTestsPlugin.RUN_VALGRIND) {
+ return new ValgrindStubCommand();
+ } else {
+ return new ValgrindCommand();
+ }
+ }
} \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubCommand.java b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubCommand.java
index 98e510aaba..c76f64de8e 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubCommand.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubCommand.java
@@ -17,18 +17,18 @@ import org.eclipse.linuxtools.internal.valgrind.core.ValgrindCommand;
public class ValgrindStubCommand extends ValgrindCommand {
- @Override
- public String whichVersion(IProject project) {
- return "valgrind-3.4.0"; //$NON-NLS-1$
- }
+ @Override
+ public String whichVersion(IProject project) {
+ return "valgrind-3.4.0"; //$NON-NLS-1$
+ }
- @Override
- public void execute(String[] commandArray, Object env, File wd, boolean usePty, IProject project) {
- args = commandArray;
- }
+ @Override
+ public void execute(String[] commandArray, Object env, File wd, boolean usePty, IProject project) {
+ args = commandArray;
+ }
- @Override
- public Process getProcess() {
- return null;
- }
+ @Override
+ public Process getProcess() {
+ return null;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubProcess.java b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubProcess.java
index 809b65eaa0..f01312dffa 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubProcess.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubProcess.java
@@ -18,68 +18,68 @@ import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.core.model.IStreamsProxy;
public class ValgrindStubProcess implements IProcess {
- protected Map<String, String> attributes;
- protected ILaunch launch;
- protected String label;
- protected IStreamsProxy streamsProxy;
-
- public ValgrindStubProcess(ILaunch launch, String label) {
- attributes = new HashMap<>();
- streamsProxy = new ValgrindStubStreamsProxy();
- this.launch = launch;
- this.label = label;
-
- launch.addProcess(this);
- }
-
- @Override
- public String getAttribute(String key) {
- return attributes.get(key);
- }
-
- @Override
- public int getExitValue() {
- return 0;
- }
-
- @Override
- public String getLabel() {
- return label;
- }
-
- @Override
- public ILaunch getLaunch() {
- return launch;
- }
-
- @Override
- public IStreamsProxy getStreamsProxy() {
- return streamsProxy;
- }
-
- @Override
- public void setAttribute(String key, String value) {
- attributes.put(key, value);
- }
-
- @Override
- @SuppressWarnings("rawtypes")
- public Object getAdapter(Class adapter) {
- return null;
- }
-
- @Override
- public boolean canTerminate() {
- return true;
- }
-
- @Override
- public boolean isTerminated() {
- return true;
- }
-
- @Override
- public void terminate() {
- }
+ protected Map<String, String> attributes;
+ protected ILaunch launch;
+ protected String label;
+ protected IStreamsProxy streamsProxy;
+
+ public ValgrindStubProcess(ILaunch launch, String label) {
+ attributes = new HashMap<>();
+ streamsProxy = new ValgrindStubStreamsProxy();
+ this.launch = launch;
+ this.label = label;
+
+ launch.addProcess(this);
+ }
+
+ @Override
+ public String getAttribute(String key) {
+ return attributes.get(key);
+ }
+
+ @Override
+ public int getExitValue() {
+ return 0;
+ }
+
+ @Override
+ public String getLabel() {
+ return label;
+ }
+
+ @Override
+ public ILaunch getLaunch() {
+ return launch;
+ }
+
+ @Override
+ public IStreamsProxy getStreamsProxy() {
+ return streamsProxy;
+ }
+
+ @Override
+ public void setAttribute(String key, String value) {
+ attributes.put(key, value);
+ }
+
+ @Override
+ @SuppressWarnings("rawtypes")
+ public Object getAdapter(Class adapter) {
+ return null;
+ }
+
+ @Override
+ public boolean canTerminate() {
+ return true;
+ }
+
+ @Override
+ public boolean isTerminated() {
+ return true;
+ }
+
+ @Override
+ public void terminate() {
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubStreamsProxy.java b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubStreamsProxy.java
index d212ebdaa8..b335b16fe4 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubStreamsProxy.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindStubStreamsProxy.java
@@ -15,17 +15,17 @@ import org.eclipse.debug.core.model.IStreamsProxy;
public class ValgrindStubStreamsProxy implements IStreamsProxy {
- @Override
- public IStreamMonitor getErrorStreamMonitor() {
- return null;
- }
+ @Override
+ public IStreamMonitor getErrorStreamMonitor() {
+ return null;
+ }
- @Override
- public IStreamMonitor getOutputStreamMonitor() {
- return null;
- }
+ @Override
+ public IStreamMonitor getOutputStreamMonitor() {
+ return null;
+ }
- @Override
- public void write(String input) {
- }
+ @Override
+ public void write(String input) {
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestLaunchDelegate.java b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestLaunchDelegate.java
index 1e876d8677..f305426e3b 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestLaunchDelegate.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestLaunchDelegate.java
@@ -21,44 +21,44 @@ import org.eclipse.linuxtools.internal.valgrind.core.ValgrindCommand;
import org.eclipse.linuxtools.internal.valgrind.launch.ValgrindLaunchConfigurationDelegate;
public class ValgrindTestLaunchDelegate extends
- ValgrindLaunchConfigurationDelegate {
+ ValgrindLaunchConfigurationDelegate {
- @Override
- protected ValgrindCommand getValgrindCommand() {
- if (!ValgrindTestsPlugin.RUN_VALGRIND) {
- return new ValgrindStubCommand();
- } else {
- return super.getValgrindCommand();
- }
- }
+ @Override
+ protected ValgrindCommand getValgrindCommand() {
+ if (!ValgrindTestsPlugin.RUN_VALGRIND) {
+ return new ValgrindStubCommand();
+ } else {
+ return super.getValgrindCommand();
+ }
+ }
- @Override
- protected void createDirectory(IPath path) throws IOException {
- if (ValgrindTestsPlugin.RUN_VALGRIND) {
- super.createDirectory(path);
- }
- }
+ @Override
+ protected void createDirectory(IPath path) throws IOException {
+ if (ValgrindTestsPlugin.RUN_VALGRIND) {
+ super.createDirectory(path);
+ }
+ }
- @Override
- protected IProcess createNewProcess(ILaunch launch, Process systemProcess,
- String programName) {
- IProcess process;
- if (ValgrindTestsPlugin.RUN_VALGRIND) {
- process = super
- .createNewProcess(launch, systemProcess, programName);
- } else {
- process = new ValgrindStubProcess(launch, programName);
- }
- return process;
- }
+ @Override
+ protected IProcess createNewProcess(ILaunch launch, Process systemProcess,
+ String programName) {
+ IProcess process;
+ if (ValgrindTestsPlugin.RUN_VALGRIND) {
+ process = super
+ .createNewProcess(launch, systemProcess, programName);
+ } else {
+ process = new ValgrindStubProcess(launch, programName);
+ }
+ return process;
+ }
- @Override
- protected void setOutputPath(ILaunchConfiguration config, IPath outputPath)
- throws CoreException {
- if (!ValgrindTestsPlugin.GENERATE_FILES
- && ValgrindTestsPlugin.RUN_VALGRIND) {
- super.setOutputPath(config, outputPath);
- }
- }
+ @Override
+ protected void setOutputPath(ILaunchConfiguration config, IPath outputPath)
+ throws CoreException {
+ if (!ValgrindTestsPlugin.GENERATE_FILES
+ && ValgrindTestsPlugin.RUN_VALGRIND) {
+ super.setOutputPath(config, outputPath);
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestLaunchShortcut.java b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestLaunchShortcut.java
index 410b35d77f..5d8add15fc 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestLaunchShortcut.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestLaunchShortcut.java
@@ -16,14 +16,14 @@ import org.eclipse.linuxtools.internal.valgrind.launch.ValgrindLaunchShortcut;
public class ValgrindTestLaunchShortcut extends ValgrindLaunchShortcut {
- private ILaunchConfiguration config;
+ private ILaunchConfiguration config;
- @Override
- public void launch(IBinary bin, String mode) {
- config = findLaunchConfiguration(bin, mode);
- }
-
- public ILaunchConfiguration getConfig() {
- return config;
- }
+ @Override
+ public void launch(IBinary bin, String mode) {
+ config = findLaunchConfiguration(bin, mode);
+ }
+
+ public ILaunchConfiguration getConfig() {
+ return config;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestsPlugin.java b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestsPlugin.java
index 129d8d2a31..3c2bd9fd94 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestsPlugin.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.tests/src/org/eclipse/linuxtools/internal/valgrind/tests/ValgrindTestsPlugin.java
@@ -17,51 +17,51 @@ import org.osgi.framework.Version;
public class ValgrindTestsPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.tests"; //$NON-NLS-1$
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.tests"; //$NON-NLS-1$
- // The minimum valgrind version supported for testing
- private static final Version MIN_TEST_VER = new Version(3, 7, 0);
+ // The minimum valgrind version supported for testing
+ private static final Version MIN_TEST_VER = new Version(3, 7, 0);
- // Java Runtime System Properties
- /**
- * usage: -Declipse.valgrind.tests.generateFiles=<yes|no> [default: no]
- * if yes, will run Valgrind and store its output files for each test under
- * <plugin root>/valgrindFiles
- * no, will use default output directory for valgrind's output
- */
- public static final String SYSTEM_PROPERTY_GENERATE_FILES = "eclipse.valgrind.tests.generateFiles"; //$NON-NLS-1$
- public static final boolean GENERATE_FILES = System.getProperty(SYSTEM_PROPERTY_GENERATE_FILES, "no").equals("yes"); //$NON-NLS-1$ //$NON-NLS-2$
+ // Java Runtime System Properties
+ /**
+ * usage: -Declipse.valgrind.tests.generateFiles=<yes|no> [default: no]
+ * if yes, will run Valgrind and store its output files for each test under
+ * <plugin root>/valgrindFiles
+ * no, will use default output directory for valgrind's output
+ */
+ public static final String SYSTEM_PROPERTY_GENERATE_FILES = "eclipse.valgrind.tests.generateFiles"; //$NON-NLS-1$
+ public static final boolean GENERATE_FILES = System.getProperty(SYSTEM_PROPERTY_GENERATE_FILES, "no").equals("yes"); //$NON-NLS-1$ //$NON-NLS-2$
- /**
- * usage: -Declipse.valgrind.tests.runValgrind=<yes|no> [default: yes]
- * if yes, will run Valgrind as in a normal launch
- * no, will simulate Valgrind execution with pregenerated log files
- */
- public static final String SYSTEM_PROPERTY_RUN_VALGRIND = "eclipse.valgrind.tests.runValgrind"; //$NON-NLS-1$
- // generateFiles implies runValgrind
- public static final boolean RUN_VALGRIND = (GENERATE_FILES || System.getProperty(SYSTEM_PROPERTY_RUN_VALGRIND, "yes").equals("yes")) //$NON-NLS-1$ //$NON-NLS-2$
- && versionSupported();
+ /**
+ * usage: -Declipse.valgrind.tests.runValgrind=<yes|no> [default: yes]
+ * if yes, will run Valgrind as in a normal launch
+ * no, will simulate Valgrind execution with pregenerated log files
+ */
+ public static final String SYSTEM_PROPERTY_RUN_VALGRIND = "eclipse.valgrind.tests.runValgrind"; //$NON-NLS-1$
+ // generateFiles implies runValgrind
+ public static final boolean RUN_VALGRIND = (GENERATE_FILES || System.getProperty(SYSTEM_PROPERTY_RUN_VALGRIND, "yes").equals("yes")) //$NON-NLS-1$ //$NON-NLS-2$
+ && versionSupported();
- // Launch config attribute to mock valgrind's exit code
- public static final String ATTR_MOCK_EXIT_CODE = PLUGIN_ID + ".MOCK_EXIT_CODE"; //$NON-NLS-1$
+ // Launch config attribute to mock valgrind's exit code
+ public static final String ATTR_MOCK_EXIT_CODE = PLUGIN_ID + ".MOCK_EXIT_CODE"; //$NON-NLS-1$
- /**
- * Compare currently available Valgrind version against the minimum
- * supported testing version.
- *
- * @return <code>true</code> if the current valgrind version is greater than
- * or equal to the minimum supported test version, and
- * <code>false</code> otherwise.
- */
- public static boolean versionSupported() {
- Version valgrindVersion = new Version(0, 0, 0);
- try {
- valgrindVersion = ValgrindLaunchPlugin.getDefault()
- .getValgrindVersion(null);
- } catch (CoreException e) {
- return false;
- }
- return valgrindVersion.compareTo(MIN_TEST_VER) >= 0;
- }
+ /**
+ * Compare currently available Valgrind version against the minimum
+ * supported testing version.
+ *
+ * @return <code>true</code> if the current valgrind version is greater than
+ * or equal to the minimum supported test version, and
+ * <code>false</code> otherwise.
+ */
+ public static boolean versionSupported() {
+ Version valgrindVersion = new Version(0, 0, 0);
+ try {
+ valgrindVersion = ValgrindLaunchPlugin.getDefault()
+ .getValgrindVersion(null);
+ } catch (CoreException e) {
+ return false;
+ }
+ return valgrindVersion.compareTo(MIN_TEST_VER) >= 0;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ColorManager.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ColorManager.java
index 11641f0a8d..aeeac306b0 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ColorManager.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ColorManager.java
@@ -23,21 +23,21 @@ import org.eclipse.swt.widgets.Display;
public class ColorManager {
- private Map<RGB, Color> colorTable = new HashMap<>(10);
+ private Map<RGB, Color> colorTable = new HashMap<>(10);
- public void dispose() {
- Iterator<Color> e = colorTable.values().iterator();
- while (e.hasNext()) {
- e.next().dispose();
- }
- }
+ public void dispose() {
+ Iterator<Color> e = colorTable.values().iterator();
+ while (e.hasNext()) {
+ e.next().dispose();
+ }
+ }
- public Color getColor(RGB rgb) {
- Color color = colorTable.get(rgb);
- if (color == null) {
- color = new Color(Display.getCurrent(), rgb);
- colorTable.put(rgb, color);
- }
- return color;
- }
+ public Color getColor(RGB rgb) {
+ Color color = colorTable.get(rgb);
+ if (color == null) {
+ color = new Color(Display.getCurrent(), rgb);
+ colorTable.put(rgb, color);
+ }
+ return color;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ISuppressionsColorConstants.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ISuppressionsColorConstants.java
index b99dc2e27d..84dba7180b 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ISuppressionsColorConstants.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ISuppressionsColorConstants.java
@@ -1,6 +1,6 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Phil Muldoon <pkmuldoon@picobot.org>.
- *
+ *
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
@@ -15,9 +15,9 @@ package org.eclipse.linuxtools.internal.valgrind.ui.editor;
import org.eclipse.swt.graphics.RGB;
public interface ISuppressionsColorConstants {
- RGB DEFAULT = new RGB(0, 0, 0);
- RGB TOOL = new RGB(153, 122, 0);
- RGB SUPP_TYPE = new RGB(0, 153, 122);
- RGB CONTEXT = new RGB(122, 0, 153);
- RGB COMMENT = new RGB(0, 99, 166);
+ RGB DEFAULT = new RGB(0, 0, 0);
+ RGB TOOL = new RGB(153, 122, 0);
+ RGB SUPP_TYPE = new RGB(0, 153, 122);
+ RGB CONTEXT = new RGB(122, 0, 153);
+ RGB COMMENT = new RGB(0, 99, 166);
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/Messages.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/Messages.java
index 39bce45e9f..8b6167ce43 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/Messages.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/Messages.java
@@ -14,19 +14,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.ui.editor.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.ui.editor.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionKindRule.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionKindRule.java
index 1b65507797..b38886f8bd 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionKindRule.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionKindRule.java
@@ -23,133 +23,133 @@ import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.rules.WordRule;
public class SuppressionKindRule implements IRule {
- private Map<String, List<String>> kinds;
- private IToken token;
- private WordRule subrule;
-
- private static final IToken DUMMY_TOKEN = new Token(null);
- private static final char[] COLON = new char[] { ':' };
-
- public SuppressionKindRule(Map<String, List<String>> suppKinds, IToken successToken) {
- kinds = suppKinds;
- token = successToken;
-
- final List<String> suppKindsList = new ArrayList<>();
- for (List<String> entry : suppKinds.values()) {
- suppKindsList.addAll(entry);
- }
-
- subrule = new WordRule(new IWordDetector() {
-
- @Override
- public boolean isWordStart(char c) {
- for (String kind : suppKindsList) {
- if (c == kind.charAt(0)) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public boolean isWordPart(char c) {
- return Character.isJavaIdentifierPart(c);
- }
-
- });
-
- for (String kind : suppKindsList) {
- subrule.addWord(kind, DUMMY_TOKEN);
- }
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner) {
- IToken result = subrule.evaluate(scanner);
- StringBuffer tool = new StringBuffer();
- StringBuffer kind = new StringBuffer();
-
- if (!result.isUndefined()) {
- boolean match = true;
-
- // move to beginning of token
- int tokenLength = ((SuppressionsElementScanner) scanner).getTokenLength();
- for (int i = 0; i < tokenLength; i++) {
- scanner.unread();
- }
-
- // check first char before token is a ':'
- match = checkColon(scanner);
- if (match) {
- // move to beginning of line
- int preTokenLength = 0;
- while (scanner.getColumn() > 0) {
- scanner.unread();
- preTokenLength++;
- }
-
- // ensure any leading characters are whitespace
- boolean foundChar = false;
- while (preTokenLength-- > 1) { // skip colon
- int ch = scanner.read();
- if (match && !Character.isWhitespace(ch)) {
- foundChar = true;
- tool.append(Character.toChars(ch));
- }
- else if (foundChar) {
- // encountered whitespace after tool name started
- match = false;
- }
- }
-
- scanner.read(); // consume colon
-
- // reset to end of token
- for (int i = 0; i < tokenLength; i++) {
- int ch = scanner.read();
- if (match) {
- kind.append(Character.toChars(ch));
- }
- }
-
- // assert kind is valid for tool
- if (match) {
- List<String> kindList = kinds.get(tool.toString());
- if (kindList == null || !kindList.contains(kind.toString())) {
- match = false;
- }
- }
- else {
- // reset to beginning of token
- unreadBuffer(scanner, tokenLength);
- }
- }
-
- if (!match) {
- result = Token.UNDEFINED;
- }
- else {
- result = token;
- }
- }
-
- return result;
- }
-
- private void unreadBuffer(ICharacterScanner scanner, int length) {
- for (int i = 0; i < length; i++) {
- scanner.unread();
- }
- }
-
- private boolean checkColon(ICharacterScanner scanner) {
- if (scanner.getColumn() == 0) {
- // nothing to read
- return false;
- }
- scanner.unread();
- int ch = scanner.read();
- return Arrays.equals(Character.toChars(ch), COLON);
- }
+ private Map<String, List<String>> kinds;
+ private IToken token;
+ private WordRule subrule;
+
+ private static final IToken DUMMY_TOKEN = new Token(null);
+ private static final char[] COLON = new char[] { ':' };
+
+ public SuppressionKindRule(Map<String, List<String>> suppKinds, IToken successToken) {
+ kinds = suppKinds;
+ token = successToken;
+
+ final List<String> suppKindsList = new ArrayList<>();
+ for (List<String> entry : suppKinds.values()) {
+ suppKindsList.addAll(entry);
+ }
+
+ subrule = new WordRule(new IWordDetector() {
+
+ @Override
+ public boolean isWordStart(char c) {
+ for (String kind : suppKindsList) {
+ if (c == kind.charAt(0)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isWordPart(char c) {
+ return Character.isJavaIdentifierPart(c);
+ }
+
+ });
+
+ for (String kind : suppKindsList) {
+ subrule.addWord(kind, DUMMY_TOKEN);
+ }
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner) {
+ IToken result = subrule.evaluate(scanner);
+ StringBuffer tool = new StringBuffer();
+ StringBuffer kind = new StringBuffer();
+
+ if (!result.isUndefined()) {
+ boolean match = true;
+
+ // move to beginning of token
+ int tokenLength = ((SuppressionsElementScanner) scanner).getTokenLength();
+ for (int i = 0; i < tokenLength; i++) {
+ scanner.unread();
+ }
+
+ // check first char before token is a ':'
+ match = checkColon(scanner);
+ if (match) {
+ // move to beginning of line
+ int preTokenLength = 0;
+ while (scanner.getColumn() > 0) {
+ scanner.unread();
+ preTokenLength++;
+ }
+
+ // ensure any leading characters are whitespace
+ boolean foundChar = false;
+ while (preTokenLength-- > 1) { // skip colon
+ int ch = scanner.read();
+ if (match && !Character.isWhitespace(ch)) {
+ foundChar = true;
+ tool.append(Character.toChars(ch));
+ }
+ else if (foundChar) {
+ // encountered whitespace after tool name started
+ match = false;
+ }
+ }
+
+ scanner.read(); // consume colon
+
+ // reset to end of token
+ for (int i = 0; i < tokenLength; i++) {
+ int ch = scanner.read();
+ if (match) {
+ kind.append(Character.toChars(ch));
+ }
+ }
+
+ // assert kind is valid for tool
+ if (match) {
+ List<String> kindList = kinds.get(tool.toString());
+ if (kindList == null || !kindList.contains(kind.toString())) {
+ match = false;
+ }
+ }
+ else {
+ // reset to beginning of token
+ unreadBuffer(scanner, tokenLength);
+ }
+ }
+
+ if (!match) {
+ result = Token.UNDEFINED;
+ }
+ else {
+ result = token;
+ }
+ }
+
+ return result;
+ }
+
+ private void unreadBuffer(ICharacterScanner scanner, int length) {
+ for (int i = 0; i < length; i++) {
+ scanner.unread();
+ }
+ }
+
+ private boolean checkColon(ICharacterScanner scanner) {
+ if (scanner.getColumn() == 0) {
+ // nothing to read
+ return false;
+ }
+ scanner.unread();
+ int ch = scanner.read();
+ return Arrays.equals(Character.toChars(ch), COLON);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionToolRule.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionToolRule.java
index 176462701a..f2d45b3249 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionToolRule.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionToolRule.java
@@ -20,98 +20,98 @@ import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.rules.WordRule;
public class SuppressionToolRule implements IRule {
- private String[] toolList;
- private IToken token;
- private WordRule subrule;
-
- private static final IToken DUMMY_TOKEN = new Token(null);
- private static final char[] COLON = new char[] { ':' };
-
- public SuppressionToolRule(String[] tools, IToken successToken) {
- toolList = tools;
- token = successToken;
- subrule = new WordRule(new IWordDetector() {
-
- @Override
- public boolean isWordStart(char c) {
- for (String tool : toolList) {
- if (c == tool.charAt(0)) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public boolean isWordPart(char c) {
- return c != ':';
- }
-
- });
-
- for (String tool : toolList) {
- subrule.addWord(tool, DUMMY_TOKEN);
- }
- }
-
- @Override
- public IToken evaluate(ICharacterScanner scanner) {
- IToken result = subrule.evaluate(scanner);
- if (!result.isUndefined()) {
- boolean match = true;
-
- int tokenLength = ((SuppressionsElementScanner) scanner).getTokenLength();
- match = checkColon(scanner);
- if (match) {
- // move to beginning of token
- for (int i = 0; i < tokenLength; i++) {
- scanner.unread();
- }
-
- // move to beginning of line
- int indentLength = 0;
- while (scanner.getColumn() > 0) {
- scanner.unread();
- indentLength++;
- }
-
- // ensure any leading characters are whitespace
- while (indentLength-- > 0) {
- int ch = scanner.read();
- if (!Character.isWhitespace(ch)) {
- match = false;
- }
- }
-
- // reset to end of token
- for (int i = 0; i < tokenLength; i++) {
- scanner.read();
- }
- }
-
- if (!match) {
- unreadBuffer(scanner, tokenLength);
- result = Token.UNDEFINED;
- } else {
- result = token;
- }
- }
-
- return result;
- }
-
- private boolean checkColon(ICharacterScanner scanner) {
- int ch = scanner.read();
- if (ch == ICharacterScanner.EOF) {
- return false;
- }
- scanner.unread();
- return Arrays.equals(Character.toChars(ch), COLON);
- }
-
- private void unreadBuffer(ICharacterScanner scanner, int length) {
- for (int i = 0; i < length; i++) {
- scanner.unread();
- }
- }
+ private String[] toolList;
+ private IToken token;
+ private WordRule subrule;
+
+ private static final IToken DUMMY_TOKEN = new Token(null);
+ private static final char[] COLON = new char[] { ':' };
+
+ public SuppressionToolRule(String[] tools, IToken successToken) {
+ toolList = tools;
+ token = successToken;
+ subrule = new WordRule(new IWordDetector() {
+
+ @Override
+ public boolean isWordStart(char c) {
+ for (String tool : toolList) {
+ if (c == tool.charAt(0)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public boolean isWordPart(char c) {
+ return c != ':';
+ }
+
+ });
+
+ for (String tool : toolList) {
+ subrule.addWord(tool, DUMMY_TOKEN);
+ }
+ }
+
+ @Override
+ public IToken evaluate(ICharacterScanner scanner) {
+ IToken result = subrule.evaluate(scanner);
+ if (!result.isUndefined()) {
+ boolean match = true;
+
+ int tokenLength = ((SuppressionsElementScanner) scanner).getTokenLength();
+ match = checkColon(scanner);
+ if (match) {
+ // move to beginning of token
+ for (int i = 0; i < tokenLength; i++) {
+ scanner.unread();
+ }
+
+ // move to beginning of line
+ int indentLength = 0;
+ while (scanner.getColumn() > 0) {
+ scanner.unread();
+ indentLength++;
+ }
+
+ // ensure any leading characters are whitespace
+ while (indentLength-- > 0) {
+ int ch = scanner.read();
+ if (!Character.isWhitespace(ch)) {
+ match = false;
+ }
+ }
+
+ // reset to end of token
+ for (int i = 0; i < tokenLength; i++) {
+ scanner.read();
+ }
+ }
+
+ if (!match) {
+ unreadBuffer(scanner, tokenLength);
+ result = Token.UNDEFINED;
+ } else {
+ result = token;
+ }
+ }
+
+ return result;
+ }
+
+ private boolean checkColon(ICharacterScanner scanner) {
+ int ch = scanner.read();
+ if (ch == ICharacterScanner.EOF) {
+ return false;
+ }
+ scanner.unread();
+ return Arrays.equals(Character.toChars(ch), COLON);
+ }
+
+ private void unreadBuffer(ICharacterScanner scanner, int length) {
+ for (int i = 0; i < length; i++) {
+ scanner.unread();
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsConfiguration.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsConfiguration.java
index 4bf4e0c095..704456800b 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsConfiguration.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsConfiguration.java
@@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Phil Muldoon <pkmuldoon@picobot.org>.
- *
+ *
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * Phil Muldoon <pkmuldoon@picobot.org> - initial API.
+ * Phil Muldoon <pkmuldoon@picobot.org> - initial API.
* Red Hat - modifications for use with Valgrind plugins.
*******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.ui.editor;
@@ -24,60 +24,60 @@ import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
public class SuppressionsConfiguration extends SourceViewerConfiguration {
-
- private SuppressionsEditor editor;
- private SuppressionsElementScanner elementScanner;
- public SuppressionsConfiguration(ColorManager colorManager, SuppressionsEditor editor) {
- this.editor = editor;
- elementScanner = new SuppressionsElementScanner(colorManager);
- }
-
- @Override
- public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
- return SuppressionsPartitionScanner.SUPP_CONTENT_TYPES;
- }
-
- @Override
- public IPresentationReconciler getPresentationReconciler(
- ISourceViewer sourceViewer) {
- PresentationReconciler reconciler = new PresentationReconciler();
+ private SuppressionsEditor editor;
+ private SuppressionsElementScanner elementScanner;
+
+ public SuppressionsConfiguration(ColorManager colorManager, SuppressionsEditor editor) {
+ this.editor = editor;
+ elementScanner = new SuppressionsElementScanner(colorManager);
+ }
+
+ @Override
+ public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
+ return SuppressionsPartitionScanner.SUPP_CONTENT_TYPES;
+ }
+
+ @Override
+ public IPresentationReconciler getPresentationReconciler(
+ ISourceViewer sourceViewer) {
+ PresentationReconciler reconciler = new PresentationReconciler();
+
+ DefaultDamagerRepairer dr = new DefaultDamagerRepairer(elementScanner);
+ reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
+ reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
+
+ dr = new DefaultDamagerRepairer(elementScanner);
+ reconciler.setDamager(dr, SuppressionsPartitionScanner.SUPP_TOOL);
+ reconciler.setRepairer(dr, SuppressionsPartitionScanner.SUPP_TOOL);
+
+ dr = new DefaultDamagerRepairer(elementScanner);
+ reconciler.setDamager(dr, SuppressionsPartitionScanner.SUPP_TYPE);
+ reconciler.setRepairer(dr, SuppressionsPartitionScanner.SUPP_TYPE);
+
+ dr = new DefaultDamagerRepairer(elementScanner);
+ reconciler.setDamager(dr, SuppressionsPartitionScanner.SUPP_CONTEXT);
+ reconciler.setRepairer(dr, SuppressionsPartitionScanner.SUPP_CONTEXT);
+
+ return reconciler;
+ }
+
+ @Override
+ public IReconciler getReconciler(ISourceViewer sourceViewer) {
+ SuppressionsReconcilingStrategy strategy = new SuppressionsReconcilingStrategy(editor);
+ return new MonoReconciler(strategy, false);
+ }
+
+ @Override
+ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
+ ContentAssistant assistant = new ContentAssistant();
+ assistant.setContentAssistProcessor(new SuppressionsContentAssistProcessor(), IDocument.DEFAULT_CONTENT_TYPE);
+ assistant.setContentAssistProcessor(new SuppressionsContentAssistProcessor(), SuppressionsPartitionScanner.SUPP_TOOL);
+ assistant.setContentAssistProcessor(new SuppressionsContentAssistProcessor(), SuppressionsPartitionScanner.SUPP_TYPE);
+ assistant.setContentAssistProcessor(new SuppressionsContentAssistProcessor(), SuppressionsPartitionScanner.SUPP_CONTEXT);
+ assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
+ assistant.enableAutoInsert(true);
+ return assistant;
+ }
- DefaultDamagerRepairer dr = new DefaultDamagerRepairer(elementScanner);
- reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
- reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
-
- dr = new DefaultDamagerRepairer(elementScanner);
- reconciler.setDamager(dr, SuppressionsPartitionScanner.SUPP_TOOL);
- reconciler.setRepairer(dr, SuppressionsPartitionScanner.SUPP_TOOL);
-
- dr = new DefaultDamagerRepairer(elementScanner);
- reconciler.setDamager(dr, SuppressionsPartitionScanner.SUPP_TYPE);
- reconciler.setRepairer(dr, SuppressionsPartitionScanner.SUPP_TYPE);
-
- dr = new DefaultDamagerRepairer(elementScanner);
- reconciler.setDamager(dr, SuppressionsPartitionScanner.SUPP_CONTEXT);
- reconciler.setRepairer(dr, SuppressionsPartitionScanner.SUPP_CONTEXT);
-
- return reconciler;
- }
-
- @Override
- public IReconciler getReconciler(ISourceViewer sourceViewer) {
- SuppressionsReconcilingStrategy strategy = new SuppressionsReconcilingStrategy(editor);
- return new MonoReconciler(strategy, false);
- }
-
- @Override
- public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
- ContentAssistant assistant = new ContentAssistant();
- assistant.setContentAssistProcessor(new SuppressionsContentAssistProcessor(), IDocument.DEFAULT_CONTENT_TYPE);
- assistant.setContentAssistProcessor(new SuppressionsContentAssistProcessor(), SuppressionsPartitionScanner.SUPP_TOOL);
- assistant.setContentAssistProcessor(new SuppressionsContentAssistProcessor(), SuppressionsPartitionScanner.SUPP_TYPE);
- assistant.setContentAssistProcessor(new SuppressionsContentAssistProcessor(), SuppressionsPartitionScanner.SUPP_CONTEXT);
- assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
- assistant.enableAutoInsert(true);
- return assistant;
- }
-
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsContentAssistProcessor.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsContentAssistProcessor.java
index 6d2e82b140..b9c3698a0d 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsContentAssistProcessor.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsContentAssistProcessor.java
@@ -23,124 +23,124 @@ import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
public class SuppressionsContentAssistProcessor implements
- IContentAssistProcessor {
-
- @Override
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
- int offset) {
- List<ICompletionProposal> completions = new ArrayList<>();
-
- IDocument doc = viewer.getDocument();
- try {
- // check if we're in the middle of a word
- String prefix = completionWord(doc, offset);
-
- int replacementOffset = offset;
- int replacementLength = 0;
- if (prefix != null) {
- // replacing what's been typed so far
- replacementLength = prefix.length();
- // subtract prefix length from offset
- replacementOffset -= replacementLength;
- }
- String toolName = getToolName(doc, replacementOffset);
- String[] words = getCompletionStrings(prefix, toolName);
- for (String word : words) {
- completions.add(new CompletionProposal(word, replacementOffset, replacementLength, word.length()));
- }
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
-
- return completions.toArray(new ICompletionProposal[completions.size()]);
- }
-
- @Override
- public IContextInformation[] computeContextInformation(ITextViewer viewer,
- int offset) {
- return new IContextInformation[0];
- }
-
- @Override
- public char[] getCompletionProposalAutoActivationCharacters() {
- return null;
- }
-
- @Override
- public char[] getContextInformationAutoActivationCharacters() {
- return null;
- }
-
- @Override
- public IContextInformationValidator getContextInformationValidator() {
- return null;
- }
-
- @Override
- public String getErrorMessage() {
- return null;
- }
-
- private String completionWord(IDocument doc, int offset)
- throws BadLocationException {
- String word = null;
- if (offset > 0) {
- for (int n = offset - 1; n >= 0 && word == null; n--) {
- char c = doc.getChar(n);
- if (!Character.isLetterOrDigit(c)) {
- word = doc.get(n + 1, offset - n - 1);
- }
- else if (n == 0) {
- // beginning of file
- word = doc.get(0, offset - n);
- }
- }
- }
- return word;
- }
-
- private String[] getCompletionStrings(String prefix, String toolName) {
- List<String> words = new ArrayList<>();
-
- // If the cursor is after "Memcheck:"
- if (toolName != null && toolName.equals(SuppressionsElementScanner.MEMCHECK)) {
- for (String word : SuppressionsElementScanner.MEMCHECK_SUPP_TYPES) {
- if (prefix == null || word.startsWith(prefix)) {
- words.add(word);
- }
- }
- } else {
- if (prefix == null || SuppressionsElementScanner.MEMCHECK.startsWith(prefix)) {
- words.add(SuppressionsElementScanner.MEMCHECK + ":"); //$NON-NLS-1$
- }
-
- for (String word : SuppressionsElementScanner.CONTEXTS) {
- if (prefix == null || word.startsWith(prefix)) {
- words.add(word + ":"); //$NON-NLS-1$
- }
- }
- }
- return words.toArray(new String[words.size()]);
- }
-
- private String getToolName(IDocument doc, int offset) throws BadLocationException {
- String tool = null;
- if (offset > 0) {
- char c = doc.getChar(--offset);
- // syntax is "toolName:suppressionKind"
- if (c == ':' && offset > 0) {
- for (int n = offset - 1; n >= 0 && tool == null; n--) {
- c = doc.getChar(n);
- if (!Character.isLetter(c)) {
- tool = doc.get(n + 1, offset - n - 1);
- } else if (n == 0) {
- // Beginning of file
- tool = doc.get(0, offset - n);
- }
- }
- }
- }
- return tool;
- }
+ IContentAssistProcessor {
+
+ @Override
+ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
+ int offset) {
+ List<ICompletionProposal> completions = new ArrayList<>();
+
+ IDocument doc = viewer.getDocument();
+ try {
+ // check if we're in the middle of a word
+ String prefix = completionWord(doc, offset);
+
+ int replacementOffset = offset;
+ int replacementLength = 0;
+ if (prefix != null) {
+ // replacing what's been typed so far
+ replacementLength = prefix.length();
+ // subtract prefix length from offset
+ replacementOffset -= replacementLength;
+ }
+ String toolName = getToolName(doc, replacementOffset);
+ String[] words = getCompletionStrings(prefix, toolName);
+ for (String word : words) {
+ completions.add(new CompletionProposal(word, replacementOffset, replacementLength, word.length()));
+ }
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
+
+ return completions.toArray(new ICompletionProposal[completions.size()]);
+ }
+
+ @Override
+ public IContextInformation[] computeContextInformation(ITextViewer viewer,
+ int offset) {
+ return new IContextInformation[0];
+ }
+
+ @Override
+ public char[] getCompletionProposalAutoActivationCharacters() {
+ return null;
+ }
+
+ @Override
+ public char[] getContextInformationAutoActivationCharacters() {
+ return null;
+ }
+
+ @Override
+ public IContextInformationValidator getContextInformationValidator() {
+ return null;
+ }
+
+ @Override
+ public String getErrorMessage() {
+ return null;
+ }
+
+ private String completionWord(IDocument doc, int offset)
+ throws BadLocationException {
+ String word = null;
+ if (offset > 0) {
+ for (int n = offset - 1; n >= 0 && word == null; n--) {
+ char c = doc.getChar(n);
+ if (!Character.isLetterOrDigit(c)) {
+ word = doc.get(n + 1, offset - n - 1);
+ }
+ else if (n == 0) {
+ // beginning of file
+ word = doc.get(0, offset - n);
+ }
+ }
+ }
+ return word;
+ }
+
+ private String[] getCompletionStrings(String prefix, String toolName) {
+ List<String> words = new ArrayList<>();
+
+ // If the cursor is after "Memcheck:"
+ if (toolName != null && toolName.equals(SuppressionsElementScanner.MEMCHECK)) {
+ for (String word : SuppressionsElementScanner.MEMCHECK_SUPP_TYPES) {
+ if (prefix == null || word.startsWith(prefix)) {
+ words.add(word);
+ }
+ }
+ } else {
+ if (prefix == null || SuppressionsElementScanner.MEMCHECK.startsWith(prefix)) {
+ words.add(SuppressionsElementScanner.MEMCHECK + ":"); //$NON-NLS-1$
+ }
+
+ for (String word : SuppressionsElementScanner.CONTEXTS) {
+ if (prefix == null || word.startsWith(prefix)) {
+ words.add(word + ":"); //$NON-NLS-1$
+ }
+ }
+ }
+ return words.toArray(new String[words.size()]);
+ }
+
+ private String getToolName(IDocument doc, int offset) throws BadLocationException {
+ String tool = null;
+ if (offset > 0) {
+ char c = doc.getChar(--offset);
+ // syntax is "toolName:suppressionKind"
+ if (c == ':' && offset > 0) {
+ for (int n = offset - 1; n >= 0 && tool == null; n--) {
+ c = doc.getChar(n);
+ if (!Character.isLetter(c)) {
+ tool = doc.get(n + 1, offset - n - 1);
+ } else if (n == 0) {
+ // Beginning of file
+ tool = doc.get(0, offset - n);
+ }
+ }
+ }
+ }
+ return tool;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsDocumentProvider.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsDocumentProvider.java
index 492566ef40..f12775d359 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsDocumentProvider.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsDocumentProvider.java
@@ -19,21 +19,21 @@ import org.eclipse.ui.editors.text.TextFileDocumentProvider;
public class SuppressionsDocumentProvider extends TextFileDocumentProvider {
- @Override
- public IDocument getDocument(Object element) {
- IDocument document = super.getDocument(element);
- if (document != null) {
- FastPartitioner partitioner = new FastPartitioner(
- new RuleBasedPartitionScanner(),
- SuppressionsPartitionScanner.SUPP_CONTENT_TYPES);
+ @Override
+ public IDocument getDocument(Object element) {
+ IDocument document = super.getDocument(element);
+ if (document != null) {
+ FastPartitioner partitioner = new FastPartitioner(
+ new RuleBasedPartitionScanner(),
+ SuppressionsPartitionScanner.SUPP_CONTENT_TYPES);
- partitioner.connect(document, false);
- if (document.getDocumentPartitioner() == null) {
- document.setDocumentPartitioner(partitioner);
- }
- }
- return document;
+ partitioner.connect(document, false);
+ if (document.getDocumentPartitioner() == null) {
+ document.setDocumentPartitioner(partitioner);
+ }
+ }
+ return document;
- }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsEditor.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsEditor.java
index 2248d4da63..3de6946f19 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsEditor.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsEditor.java
@@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Phil Muldoon <pkmuldoon@picobot.org>.
- *
+ *
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * Phil Muldoon <pkmuldoon@picobot.org> - initial API.
+ * Phil Muldoon <pkmuldoon@picobot.org> - initial API.
* Red Hat - modifications for use with Valgrind plugins.
*******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.ui.editor;
@@ -26,54 +26,54 @@ import org.eclipse.ui.editors.text.TextEditor;
public class SuppressionsEditor extends TextEditor {
-
- private ColorManager colorManager;
- private ProjectionAnnotationModel annotationModel;
- private Annotation[] oldAnnotations;
-
- public SuppressionsEditor() {
- this.colorManager = new ColorManager();
- setSourceViewerConfiguration(new SuppressionsConfiguration(colorManager, this));
- setDocumentProvider(new SuppressionsDocumentProvider());
- oldAnnotations = null;
- }
-
- @Override
- public void createPartControl(Composite parent) {
- super.createPartControl(parent);
- ProjectionViewer viewer =(ProjectionViewer)getSourceViewer();
- ProjectionSupport projectionSupport = new ProjectionSupport(viewer, getAnnotationAccess(), getSharedColors());
- projectionSupport.install();
- viewer.doOperation(ProjectionViewer.TOGGLE);
- annotationModel = viewer.getProjectionAnnotationModel();
- }
-
- @Override
- protected ISourceViewer createSourceViewer(Composite parent,
- IVerticalRuler ruler, int styles) {
-
- ISourceViewer viewer = new ProjectionViewer(parent, ruler,
- getOverviewRuler(), isOverviewRulerVisible(), styles);
- getSourceViewerDecorationSupport(viewer);
- return viewer;
- }
-
- public void updateFoldingStructure(Position[] updatedPositions) {
- Annotation[] updatedAnnotations = new Annotation[updatedPositions.length];
- HashMap<ProjectionAnnotation, Position> newAnnotations = new HashMap<>();
- for (int i = 0; i < updatedPositions.length; i++) {
- ProjectionAnnotation annotation = new ProjectionAnnotation();
- newAnnotations.put(annotation, updatedPositions[i]);
- updatedAnnotations[i] = annotation;
- }
- annotationModel.modifyAnnotations(oldAnnotations, newAnnotations, null);
- oldAnnotations = updatedAnnotations;
- }
-
- @Override
- public void dispose() {
- colorManager.dispose();
- super.dispose();
- }
-
+
+ private ColorManager colorManager;
+ private ProjectionAnnotationModel annotationModel;
+ private Annotation[] oldAnnotations;
+
+ public SuppressionsEditor() {
+ this.colorManager = new ColorManager();
+ setSourceViewerConfiguration(new SuppressionsConfiguration(colorManager, this));
+ setDocumentProvider(new SuppressionsDocumentProvider());
+ oldAnnotations = null;
+ }
+
+ @Override
+ public void createPartControl(Composite parent) {
+ super.createPartControl(parent);
+ ProjectionViewer viewer =(ProjectionViewer)getSourceViewer();
+ ProjectionSupport projectionSupport = new ProjectionSupport(viewer, getAnnotationAccess(), getSharedColors());
+ projectionSupport.install();
+ viewer.doOperation(ProjectionViewer.TOGGLE);
+ annotationModel = viewer.getProjectionAnnotationModel();
+ }
+
+ @Override
+ protected ISourceViewer createSourceViewer(Composite parent,
+ IVerticalRuler ruler, int styles) {
+
+ ISourceViewer viewer = new ProjectionViewer(parent, ruler,
+ getOverviewRuler(), isOverviewRulerVisible(), styles);
+ getSourceViewerDecorationSupport(viewer);
+ return viewer;
+ }
+
+ public void updateFoldingStructure(Position[] updatedPositions) {
+ Annotation[] updatedAnnotations = new Annotation[updatedPositions.length];
+ HashMap<ProjectionAnnotation, Position> newAnnotations = new HashMap<>();
+ for (int i = 0; i < updatedPositions.length; i++) {
+ ProjectionAnnotation annotation = new ProjectionAnnotation();
+ newAnnotations.put(annotation, updatedPositions[i]);
+ updatedAnnotations[i] = annotation;
+ }
+ annotationModel.modifyAnnotations(oldAnnotations, newAnnotations, null);
+ oldAnnotations = updatedAnnotations;
+ }
+
+ @Override
+ public void dispose() {
+ colorManager.dispose();
+ super.dispose();
+ }
+
} \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsElementScanner.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsElementScanner.java
index 322124dd8c..ee6601ef0a 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsElementScanner.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsElementScanner.java
@@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Phil Muldoon <pkmuldoon@picobot.org>.
- *
+ *
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * Phil Muldoon <pkmuldoon@picobot.org> - initial API.
+ * Phil Muldoon <pkmuldoon@picobot.org> - initial API.
* Red Hat - modifications for use with Valgrind plugins.
*******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.ui.editor;
@@ -29,47 +29,47 @@ import org.eclipse.swt.SWT;
public class SuppressionsElementScanner extends BufferedRuleBasedScanner {
- public static final String MEMCHECK = "Memcheck"; //$NON-NLS-1$
- public static final String[] MEMCHECK_SUPP_TYPES = new String[] {
- "Value0", "Value1", "Value2", "Value4", "Value8", "Value16", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "Cond", //$NON-NLS-1$
- "Addr1", "Addr2", "Addr4", "Addr8", "Addr16", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- "Jump", //$NON-NLS-1$
- "Param", //$NON-NLS-1$
- "Free", //$NON-NLS-1$
- "Overlap", //$NON-NLS-1$
- "Leak" //$NON-NLS-1$
- };
- public static final String[] CONTEXTS = new String[] { "obj", "fun" //$NON-NLS-1$ //$NON-NLS-2$
- };
+ public static final String MEMCHECK = "Memcheck"; //$NON-NLS-1$
+ public static final String[] MEMCHECK_SUPP_TYPES = new String[] {
+ "Value0", "Value1", "Value2", "Value4", "Value8", "Value16", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "Cond", //$NON-NLS-1$
+ "Addr1", "Addr2", "Addr4", "Addr8", "Addr16", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ "Jump", //$NON-NLS-1$
+ "Param", //$NON-NLS-1$
+ "Free", //$NON-NLS-1$
+ "Overlap", //$NON-NLS-1$
+ "Leak" //$NON-NLS-1$
+ };
+ public static final String[] CONTEXTS = new String[] { "obj", "fun" //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ public SuppressionsElementScanner(ColorManager colorManager) {
+ String[] tools = { MEMCHECK };
+ Map<String, List<String>> kinds = new HashMap<>();
+ kinds.put(MEMCHECK, Arrays.asList(MEMCHECK_SUPP_TYPES));
+
+ IToken defaultToken = new Token(new TextAttribute(colorManager
+ .getColor(ISuppressionsColorConstants.DEFAULT)));
+ IToken toolToken = new Token(new TextAttribute(colorManager
+ .getColor(ISuppressionsColorConstants.TOOL), null, SWT.BOLD));
+ IToken suppKindToken = new Token(new TextAttribute(colorManager
+ .getColor(ISuppressionsColorConstants.SUPP_TYPE)));
+ IToken contextToken = new Token(new TextAttribute(colorManager
+ .getColor(ISuppressionsColorConstants.CONTEXT), null, SWT.BOLD));
+ IToken commentToken = new Token(new TextAttribute(colorManager
+ .getColor(ISuppressionsColorConstants.COMMENT)));
- public SuppressionsElementScanner(ColorManager colorManager) {
- String[] tools = { MEMCHECK };
- Map<String, List<String>> kinds = new HashMap<>();
- kinds.put(MEMCHECK, Arrays.asList(MEMCHECK_SUPP_TYPES));
-
- IToken defaultToken = new Token(new TextAttribute(colorManager
- .getColor(ISuppressionsColorConstants.DEFAULT)));
- IToken toolToken = new Token(new TextAttribute(colorManager
- .getColor(ISuppressionsColorConstants.TOOL), null, SWT.BOLD));
- IToken suppKindToken = new Token(new TextAttribute(colorManager
- .getColor(ISuppressionsColorConstants.SUPP_TYPE)));
- IToken contextToken = new Token(new TextAttribute(colorManager
- .getColor(ISuppressionsColorConstants.CONTEXT), null, SWT.BOLD));
- IToken commentToken = new Token(new TextAttribute(colorManager
- .getColor(ISuppressionsColorConstants.COMMENT)));
-
- setDefaultReturnToken(defaultToken);
- setRules(new IRule[] {
- new EndOfLineRule("#", commentToken), //$NON-NLS-1$
- new SuppressionToolRule(tools, toolToken),
- new SuppressionKindRule(kinds, suppKindToken),
- new SuppressionToolRule(CONTEXTS, contextToken),
- new WhitespaceRule(new IWhitespaceDetector() {
- @Override
- public boolean isWhitespace(char c) {
- return Character.isWhitespace(c);
- }
- }) });
- }
+ setDefaultReturnToken(defaultToken);
+ setRules(new IRule[] {
+ new EndOfLineRule("#", commentToken), //$NON-NLS-1$
+ new SuppressionToolRule(tools, toolToken),
+ new SuppressionKindRule(kinds, suppKindToken),
+ new SuppressionToolRule(CONTEXTS, contextToken),
+ new WhitespaceRule(new IWhitespaceDetector() {
+ @Override
+ public boolean isWhitespace(char c) {
+ return Character.isWhitespace(c);
+ }
+ }) });
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsPartitionScanner.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsPartitionScanner.java
index 83823da146..8419a2481a 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsPartitionScanner.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsPartitionScanner.java
@@ -1,13 +1,13 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Phil Muldoon <pkmuldoon@picobot.org>.
- *
+ *
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * Phil Muldoon <pkmuldoon@picobot.org> - initial API.
+ * Phil Muldoon <pkmuldoon@picobot.org> - initial API.
* Red Hat - modifications for use with Valgrind plugins.
*******************************************************************************/
package org.eclipse.linuxtools.internal.valgrind.ui.editor;
@@ -20,19 +20,19 @@ import org.eclipse.jface.text.rules.RuleBasedPartitionScanner;
import org.eclipse.jface.text.rules.Token;
public class SuppressionsPartitionScanner extends RuleBasedPartitionScanner {
- public static final String SUPP_TOOL = "__supp_tool"; //$NON-NLS-1$
- public static final String SUPP_TYPE = "__supp_type"; //$NON-NLS-1$
- public static final String SUPP_CONTEXT = "__supp_context"; //$NON-NLS-1$
- public static final String SUPP_COMMENT = "__supp_comment"; //$NON-NLS-1$
-
- public static final String[] SUPP_CONTENT_TYPES = { IDocument.DEFAULT_CONTENT_TYPE, SUPP_TOOL, SUPP_TYPE, SUPP_CONTEXT, SUPP_COMMENT };
-
- public SuppressionsPartitionScanner() {
- IToken commentToken = new Token(SUPP_COMMENT);
-
- setPredicateRules(new IPredicateRule[] {
- new EndOfLineRule("#", commentToken) //$NON-NLS-1$
- });
- }
+ public static final String SUPP_TOOL = "__supp_tool"; //$NON-NLS-1$
+ public static final String SUPP_TYPE = "__supp_type"; //$NON-NLS-1$
+ public static final String SUPP_CONTEXT = "__supp_context"; //$NON-NLS-1$
+ public static final String SUPP_COMMENT = "__supp_comment"; //$NON-NLS-1$
+
+ public static final String[] SUPP_CONTENT_TYPES = { IDocument.DEFAULT_CONTENT_TYPE, SUPP_TOOL, SUPP_TYPE, SUPP_CONTEXT, SUPP_COMMENT };
+
+ public SuppressionsPartitionScanner() {
+ IToken commentToken = new Token(SUPP_COMMENT);
+
+ setPredicateRules(new IPredicateRule[] {
+ new EndOfLineRule("#", commentToken) //$NON-NLS-1$
+ });
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsReconcilingStrategy.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsReconcilingStrategy.java
index 38d7d6df0a..0c59cb5f1f 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsReconcilingStrategy.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/SuppressionsReconcilingStrategy.java
@@ -26,69 +26,69 @@ import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension;
import org.eclipse.swt.widgets.Display;
public class SuppressionsReconcilingStrategy implements IReconcilingStrategy,
- IReconcilingStrategyExtension {
- private SuppressionsEditor editor;
- private IDocument document;
- private List<Position> positions;
- private IProgressMonitor monitor;
+ IReconcilingStrategyExtension {
+ private SuppressionsEditor editor;
+ private IDocument document;
+ private List<Position> positions;
+ private IProgressMonitor monitor;
- public SuppressionsReconcilingStrategy(SuppressionsEditor editor) {
- this.editor = editor;
- positions = new ArrayList<>();
- }
+ public SuppressionsReconcilingStrategy(SuppressionsEditor editor) {
+ this.editor = editor;
+ positions = new ArrayList<>();
+ }
- @Override
- public void reconcile(IRegion partition) {
- initialReconcile();
- }
+ @Override
+ public void reconcile(IRegion partition) {
+ initialReconcile();
+ }
- @Override
- public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
- initialReconcile();
- }
+ @Override
+ public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) {
+ initialReconcile();
+ }
- @Override
- public void setDocument(IDocument document) {
- this.document = document;
- }
+ @Override
+ public void setDocument(IDocument document) {
+ this.document = document;
+ }
- @Override
- public void initialReconcile() {
- int start = -1;
- int end = document.getLength();
- int worked = 0;
- monitor.beginTask(Messages.getString("SuppressionsReconcilingStrategy.Monitor_title"), 10); //$NON-NLS-1$
- for (int pos = 0; pos < end; pos++) {
- try {
- char ch = document.getChar(pos);
- if (ch == '{') {
- start = pos;
- } else if (ch == '}' && start > 0) {
- positions.add(new Position(start, pos - start + 1));
- start = -1; // reset
- }
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
+ @Override
+ public void initialReconcile() {
+ int start = -1;
+ int end = document.getLength();
+ int worked = 0;
+ monitor.beginTask(Messages.getString("SuppressionsReconcilingStrategy.Monitor_title"), 10); //$NON-NLS-1$
+ for (int pos = 0; pos < end; pos++) {
+ try {
+ char ch = document.getChar(pos);
+ if (ch == '{') {
+ start = pos;
+ } else if (ch == '}' && start > 0) {
+ positions.add(new Position(start, pos - start + 1));
+ start = -1; // reset
+ }
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
- if (pos * 10 / end > worked) {
- monitor.worked(1);
- worked++;
- }
- }
- monitor.done();
+ if (pos * 10 / end > worked) {
+ monitor.worked(1);
+ worked++;
+ }
+ }
+ monitor.done();
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- editor.updateFoldingStructure(positions.toArray(new Position[positions.size()]));
- }
- });
- }
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ editor.updateFoldingStructure(positions.toArray(new Position[positions.size()]));
+ }
+ });
+ }
- @Override
- public void setProgressMonitor(IProgressMonitor monitor) {
- this.monitor = monitor;
- }
+ @Override
+ public void setProgressMonitor(IProgressMonitor monitor) {
+ this.monitor = monitor;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ValgrindEditorPlugin.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ValgrindEditorPlugin.java
index 110e553c37..9b368a03c3 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ValgrindEditorPlugin.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/ValgrindEditorPlugin.java
@@ -15,6 +15,6 @@ package org.eclipse.linuxtools.internal.valgrind.ui.editor;
* The activator class controls the plug-in life cycle
*/
public interface ValgrindEditorPlugin {
- // The plug-in ID
- String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.ui.editor"; //$NON-NLS-1$
+ // The plug-in ID
+ String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.ui.editor"; //$NON-NLS-1$
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/wizards/Messages.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/wizards/Messages.java
index 656512c05b..6c71733baf 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/wizards/Messages.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/wizards/Messages.java
@@ -14,19 +14,19 @@ import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.ui.editor.wizards.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.ui.editor.wizards.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/wizards/NewSuppressionWizard.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/wizards/NewSuppressionWizard.java
index a7902d3904..5e3fd53e2a 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/wizards/NewSuppressionWizard.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.editor/src/org/eclipse/linuxtools/internal/valgrind/ui/editor/wizards/NewSuppressionWizard.java
@@ -52,130 +52,130 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
*/
public class NewSuppressionWizard extends Wizard implements INewWizard {
- private static final String EXT_SUPP = "supp"; //$NON-NLS-1$
- private WizardNewFileCreationPage page;
- private IStructuredSelection selection;
+ private static final String EXT_SUPP = "supp"; //$NON-NLS-1$
+ private WizardNewFileCreationPage page;
+ private IStructuredSelection selection;
- /**
- * Constructor for NewSuppressionWizard.
- */
- public NewSuppressionWizard() {
- super();
- setNeedsProgressMonitor(true);
- }
+ /**
+ * Constructor for NewSuppressionWizard.
+ */
+ public NewSuppressionWizard() {
+ super();
+ setNeedsProgressMonitor(true);
+ }
- /**
- * Adding the page to the wizard.
- */
+ /**
+ * Adding the page to the wizard.
+ */
- @Override
- public void addPages() {
- page = new WizardNewFileCreationPage("newSuppressionPage", selection); //$NON-NLS-1$
- page.setTitle(Messages.getString("NewSuppressionWizard.NewWizard_title")); //$NON-NLS-1$
- page.setDescription(Messages.getString("NewSuppressionWizard.NewWizard_description")); //$NON-NLS-1$
- page.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(ValgrindEditorPlugin.PLUGIN_ID, "icons/newsupp_wiz.png")); //$NON-NLS-1$
- page.setFileExtension(EXT_SUPP);
- addPage(page);
- }
+ @Override
+ public void addPages() {
+ page = new WizardNewFileCreationPage("newSuppressionPage", selection); //$NON-NLS-1$
+ page.setTitle(Messages.getString("NewSuppressionWizard.NewWizard_title")); //$NON-NLS-1$
+ page.setDescription(Messages.getString("NewSuppressionWizard.NewWizard_description")); //$NON-NLS-1$
+ page.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(ValgrindEditorPlugin.PLUGIN_ID, "icons/newsupp_wiz.png")); //$NON-NLS-1$
+ page.setFileExtension(EXT_SUPP);
+ addPage(page);
+ }
- /**
- * This method is called when 'Finish' button is pressed in
- * the wizard. We will create an operation and run it
- * using wizard as execution context.
- */
- @Override
- public boolean performFinish() {
- final String containerName = page.getContainerFullPath().toOSString();
- final String fileName = page.getFileName();
- IRunnableWithProgress op = new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor) throws InvocationTargetException {
- try {
- doFinish(containerName, fileName, monitor);
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
- };
- try {
- getContainer().run(true, false, op);
- } catch (InterruptedException e) {
- return false;
- } catch (InvocationTargetException e) {
- Throwable realException = e.getTargetException();
- MessageDialog.openError(getShell(), Messages.getString("NewSuppressionWizard.performFinish_error"), realException.getMessage()); //$NON-NLS-1$
- return false;
- }
- return true;
- }
+ /**
+ * This method is called when 'Finish' button is pressed in
+ * the wizard. We will create an operation and run it
+ * using wizard as execution context.
+ */
+ @Override
+ public boolean performFinish() {
+ final String containerName = page.getContainerFullPath().toOSString();
+ final String fileName = page.getFileName();
+ IRunnableWithProgress op = new IRunnableWithProgress() {
+ @Override
+ public void run(IProgressMonitor monitor) throws InvocationTargetException {
+ try {
+ doFinish(containerName, fileName, monitor);
+ } catch (CoreException e) {
+ throw new InvocationTargetException(e);
+ } finally {
+ monitor.done();
+ }
+ }
+ };
+ try {
+ getContainer().run(true, false, op);
+ } catch (InterruptedException e) {
+ return false;
+ } catch (InvocationTargetException e) {
+ Throwable realException = e.getTargetException();
+ MessageDialog.openError(getShell(), Messages.getString("NewSuppressionWizard.performFinish_error"), realException.getMessage()); //$NON-NLS-1$
+ return false;
+ }
+ return true;
+ }
- /**
- * The worker method. It will find the container, create the
- * file if missing or just replace its contents, and open
- * the editor on the newly created file.
- */
+ /**
+ * The worker method. It will find the container, create the
+ * file if missing or just replace its contents, and open
+ * the editor on the newly created file.
+ */
- private void doFinish(
- String containerName,
- String fileName,
- IProgressMonitor monitor)
- throws CoreException {
- // create a sample file
- monitor.beginTask(NLS.bind(Messages.getString("NewSuppressionWizard.Creating_task"), fileName), 2); //$NON-NLS-1$
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IResource resource = root.findMember(new Path(containerName));
- if (!resource.exists() || !(resource instanceof IContainer)) {
- throwCoreException(NLS.bind(Messages.getString("NewSuppressionWizard.Container_not_exist_error"), containerName)); //$NON-NLS-1$
- }
- IContainer container = (IContainer) resource;
- final IFile file = container.getFile(new Path(fileName));
- try (InputStream stream = openContentStream()){
- if (file.exists()) {
- file.setContents(stream, true, true, monitor);
- } else {
- file.create(stream, true, monitor);
- }
- } catch (IOException e) {
- }
- monitor.worked(1);
- monitor.setTaskName(Messages.getString("NewSuppressionWizard.Opening_file_task")); //$NON-NLS-1$
- getShell().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- IWorkbenchPage page =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- try {
- IDE.openEditor(page, file, true);
- } catch (PartInitException e) {
- }
- }
- });
- monitor.worked(1);
- }
+ private void doFinish(
+ String containerName,
+ String fileName,
+ IProgressMonitor monitor)
+ throws CoreException {
+ // create a sample file
+ monitor.beginTask(NLS.bind(Messages.getString("NewSuppressionWizard.Creating_task"), fileName), 2); //$NON-NLS-1$
+ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
+ IResource resource = root.findMember(new Path(containerName));
+ if (!resource.exists() || !(resource instanceof IContainer)) {
+ throwCoreException(NLS.bind(Messages.getString("NewSuppressionWizard.Container_not_exist_error"), containerName)); //$NON-NLS-1$
+ }
+ IContainer container = (IContainer) resource;
+ final IFile file = container.getFile(new Path(fileName));
+ try (InputStream stream = openContentStream()){
+ if (file.exists()) {
+ file.setContents(stream, true, true, monitor);
+ } else {
+ file.create(stream, true, monitor);
+ }
+ } catch (IOException e) {
+ }
+ monitor.worked(1);
+ monitor.setTaskName(Messages.getString("NewSuppressionWizard.Opening_file_task")); //$NON-NLS-1$
+ getShell().getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ IWorkbenchPage page =
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
+ try {
+ IDE.openEditor(page, file, true);
+ } catch (PartInitException e) {
+ }
+ }
+ });
+ monitor.worked(1);
+ }
- /**
- * We will initialize file contents with a sample text.
- */
+ /**
+ * We will initialize file contents with a sample text.
+ */
- private InputStream openContentStream() {
- return new ByteArrayInputStream("{\n\t\n}".getBytes());
- }
+ private InputStream openContentStream() {
+ return new ByteArrayInputStream("{\n\t\n}".getBytes());
+ }
- private void throwCoreException(String message) throws CoreException {
- IStatus status =
- new Status(IStatus.ERROR, ValgrindEditorPlugin.PLUGIN_ID, IStatus.OK, message, null);
- throw new CoreException(status);
- }
+ private void throwCoreException(String message) throws CoreException {
+ IStatus status =
+ new Status(IStatus.ERROR, ValgrindEditorPlugin.PLUGIN_ID, IStatus.OK, message, null);
+ throw new CoreException(status);
+ }
- /**
- * We will accept the selection in the workbench to see if
- * we can initialize from it.
- * @see org.eclipse.ui.IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
- */
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- this.selection = selection;
- }
+ /**
+ * We will accept the selection in the workbench to see if
+ * we can initialize from it.
+ * @see org.eclipse.ui.IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
+ */
+ @Override
+ public void init(IWorkbench workbench, IStructuredSelection selection) {
+ this.selection = selection;
+ }
} \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.tests/pom.xml b/valgrind/org.eclipse.linuxtools.valgrind.ui.tests/pom.xml
index 35f07898da..e225cf9c8f 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.tests/pom.xml
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.tests/pom.xml
@@ -31,7 +31,7 @@
<configuration>
<testSuite>org.eclipse.linuxtools.valgrind.ui.tests</testSuite>
<testClass>org.eclipse.linuxtools.internal.valgrind.ui.quickfixes.tests.AllTests</testClass>
- <useUIHarness>true</useUIHarness>
+ <useUIHarness>true</useUIHarness>
<useUIThread>true</useUIThread>
<product>org.eclipse.product.ide</product>
</configuration>
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui.tests/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/tests/WrongDeallocationResolutionTest.java b/valgrind/org.eclipse.linuxtools.valgrind.ui.tests/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/tests/WrongDeallocationResolutionTest.java
index bec9fc728f..2858d74103 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui.tests/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/tests/WrongDeallocationResolutionTest.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui.tests/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/tests/WrongDeallocationResolutionTest.java
@@ -34,145 +34,145 @@ import org.junit.Test;
public class WrongDeallocationResolutionTest extends AbstractValgrindTest {
- private final String EMPTY_STRING = ""; //$NON-NLS-1$
- private final String VALGRIND_MARKER_TYPE = "org.eclipse.linuxtools.valgrind.launch.marker"; //$NON-NLS-1$
- private Document document;
- private IMarker[] markers;
-
- @Override
- protected String getToolID() {
- return "org.eclipse.linuxtools.valgrind.launch.memcheck"; //$NON-NLS-1$
- }
-
- @Before
- public void prep() throws Exception {
- proj = createProjectAndBuild("wrongDeallocTest"); //$NON-NLS-1$
- ILaunchConfiguration config = createConfiguration(proj.getProject());
- doLaunch(config, "wrongDeallocTest"); //$NON-NLS-1$
-
- document = new Document();
- InputStream fileInputStream = proj.getProject()
- .getFile("wrongDealloc.cpp").getContents(); //$NON-NLS-1$
- try (Scanner scanner = new Scanner(fileInputStream)) {
- scanner.useDelimiter("\\A"); //$NON-NLS-1$
- String content;
- if (scanner.hasNext()) {
- content = scanner.next();
- } else {
- content = EMPTY_STRING;
- }
- document.set(content);
- }
- markers = proj.getProject().findMarkers(VALGRIND_MARKER_TYPE, true, 1);
- Arrays.sort(markers, new MarkerComparator());
- }
-
- @Override
- @After
- public void tearDown() throws CoreException {
- deleteProject(proj);
- super.tearDown();
- }
-
- @Test
- public void testMallocDeleteQuickFix() throws CoreException {
- IMarker mallocDeleteMarker = markers[1];
- int markerLine = mallocDeleteMarker.getAttribute(IMarker.LINE_NUMBER,
- -1);
-
- createResolutionAndApply(mallocDeleteMarker);
-
- String newContent = getLineContent(document, markerLine);
- assertTrue(newContent.contains("free")); //$NON-NLS-1$
- assertFalse(newContent.contains("delete")); //$NON-NLS-1$
- }
-
- @Test
- public void testMallocDeleteArrayQuickFix() throws CoreException {
- IMarker mallocDeleteArrayMarker = markers[3];
- int markerLine = mallocDeleteArrayMarker.getAttribute(
- IMarker.LINE_NUMBER, -1);
-
- createResolutionAndApply(mallocDeleteArrayMarker);
-
- String newContent = getLineContent(document, markerLine);
- assertTrue(newContent.contains("free")); //$NON-NLS-1$
- assertFalse(newContent.contains("delete")); //$NON-NLS-1$
- assertFalse(newContent.contains("[")); //$NON-NLS-1$
- }
-
- @Test
- public void testNewFreeQuickFix() throws CoreException {
- IMarker newFreeMarker = markers[5];
- int markerLine = newFreeMarker.getAttribute(IMarker.LINE_NUMBER, -1);
-
- createResolutionAndApply(newFreeMarker);
-
- String newContent = getLineContent(document, markerLine);
- assertTrue(newContent.contains("delete")); //$NON-NLS-1$
- assertFalse(newContent.contains("free")); //$NON-NLS-1$
- }
-
- @Test
- public void testNewArrayFreeQuickFix() throws CoreException {
- IMarker newArrayFreeMarker = markers[7];
- int markerLine = newArrayFreeMarker.getAttribute(IMarker.LINE_NUMBER,
- -1);
-
- createResolutionAndApply(newArrayFreeMarker);
-
- String newContent = getLineContent(document, markerLine);
- assertTrue(newContent.contains("delete[]")); //$NON-NLS-1$
- assertFalse(newContent.contains("free")); //$NON-NLS-1$
- }
-
- @Test
- public void testNewArrayDeleteQuickFix() throws CoreException {
- IMarker newArrayDeleteMarker = markers[9];
- int markerLine = newArrayDeleteMarker.getAttribute(IMarker.LINE_NUMBER,
- -1);
-
- createResolutionAndApply(newArrayDeleteMarker);
-
- String newContent = getLineContent(document, markerLine);
- assertTrue(newContent.contains("delete[]")); //$NON-NLS-1$
- }
-
- private void createResolutionAndApply(IMarker marker) throws CoreException {
- WrongDeallocationResolution resolution = new WrongDeallocationResolution();
- assertNotNull(resolution);
-
- int numMarkersBefore = proj.getProject().findMarkers(
- VALGRIND_MARKER_TYPE, true, 1).length;
- resolution.apply(marker, document);
- int numMarkersAfter = proj.getProject().findMarkers(
- VALGRIND_MARKER_TYPE, true, 1).length;
-
- assertEquals(numMarkersAfter, numMarkersBefore - 2);
- }
-
- private String getLineContent(Document document, int line) {
- try {
- int lineOffset = document.getLineOffset(line - 1);
- int lineLength = document.getLineLength(line - 1);
- return document.get(lineOffset, lineLength);
- } catch (BadLocationException e) {
- return null;
- }
- }
-
- private static class MarkerComparator implements Comparator<IMarker> {
- @Override
- public int compare(IMarker marker1, IMarker marker2) {
- int line1 = marker1.getAttribute(IMarker.LINE_NUMBER, -1);
- int line2 = marker2.getAttribute(IMarker.LINE_NUMBER, -1);
-
- if (line1 > line2) {
- return 1;
- } else if (line2 > line1) {
- return -1;
- }
- return 0;
- }
- }
+ private final String EMPTY_STRING = ""; //$NON-NLS-1$
+ private final String VALGRIND_MARKER_TYPE = "org.eclipse.linuxtools.valgrind.launch.marker"; //$NON-NLS-1$
+ private Document document;
+ private IMarker[] markers;
+
+ @Override
+ protected String getToolID() {
+ return "org.eclipse.linuxtools.valgrind.launch.memcheck"; //$NON-NLS-1$
+ }
+
+ @Before
+ public void prep() throws Exception {
+ proj = createProjectAndBuild("wrongDeallocTest"); //$NON-NLS-1$
+ ILaunchConfiguration config = createConfiguration(proj.getProject());
+ doLaunch(config, "wrongDeallocTest"); //$NON-NLS-1$
+
+ document = new Document();
+ InputStream fileInputStream = proj.getProject()
+ .getFile("wrongDealloc.cpp").getContents(); //$NON-NLS-1$
+ try (Scanner scanner = new Scanner(fileInputStream)) {
+ scanner.useDelimiter("\\A"); //$NON-NLS-1$
+ String content;
+ if (scanner.hasNext()) {
+ content = scanner.next();
+ } else {
+ content = EMPTY_STRING;
+ }
+ document.set(content);
+ }
+ markers = proj.getProject().findMarkers(VALGRIND_MARKER_TYPE, true, 1);
+ Arrays.sort(markers, new MarkerComparator());
+ }
+
+ @Override
+ @After
+ public void tearDown() throws CoreException {
+ deleteProject(proj);
+ super.tearDown();
+ }
+
+ @Test
+ public void testMallocDeleteQuickFix() throws CoreException {
+ IMarker mallocDeleteMarker = markers[1];
+ int markerLine = mallocDeleteMarker.getAttribute(IMarker.LINE_NUMBER,
+ -1);
+
+ createResolutionAndApply(mallocDeleteMarker);
+
+ String newContent = getLineContent(document, markerLine);
+ assertTrue(newContent.contains("free")); //$NON-NLS-1$
+ assertFalse(newContent.contains("delete")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testMallocDeleteArrayQuickFix() throws CoreException {
+ IMarker mallocDeleteArrayMarker = markers[3];
+ int markerLine = mallocDeleteArrayMarker.getAttribute(
+ IMarker.LINE_NUMBER, -1);
+
+ createResolutionAndApply(mallocDeleteArrayMarker);
+
+ String newContent = getLineContent(document, markerLine);
+ assertTrue(newContent.contains("free")); //$NON-NLS-1$
+ assertFalse(newContent.contains("delete")); //$NON-NLS-1$
+ assertFalse(newContent.contains("[")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testNewFreeQuickFix() throws CoreException {
+ IMarker newFreeMarker = markers[5];
+ int markerLine = newFreeMarker.getAttribute(IMarker.LINE_NUMBER, -1);
+
+ createResolutionAndApply(newFreeMarker);
+
+ String newContent = getLineContent(document, markerLine);
+ assertTrue(newContent.contains("delete")); //$NON-NLS-1$
+ assertFalse(newContent.contains("free")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testNewArrayFreeQuickFix() throws CoreException {
+ IMarker newArrayFreeMarker = markers[7];
+ int markerLine = newArrayFreeMarker.getAttribute(IMarker.LINE_NUMBER,
+ -1);
+
+ createResolutionAndApply(newArrayFreeMarker);
+
+ String newContent = getLineContent(document, markerLine);
+ assertTrue(newContent.contains("delete[]")); //$NON-NLS-1$
+ assertFalse(newContent.contains("free")); //$NON-NLS-1$
+ }
+
+ @Test
+ public void testNewArrayDeleteQuickFix() throws CoreException {
+ IMarker newArrayDeleteMarker = markers[9];
+ int markerLine = newArrayDeleteMarker.getAttribute(IMarker.LINE_NUMBER,
+ -1);
+
+ createResolutionAndApply(newArrayDeleteMarker);
+
+ String newContent = getLineContent(document, markerLine);
+ assertTrue(newContent.contains("delete[]")); //$NON-NLS-1$
+ }
+
+ private void createResolutionAndApply(IMarker marker) throws CoreException {
+ WrongDeallocationResolution resolution = new WrongDeallocationResolution();
+ assertNotNull(resolution);
+
+ int numMarkersBefore = proj.getProject().findMarkers(
+ VALGRIND_MARKER_TYPE, true, 1).length;
+ resolution.apply(marker, document);
+ int numMarkersAfter = proj.getProject().findMarkers(
+ VALGRIND_MARKER_TYPE, true, 1).length;
+
+ assertEquals(numMarkersAfter, numMarkersBefore - 2);
+ }
+
+ private String getLineContent(Document document, int line) {
+ try {
+ int lineOffset = document.getLineOffset(line - 1);
+ int lineLength = document.getLineLength(line - 1);
+ return document.get(lineOffset, lineLength);
+ } catch (BadLocationException e) {
+ return null;
+ }
+ }
+
+ private static class MarkerComparator implements Comparator<IMarker> {
+ @Override
+ public int compare(IMarker marker1, IMarker marker2) {
+ int line1 = marker1.getAttribute(IMarker.LINE_NUMBER, -1);
+ int line2 = marker2.getAttribute(IMarker.LINE_NUMBER, -1);
+
+ if (line1 > line2) {
+ return 1;
+ } else if (line2 > line1) {
+ return -1;
+ }
+ return 0;
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui/plugin.xml b/valgrind/org.eclipse.linuxtools.valgrind.ui/plugin.xml
index 554a002cd4..34d9c37689 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui/plugin.xml
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui/plugin.xml
@@ -55,21 +55,21 @@
<extension
point="org.eclipse.ui.editors.markerAnnotationSpecification">
<specification
- annotationType="org.eclipse.linuxtools.valgrind.annotation.error"
+ annotationType="org.eclipse.linuxtools.valgrind.annotation.error"
label="%marker.editor.error"
icon="icons/valgrind-error.png"
quickFixIcon="icons/valgrind-error.png"
presentationLayer="6">
</specification>
<specification
- annotationType="org.eclipse.linuxtools.valgrind.annotation.warning"
+ annotationType="org.eclipse.linuxtools.valgrind.annotation.warning"
label="%marker.editor.warning"
icon="icons/valgrind-warning.png"
quickFixIcon="icons/valgrind-warning.png"
presentationLayer="5">
</specification>
<specification
- annotationType="org.eclipse.linuxtools.valgrind.annotation.info"
+ annotationType="org.eclipse.linuxtools.valgrind.annotation.info"
label="%marker.editor.info"
icon="icons/valgrind-info.png"
presentationLayer="4">
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/CoreMessagesViewer.java b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/CoreMessagesViewer.java
index c79587598b..24c66db9af 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/CoreMessagesViewer.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/CoreMessagesViewer.java
@@ -53,180 +53,180 @@ import org.eclipse.ui.plugin.AbstractUIPlugin;
public class CoreMessagesViewer {
- static ImageRegistry imageRegistry = new ImageRegistry();
-
- private static final String VALGRIND_ERROR = "Valgrind_Error"; //$NON-NLS-1$
- /**
- * @since 0.10
- */
- private static final String VALGRIND_INFO = "Valgrind_Info"; //$NON-NLS-1$
- private static final String VALGRIND_ERROR_IMAGE = "icons/valgrind-error.png"; //$NON-NLS-1$
- /**
- * @since 0.10
- */
- public static final String VALGRIND_INFO_IMAGE = "icons/valgrind-info.png"; //$NON-NLS-1$
- private IDoubleClickListener doubleClickListener;
- private ITreeContentProvider contentProvider;
-
- private TreeViewer viewer;
-
- public CoreMessagesViewer(Composite parent, int style) {
- viewer = new TreeViewer(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | style);
- viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
- if (imageRegistry.getDescriptor(VALGRIND_ERROR) == null) {
- ImageDescriptor d = AbstractUIPlugin.imageDescriptorFromPlugin(ValgrindUIPlugin.PLUGIN_ID, VALGRIND_ERROR_IMAGE);
- if (d != null) {
- imageRegistry.put(VALGRIND_ERROR, d);
- }
- }
- if (imageRegistry.getDescriptor(VALGRIND_INFO) == null) {
- ImageDescriptor d = AbstractUIPlugin.imageDescriptorFromPlugin(ValgrindUIPlugin.PLUGIN_ID, VALGRIND_INFO_IMAGE);
- if (d != null) {
- imageRegistry.put(VALGRIND_INFO, d);
- }
- }
- contentProvider = new ITreeContentProvider() {
-
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof Object[]) {
- return (Object[]) parentElement;
- }
- return ((IValgrindMessage) parentElement).getChildren();
- }
-
- @Override
- public Object getParent(Object element) {
- return ((IValgrindMessage) element).getParent();
- }
-
- @Override
- public boolean hasChildren(Object element) {
- return getChildren(element).length > 0;
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- @Override
- public void dispose() {}
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput,
- Object newInput) {}
-
- };
- viewer.setContentProvider(contentProvider);
-
- viewer.setLabelProvider(new LabelProvider() {
- @Override
- public String getText(Object element) {
- return ((IValgrindMessage) element).getText();
- }
-
- @Override
- public Image getImage(Object element) {
- Image image;
- if (element instanceof ValgrindStackFrame) {
- image = DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_STACKFRAME);
- } else if (element instanceof ValgrindError) {
- image = imageRegistry.get(VALGRIND_ERROR);
- } else {
- image = imageRegistry.get(VALGRIND_INFO);
- }
- return image;
- }
-
- });
-
- doubleClickListener = new IDoubleClickListener() {
-
- @Override
- public void doubleClick(DoubleClickEvent event) {
- Object element = ((TreeSelection) event.getSelection()).getFirstElement();
- if (element instanceof ValgrindStackFrame) {
- ValgrindStackFrame frame = (ValgrindStackFrame) element;
- ILaunch launch = frame.getLaunch();
- ISourceLocator locator = launch.getSourceLocator();
- if (locator instanceof AbstractSourceLookupDirector) {
- AbstractSourceLookupDirector director = (AbstractSourceLookupDirector) locator;
- ISourceLookupParticipant[] participants = director.getParticipants();
- if (participants.length == 0) {
- // source locator likely disposed, try recreating it
- IPersistableSourceLocator sourceLocator;
- ILaunchConfiguration config = launch.getLaunchConfiguration();
- if (config != null) {
- try {
- String id = config.getAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_ID, (String) null);
- if (id == null) {
- sourceLocator = CDebugUIPlugin.createDefaultSourceLocator();
- sourceLocator.initializeDefaults(config);
- } else {
- sourceLocator = DebugPlugin.getDefault().getLaunchManager().newSourceLocator(id);
- String memento = config.getAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_MEMENTO, (String) null);
- if (memento == null) {
- sourceLocator.initializeDefaults(config);
- } else {
- sourceLocator.initializeFromMemento(memento);
- }
- }
-
- // replace old source locator
- locator = sourceLocator;
- launch.setSourceLocator(sourceLocator);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
- }
- ISourceLookupResult result = DebugUITools.lookupSource(frame.getFile(), locator);
-
- try {
- ProfileUIUtils.openEditorAndSelect(result, frame.getLine());
- } catch (PartInitException|BadLocationException e) {
- e.printStackTrace();
- }
- }
- else {
- if (viewer.getExpandedState(element)) {
- viewer.collapseToLevel(element, AbstractTreeViewer.ALL_LEVELS);
- } else {
- viewer.expandToLevel(element, 1);
- }
- }
- }
- };
- viewer.addDoubleClickListener(doubleClickListener);
-
- final ExpandAction expandAction = new ExpandAction(viewer);
- final CollapseAction collapseAction = new CollapseAction(viewer);
-
- MenuManager manager = new MenuManager();
- manager.addMenuListener(new IMenuListener() {
- @Override
- public void menuAboutToShow(IMenuManager manager) {
- ITreeSelection selection = (ITreeSelection) viewer.getSelection();
- Object element = selection.getFirstElement();
- if (contentProvider.hasChildren(element)) {
- manager.add(expandAction);
- manager.add(collapseAction);
- }
- }
- });
-
- manager.setRemoveAllWhenShown(true);
- Menu contextMenu = manager.createContextMenu(viewer.getTree());
- viewer.getControl().setMenu(contextMenu);
- }
-
- public IDoubleClickListener getDoubleClickListener() {
- return doubleClickListener;
- }
-
- public TreeViewer getTreeViewer() {
- return viewer;
- }
+ static ImageRegistry imageRegistry = new ImageRegistry();
+
+ private static final String VALGRIND_ERROR = "Valgrind_Error"; //$NON-NLS-1$
+ /**
+ * @since 0.10
+ */
+ private static final String VALGRIND_INFO = "Valgrind_Info"; //$NON-NLS-1$
+ private static final String VALGRIND_ERROR_IMAGE = "icons/valgrind-error.png"; //$NON-NLS-1$
+ /**
+ * @since 0.10
+ */
+ public static final String VALGRIND_INFO_IMAGE = "icons/valgrind-info.png"; //$NON-NLS-1$
+ private IDoubleClickListener doubleClickListener;
+ private ITreeContentProvider contentProvider;
+
+ private TreeViewer viewer;
+
+ public CoreMessagesViewer(Composite parent, int style) {
+ viewer = new TreeViewer(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | style);
+ viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
+ if (imageRegistry.getDescriptor(VALGRIND_ERROR) == null) {
+ ImageDescriptor d = AbstractUIPlugin.imageDescriptorFromPlugin(ValgrindUIPlugin.PLUGIN_ID, VALGRIND_ERROR_IMAGE);
+ if (d != null) {
+ imageRegistry.put(VALGRIND_ERROR, d);
+ }
+ }
+ if (imageRegistry.getDescriptor(VALGRIND_INFO) == null) {
+ ImageDescriptor d = AbstractUIPlugin.imageDescriptorFromPlugin(ValgrindUIPlugin.PLUGIN_ID, VALGRIND_INFO_IMAGE);
+ if (d != null) {
+ imageRegistry.put(VALGRIND_INFO, d);
+ }
+ }
+ contentProvider = new ITreeContentProvider() {
+
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ if (parentElement instanceof Object[]) {
+ return (Object[]) parentElement;
+ }
+ return ((IValgrindMessage) parentElement).getChildren();
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ return ((IValgrindMessage) element).getParent();
+ }
+
+ @Override
+ public boolean hasChildren(Object element) {
+ return getChildren(element).length > 0;
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ return getChildren(inputElement);
+ }
+
+ @Override
+ public void dispose() {}
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput,
+ Object newInput) {}
+
+ };
+ viewer.setContentProvider(contentProvider);
+
+ viewer.setLabelProvider(new LabelProvider() {
+ @Override
+ public String getText(Object element) {
+ return ((IValgrindMessage) element).getText();
+ }
+
+ @Override
+ public Image getImage(Object element) {
+ Image image;
+ if (element instanceof ValgrindStackFrame) {
+ image = DebugUITools.getImage(IDebugUIConstants.IMG_OBJS_STACKFRAME);
+ } else if (element instanceof ValgrindError) {
+ image = imageRegistry.get(VALGRIND_ERROR);
+ } else {
+ image = imageRegistry.get(VALGRIND_INFO);
+ }
+ return image;
+ }
+
+ });
+
+ doubleClickListener = new IDoubleClickListener() {
+
+ @Override
+ public void doubleClick(DoubleClickEvent event) {
+ Object element = ((TreeSelection) event.getSelection()).getFirstElement();
+ if (element instanceof ValgrindStackFrame) {
+ ValgrindStackFrame frame = (ValgrindStackFrame) element;
+ ILaunch launch = frame.getLaunch();
+ ISourceLocator locator = launch.getSourceLocator();
+ if (locator instanceof AbstractSourceLookupDirector) {
+ AbstractSourceLookupDirector director = (AbstractSourceLookupDirector) locator;
+ ISourceLookupParticipant[] participants = director.getParticipants();
+ if (participants.length == 0) {
+ // source locator likely disposed, try recreating it
+ IPersistableSourceLocator sourceLocator;
+ ILaunchConfiguration config = launch.getLaunchConfiguration();
+ if (config != null) {
+ try {
+ String id = config.getAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_ID, (String) null);
+ if (id == null) {
+ sourceLocator = CDebugUIPlugin.createDefaultSourceLocator();
+ sourceLocator.initializeDefaults(config);
+ } else {
+ sourceLocator = DebugPlugin.getDefault().getLaunchManager().newSourceLocator(id);
+ String memento = config.getAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_MEMENTO, (String) null);
+ if (memento == null) {
+ sourceLocator.initializeDefaults(config);
+ } else {
+ sourceLocator.initializeFromMemento(memento);
+ }
+ }
+
+ // replace old source locator
+ locator = sourceLocator;
+ launch.setSourceLocator(sourceLocator);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ ISourceLookupResult result = DebugUITools.lookupSource(frame.getFile(), locator);
+
+ try {
+ ProfileUIUtils.openEditorAndSelect(result, frame.getLine());
+ } catch (PartInitException|BadLocationException e) {
+ e.printStackTrace();
+ }
+ }
+ else {
+ if (viewer.getExpandedState(element)) {
+ viewer.collapseToLevel(element, AbstractTreeViewer.ALL_LEVELS);
+ } else {
+ viewer.expandToLevel(element, 1);
+ }
+ }
+ }
+ };
+ viewer.addDoubleClickListener(doubleClickListener);
+
+ final ExpandAction expandAction = new ExpandAction(viewer);
+ final CollapseAction collapseAction = new CollapseAction(viewer);
+
+ MenuManager manager = new MenuManager();
+ manager.addMenuListener(new IMenuListener() {
+ @Override
+ public void menuAboutToShow(IMenuManager manager) {
+ ITreeSelection selection = (ITreeSelection) viewer.getSelection();
+ Object element = selection.getFirstElement();
+ if (contentProvider.hasChildren(element)) {
+ manager.add(expandAction);
+ manager.add(collapseAction);
+ }
+ }
+ });
+
+ manager.setRemoveAllWhenShown(true);
+ Menu contextMenu = manager.createContextMenu(viewer.getTree());
+ viewer.getControl().setMenu(contextMenu);
+ }
+
+ public IDoubleClickListener getDoubleClickListener() {
+ return doubleClickListener;
+ }
+
+ public TreeViewer getTreeViewer() {
+ return viewer;
+ }
} \ No newline at end of file
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/Messages.java b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/Messages.java
index b6b25046dc..f3a6bd6423 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/Messages.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/Messages.java
@@ -15,19 +15,19 @@ import java.util.ResourceBundle;
@SuppressWarnings("javadoc")
public class Messages {
- private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.ui.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.linuxtools.internal.valgrind.ui.messages"; //$NON-NLS-1$
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
- .getBundle(BUNDLE_NAME);
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
+ .getBundle(BUNDLE_NAME);
- private Messages() {
- }
+ private Messages() {
+ }
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/ValgrindUIPlugin.java b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/ValgrindUIPlugin.java
index 9a3cc88111..a8e826afb8 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/ValgrindUIPlugin.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/ValgrindUIPlugin.java
@@ -28,168 +28,168 @@ import org.osgi.framework.BundleContext;
public class ValgrindUIPlugin extends AbstractUIPlugin {
- /**
- * The plug-in ID.
- */
- public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.ui"; //$NON-NLS-1$
-
- // Extension point constants
- private static final String VIEW_EXT_ID = "valgrindToolViews"; //$NON-NLS-1$
- protected static final String EXT_ELEMENT = "view"; //$NON-NLS-1$
- protected static final String EXT_ATTR_ID = "definitionId"; //$NON-NLS-1$
- protected static final String EXT_ATTR_CLASS = "class"; //$NON-NLS-1$
-
- private HashMap<String, IConfigurationElement> toolMap;
-
- // The shared instance
- private static ValgrindUIPlugin plugin;
-
- private ValgrindViewPart view;
- // The page containing the created Valgrind view
- private IWorkbenchPage activePage;
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static ValgrindUIPlugin getDefault() {
- return plugin;
- }
-
- public void createView(final String contentDescription, final String toolID) {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- try {
- activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- activePage.showView(IValgrindToolView.VIEW_ID, null, IWorkbenchPage.VIEW_CREATE);
- // Bug #366831 Need to show the view otherwise the toolbar is disposed.
- activePage.showView(IValgrindToolView.VIEW_ID);
-
- // create the view's tool specific controls and populate content description
- view.createDynamicContent(contentDescription, toolID);
-
- view.refreshView();
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- });
- }
-
- /**
- * Shows the Valgrind view in the active page and gives it focus.
- */
- public void showView() {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- try {
- activePage.showView(IValgrindToolView.VIEW_ID);
- } catch (PartInitException e) {
- e.printStackTrace();
- }
- }
- });
- }
-
- /**
- * Refreshes the Valgrind view
- */
- public void refreshView() {
- if (view != null) {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- view.refreshView();
- }
- });
- }
- }
-
- /**
- * Empties the contents of the view and restores its original state.
- */
- public void resetView() {
- if (view != null) {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- try {
- view.createDynamicContent(Messages.getString("ValgrindViewPart.No_Valgrind_output"), null); //$NON-NLS-1$
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- });
- }
- }
-
- protected void setView(ValgrindViewPart view) {
- this.view = view;
- }
-
- /**
- * @return the Valgrind view
- */
- public ValgrindViewPart getView() {
- return view;
- }
-
- private void initializeToolMap() {
- toolMap = new HashMap<>();
- IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(PLUGIN_ID, VIEW_EXT_ID);
- IConfigurationElement[] configs = extPoint.getConfigurationElements();
- for (IConfigurationElement config : configs) {
- if (config.getName().equals(EXT_ELEMENT)) {
- String id = config.getAttribute(EXT_ATTR_ID);
- if (id != null && config.getAttribute(EXT_ATTR_CLASS) != null) {
- toolMap.put(id, config);
- }
- }
- }
- }
-
- private HashMap<String, IConfigurationElement> getToolMap() {
- if (toolMap == null) {
- initializeToolMap();
- }
- return toolMap;
- }
-
- public IValgrindToolView getToolView(String id) throws CoreException {
- IValgrindToolView view = null;
- IConfigurationElement config = getToolMap().get(id);
- if (config != null) {
- Object obj = config.createExecutableExtension(EXT_ATTR_CLASS);
- if (obj instanceof IValgrindToolView) {
- view = (IValgrindToolView) obj;
- }
- }
- if (view == null) {
- throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, Messages.getString("ValgrindUIPlugin.Cannot_retrieve_view"))); //$NON-NLS-1$
- }
- return view;
- }
+ /**
+ * The plug-in ID.
+ */
+ public static final String PLUGIN_ID = "org.eclipse.linuxtools.valgrind.ui"; //$NON-NLS-1$
+
+ // Extension point constants
+ private static final String VIEW_EXT_ID = "valgrindToolViews"; //$NON-NLS-1$
+ protected static final String EXT_ELEMENT = "view"; //$NON-NLS-1$
+ protected static final String EXT_ATTR_ID = "definitionId"; //$NON-NLS-1$
+ protected static final String EXT_ATTR_CLASS = "class"; //$NON-NLS-1$
+
+ private HashMap<String, IConfigurationElement> toolMap;
+
+ // The shared instance
+ private static ValgrindUIPlugin plugin;
+
+ private ValgrindViewPart view;
+ // The page containing the created Valgrind view
+ private IWorkbenchPage activePage;
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static ValgrindUIPlugin getDefault() {
+ return plugin;
+ }
+
+ public void createView(final String contentDescription, final String toolID) {
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
+ activePage.showView(IValgrindToolView.VIEW_ID, null, IWorkbenchPage.VIEW_CREATE);
+ // Bug #366831 Need to show the view otherwise the toolbar is disposed.
+ activePage.showView(IValgrindToolView.VIEW_ID);
+
+ // create the view's tool specific controls and populate content description
+ view.createDynamicContent(contentDescription, toolID);
+
+ view.refreshView();
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+ }
+
+ /**
+ * Shows the Valgrind view in the active page and gives it focus.
+ */
+ public void showView() {
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ activePage.showView(IValgrindToolView.VIEW_ID);
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+ }
+
+ /**
+ * Refreshes the Valgrind view
+ */
+ public void refreshView() {
+ if (view != null) {
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ view.refreshView();
+ }
+ });
+ }
+ }
+
+ /**
+ * Empties the contents of the view and restores its original state.
+ */
+ public void resetView() {
+ if (view != null) {
+ Display.getDefault().syncExec(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ view.createDynamicContent(Messages.getString("ValgrindViewPart.No_Valgrind_output"), null); //$NON-NLS-1$
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+ }
+ }
+
+ protected void setView(ValgrindViewPart view) {
+ this.view = view;
+ }
+
+ /**
+ * @return the Valgrind view
+ */
+ public ValgrindViewPart getView() {
+ return view;
+ }
+
+ private void initializeToolMap() {
+ toolMap = new HashMap<>();
+ IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(PLUGIN_ID, VIEW_EXT_ID);
+ IConfigurationElement[] configs = extPoint.getConfigurationElements();
+ for (IConfigurationElement config : configs) {
+ if (config.getName().equals(EXT_ELEMENT)) {
+ String id = config.getAttribute(EXT_ATTR_ID);
+ if (id != null && config.getAttribute(EXT_ATTR_CLASS) != null) {
+ toolMap.put(id, config);
+ }
+ }
+ }
+ }
+
+ private HashMap<String, IConfigurationElement> getToolMap() {
+ if (toolMap == null) {
+ initializeToolMap();
+ }
+ return toolMap;
+ }
+
+ public IValgrindToolView getToolView(String id) throws CoreException {
+ IValgrindToolView view = null;
+ IConfigurationElement config = getToolMap().get(id);
+ if (config != null) {
+ Object obj = config.createExecutableExtension(EXT_ATTR_CLASS);
+ if (obj instanceof IValgrindToolView) {
+ view = (IValgrindToolView) obj;
+ }
+ }
+ if (view == null) {
+ throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID, Messages.getString("ValgrindUIPlugin.Cannot_retrieve_view"))); //$NON-NLS-1$
+ }
+ return view;
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/ValgrindViewPart.java b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/ValgrindViewPart.java
index 97a4ebde52..9b2abcfb03 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/ValgrindViewPart.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/ValgrindViewPart.java
@@ -33,181 +33,181 @@ import org.eclipse.ui.part.ViewPart;
public class ValgrindViewPart extends ViewPart {
private static final String TOOLBAR_LOC_GROUP_ID = "toolbarLocal"; //$NON-NLS-1$
- private PageBook pageBook;
- private Composite dynamicViewHolder;
- private IValgrindToolView dynamicView;
- private ActionContributionItem[] dynamicActions;
- private IValgrindMessage[] messages;
- private CoreMessagesViewer messagesViewer;
- private Action showCoreAction;
- private Action showToolAction;
- private boolean hasDynamicContent = false;
-
- @Override
- public void createPartControl(Composite parent) {
- setContentDescription(Messages.getString("ValgrindViewPart.No_Valgrind_output")); //$NON-NLS-1$
-
- pageBook = new PageBook(parent, SWT.NONE);
- pageBook.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- messagesViewer = new CoreMessagesViewer(pageBook, SWT.NONE);
-
- dynamicViewHolder = new Composite(pageBook, SWT.NONE);
- GridLayout dynamicViewLayout = new GridLayout();
- dynamicViewLayout.marginWidth = dynamicViewLayout.marginHeight = 0;
- dynamicViewHolder.setLayout(dynamicViewLayout);
- dynamicViewHolder.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- showCoreAction = new Action(Messages.getString("ValgrindViewPart.Show_Core_Action"), IAction.AS_RADIO_BUTTON) { //$NON-NLS-1$
- @Override
- public void run() {
- showCorePage();
- }
- };
- showToolAction = new Action(Messages.getString("ValgrindViewPart.Show_Tool_Action"), IAction.AS_RADIO_BUTTON) { //$NON-NLS-1$
- @Override
- public void run() {
- showToolPage();
- }
- };
-
- ValgrindUIPlugin.getDefault().setView(this);
- }
-
- public IValgrindToolView createDynamicContent(String description, String toolID) throws CoreException {
- setContentDescription(description);
-
- // remove tool specific toolbar controls
- IToolBarManager toolbar = getViewSite().getActionBars().getToolBarManager();
- ToolBar tb = ((ToolBarManager) toolbar).getControl();
- if (tb == null || tb.isDisposed()) {
- throw new CoreException(new Status(IStatus.ERROR, ValgrindUIPlugin.PLUGIN_ID, "Toolbar is disposed")); //$NON-NLS-1$
- }
-
- if (dynamicActions != null) {
- for (ActionContributionItem item : dynamicActions) {
- toolbar.remove(item);
- }
- }
-
- // remove old view controls
- if (dynamicView != null) {
- dynamicView.dispose();
- }
-
- // remove old messages
- if (messages != null){
- messagesViewer.getTreeViewer().setInput(null);
- messages = null;
- }
-
- for (Control child : dynamicViewHolder.getChildren()) {
- if (!child.isDisposed()) {
- child.dispose();
- }
- }
-
- if (toolID != null) {
- dynamicView = ValgrindUIPlugin.getDefault().getToolView(toolID);
- dynamicView.createPartControl(dynamicViewHolder);
-
- // create toolbar items
- IAction[] actions = dynamicView.getToolbarActions();
- if (actions != null) {
- dynamicActions = new ActionContributionItem[actions.length];
- for (int i = 0; i < actions.length; i++) {
- dynamicActions[i] = new ActionContributionItem(actions[i]);
- toolbar.appendToGroup(TOOLBAR_LOC_GROUP_ID, dynamicActions[i]);
- }
- }
- } else {
- dynamicView = null;
- }
-
- // remove old menu items
- IMenuManager menu = getViewSite().getActionBars().getMenuManager();
- menu.removeAll();
- // was content was created?
- hasDynamicContent = dynamicViewHolder.getChildren().length > 0;
- if (hasDynamicContent) {
- menu.add(showCoreAction);
- menu.add(showToolAction);
- }
-
- menu.update(true);
- toolbar.update(true);
- // Update to notify the workbench items have been changed
- getViewSite().getActionBars().updateActionBars();
- dynamicViewHolder.layout(true);
-
- return dynamicView;
- }
-
- public void setMessages(IValgrindMessage[] messages) {
- this.messages = messages;
- }
-
- public IValgrindMessage[] getMessages() {
- return messages;
- }
-
- @Override
- public void setFocus() {
- if (dynamicView != null) {
- dynamicView.setFocus();
- }
- }
-
- public void refreshView() {
- if (messages != null && messages.length > 0) {
- messagesViewer.getTreeViewer().setInput(messages);
-
- // decide which page to show
- if (hasDynamicContent && messages[0] instanceof ValgrindInfo) {
- // no valgrind messages to show
- showCoreAction.setEnabled(false);
- showToolPage();
- }
- else {
- showCoreAction.setEnabled(true);
- showCorePage();
- }
- }
- if (dynamicView != null) {
- dynamicView.refreshView();
- }
- }
-
- @Override
- public void dispose() {
- if (dynamicView != null) {
- dynamicView.dispose();
- }
-
- // Unset this view in the UI plugin
- ValgrindUIPlugin.getDefault().setView(null);
-
- super.dispose();
- }
-
- public IValgrindToolView getDynamicView() {
- return dynamicView;
- }
-
- public CoreMessagesViewer getMessagesViewer() {
- return messagesViewer;
- }
-
- private void showCorePage() {
- pageBook.showPage(messagesViewer.getTreeViewer().getControl());
- showCoreAction.setChecked(true);
- showToolAction.setChecked(false);
- }
-
- private void showToolPage() {
- pageBook.showPage(dynamicViewHolder);
- showToolAction.setChecked(true);
- showCoreAction.setChecked(false);
- }
+ private PageBook pageBook;
+ private Composite dynamicViewHolder;
+ private IValgrindToolView dynamicView;
+ private ActionContributionItem[] dynamicActions;
+ private IValgrindMessage[] messages;
+ private CoreMessagesViewer messagesViewer;
+ private Action showCoreAction;
+ private Action showToolAction;
+ private boolean hasDynamicContent = false;
+
+ @Override
+ public void createPartControl(Composite parent) {
+ setContentDescription(Messages.getString("ValgrindViewPart.No_Valgrind_output")); //$NON-NLS-1$
+
+ pageBook = new PageBook(parent, SWT.NONE);
+ pageBook.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ messagesViewer = new CoreMessagesViewer(pageBook, SWT.NONE);
+
+ dynamicViewHolder = new Composite(pageBook, SWT.NONE);
+ GridLayout dynamicViewLayout = new GridLayout();
+ dynamicViewLayout.marginWidth = dynamicViewLayout.marginHeight = 0;
+ dynamicViewHolder.setLayout(dynamicViewLayout);
+ dynamicViewHolder.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ showCoreAction = new Action(Messages.getString("ValgrindViewPart.Show_Core_Action"), IAction.AS_RADIO_BUTTON) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ showCorePage();
+ }
+ };
+ showToolAction = new Action(Messages.getString("ValgrindViewPart.Show_Tool_Action"), IAction.AS_RADIO_BUTTON) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ showToolPage();
+ }
+ };
+
+ ValgrindUIPlugin.getDefault().setView(this);
+ }
+
+ public IValgrindToolView createDynamicContent(String description, String toolID) throws CoreException {
+ setContentDescription(description);
+
+ // remove tool specific toolbar controls
+ IToolBarManager toolbar = getViewSite().getActionBars().getToolBarManager();
+ ToolBar tb = ((ToolBarManager) toolbar).getControl();
+ if (tb == null || tb.isDisposed()) {
+ throw new CoreException(new Status(IStatus.ERROR, ValgrindUIPlugin.PLUGIN_ID, "Toolbar is disposed")); //$NON-NLS-1$
+ }
+
+ if (dynamicActions != null) {
+ for (ActionContributionItem item : dynamicActions) {
+ toolbar.remove(item);
+ }
+ }
+
+ // remove old view controls
+ if (dynamicView != null) {
+ dynamicView.dispose();
+ }
+
+ // remove old messages
+ if (messages != null){
+ messagesViewer.getTreeViewer().setInput(null);
+ messages = null;
+ }
+
+ for (Control child : dynamicViewHolder.getChildren()) {
+ if (!child.isDisposed()) {
+ child.dispose();
+ }
+ }
+
+ if (toolID != null) {
+ dynamicView = ValgrindUIPlugin.getDefault().getToolView(toolID);
+ dynamicView.createPartControl(dynamicViewHolder);
+
+ // create toolbar items
+ IAction[] actions = dynamicView.getToolbarActions();
+ if (actions != null) {
+ dynamicActions = new ActionContributionItem[actions.length];
+ for (int i = 0; i < actions.length; i++) {
+ dynamicActions[i] = new ActionContributionItem(actions[i]);
+ toolbar.appendToGroup(TOOLBAR_LOC_GROUP_ID, dynamicActions[i]);
+ }
+ }
+ } else {
+ dynamicView = null;
+ }
+
+ // remove old menu items
+ IMenuManager menu = getViewSite().getActionBars().getMenuManager();
+ menu.removeAll();
+ // was content was created?
+ hasDynamicContent = dynamicViewHolder.getChildren().length > 0;
+ if (hasDynamicContent) {
+ menu.add(showCoreAction);
+ menu.add(showToolAction);
+ }
+
+ menu.update(true);
+ toolbar.update(true);
+ // Update to notify the workbench items have been changed
+ getViewSite().getActionBars().updateActionBars();
+ dynamicViewHolder.layout(true);
+
+ return dynamicView;
+ }
+
+ public void setMessages(IValgrindMessage[] messages) {
+ this.messages = messages;
+ }
+
+ public IValgrindMessage[] getMessages() {
+ return messages;
+ }
+
+ @Override
+ public void setFocus() {
+ if (dynamicView != null) {
+ dynamicView.setFocus();
+ }
+ }
+
+ public void refreshView() {
+ if (messages != null && messages.length > 0) {
+ messagesViewer.getTreeViewer().setInput(messages);
+
+ // decide which page to show
+ if (hasDynamicContent && messages[0] instanceof ValgrindInfo) {
+ // no valgrind messages to show
+ showCoreAction.setEnabled(false);
+ showToolPage();
+ }
+ else {
+ showCoreAction.setEnabled(true);
+ showCorePage();
+ }
+ }
+ if (dynamicView != null) {
+ dynamicView.refreshView();
+ }
+ }
+
+ @Override
+ public void dispose() {
+ if (dynamicView != null) {
+ dynamicView.dispose();
+ }
+
+ // Unset this view in the UI plugin
+ ValgrindUIPlugin.getDefault().setView(null);
+
+ super.dispose();
+ }
+
+ public IValgrindToolView getDynamicView() {
+ return dynamicView;
+ }
+
+ public CoreMessagesViewer getMessagesViewer() {
+ return messagesViewer;
+ }
+
+ private void showCorePage() {
+ pageBook.showPage(messagesViewer.getTreeViewer().getControl());
+ showCoreAction.setChecked(true);
+ showToolAction.setChecked(false);
+ }
+
+ private void showToolPage() {
+ pageBook.showPage(dynamicViewHolder);
+ showToolAction.setChecked(true);
+ showCoreAction.setChecked(false);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/AbstractValgrindMarkerResolution.java b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/AbstractValgrindMarkerResolution.java
index 4a4ef0ac65..6610166c20 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/AbstractValgrindMarkerResolution.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/AbstractValgrindMarkerResolution.java
@@ -29,55 +29,55 @@ import org.eclipse.jface.text.IDocument;
*/
public abstract class AbstractValgrindMarkerResolution extends AbstractCodanCMarkerResolution {
- /**
- * Returns the enclosed AST node in the given marker.
- * @param marker The {@link IMarker} containing the {@link IASTNode}
- * @return the enclosed {@link IASTNode}
- */
- protected IASTNode getIASTNode(IMarker marker, IDocument document){
- int offset = this.getOffset(marker, document);
- int length = this.getLength(marker, document);
+ /**
+ * Returns the enclosed AST node in the given marker.
+ * @param marker The {@link IMarker} containing the {@link IASTNode}
+ * @return the enclosed {@link IASTNode}
+ */
+ protected IASTNode getIASTNode(IMarker marker, IDocument document){
+ int offset = this.getOffset(marker, document);
+ int length = this.getLength(marker, document);
- IASTNode node = null;
- IASTTranslationUnit ast = getASTTranslationUnit(marker);
+ IASTNode node = null;
+ IASTTranslationUnit ast = getASTTranslationUnit(marker);
- IASTNodeSelector nodeSelector = ast.getNodeSelector(marker.getResource().getLocationURI().getPath());
- node = nodeSelector.findFirstContainedNode(offset, length);
+ IASTNodeSelector nodeSelector = ast.getNodeSelector(marker.getResource().getLocationURI().getPath());
+ node = nodeSelector.findFirstContainedNode(offset, length);
- return node;
- }
+ return node;
+ }
- /**
- * Returns the translation unit that contains the given marker.
- * @param marker The {@link IMarker} from which the {@link IASTTranslationUnit} will be obtained
- * @return {@link IASTTranslationUnit} containing the marker
- */
- private IASTTranslationUnit getASTTranslationUnit(IMarker marker){
- ITranslationUnit tu = getTranslationUnitViaEditor(marker);
- try {
- return tu.getAST();
- } catch (CoreException e) {
- return null;
- }
- }
+ /**
+ * Returns the translation unit that contains the given marker.
+ * @param marker The {@link IMarker} from which the {@link IASTTranslationUnit} will be obtained
+ * @return {@link IASTTranslationUnit} containing the marker
+ */
+ private IASTTranslationUnit getASTTranslationUnit(IMarker marker){
+ ITranslationUnit tu = getTranslationUnitViaEditor(marker);
+ try {
+ return tu.getAST();
+ } catch (CoreException e) {
+ return null;
+ }
+ }
- /**
- * Returns the length of the code contained in the given marker or
- * -1 if the location does not exist in the document.
- * @param marker {@link IMarker} from which the length will be obtained
- * @return length of the code enclosed in the {@link IMarker}
- */
- private int getLength(IMarker marker, IDocument document) {
- int charStart = marker.getAttribute(IMarker.CHAR_START, -1);
- int charEnd = marker.getAttribute(IMarker.CHAR_END, -1);
- if (charEnd != -1 && charStart != -1) {
- return charEnd - charStart;
- }
- int line = marker.getAttribute(IMarker.LINE_NUMBER, -1) -1;
- try {
- return document.getLineLength(line);
- } catch (BadLocationException e) {
- return -1;
- }
+ /**
+ * Returns the length of the code contained in the given marker or
+ * -1 if the location does not exist in the document.
+ * @param marker {@link IMarker} from which the length will be obtained
+ * @return length of the code enclosed in the {@link IMarker}
+ */
+ private int getLength(IMarker marker, IDocument document) {
+ int charStart = marker.getAttribute(IMarker.CHAR_START, -1);
+ int charEnd = marker.getAttribute(IMarker.CHAR_END, -1);
+ if (charEnd != -1 && charStart != -1) {
+ return charEnd - charStart;
+ }
+ int line = marker.getAttribute(IMarker.LINE_NUMBER, -1) -1;
+ try {
+ return document.getLineLength(line);
+ } catch (BadLocationException e) {
+ return -1;
+ }
}
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/ValgrindResolutionGenerator.java b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/ValgrindResolutionGenerator.java
index 27ab5a6aca..82ba44f06b 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/ValgrindResolutionGenerator.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/ValgrindResolutionGenerator.java
@@ -23,19 +23,19 @@ import org.eclipse.ui.IMarkerResolutionGenerator2;
*/
public class ValgrindResolutionGenerator implements IMarkerResolutionGenerator2 {
- @Override
- public IMarkerResolution[] getResolutions(IMarker marker) {
- String message = marker.getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$
- if(message.contains(Messages.getString("ValgrindMemcheckQuickFixes.Wrong_dealloc_message"))){ //$NON-NLS-1$
- return new IMarkerResolution[]{new WrongDeallocationResolution()};
- } else {
- return new IMarkerResolution[0];
- }
- }
+ @Override
+ public IMarkerResolution[] getResolutions(IMarker marker) {
+ String message = marker.getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$
+ if(message.contains(Messages.getString("ValgrindMemcheckQuickFixes.Wrong_dealloc_message"))){ //$NON-NLS-1$
+ return new IMarkerResolution[]{new WrongDeallocationResolution()};
+ } else {
+ return new IMarkerResolution[0];
+ }
+ }
- @Override
- public boolean hasResolutions(IMarker marker) {
- String message = marker.getAttribute(IMarker.MESSAGE, "" ); //$NON-NLS-1$
- return message.contains(Messages.getString("ValgrindMemcheckQuickFixes.Wrong_dealloc_message")) ? true: false; //$NON-NLS-1$
- }
+ @Override
+ public boolean hasResolutions(IMarker marker) {
+ String message = marker.getAttribute(IMarker.MESSAGE, "" ); //$NON-NLS-1$
+ return message.contains(Messages.getString("ValgrindMemcheckQuickFixes.Wrong_dealloc_message")) ? true: false; //$NON-NLS-1$
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/WrongDeallocationResolution.java b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/WrongDeallocationResolution.java
index 854b42ae33..769baa51b9 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/WrongDeallocationResolution.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/internal/valgrind/ui/quickfixes/WrongDeallocationResolution.java
@@ -39,235 +39,235 @@ import org.eclipse.ui.PlatformUI;
* @author rafaelmt
*/
public class WrongDeallocationResolution extends AbstractValgrindMarkerResolution {
- private static final String DELETE = "delete"; //$NON-NLS-1$
- private static final String FREE = "free"; //$NON-NLS-1$
- private static final String NEW = "new"; //$NON-NLS-1$
+ private static final String DELETE = "delete"; //$NON-NLS-1$
+ private static final String FREE = "free"; //$NON-NLS-1$
+ private static final String NEW = "new"; //$NON-NLS-1$
- @Override
- public void apply(IMarker marker, IDocument document) {
- try {
- IASTNode astNode = getIASTNode(marker, document);
- if(astNode != null) {
- int nodeLength = astNode.getFileLocation().getNodeLength();
- int nodeOffset = astNode.getFileLocation().getNodeOffset();
- String content = document.get(nodeOffset, nodeLength);
- if(content.contains(DELETE)){
- String allocFunction = getAllocFunction(marker, document);
- if(allocFunction.contains(NEW)){
- content = document.get(nodeOffset, nodeLength).replace(DELETE, DELETE + "[]"); //$NON-NLS-1$
- document.replace(nodeOffset, nodeLength, content);
- } else {
- addParentheses(astNode, document);
- if(content.contains("[")){ //$NON-NLS-1$
- removeBrackets(astNode, document);
- }
- content = document.get(nodeOffset, nodeLength).replace(DELETE, FREE);
- document.replace(nodeOffset, nodeLength, content);
- }
- } else if(content.contains(FREE)){
- if(getAllocFunction(marker, document).contains("[")){ //$NON-NLS-1$
- content = content.concat("[]"); //$NON-NLS-1$
- }
- content = content.replace(FREE, DELETE);
- document.replace(nodeOffset, nodeLength, content);
- }
+ @Override
+ public void apply(IMarker marker, IDocument document) {
+ try {
+ IASTNode astNode = getIASTNode(marker, document);
+ if(astNode != null) {
+ int nodeLength = astNode.getFileLocation().getNodeLength();
+ int nodeOffset = astNode.getFileLocation().getNodeOffset();
+ String content = document.get(nodeOffset, nodeLength);
+ if(content.contains(DELETE)){
+ String allocFunction = getAllocFunction(marker, document);
+ if(allocFunction.contains(NEW)){
+ content = document.get(nodeOffset, nodeLength).replace(DELETE, DELETE + "[]"); //$NON-NLS-1$
+ document.replace(nodeOffset, nodeLength, content);
+ } else {
+ addParentheses(astNode, document);
+ if(content.contains("[")){ //$NON-NLS-1$
+ removeBrackets(astNode, document);
+ }
+ content = document.get(nodeOffset, nodeLength).replace(DELETE, FREE);
+ document.replace(nodeOffset, nodeLength, content);
+ }
+ } else if(content.contains(FREE)){
+ if(getAllocFunction(marker, document).contains("[")){ //$NON-NLS-1$
+ content = content.concat("[]"); //$NON-NLS-1$
+ }
+ content = content.replace(FREE, DELETE);
+ document.replace(nodeOffset, nodeLength, content);
+ }
- IValgrindMessage message = getMessage(marker);
- removeMessage(message.getParent());
- ValgrindStackFrame nestedStackFrame = getStackBottom(getNestedStack(message.getParent()));
- int nestedLine = nestedStackFrame.getLine();
- String nestedFile = nestedStackFrame.getFile();
- removeMarker(nestedFile, nestedLine, marker.getType());
- marker.delete();
- }
- } catch (BadLocationException|CoreException e ){
- Status status = new Status(IStatus.ERROR, ValgrindUIPlugin.PLUGIN_ID, null, e);
- String title = Messages.getString("ValgrindMemcheckQuickFixes.Valgrind_error_title"); //$NON-NLS-1$
- String message = Messages.getString("ValgrindMemcheckQuickFixes.Error_applying_quickfix"); //$NON-NLS-1$
- showErrorMessage(title, message, status);
- }
- }
+ IValgrindMessage message = getMessage(marker);
+ removeMessage(message.getParent());
+ ValgrindStackFrame nestedStackFrame = getStackBottom(getNestedStack(message.getParent()));
+ int nestedLine = nestedStackFrame.getLine();
+ String nestedFile = nestedStackFrame.getFile();
+ removeMarker(nestedFile, nestedLine, marker.getType());
+ marker.delete();
+ }
+ } catch (BadLocationException|CoreException e ){
+ Status status = new Status(IStatus.ERROR, ValgrindUIPlugin.PLUGIN_ID, null, e);
+ String title = Messages.getString("ValgrindMemcheckQuickFixes.Valgrind_error_title"); //$NON-NLS-1$
+ String message = Messages.getString("ValgrindMemcheckQuickFixes.Error_applying_quickfix"); //$NON-NLS-1$
+ showErrorMessage(title, message, status);
+ }
+ }
- @Override
- public String getLabel() {
- return Messages.getString("ValgrindMemcheckQuickFixes.Wrong_dealloc_label"); //$NON-NLS-1$
- }
+ @Override
+ public String getLabel() {
+ return Messages.getString("ValgrindMemcheckQuickFixes.Wrong_dealloc_label"); //$NON-NLS-1$
+ }
- /**
- * Displays a pop-up indicating that an error occurred
- * @param title The title of the pop-up window
- * @param message The message of the pop-up window
- * @param status {@link IStatus} containing information about the error
- */
- private void showErrorMessage(String title, String message, IStatus status){
- Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
- ErrorDialog.openError(shell, title, message, status);
- }
+ /**
+ * Displays a pop-up indicating that an error occurred
+ * @param title The title of the pop-up window
+ * @param message The message of the pop-up window
+ * @param status {@link IStatus} containing information about the error
+ */
+ private void showErrorMessage(String title, String message, IStatus status){
+ Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
+ ErrorDialog.openError(shell, title, message, status);
+ }
- /**
- * Adds parentheses to a function call (if necessary)
- * @param node {@link IASTNode} containing the function call
- * @throws BadLocationException
- */
- private void addParentheses(IASTNode node, IDocument document) throws BadLocationException{
- IASTNode[] children = node.getChildren();
- if(children.length > 0 && !children[0].getRawSignature().contains("(")) { //$NON-NLS-1$
- IASTNode childNode = children[0];
- int childNodeLength = childNode.getFileLocation().getNodeLength();
- int childNodeOffset = childNode.getFileLocation().getNodeOffset();
- String childContent = document.get(childNodeOffset, childNodeLength);
- String newChild = "(".concat(childContent).concat(")"); //$NON-NLS-1$//$NON-NLS-2$
- // Skewed 1 char to left to remove space before parentheses
- document.replace(childNodeOffset - 1, childNodeLength + 1, newChild);
- }
- }
+ /**
+ * Adds parentheses to a function call (if necessary)
+ * @param node {@link IASTNode} containing the function call
+ * @throws BadLocationException
+ */
+ private void addParentheses(IASTNode node, IDocument document) throws BadLocationException{
+ IASTNode[] children = node.getChildren();
+ if(children.length > 0 && !children[0].getRawSignature().contains("(")) { //$NON-NLS-1$
+ IASTNode childNode = children[0];
+ int childNodeLength = childNode.getFileLocation().getNodeLength();
+ int childNodeOffset = childNode.getFileLocation().getNodeOffset();
+ String childContent = document.get(childNodeOffset, childNodeLength);
+ String newChild = "(".concat(childContent).concat(")"); //$NON-NLS-1$//$NON-NLS-2$
+ // Skewed 1 char to left to remove space before parentheses
+ document.replace(childNodeOffset - 1, childNodeLength + 1, newChild);
+ }
+ }
- /**
- * Returns the allocation function that relates to the given marker
- * @param marker {@link IMarker} object that points to where the wrong de-allocation function is
- * @return {@link String} object containing the allocation function
- * @throws BadLocationException
- */
- private String getAllocFunction(IMarker marker, IDocument document) throws BadLocationException {
- IValgrindMessage allocMessage = null;
- String file = marker.getResource().getName();
- int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
+ /**
+ * Returns the allocation function that relates to the given marker
+ * @param marker {@link IMarker} object that points to where the wrong de-allocation function is
+ * @return {@link String} object containing the allocation function
+ * @throws BadLocationException
+ */
+ private String getAllocFunction(IMarker marker, IDocument document) throws BadLocationException {
+ IValgrindMessage allocMessage = null;
+ String file = marker.getResource().getName();
+ int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
- IValgrindMessage[] wrongDeallocMessages = getMessagesByText(Messages.getString("ValgrindMemcheckQuickFixes.Wrong_dealloc_message")); //$NON-NLS-1$
- for (IValgrindMessage wrongDeallocMessage : wrongDeallocMessages) {
- ValgrindStackFrame stackBottom = getStackBottom(wrongDeallocMessage);
- int stackBottomLine = stackBottom.getLine();
- String stackBottomFile = stackBottom.getFile();
- if(stackBottomLine == line && file != null && file.equals(stackBottomFile)){
- allocMessage = getStackBottom(getNestedStack(wrongDeallocMessage));
- }
- }
- if(allocMessage instanceof ValgrindStackFrame){
- int allocLine = ((ValgrindStackFrame)allocMessage).getLine() - 1;
- int allocOffset = document.getLineOffset(allocLine);
- int allocLength = document.getLineLength(allocLine);
- return document.get(allocOffset, allocLength);
- }
- return null;
- }
+ IValgrindMessage[] wrongDeallocMessages = getMessagesByText(Messages.getString("ValgrindMemcheckQuickFixes.Wrong_dealloc_message")); //$NON-NLS-1$
+ for (IValgrindMessage wrongDeallocMessage : wrongDeallocMessages) {
+ ValgrindStackFrame stackBottom = getStackBottom(wrongDeallocMessage);
+ int stackBottomLine = stackBottom.getLine();
+ String stackBottomFile = stackBottom.getFile();
+ if(stackBottomLine == line && file != null && file.equals(stackBottomFile)){
+ allocMessage = getStackBottom(getNestedStack(wrongDeallocMessage));
+ }
+ }
+ if(allocMessage instanceof ValgrindStackFrame){
+ int allocLine = ((ValgrindStackFrame)allocMessage).getLine() - 1;
+ int allocOffset = document.getLineOffset(allocLine);
+ int allocLength = document.getLineLength(allocLine);
+ return document.get(allocOffset, allocLength);
+ }
+ return null;
+ }
- /**
- * Remove array brackets (if present)
- * @param node {@link IASTNode} from which the brackets will be removed
- * @throws BadLocationException
- */
- private void removeBrackets(IASTNode node, IDocument document) throws BadLocationException{
- int nodeLength = node.getFileLocation().getNodeLength();
- int nodeOffset = node.getFileLocation().getNodeOffset();
- String content = document.get(nodeOffset, nodeLength);
- String newContent = content.replace("[","").replace("]",""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
- document.replace(nodeOffset, nodeLength, newContent);
- }
+ /**
+ * Remove array brackets (if present)
+ * @param node {@link IASTNode} from which the brackets will be removed
+ * @throws BadLocationException
+ */
+ private void removeBrackets(IASTNode node, IDocument document) throws BadLocationException{
+ int nodeLength = node.getFileLocation().getNodeLength();
+ int nodeOffset = node.getFileLocation().getNodeOffset();
+ String content = document.get(nodeOffset, nodeLength);
+ String newContent = content.replace("[","").replace("]",""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
+ document.replace(nodeOffset, nodeLength, newContent);
+ }
- /**
- * Returns all of the messages from the currently active Valgrind view that
- * contains a given {@link String} in their description.
- * @param text the {@link String} to match the Valgrind messages' descriptions
- * @return All messages containing the given text.
- */
- private IValgrindMessage[] getMessagesByText(String text) {
- ValgrindViewPart valgrindView = ValgrindUIPlugin.getDefault().getView();
- ArrayList<IValgrindMessage> foundMessages = new ArrayList<>();
+ /**
+ * Returns all of the messages from the currently active Valgrind view that
+ * contains a given {@link String} in their description.
+ * @param text the {@link String} to match the Valgrind messages' descriptions
+ * @return All messages containing the given text.
+ */
+ private IValgrindMessage[] getMessagesByText(String text) {
+ ValgrindViewPart valgrindView = ValgrindUIPlugin.getDefault().getView();
+ ArrayList<IValgrindMessage> foundMessages = new ArrayList<>();
- if(valgrindView != null){
- IValgrindMessage[] messages = valgrindView.getMessages();
+ if(valgrindView != null){
+ IValgrindMessage[] messages = valgrindView.getMessages();
- if(messages != null && messages.length != 0){
- for (IValgrindMessage message : messages) {
- if(message.getText().contains(text)){
- foundMessages.add(message);
- }
- }
- }
- }
- IValgrindMessage[] foundMessagesArray = new IValgrindMessage[foundMessages.size()];
- foundMessages.toArray(foundMessagesArray);
- return foundMessagesArray;
- }
+ if(messages != null && messages.length != 0){
+ for (IValgrindMessage message : messages) {
+ if(message.getText().contains(text)){
+ foundMessages.add(message);
+ }
+ }
+ }
+ }
+ IValgrindMessage[] foundMessagesArray = new IValgrindMessage[foundMessages.size()];
+ foundMessages.toArray(foundMessagesArray);
+ return foundMessagesArray;
+ }
- /**
- * Return the last nested element from a given {@link IValgrindMessage}, or null if there are
- * no nested messages.
- * @param message
- * @return The {@link ValgrindStackFrame} in the bottom of the nested stack
- */
- private ValgrindStackFrame getStackBottom(IValgrindMessage message){
- ValgrindStackFrame stackBottom = null;
- IValgrindMessage[] children = message.getChildren();
- for (IValgrindMessage child : children) {
- if(child instanceof ValgrindStackFrame){
- stackBottom = (ValgrindStackFrame) child;
- }
- }
- return stackBottom;
- }
+ /**
+ * Return the last nested element from a given {@link IValgrindMessage}, or null if there are
+ * no nested messages.
+ * @param message
+ * @return The {@link ValgrindStackFrame} in the bottom of the nested stack
+ */
+ private ValgrindStackFrame getStackBottom(IValgrindMessage message){
+ ValgrindStackFrame stackBottom = null;
+ IValgrindMessage[] children = message.getChildren();
+ for (IValgrindMessage child : children) {
+ if(child instanceof ValgrindStackFrame){
+ stackBottom = (ValgrindStackFrame) child;
+ }
+ }
+ return stackBottom;
+ }
- /**
- * Returns the {@link IValgrindMessage} element from the Valgrind View that represents
- * a given Marker
- * @param marker the marker to which the ValgrindMessage relates
- * @return {@link IValgrindMessage} that represents the {@link IMarker}
- */
- private IValgrindMessage getMessage(IMarker marker) {
- IValgrindMessage message = null;
- String file = marker.getResource().getName();
- int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
- IValgrindMessage[] wrongDeallocMessages = getMessagesByText(Messages.getString("ValgrindMemcheckQuickFixes.Wrong_dealloc_message")); //$NON-NLS-1$
- for (IValgrindMessage wrongDeallocMessage : wrongDeallocMessages) {
- ValgrindStackFrame stackBottom = getStackBottom(wrongDeallocMessage);
- int stackBottomLine = stackBottom.getLine();
- String stackBottomFile = stackBottom.getFile();
- if(stackBottomLine == line && file != null && file.equals(stackBottomFile)){
- message = stackBottom;
- }
- }
- return message;
- }
+ /**
+ * Returns the {@link IValgrindMessage} element from the Valgrind View that represents
+ * a given Marker
+ * @param marker the marker to which the ValgrindMessage relates
+ * @return {@link IValgrindMessage} that represents the {@link IMarker}
+ */
+ private IValgrindMessage getMessage(IMarker marker) {
+ IValgrindMessage message = null;
+ String file = marker.getResource().getName();
+ int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
+ IValgrindMessage[] wrongDeallocMessages = getMessagesByText(Messages.getString("ValgrindMemcheckQuickFixes.Wrong_dealloc_message")); //$NON-NLS-1$
+ for (IValgrindMessage wrongDeallocMessage : wrongDeallocMessages) {
+ ValgrindStackFrame stackBottom = getStackBottom(wrongDeallocMessage);
+ int stackBottomLine = stackBottom.getLine();
+ String stackBottomFile = stackBottom.getFile();
+ if(stackBottomLine == line && file != null && file.equals(stackBottomFile)){
+ message = stackBottom;
+ }
+ }
+ return message;
+ }
- /**
- * Returns the nested stack from a given ValgrindMessage in the Valgrind View
- * @param message The message from which the stack will be acquired
- * @return {@link ValgrindError} object containing the nested stack
- */
- private ValgrindError getNestedStack(IValgrindMessage message){
- ValgrindError nestedError = null;
- IValgrindMessage[] children = message.getChildren();
- for (IValgrindMessage child : children) {
- if(child instanceof ValgrindError){
- nestedError = (ValgrindError)child;
- }
- }
- return nestedError;
- }
+ /**
+ * Returns the nested stack from a given ValgrindMessage in the Valgrind View
+ * @param message The message from which the stack will be acquired
+ * @return {@link ValgrindError} object containing the nested stack
+ */
+ private ValgrindError getNestedStack(IValgrindMessage message){
+ ValgrindError nestedError = null;
+ IValgrindMessage[] children = message.getChildren();
+ for (IValgrindMessage child : children) {
+ if(child instanceof ValgrindError){
+ nestedError = (ValgrindError)child;
+ }
+ }
+ return nestedError;
+ }
- /**
- * Removes marker from file
- *
- * @param file The file containing the marker
- * @param line The line in which the marker that will be removed is
- * @param markerType The type of marker to be removed
- * @throws CoreException
- */
- private void removeMarker(String file, int line, String markerType) throws CoreException {
- IMarker[] markers = ResourcesPlugin.getWorkspace().getRoot().findMarkers(markerType, false, IResource.DEPTH_INFINITE);
- for (IMarker marker : markers) {
- if(marker.getAttribute(IMarker.LINE_NUMBER, 0) == line && marker.getResource().getName().equals(file)){
- marker.delete();
- }
- }
- }
+ /**
+ * Removes marker from file
+ *
+ * @param file The file containing the marker
+ * @param line The line in which the marker that will be removed is
+ * @param markerType The type of marker to be removed
+ * @throws CoreException
+ */
+ private void removeMarker(String file, int line, String markerType) throws CoreException {
+ IMarker[] markers = ResourcesPlugin.getWorkspace().getRoot().findMarkers(markerType, false, IResource.DEPTH_INFINITE);
+ for (IMarker marker : markers) {
+ if(marker.getAttribute(IMarker.LINE_NUMBER, 0) == line && marker.getResource().getName().equals(file)){
+ marker.delete();
+ }
+ }
+ }
- /**
- * Removes message from Valgrind view.
- * @param message The message to be removed
- */
- private void removeMessage(IValgrindMessage message){
- ValgrindViewPart valgrindView = ValgrindUIPlugin.getDefault().getView();
- valgrindView.getMessagesViewer().getTreeViewer().remove(message);
- }
+ /**
+ * Removes message from Valgrind view.
+ * @param message The message to be removed
+ */
+ private void removeMessage(IValgrindMessage message){
+ ValgrindViewPart valgrindView = ValgrindUIPlugin.getDefault().getView();
+ valgrindView.getMessagesViewer().getTreeViewer().remove(message);
+ }
}
diff --git a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/valgrind/ui/IValgrindToolView.java b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/valgrind/ui/IValgrindToolView.java
index 45bfef6c27..5fe606414e 100644
--- a/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/valgrind/ui/IValgrindToolView.java
+++ b/valgrind/org.eclipse.linuxtools.valgrind.ui/src/org/eclipse/linuxtools/valgrind/ui/IValgrindToolView.java
@@ -25,15 +25,15 @@ public interface IValgrindToolView extends IViewPart {
*/
String VIEW_ID = ValgrindUIPlugin.PLUGIN_ID + ".valgrindview"; //$NON-NLS-1$
- /**
- * Provides a mechanism to add actions to the Valgrind view's toolbar.
- * @return An array of actions to add to the toolbar
- */
- IAction[] getToolbarActions();
+ /**
+ * Provides a mechanism to add actions to the Valgrind view's toolbar.
+ * @return An array of actions to add to the toolbar
+ */
+ IAction[] getToolbarActions();
- /**
- * Refreshes the controls within this view.
- */
- void refreshView();
+ /**
+ * Refreshes the controls within this view.
+ */
+ void refreshView();
}

Back to the top